logs of my work and digital life
Asp.net
Observer pattern with .net
Jul 8th
Hi folks,
Well I am investigating design patterns by reading an article so after reading a bit I thought it would be nice if I write some code and test it.
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
/// <summary>
/// Product Class
/// </summary>
public class Product
{
public delegate void NameChangeEventHandler(int a);
public event NameChangeEventHandler NameChanged;
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
if (NameChanged != null)
{
NameChanged(5);
}
}
}
public Product(string name)
{
Name = name;
}
public void PrintName()
{
Console.WriteLine("ProductName={0}", Name);
}
}
/// <summary>
/// Test Class
/// </summary>
public class Test
{
public Test(Product P)
{
P.NameChanged += new Product.NameChangeEventHandler(ChangeDetected);
}
public void ChangeDetected(int a)
{
Console.WriteLine("change found,argument passed is {0}",a);
}
}
static void Main(string[] args)
{
Product p = new Product("najam awan");
p.PrintName();
Test t = new Test(p);
p.Name = "najaf awan";
p.PrintName();
Console.ReadKey();
}
}
}
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.
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/
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);
How to get directory name of the page currently displaying
Nov 6th
If you want to know only the directory name not the full path of the page that is currently displaying you can use this code
string sPath = System.Web.HttpContext.Current.Request.Url.AbsolutePath;
System.IO.FileInfo oInfo = new System.IO.FileInfo(sPath);
string sRet = oInfo.Directory.Name.ToString();
Response.Write(“<br><br>Directory name===” + sRet + “<br><br>”);
Happy Coding
Najam Sikander Awan