Author Archives: charithrasanga

About charithrasanga

Im a .Net developer and a enthusiastic

Dynamically Building a Model with Code First

romiller.com

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:

[AttributeUsage(AttributeTargets.Class)]
public class PersistentAttribute : Attribute
{
}

Now we can add some logic to the…

View original post 404 more words

Advertisements

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()
   {
     IsActive=true;
   }
   public int Id { get; set; }
   public string Name {get;set; }
   public string Description { get; set; }
   public bool IsActive { get;set;}

 }

Load Asp.net 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

 HTML 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>


<div class="content-box-large box-with-header">
 @(Html.Kendo().Grid((IEnumerable<MyViewModels.MyViewModel>)ViewData["EmpData"])
 .Name("myKendoGrid")
 .Columns(columns =>
 {
 columns.Bound(p => p.aaa).Title("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
 .Ajax()
 
 )
 )
 


</div>

</div>

</div>

 

Step 3: Wire up your events accordingly 

Razor Code


@(Html.Kendo().Button()
.Name("btnView")
.Content("View Data")
.Icon("search")
.Events(ev =&gt; ev.Click("BtnViewClick"))
)

 
Javascript

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()); 

$.ajax(
{ 
  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 asp.net

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 asp.net 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

</pre>
<div id="reportDiv" class="col-md-8 col-sm-8">
<div class="panel panel-default">
<div class="panel-heading">
<h4>Select Range</h4>
</div>
<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>
<div id="chart_SalesOverview"></div>
</div>
</div>
</div>
<pre>

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.


 [WebMethod]
 [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)
        {
          j++;
          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="https://www.google.com/jsapi" 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.

    <script>

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

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

           // call web method with parameters
            $.ajax({
                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
                google.setOnLoadCallback(drawChart);
                drawChart();
            });
        });

        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);
        }

</script>

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

Domain Redirection via .htaccess while keeping other url parameters.

Lets say if you want to redirect your visitors from  http://www.domainA.com/?p=667 to http://www.domainB.com/?p=667

you can achive this via adding following code to your .htaccess file.

Options +FollowSymlinks -MultiViews
RewriteEngine on

# for http
RewriteCond %{HTTP_HOST} ^(www\.)?domainA\.com$ [NC]
RewriteCond %{SERVER_PORT} =80
RewriteRule ^(.*)$ http://www.domainB.com/$1 [R=301,L]

# for https
RewriteCond %{HTTP_HOST} ^(www\.)?domainA\.com$ [NC]
RewriteCond %{SERVER_PORT} =443
RewriteRule ^(.*)$ https://www.domainB.com/$1 [R=301,L]

Reference : http://stackoverflow.com/questions/5956844/how-to-redirect-a-url-by-only-changing-the-domain-name-while-keeping-other-url?rq=1

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)
            {
                return;
            }

            if (m.Msg == WM_NCLBUTTONDOWN && m.WParam.ToInt32() == HTCAPTION)
            {
                return;
            }

            base.WndProc(ref m);
 }



Asp.net Image Manipulation with http://imageresizing.net/

http://imageresizing.net/ facilitate powerful yet simple and solid foundation for image manipulation library for asp.net..  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