Friday, 22 November 2013

Create Wcf Service using Entity Framework

In this article i am going to explain CRUD operations in WCF services using Entity Framework.First create one Customer Table in database.Now i want to get all the customers data from database for this i implemented one method called GetCustomers like this i implemented different methods for inserting data into database table,Update data into  Customers table and deleting customers.

Create Customer table in Database

In customer table fields are CustomerId,CustomerName,Address,Email.
Now go to Visual Studio . Follow this path ,File=>New=>Project =>WcfServiceApplication and name it as CustomerServices and click OK


Go to Iservice1.cs file and write the following code in Iservice1 interface
  [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        string GetData(int value);

        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);

        // TODO: Add your service operations here
        [OperationContract]
        List<Customer> GetCustomers();
        [OperationContract]
        bool InsertCustomer(Customer obj);     
        [OperationContract]
        bool UpdateCustomer(Customer obj);
        [OperationContract]
        bool DeleteCustomer(int cid);
    }

write another class named as Customer  in Iservice1.cs
[DataContract]
    public class Customer
    {
        [DataMember]
        public int CustomerId { get; set; }
        [DataMember]
        public string CustomerName { get; set; }
        [DataMember]
        public string Address { get; set; }
        [DataMember]
        public string Email { get; set; }
    }



Right click on the ‘CustomerServices’ project in Solution Explorer > Add > New Item. Select the Data Template > ADO.NET Entity Data Model and click Add.

 Now select Generate from database and click on Next




click on New Connection



 Write the server name with in textbox .if you are using Sql Server Authentication then fill username and password, and select database which you are using. click on OK.
 Now you get the following screen ,check the check box having  Yes,include the sensitive data in connection string. Now click on Next




Now select customer table and click on finish. you get the following entity model

 Now change the Customer name to CustomerEntity because the project has already one Customer class in Iservice1.cs file.
To change class name right click on Customer and click on Rename and change it to CustomerEntity


Now go to Service1.svc.cs file and write the method for Getting customers data from database

public List<Customer> GetCustomers()
        {
             Customer customer=null;
            List<Customer> lstcust = new List<Customer>();
            using(var context=new RaviEntities())
            {
                var customerEntity = (from cust in context.CustomerEntities select cust).ToList();
                if (customerEntity != null)
                    foreach (var cust in customerEntity)
                    {
                        customer = new Customer();
                        customer.CustomerId = cust.CustomerId;
                        customer.CustomerName = cust.CustomerName;
                        customer.Address = cust.Address;
                        customer.Email = cust.Email;
                        lstcust.Add(customer);
                    }
            }       
            return lstcust;
        }

Implement the method for inserting data into customer table

 public bool InsertCustomer(Customer obj)
        {
            CustomerEntity objcust = new CustomerEntity()
            {
                CustomerId = obj.CustomerId,
                CustomerName = obj.CustomerName,
                Address = obj.Address,
                Email = obj.Email
            };
            RaviEntities db = new RaviEntities();
            db.CustomerEntities.AddObject(objcust);
            // db.AddToCustomerEntities(objcust);
            db.SaveChanges();
            return true;
        }





 Implement the method for update data into customer table
   public bool UpdateCustomer(Customer obj)
        {
            var custId = obj.CustomerId;
            using (RaviEntities context = new RaviEntities())
            {
                var customerEntity = (from c in context.CustomerEntities where c.CustomerId == custId select c).Single();
                if (customerEntity != null)
                {
                    customerEntity.CustomerId = obj.CustomerId;
                    customerEntity.CustomerName = obj.CustomerName;
                    customerEntity.Address = obj.Address;
                    customerEntity.Email = obj.Email;
                    context.CustomerEntities.DeleteObject(customerEntity);
                    context.SaveChanges();
                    context.AddToCustomerEntities(customerEntity);
                    context.SaveChanges();
                }
            }

            return true;
        }


Implementing Method for Deleting the customer


  public bool DeleteCustomer(int cid)
        {
            using (RaviEntities context = new RaviEntities())
            {
                var customerEntity = (from c in context.CustomerEntities where c.CustomerId == cid select c).Single();
                if (customerEntity != null)
                {
                    context.CustomerEntities.DeleteObject(customerEntity);
                    context.SaveChanges();           
                }
            } 
            return true;
        }



Now  run the application and copy the url
http://localhost:3970/Service1.svc 

Check wcf services are working are not

How to check Wcf Services  :


Go to  Visual Studio Command Prompt and type wcftestclient and click Enter key. Now it opens another window


Now click on addservice and paste that url and click OK. you get the all methods in the services

For Getting All Customers ..double click on the method.=>Click on Invoke=> Select Ok
Now you get the following output



Similarly you can check all the methods like this.


Wednesday, 13 November 2013

Static Dropdown List in MVC 4

A dropdownlist in MVC is a collection of selectlistitem objects.

Here i am going to explain, how to get a static dropdown list without getting values from database .

Go to Home Controller and add another action method named as Departments
and add view to Departments


Go to Departments.cshtml and write the following code.

@Html.DropDownList("Departments", new List<SelectListItem>
{
new SelectListItem{Text="IT",Value=""},
new SelectListItem{Text="HR",Value=""},
new SelectListItem{Text="Finance",Value=""},
new SelectListItem{Text="Accounts",Value=""}
},"Select Department") 



Now run the application and you will see the static dropdown list
































This is the sample example for Dropdown list

keywords:MVC 4 Dropdownlist,dropdownlist in mvc4,static drop down list in mvc , dropdownlist in mvc,mvc dropdownlist,MVC 3 Dropdownlist,Asp.Net MVC 4 Dropdownlist,generate sample dropdownlist in mvc 5,generate sample dropdownlist in mvc,how to create static dropdownlist in mvc 4,
,how to create static dropdownlist in mvc,,how to create static dropdownlist in mvc5


Monday, 4 November 2013

Sample MVC 4 Application Using Code First

Creating Your First Application

You can create MVC 4 Web Application by using visual C# or Visual Basic.Go to File=>Select New=>Project and click on Project..Select ASP.NET MVC 4 web Apllication and name your project as MvcEmployee and click OK.




In MvcEmployee Project dialog box select Internet Application.Leave Razor as default View Engine.And click OK.


By default we get Home Controller And Account Controller




 Now Add Class to Model folder in the Application and name it as Employee


In Employee Class write the below code.
public class Employee
    {   
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public string DateofBirth { get; set; }
        public string Address { get; set; }
        public int Salary { get; set; }
    }





Add [Key] attribute above id....using System.ComponentModel.DataAnnotations namespace

Go to Web.config file and change the connection string as

<connectionStrings>
    <add name="EmployeeDb" connectionString="Persist Security Info=False;User ID=sa;Password=007;Data Source=USER-30\SQLEXPRESS2K8;Initial Catalog=aspnet-MvcEmployee-20131105123901" providerName="System.Data.SqlClient" />
  </connectionStrings>

 

Now go to Tools--->Library Package Manager--->click on Package Manager 
 Console

Write the following in PM Console

Enable-Migrations

and press Enter Key

Now getting following error

More than one context type was found in the assembly 'MvcEmployee'.
To enable migrations for MvcEmployee.Models.UsersContext, use Enable-Migrations -ContextTypeName MvcEmployee.Models.UsersContext.
To enable migrations for MvcEmployee.Models.DataContext, use Enable-Migrations -ContextTypeName MvcEmployee.Models.DataContext.






Now write the following in PM Console

Enable-Migrations -ContextTypeName MvcEmployee.Models.DataContext 

and press Enter key

Now you saw the following message in PM Console

Checking if the context targets an existing database...
Code First Migrations enabled for project MvcEmployee.


Now observe the solution explorer.The New folder is added named as Migrations.In configuration.cs change the following code

 public Configuration()
        {
            AutomaticMigrationsEnabled = true;
            AutomaticMigrationDataLossAllowed = true;
        }






Add another class to Model folder name it as DataContext Class.


 add  MvcEmployee.Migrations namespace to the DataContext class.

and write the following code in Datacontext class

 Add following namespace  using System.Data.Entity;

public class DataContext:DbContext
    {

 public DataContext() : base("EmployeeDb")
        {
        }
        public DbSet<Employee> employee { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {

            base.OnModelCreating(modelBuilder);
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<DataContext, Configuration>());
            modelBuilder.Entity<Employee>().ToTable("employee");
        }


}  Now add the controller Name it as Employee

Go to Controller folder Right click==>Add==>click on Controller

Now Change The Controller Name as EmployeeController and select template 

Mvc Controller with read/write actions and views ,using Entity Framework

Select Model Class as Employee (MvcEmployee.Models) 

and select  Data Context Class as DataContext (MvcEmployee.Models) 

Now Click on Add 






 Now run the application  and append the Employee to the url

observe the following screen shot




Now go to Database observe the database is created or not



Click on Create New and add one record and corresponding record in database table.





We can edit , update and delete  the records.This is the example for sample Mvc Application using Code first.

Key words: Sample Mvc 4 application, Sample Mvc 4 application using code first,Mv4 project,code first example in mvc4,asp.net mvc4 application,asp.net mvc4 application using code first