logs of my work and digital life
Posts tagged asp.net
ELMAH: Error Logging Modules and Handlers
Jun 24th
Today from a blog I discovered this project called ELMAH: Error Logging Modules and Handlers by the name you can guessed by now what it does
and let me tell you it does it very well. After reading a tutorial ELMAH plugged into my asp.net 3.5 test project and working good. I really liked it and thinking to use it into my future projects.
If you need a serious error logging utiliy download ELMAH now.
Show Detailed ASP.NET Error Messages to Developers
Jun 24th
If ELMAH project will not work for me I will implement this error handling technique from scott gu blog.
BLL – Business layer with Linq
Jun 8th
Hello guys,
This is my first Bll class that is using linq and returning objects to presentation layer. Main data component class is ItemsDT which contain another skeleton class “ItemGridView” for custom view of items data table. “ItemGridView” contains basically have the fields that i want to show in my presentation layer. Note that items datatable has many column which can be reterived by calling AllItems() method.
If you just want to list all the methods into your table that is also included into your linq to sql file then you can set your method return type to list collection of the type that specified in dbml file (linq to sql). For example if you add items table into your linq to sql you will have a new type or class called Item. From your linq code you can return all the rows into the table as objects. Now these objects you can have as list collection of type Items so your method can return List<Items> and this return list will bind to any databound control like grid view with ease.
Problem arises if someone say only show selective columns then if you try to select few colums you will see visual studio provding you hint that objects return from the linq query will be of annonymous type. So to tackle this you have two options either spicy your return varriable of object type or write a skelton class that have all those columns you want to have from your datable. Below is the code with skelton class approch its easy to guess skelton class will define a type and visual studio will not alert anymore by saying your objects are of annonymous type.
{
[System.ComponentModel.DataObjectMethod(System.ComponentModel.DataObjectMethodType.Select)]
public static List<Items> AllItems()
{
DBDataContext db = new DBDataContext();
return (from t in db.Items select t).ToList<Items>();
}
public class ItemGridView
{
public int itemID { get; set; }
public string itemName { get; set; }
public string itemgroupName { get; set; }
}
[System.ComponentModel.DataObjectMethod(System.ComponentModel.DataObjectMethodType.Select)]
public static List<ItemGridView> ListSubGroups_Admin()
{
return (from t in AllItems() select new ItemGridView {
itemID = t.sgID,
itemName = t.sgName,
itemgroupName = t.Group.gName
}).ToList<ItemGridView>();
}
Consuming asp.net webservice with jquery
Feb 3rd
hi guys,
Well I like to share one more experiment with you that is how to call a webservice from your javascript(jquery). For that again you need to have an asp.net ajax enable website.
Lets first examine what are the requiments for webservice if we need to call it from javascript well after having asp.net ajax enable website first is you should mark your serverice as [ScriptService] what it does it will make all the methods/functions of your webservice to be accessable from javascript code and it also serialise your webservice response using JASON .
By default asp.net web services use soap for communication scriptservice marker make your webservice to use JASON.
Now lets defien the method in our webservice which we want to be accessable by our javascript code.
public int AddingNumbers(int a, int b)
{
return a + b;
}
That’s it now lets move to client side code.
$.ajax({
type: "POST",
url: "WebServices/MyWS.asmx/AddingNumbers",
data: "{‘a’:’1′,’b':’2′}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
alert(msg);
},
error: function()
{
alert("Request can’t made using ajax");
}
});//ajax ends here
});// document ready ends here
In above javasrcipt code we are making an ajax post request we set contentType to “application/json; charset=utf-8″ and dataType to “json” and passing a=1,b=2 as are data input parameters note that varriables name are same as verriables declared in webservice’s function AddingNumbers input parameters.
Please read articles from following links to know more and have a strong background.
http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/
http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/
http://www.keithrousseau.com/blog/2008/05/using-jquery-json-with-aspnet/
Calling asp.net page methods with jquery
Feb 3rd
Hi guyz,
Today I am sharing how to call asp.net web page code behind methods from client side javascript in my case it will be jquery.
Let us divide this into two parts the server side and client side on server side we have to write a function or page method.
public static string AddStrings(string a, string b)
{
return string.Format("my friend answer is {0}", a + b);
}
Note that we mark our AddStrings function as WebMethod and its public and static this is the basic requirement for the funtion if you want to call it from javascript or jquery.
Function itlsef is pretty simple all it does takes two strings join them and return the result. Thats all we need to write for server side.
$.ajax({
type: "POST",
url: "Default.aspx/AddStrings",
data: "{a:’najam ‘,b:’sikander’}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
alert(msg);
},
error: function()
{
alert("Request can’t made using ajax");
}
});//ajax ends here
});// document ready ends here
Client side has its own requirements first its better to use post request if you want any result back from server and then you should use json as communication medium and for that we need to set content type and data type as
contentType: “application/json; charset=utf-8″, dataType: “json” and we should supply the input data with our request. Please note that if your server side function expecting two parameters named “a” and “b” you should name your javascript input parameters same as server side parameters thats why in data section we have same name of the varriables. Example data: “{a:’najam ‘,b:’sikander’}”,
Last requirement is your web.config should have entries for asp.net ajax sections. If you are building from scrath you can shoose asp.net ajax website as template when starting new website.
Please read articles from following links to know more and have a strong background.
http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/
http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/
http://www.keithrousseau.com/blog/2008/05/using-jquery-json-with-aspnet/
Sql Data Srouce Control Updating Data From Database
Jul 17th
hey guyz finally we have to learn how to update our tables in database so only for you guys here is my sample code
string giftId = GridView1.SelectedRow.Cells[0].Text.ToString(); //getting an id
SqlDataSource myDbSource = new SqlDataSource();
myDbSource.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
//myDbSource.InsertCommand = “update gifts set giftActivate=1 where giftId=” + Entrydate + “)”;
myDbSource.UpdateCommand = “update gifts set giftActivate=’1′ where giftId=” + giftId;
myDbSource.ProviderName = “System.Data.SqlClient”;
myDbSource.Update();
Well this code set giftActive flag to 1 for all the rows matched with giftid value.
Sql Data Srouce Control Deleting Data From Database
Jul 17th
Hey guyz today i will show you how to fire delete query by using our beloved control sqldatasource.
Here is the code
SqlDataSource myDbSource22 = new SqlDataSource();
myDbSource22.ConnectionString = ConfigurationManager.ConnectionStrings["lalConnectionString"].ConnectionString;
myDbSource22.ProviderName = “System.Data.SqlClient”;
myDbSource22.DeleteCommand = “delete from ProductsGroups where pid = ” + productId;
myDbSource22.Delete();
All it does it deletes all the rows for a given productID from table productgroups. Simple right
Sql Data Srouce Control Inserting Data Into Database
Jul 17th
hey guyz how are you ??
Me back with my sqldatasource series. Today i will show you how to fire insert query using sqldatasource control into code behind i am using c#.
Below is the sample code UserID is the parameter passing into a function as an argument.
DateTime Entrydate = DateTime.Today;
SqlDataSource myDbSource = new SqlDataSource();
myDbSource.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
myDbSource.InsertCommand = “insert into tbl_invoices (user,Entrydate) values (” + UserID + “,’” + Entrydate + “‘)”;
myDbSource.ProviderName = “System.Data.SqlClient”;
myDbSource.Insert();
myDbSource.SelectCommand = “SELECT IDENT_CURRENT(‘tbl_invoices’)”;
DataView dv = (DataView)myDbSource.Select(new DataSourceSelectArguments());
DataTable dt = dv.Table;
string invNumber = dt.Rows[0][0].ToString();
return invNumber.ToString();
//return string.Empty;
Code above is very simple what it does simple take UserID as an argument and then insert a new record into tbl_invoices table and then after it i am firing a select statement that returns the latest ID into tbl_invoices table. SELECT IDENT_CURRENT(‘table name’) return the id of the last record inserted into the table.
Happy coding bye
Sql Data Srouce Control Fetch data from database
Jul 16th
Hi in asp.net 2.0 this new datasource control has been added and i liked it alot and i used it on many places so i thought it would be nice if I share my knowledge with all my readers so first of all i would just like to show you how to retrieve some data from your database into C# code behind file.
string userID = string.Empty;
string UserName=”najam”;
SqlDataSource myDbSource = new SqlDataSource();
myDbSource.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
myDbSource.SelectCommand = “select userId from Users where userName=’” + UserName + “‘”;
myDbSource.ProviderName = “System.Data.SqlClient”;
DataView dv = (DataView)myDbSource.Select(new DataSourceSelectArguments());
DataTable dt = dv.Table;
if (dt.Rows.Count > 0)
{
userID = dt.Rows[0][0].ToString();
}
Above code will return user id if username supplied. You will see no data adapters or command object.
If you like instead of creating sql datasrouce control in code behind just drag and drop it onto ur aspx page and then in your code behind reference it that will shorten the line of code for fetching data from your database.
Read SMTP settings from asp.net web.config
Jul 16th
hi guyz
Sorry for writing after such a long time i guess i am very busy now a days so for a project i needed to read my smtp email settings defined in my web.config file so after some efforts i am able to read these settings direct from my system .net section.
System.Net.Configuration.MailSettingsSectionGroup settings = (System.Net.Configuration.MailSettingsSectionGroup) config.GetSectionGroup("system.net/mailSettings");
Response.Write("<br>Username="+settings.Smtp.Network.UserName);
Response.Write("<br>Password=" + settings.Smtp.Network.Password);
Response.Write("<br>host=" + settings.Smtp.Network.Host);
Response.Write("<br>port=" + settings.Smtp.Network.Port);
Response.Write("<br>from=" + settings.Smtp.From);