One To Many,Many To Many In Entity Framework Practical Approach

. Sunday, December 23, 2012
0 comments

Hi Guys,
I wondered through lots of places to find solution of my problem that How to establish One To Many,Many To Many Relationships in Entity Framework,but I didn't find any good solution so finally decided to create my own practical solution for this.

In my solution I'm providing following things :-
a)Created the corresponding database for relationships like One To One,Many To One (vice-versa),Many To Many etc.
b) Established Entity-Framework Model from Database i.e. Database First Technique.
c) Performed Add in Many To One & Many To Many Relationships.
d) Performed Cascade Delete in relationships
e)Give me one commitment to Perform Cascade update after finding the complete solution so that my this post will get succeed.

You should follow the exact approach which I shown in the example given for saving of many to many deleting etc, such techniques are built-in features of Entity-Framework Relationship Model we should use them.

Please find the complete code from my GitHub repository Here.

Hope you'll enjoy my this article Please feel free to comment.
Thanks Happy Coding.

Creating classes in Javascript

. Sunday, November 18, 2012
0 comments

Hi Guys,

If you searched for classes in javascript ? then you are on the right place, Well like any other technology javascript also supports for oops but unfortunately it does not support for classes, Yes , Javascript is a class-less technology script.

We can simulate class behavior in javascript by creating an object for the function and then we can achieve behavior for accessing various methods of that function through the object created.

Lets take a look 
 
function Car( model ) {
  var value=1; //private member   

  this.model = model;  //all members with this are public
  this.color = "silver";
  this.year  = "2012";
  this.getInfo = function () {
    return this.model + " " + this.year;
  };
}

Now we create an object for this function to access method like this


function Run()
{
var myCar = new Car("ford");
myCar.year = "2010";
alert( myCar.getInfo() );
}

First we create object of Car then we set the year property and then accessed the method , all these are available only because its declared as public with 'this.' but we would not access value member as its declared privately, so here's we are achieving encapsulation by hiding the some members declared privately,which can be used for security purpose.
Please find the complete code on git here

Disable functionality with jquery -a simple approach

. Wednesday, October 24, 2012
0 comments

Hi Guys,
How can you disable any control with particular Id/class etc of html, with jquery its fairly very simple
create a method which will disable the control.
Note : that the disable method is not jquery's method . Its a custom method (command) created for our application use.
 
(function ($) {
   $.fn.disable = function () {
       return $(this).each(function () { 
            $(this).attr('disabled', 'disabled'); 
       });
    };

Now access the element with Id(in my case)

 
var input = $('#txtname');
// Disable all the controls having
input.disable();

body of html appear like this

 
             
                

as all of you know now i'm using git so please download the complete example from here

Add/Delete Row In Table Using Javascript

. Thursday, October 18, 2012
0 comments

Hi Guys,Today I will tell you how can you add/delete rows of html table using javascript functions,so lets start with this.
First I m creating a html table very simple table with one row as default to appear.

 
    
Quantity

Now create two buttons which will be used to add/delete row as follows 
 
    
    

What the magic going on here on click of both the buttons ?????
well , when you click on Add Row button javascript function addRowProduct is called which receives the id of table,we've passed inside the single quote, and inside this function we did following :
a) access the table by its id and assign it to var variable.
b) find the total number of rows right now,and insert a empty row to current index which equals to total row count here.
c)create cell at first position i.e. 0 of row and append an element of type input with  its properties like id,type,class name etc inside this cell.

Similarly when clicking on delete button javascript function deleteRow called in which we did following :
a)access the table by its id in var type variable.
b) find the total number of row in table.
c)delete the row of total row count minus 1.

what's the interesting point to remember here is  table row index starts from 0 so while add new row we just need to insert the row with total row count which automatically inserts row to current index and count increases by one while deleting the row we passes the total row count minus 1 because its deletes by index so if total row count is n then we need to delete the row at n-1 index to delete the max. row.
One good news for all my readers now I m on github (a social coding site uses git (distributed version control system)) so that I can share the running code as well for better understanding of how things are happening.
Really amazing isn't it .
Please find the entire code for this stuff here.
Thanks and happy coding... 

UrlRewritingNet with asp.net

. Saturday, August 25, 2012
0 comments

What’s a Url Rewriting ?

Well, writing urls in such a friendly manner so that it can be more readable and seo-friendly, we use urlrewriting.

for example suppose i am having an url like

http://domainname.com/mypage.aspx?Id=1

after using url rewriting i can rewrite this url like

http://domainname.com/mypage.aspx/1

isn’t it more readable off course it is, and in this way search engines also recognizes your url better way and good page ranking can be achieved.

read in details regarding what’s url rewriting here

For now i am using urlrewritingnet  a third party component to rewrite and redirect your urls.

so before proceeding ahead I want to also discuss regarding Url Redirection,

well url redirection is used to redirect an incoming http request from current url to any other url there are basically two types of redirections we used.

a) Http 301 (Permanent Redirect)

b) Http 302 (Temporary Redirect)

suppose some one requests for domanname.com/FirstPage and you want to display SecondPage in place of FirstPage so you can redirect user with any of the above technique.

read here regarding when to use which technique.

For Now let install this component to redirect the urls and also to redirect them.

a) Download the zip from here

b) Extract the zip and reference the urlrewritingnet.urlrewrite.dll to your project.

do the following steps inside web.config file

c) Arrange the config section inside configuration node following way

 




d) Create UrlRewritingnet Node this way



 


Your urls will be mapped here......



e) configure HttpHandler inside system.web which will listen to the requests



 




finally your whole code should look like this way



 

<?xml version="1.0"?>



























































 



Now url rewriting will work..



to give intellisense support include urlrewritingnet.xsd file into your project which is available in the package you downloaded.



here are some cool urls rewrite I done from this configuration



UrlRewrite



In the above image as shown in Image Code 100 if request made for Invoice/(.*) then request is handled by product.aspx page with query string parameter as category and this parameter we are received in code behind and the text is displayed.



In Image Code 101 if request made for Invoice/(.*)/(.*) then in two query string parameters are used one is category (as done before) another is price ,both the parameters are received in code behind.



In Image Code 102 if request made for Invoice/(.*)/(.*)/ then the query string parameters are the same way as done just before this in Image Code 101 and received them in code behind.



this is the code behind of Product.aspx page



 
protected void Page_Load(object sender, EventArgs e)
{
string item = Request.QueryString["Category"];
string price = Request.QueryString["Price"];
lblItem.Text = "You chosen the Category " + item;

if (price != null && price!="")
{
lblItem.Text += " and its price is " + price;

}
}


now what’s the interesting behind these all the mappings ???



The interesting thing which I noticed here is the prioritizing of mappings  same as we have done in asp.net mvc routing so whenever a request is made for the request as virtual url the http handler checks the route which matches first and mapped to corresponding physical url,



so you should always put most-specific-mappings first in the way and then the less-specific mappings as in above we have put invoice(.*)/(.*)/ before invoice(.*)/(.*) because if someone requests for invoice/LG/20000/ and  we’ve mapped the url first this one invoice(.*)/(.*) then at the last the price text will be 20000/ instead of being 20000,same way we put mapping invoice/(.*) after the most-specific mapping invoice/(.*)/(.*).

Response.Write inside gridview with updatepanel

. Tuesday, June 5, 2012
0 comments

Hi guys, if you are using functionality which includes response.write on button click eg : export to pdf or xls etc and its inside gridview and gridview is inside content template of UpdatePanel then response.write will not work.

Why ?

because you’re firing an ajax request (xmlhttprequest) and with response.write it actually refresh the html content which is not possible.

take an example from aspx here :

 




























InvoiceNumber
CustomerName
BillerName













from code above the thing which need to note is this



 




by specifying Postback Trigger Id with Gridview control you can PostBack controls of Gridview.



Happy coding.. Thanks

Object Datasource with different select methods

. Sunday, April 1, 2012
0 comments

Hi Guys, I am going to tell you how can we use object datasource with specifying different select method at runtime.

What does Object Datasource Do for Us ?

Object Datasource contains the record set of specified collection and later this can be bind to any data control available like gridview, list view etc.

Following are the few properties which we need to specify when using object datasource

a)Type Name : This is the name of class which method will be binded to the object datasource.

b)Select Method :  Name of the method which will return the returns the collection.

Now lets take a look at the following :

    


its a simple object datasource with set the above properties.



which retrieves all the available biller as datatable from method getall billers.



and on page load I have bind objectdatasource to gridview as follows :



protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindBillerGrid("GetAllBillers", "DataAccess.DALBiller");
}
}

private void BindBillerGrid(string selectmethod,string typename)
{

//bind objDSBiller to GrdVwBiller
GrdVwBiller.DataSource = objDSBiller;
GrdVwBiller.DataBind();

}


Now I want to set a search method in Select Method of ObjDS with some parameters, but before doing this I need to look the sequence diagram of object ds which is as follows :



 



 objectds



so before fetching data from database objectds's Selecting method is called which sets the required parameters for Defined method in property select method for now, and then invokes the specified method and after which objectds’s selected method is invoked.



so I did the following to specify two parameters here for Search Method of biller inside selecting method of objds.



    protected void objDSBiller_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
if (objDSBiller.SelectMethod=="SearchBiller")
{
//add parameters to objDSBiller
objDSBiller.SelectParameters.Add(param1);
objDSBiller.SelectParameters.Add(param2);

//set values of parameters
e.InputParameters["columnname"] = ddlBillerColumn.SelectedValue;
e.InputParameters["value"] = txtSearch.Text.Trim();
}
}


param1,param2 are defined in variable region as follows



    #region variables
Parameter param1 = new Parameter("columnname", TypeCode.String);
Parameter param2 = new Parameter("value", TypeCode.String);
#endregion


all the things will work fine except you can get an exception something like



ObjectDataSource 'XXX' could not find a non-generic method 'XXX' that has parameters: XXX, XXX



to resolve this exception we need to look at seqeunce diagram again that after fetching records from db object datasource binds the data with data control like gridview so we can remove the added parameter which were for specified select method as follows :



        //bind objDSBiller to GrdVwBiller
GrdVwBiller.DataSource = objDSBiller;
GrdVwBiller.DataBind();

//remove parameters after objectdatasource has retrieved data.
if (objDSBiller.SelectMethod == "SearchBiller")
{
objDSBiller.SelectParameters.Remove(param1);
objDSBiller.SelectParameters.Remove(param2);
}


so that object datasource’s property select method can have any other method which doesn’t have input parameters and if its having then we can specify and remove them as discussed above.





here is the complete code for the stuff discussed above



public partial class People_Biller_BillerGrid : System.Web.UI.Page
{

#region variables

BLLBiller objBllbiler = new BLLBiller();
Biller biller = new Biller();
Parameter param1 = new Parameter("columnname", TypeCode.String);
Parameter param2 = new Parameter("value", TypeCode.String);

#endregion

#region functions

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindBillerGrid("GetAllBillers", "DataAccess.DALBiller");
}
}

private void BindBillerGrid(string selectmethod,string typename)
{
//set selectmethod,typename of objDSBiller
objDSBiller.SelectMethod = selectmethod;
objDSBiller.TypeName = typename;

//bind objDSBiller to GrdVwBiller
GrdVwBiller.DataSource = objDSBiller;
GrdVwBiller.DataBind();

//remove parameters after objectdatasource has retrieved data.
if (objDSBiller.SelectMethod == "SearchBiller")
{
objDSBiller.SelectParameters.Remove(param1);
objDSBiller.SelectParameters.Remove(param2);
}

}
protected void objDSBiller_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
if (objDSBiller.SelectMethod=="SearchBiller")
{
//add parameters to objDSBiller
objDSBiller.SelectParameters.Add(param1);
objDSBiller.SelectParameters.Add(param2);

//set values of parameters
e.InputParameters["columnname"] = ddlBillerColumn.SelectedValue;
e.InputParameters["value"] = txtSearch.Text.Trim();
}
}

protected void GrdVwBiller_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
//change pageindex and bind datasource
GrdVwBiller.PageIndex = e.NewPageIndex;
GrdVwBiller.DataSource = objDSBiller;
GrdVwBiller.DataBind();
}

protected void GrdVwBiller_RowCommand(Object sender, GridViewCommandEventArgs e)
{

if (e.CommandArgument == "Edit")
{
//check if edit is clicked
int billerid;

//get the current row clicked.
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);

//Get the current row biller id.
billerid = Convert.ToInt32(GrdVwBiller.DataKeys[row.RowIndex].Value);

//redirect user to Edit Biller Page.
Response.Redirect("~/People/Biller/AddModifyBiller.aspx?billerid=" + billerid);
}
else if (e.CommandArgument == "View")
{
//check if edit is clicked
int billerid;

//get the current row clicked.
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);

//Get the current row biller id.
billerid = Convert.ToInt32(GrdVwBiller.DataKeys[row.RowIndex].Value);

//redirect user to View Biller Page.
Response.Redirect("~/People/Biller/ViewBiller.aspx?billerid=" + billerid);
}

}

protected void btnSearch_Click(object sender, EventArgs e)
{
BindBillerGrid("SearchBiller", "DataAccess.DALBiller");
}
protected void btnClear_Click(object sender, EventArgs e)
{
//clear the search data and redisplay gridbiller
BindBillerGrid("GetAllBillers", "DataAccess.DALBiller");
}

#endregion
}

Difference Between Server.Transfers and Response.Redirect in Asp.net

. Sunday, February 5, 2012
0 comments

HI Guys Today I want to tell you a little bit about these two things

a)Server.Transfer : This method is same as Response.redirect Except This Method is to   transfer user from one page to another page without generating a fresh httprequest,which means that transferring from one to another page is done at server.

Advantage : The Main advantage of using this method is less roundtrip time and hence good performance,because the user is transferred from one page to another page at server side rather than making request first at client side and sending this request to server side.

Disadvantage : The main disadvantage of using this method is url is not changed while sending user from one page to other page so User can be confused some time regarding application behavior.  when I transferred to other page the Url didn't changed but only contents are changed.

Image1 

Image2 b)

Response.Redirect : With Response.redirect method first request in send for requested page at browser's end then the browser send this request to Server,server processes the requested and send httpresponse to browser and hence in the whole process roundtrip time is exceed as compare to Server.Transfer method.

Advantage: The main Advantage of using response.redirect is user can understand the redirect in application from one page to other page as the url change when redirecting the user.

Disadvantage : The disadvantage is rountrip time is more than server.transfer which is not good from performance perspective. you can send all those things with server.transfer which you send with response.redirect like parameteres values and receiveing them in same way as did for response.redirect.

Page1.aspx.cs

    protected void Button1_Click(object sender, EventArgs e)
{
Server.Transfer("~/Page2.aspx?Id=1&Name=Vishal");
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("~/Page2.aspx?Id=1&Name=Vishal");
}

Page2.aspx.cs

	lblid.Text = Request.QueryString["Id"];
lblname.Text = Request.QueryString["Name"];

IEnumerable,IList,ICollection in C#

. Friday, January 20, 2012
4 comments

Hello Friends, I am writing blog after really a long time due to my busy work schedule, anyway Today I am going to tell you about these interfaces with their uses.
IEnumerable
Its a core interface which is used to iterate over collection of specified type.Mainly it Implements two methods:
MoveNext: which is of boolean type which tells whether there are more records to move on or not.
GetCurrent: which returns the current record from the collection.
ICollection :Implements IEnumerable
Its a Interface used to Manipulate generic Collections,as it is Implements IEnumerable interface so its obvious that this will also Implements methods MoveNext and GetCurrent,so with this interface you can iterate through collection.
Apart from this its also having its own methods like
Add:Which adds record at the end of collection.
Remove:Removes Specified Item from collection.
Contains:Its a boolean type method which tells whether collection contains the specified item or Not.
I will post code later to explain something tricky thing in this hierarchy.

class Collection
{
static void Main(string[] args)
{
//declare array
string[] arystr = new string[] { "Ajay", "Anil", "Ravi", "Vishal", "Ram" };
//Check for IEnumerable
IEnumerable enumstr = from record in arystr select record;
Console.WriteLine("Start for Enumerable");
foreach (string name in enumstr)
{
Console.WriteLine("Names are {0}", name);
}
Console.WriteLine("Ends for Enumerable");

//Check for IList
IList Liststr = (from record in arystr select record).ToList();
Console.WriteLine("Start for List");
Liststr.Add("Rakesh");
foreach (string name in Liststr)
{
Console.WriteLine("Names are {0}", name);

}
Console.WriteLine("Ends for List");

//Check for ICollection
ICollection Collectionstr = (from record in arystr select record).ToList();
Console.WriteLine("Start for Collection");

Console.Write(Collectionstr.Contains("Ram"));
foreach (string name in Collectionstr)
{
Console.WriteLine("Names are {0}", name);

}
Console.WriteLine("Ends for Collection");
Console.Read();
}
}


IList


Interface which is collection of Non-generic type objects and can be accessed by index. Its the Interface which Implements two interfaces ICollection and IEnumerable.so its obvious that this will Implements the methods of the both the interfaces.Its own methods are like


Insert: Insert the given item at specified Index.


RemoveAt:Removes the Item from Specified Index.


IndexOf : retrieves the item from specified Index.


Now Lets take and Example


When I use IL to see the compilation of above Code I get the following:


 image


image




image


image





This was for IEnumerable Which Implements two basic methods MoveNext and GetCurrent.


image


image


image


 image


 image


From IL its very clear that IList also Implements Interface IEnumerable so when I receive array of string inside IList it internally uses movenext and GetCurrent these two methods to iterate over records,and one more is the method Add,which is because its also Implements ICollection.


image


  image


image


ICollection also Implements IEnumerable but I didn’t added IL code for this, only you can see for ICollection is Contains method which is a boolean type as you can see from IL Output.


So among IList,ICollection,IEnumerable the hierarchy is like


IList Implements ICollection Implements IEnumerable.


hope you enjoyed this article. Thanks