Showing posts with label Dot Net. Show all posts
Showing posts with label Dot Net. Show all posts

Saturday, April 25, 2015

MVC & WebAPI - Model Binder

There are some specific cases in order to use model binder to MVC and WebAPI in same project.

Here i will explain step by step to implement MVC and WebAPI Model Binders

What is Model Binder?

In some cases, we should do common operations for all actions inside controller. So in that case we can add model binder and pass as parameter to actions. In below example UserModel class sent as Model Binder

public ActionResult Index([ModelBinder]UserModel model)

{
...
}

Implementing Model Binder for MVC

MVC uses different namespace such as System.Web.Mvc. So Model Binder class also should use the same.

Step 1:

Create UserModel class as required. Here we can add our required properties. In this example, i am going to display UserId and UserName

public class UserModel
    {
        public string UserId { get; set; }
        public string UserName { get; set; }

    }

Step 2:

Create custom ModelBinder class which can be implemented from System.Web.Mvc.IModelBinder as below. Here i created as partial for merging with WebAPI. If you dont need WebAPI then just have it as normal class


public partial class UserModelBinder : System.Web.Mvc.IModelBinder
    {
        public object BindModel(System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType != typeof(UserModel))
            {
                return null;
            }

            UserModel userModel = new UserModel();

            var userId = HttpContext.Current.User.Identity.GetUserId();

            if (!string.IsNullOrEmpty(userId))
            {
/// Create your custom logics to fill the other required details. In this example i can fill username
            }
            return userModel;
        }
    }

Step 3:

Register this Custom ModelBinder class into Global.asax.cs file

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //Model binder for MVC controller usermodel
            ModelBinders.Binders.Add(typeof(UserModel), new UserModelBinder());

        }

Step 4:

Use this custom model binder in action methods of MVC controller

public ActionResult Index([System.Web.Http.ModelBinding.ModelBinder]UserModel model)

{
...
 //Write your logic to do with UserModel class object
}


Thats all for MVC Model Binder.


Implementing Model Binder for WebAPI

WebAPI cannot be worked with MVC model binder. So we need to create differently. Step 1 to create UserModel is same. So i will go from Step 2

Step 2:

Create Custom Model Binder for WebAPI as follows. Here IModelBinder uses System.Web.Http.ModelBinding.

using Microsoft.AspNet.Identity;
using System.Web;
using System.Web.Http;
using System.Web.Http.ModelBinding;

public partial class UserModelBinder : IModelBinder
    {
        public bool BindModel(System.Web.Http.Controllers.HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType != typeof(UserModel))
            {
                return false;
            }

            UserModel userModel = new UserModel();

            var userId = HttpContext.Current.User.Identity.GetUserId();

            if (!string.IsNullOrEmpty(userId))
            {
               //Your logic to fill usermodel class and assign to binding context’s model
                bindingContext.Model = userModel;
                return true;
            }

            bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Error in model binding");
            return false;
        }

    }


Step 3:

Create ModelBinderProvider class as follows. It is going to be register with configuration. Here ModelBinderProvider uses namespace System.Web.Http.ModelBinding..

public class UserModelBinderProvider : ModelBinderProvider
    {
        private System.Type type;
        private UserModelBinder userModelBinder;

        public UserModelBinderProvider(System.Type type, UserModelBinder userModelBinder)
        {
            this.type = type;
            this.userModelBinder = userModelBinder;
        }

        public override IModelBinder GetBinder(HttpConfiguration configuration, System.Type modelType)
        {
            if (modelType == type)
            {
                return userModelBinder;
            }

            return null;
        }

    }


Step 4:

Register ModelBinderProvider in Global.asax.cs file under WebApiConfig register method

public static class WebApiConfig

    {
    public static void Register(HttpConfiguration config)
        {
         var provider = new UserModelBinderProvider(typeof(UserModel), new UserModelBinder());

         config.Services.Insert(typeof(ModelBinderProvider), 0, provider);


Step 5:

Use in APIController action methods as follows

[HttpGet]
        public string GetUserName([ModelBinder]UserModel model)
        {
              return model.UserName;
  }

Thats all for WebAPI Model Binder.


Wednesday, August 21, 2013

WPF - Access any control inside Template control

Following is code to get the control
[ControlType] objName = ([ControlType])ParentControlName.Template.FindName("ControlName", ParentControlName);


Ex:- 
Below is the code to get the scroll viewer of combo box and set to top

ScrollViewer cmbScrollViewer = ScrollViewer)cmbName.Template.FindName("DropDownScrollViewer", cmbName);

cmbScrollViewer.ScrollToHome();
  

Style Control template of combo box maybe as below

<ControlTemplate TargetType="{x:Type ComboBox}">
…. 
<ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto"x:Name="DropDownScrollViewer" Template="{DynamicResource ScrollViewerTemplate}" MaxWidth="330"MaxHeight="{TemplateBinding MaxDropDownHeight}">
        <ItemsPresenter/>
</ScrollViewer>
…. 

</ControlTemplate>

Wednesday, August 7, 2013

C# - How to get Property Name as string by Property Type

Create a static class for Property Helper with GetPropertyName method

public static class PropertyHelper<T>
    {
        public static string GetPropertyName<TPropObject>(Expression<Func<T, TPropObject>> propertyValue)
        {
            return ((MemberExpression)propertyValue.Body).Member.Name;
        }
    }


Call like below to get the PropertyName as string


PropertyHelper<YourClass>.GetPropertyName(r => r.YourProperty)

Thursday, July 11, 2013

WPF - Export to excel using EPPlus

Following code helpful to create a excel file from WPF

Prerequesties:-
EPPlus DLL   (Ref: http://epplus.codeplex.com/releases/view/89923)

Step 1: Create a WPF project

Step 2:  Add reference of EPPlus DLL

Step 3: Following is the sample class to export

        public class Employee
        {
            public string EmployeeName;
            public int EmployeeAge;
            public string Designation;
        }


Step 4: Create Data with values

            List<Employee> lstEmployee = new List<Employee>();
            lstEmployee.Add(new Employee() { EmployeeName = "Balaji", EmployeeAge = 16, Designation = "DE" });
            lstEmployee.Add(new Employee() { EmployeeName = "prasad", EmployeeAge = 16, Designation = "TA" });

           
Step 5: Create Header Data for excel
           List<string> lstHeader = new List<string>() { "Employee Name", "Employee Age", "Designation" };
Step 6: Create Excel Package and add Header and Column details

            ExcelPackage pck = new ExcelPackage();
            pck.Workbook.Properties.Author = "Balajiprasad";
            pck.Workbook.Properties.Title = "EPPlus in WPF";
            pck.Workbook.Properties.Company = "For Aditi Technologies";

            var ws = pck.Workbook.Worksheets.Add("Employee Details");

            //Header Section
            for (int i = 0; i < lstHeader.Count; i++)
            {
                ws.Cells[1, i + 1].Value = lstHeader[i];
                ws.Cells[1, i + 1].Style.Font.Bold = true;
            }

            //Column Value Section
            for (int i = 0; i < lstEmployee.Count; i++)
            {
                ws.Cells[i + 2, 1].Value = lstEmployee[i].EmployeeName;
                ws.Cells[i + 2, 2].Value = lstEmployee[i].EmployeeAge;
                ws.Cells[i + 2, 3].Value = lstEmployee[i].Designation;
            }


Step 7: Save as the byte array as excel

            byte[] fileText = pck.GetAsByteArray();

            SaveFileDialog dialog = new SaveFileDialog()
            {
                Filter = "Excel Worksheets (*.xlsx)|*.xlsx"
            };

            if (dialog.ShowDialog() == true)
            {
                File.WriteAllBytes(dialog.FileName, fileText);
            }


Following is the entire code

        private void GenerateExcel()
        {
            List<Employee> lstEmployee = new List<Employee>();
            lstEmployee.Add(new Employee() { EmployeeName = "Balaji", EmployeeAge = 16, Designation = "DE" });
            lstEmployee.Add(new Employee() { EmployeeName = "prasad", EmployeeAge = 16, Designation = "TA" });

            List<string> lstHeader = new List<string>() { "Employee Name", "Employee Age", "Designation" };


            ExcelPackage pck = new ExcelPackage();
            pck.Workbook.Properties.Author = "Balajiprasad";
            pck.Workbook.Properties.Title = "EPPlus in WPF";
            pck.Workbook.Properties.Company = "For Aditi Technologies";

            var ws = pck.Workbook.Worksheets.Add("Employee Details");

            //Header Section
            for (int i = 0; i < lstHeader.Count; i++)
            {
                ws.Cells[1, i + 1].Value = lstHeader[i];
                ws.Cells[1, i + 1].Style.Font.Bold = true;
            }

            //Column Value Section
            for (int i = 0; i < lstEmployee.Count; i++)
            {
                ws.Cells[i + 2, 1].Value = lstEmployee[i].EmployeeName;
                ws.Cells[i + 2, 2].Value = lstEmployee[i].EmployeeAge;
                ws.Cells[i + 2, 3].Value = lstEmployee[i].Designation;
            }

            byte[] fileText = pck.GetAsByteArray();

            SaveFileDialog dialog = new SaveFileDialog()
            {
                Filter = "Excel Worksheets (*.xlsx)|*.xlsx"
            };

            if (dialog.ShowDialog() == true)
            {
                File.WriteAllBytes(dialog.FileName, fileText);
            }

        }


public class Employee
        {
            public string EmployeeName;
            public int EmployeeAge;
            public string Designation;
        }