Category Archives: C#

Dynamically Building a Model with Code First

I’ve answered a few emails recently on this topic so it felt like time to turn it into a blog post.

In this scenario the set of classes that make up your model isn’t known at compile time and is discovered dynamically at runtime. An example of such a scenario is a WordPress/Orchard/etc. style website that allows modules to be plugged in. These modules live in a separate assembly and may contain classes that represent data to be persisted in the application database. These classes are all pulled into a central Code First model to be used for data access.

Finding the Classes

There are lots of different approaches for identifying the classes to be included in the model. For this example lets use a [Persistent] attribute, something like this:

public class PersistentAttribute : Attribute

Now we can add some logic to the…

View original post 404 more words


Code First Default Value – Easy way

There is a easy way to set default values in Entity Framework   Code first. all you need to do is just set your default value in your constructor. after all entity is also behave like an object. below example show how to set default value of IsActive Property

 public class MaterialCategory

   public MaterialCategory()
   public int Id { get; set; }
   public string Name {get;set; }
   public string Description { get; set; }
   public bool IsActive { get;set;}


Load MVC Partial View inside a Html DIV via Ajax/Jquery with parameters on Kendo UI Button Click

today i came across a  scenario where i had to load a partial view inside a div tag. this solution might come handy when you have to pass Javascript variables  via Razor Syntax. anyway there is nothing fancy..

Step 1 :  define your  div tag


<div id="DivDataEntry"></div>


Step 2 : Defile your Controller Action and partial view

Controller Action

public ActionResult LoadDataEntryGrid(string Code,string Location,int Year,int Preiod,int LDate)
DateTime testDate = new DateTime(Year, Preiod, LDate); // this is according to requirement.. can not help with that 😉

// call WCF service
DataService.DataServiceClient client = new DataService.DataServiceClient();

var data = client.SelectEmpData(Code, Location, Year, Preiod, testDate);
ViewData["EmpData"] = data;

return PartialView("_LoadDataEntryGrid");

Partial View

@model IEnumerable<MyViewModels.MyViewModel>

<div class="row">

<div class="col-md-12">

<div class="content-box-header panel-heading">

<div class="panel-title ">Leave</div>


<div class="content-box-large box-with-header">
 .Columns(columns =>
 columns.Bound(p =>"Id");
 columns.Bound(p => p.bbb);
 columns.Bound(p => p.ccc);
 columns.Bound(p => p.ddd);
 columns.Bound(p => p.eee);
 columns.Bound(p => p.fff);
 columns.Bound(p => p.ggg);
 columns.Bound(p => p.hhh);
 columns.Bound(p => p.iii);

 .Pageable(pa => pa.Enabled(false))
 .DataSource(dataSource => dataSource





Step 3: Wire up your events accordingly 

Razor Code

.Content("View Data")
.Events(ev =&gt; ev.Click("BtnViewClick"))


function BtnViewClick() {

var Code = $("#ddlLocation").data("kendoDropDownList").value();</pre>
<pre>var Location= $("#ddlLocation").data("kendoDropDownList").value();</pre>
<pre>var year = parseInt( $("#txtYear").data("kendoNumericTextBox").value()); 
var month = parseInt($("#txtMonth").data("kendoNumericTextBox").value()); 
var day = parseInt($("#txtDay").data("kendoNumericTextBox").value()); 

  type: 'POST', 
   url: '@Url.Action("CheckValidity", "MyControllerName")', // Part of business logic. you may not need to do this. 
   data: { Code: Code, Location: Location, Year: year, Month: month, Day: day }, 
   cache: false, 
   success: function (data) 
    { if (data == true)
     { // we are going to render partial view inside a Div tag // this is the part i wanted to share with you all..
       $("#DivDataEntry").load('@Url.Action("LoadDataEntryGrid", "MyControllerName")?Code=' + Code + '&Location=' + Location + '&Year=' + year + '&Preiod=' + month + '&LDate=' + day); 
error: function ()
 { alert("Error Please Try Again"); }


Cheers !!!

Creating responsive and mobile friendly charts with Ajax and C# in

Google’s chart API is really amazing. with it, you can create responsive and mobile friendly chats that users can interact with. following is a small guideline to pass parameters to WebMethod with parameters  and draw charts with returned  Json result.

Page we are referring to is Reports_Sales_SalesByCategory.aspx. note that i have a DropDownList( ID=”DropDownList1″) and DIV tag (chart_SalesOverview) in this page  rest of the code is just for styling and you can simply ignore

<div id="reportDiv" class="col-md-8 col-sm-8">
<div class="panel panel-default">
<div class="panel-heading">
<h4>Select Range</h4>
<div class="panel-body">
                    <!--Div that will hold the pie chart-->
<div class="form">
<div class="input-group text-center">
                            <asp:DropDownList ClientIDMode="Static" ID="DropDownList1" class="form-control input-lg" runat="server">
                                Last Week
                                Last Month</div>
<div id="chart_SalesOverview"></div>

Next thing is to write a WebMethod that return Json result in code behind so that we can call this method via AJAX.
Make sure to add [WebMethod] and [ScriptMethod(ResponseFormat = ResponseFormat.Json)] annotations to the method as shown. so that Ajax can discover the method. and method should be public static as well.

 [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

  public static object[] GetChartData(int days)
       List data = new List();

       data.Add(new GoogleChartData { ProductCategory = "Cat 1", RevenueAmount = 100 });
       data.Add(new GoogleChartData { ProductCategory = "Cat 2", RevenueAmount = 200 });
       data.Add(new GoogleChartData { ProductCategory = "Cat 3", RevenueAmount = 300 });

       var chartData = new object[data.Count + 1];
       chartData[0] = new object[]
           "Product Category",
           "Revenue Amount"
        int j = 0;
        foreach (var i in data)
          chartData[j] = new object[] { i.ProductCategory, i.RevenueAmount };

         return chartData;

now that we have method that return some data, we’ll jump back to aspx file where we left off. next step is to add reference to google’s Chart API. to do that add following script reference

<script src="Scripts/jquery-2.1.1.min.js">
</script><script src="" type="text/javascript"></script>

after that we have to write our java script to pull the data from our web method and draw the chart.
in this example we’ll be drawing a Pie chart.


        var chartData;
        google.load("visualization", "1", { packages: ["corechart"] });

        $(document).ready(function () {
            var parameters = {};
            parameters.days = $('#<%= DropDownList1.ClientID %>').val();

           // call web method with parameters
                url: "Reports_Sales_SalesByCategory.aspx/GetChartData",
                data: JSON.stringify(parameters),
                dataType: "json",
                type: "POST",
                contentType: "application/json; chartset=utf-8",
                success: function (data) {
                    chartData = data.d;
                error: function () {
                    alert("Something went wrong! Please try again.");
            }).done(function () {
                // after complete loading data

        function drawChart() {
            var data = google.visualization.arrayToDataTable(chartData);

            var options = {
                title: "Company Sales",
                pointSize: 5

            var pieChart = new google.visualization.PieChart(document.getElementById('chart_SalesOverview'));
            pieChart.draw(data, options);


please note that its better to render java script part  just before the end of  <HEAD> element.

Enjoy !!

What if something is wrong..

  • check your Script reference is correct and well placed.
  • make sure server control’s Client ID mode is static or you will have to get the client ID via Jquery and replace it with existing one.
  • make sure javascript’s parameter object contain variables with same names as web method’s parameters.

Reference :  Google Chart API

Winform C# – Prevent Window is being dragged from title bar

By using .net's unmanned API we can prevent window being dragged from title-bar
  protected override void WndProc(ref Message m)
            int WM_NCLBUTTONDOWN = 0xA1;
            int WM_SYSCOMMAND = 0x112;
            int HTCAPTION = 0x02;
            int SC_MOVE = 0xF010;

            if (m.Msg == WM_SYSCOMMAND && m.WParam.ToInt32() == SC_MOVE)

            if (m.Msg == WM_NCLBUTTONDOWN && m.WParam.ToInt32() == HTCAPTION)

            base.WndProc(ref m);
 } Image Manipulation with facilitate powerful yet simple and solid foundation for image manipulation library for  for both mvc and web forms.   two thumbs up for these guys..

take a look here  or you may be interested in documentation   or get in action , install via nuget package