November 9, 2005
MSN Sandbox !!!
November 7, 2005
System.Net.Mail
public void SendEmail()
{
//.Net 1.0 System.Web.Mail -- Is now Depre
/*
//We can use the constructor as well; e.g.
/*MailMessage mail = new MailMessage("ludmal@test.com", "ludmal@tst.lk", "Test", "test");*/
MailMessage mail = new MailMessage();
mail.To = "ludmal@e-solutions.lk";
mail.From = "ludmal@test.com";
mail.Body = "Body Testing";
SmtpMail.SmtpServer = "mail";
SmtpMail.Send(mail);
*/
//.Net 2.0 System.Net.Mail
MailMessage mail = new MailMessage("ludmal@test.com", "ludmal@tst.lk", "Test", "test");
/*MailAddressCollection col = new MailAddressCollection();
MailAddress sendAdd = new MailAddress("ludmal@e-solutions.lk");
*/
System.Net.Mail.SmtpClient client = new SmtpClient("mysmtp");
client.Send(mail);
}
November 4, 2005
Google's new RSS Reader
November 3, 2005
Socket Programming using .Net 2.0 System.Net.Socket
Server Code:
class MyServer
{
//Listing to the client connections.
public void Listen()
{
byte[] ipArray = new byte[4];
ipArray[0] = 127;
ipArray[1] = 0;
ipArray[2] = 0;
ipArray[3] = 1;
IPAddress add = new IPAddress(ipArray);
//This is obselete in .Net 2.0
//TcpListener tcpListener = new TcpListener(10);
TcpListener tcpListener = new TcpListener(add, 10);
tcpListener.Start();
Socket socketForClient = tcpListener.AcceptSocket();
if (socketForClient.Connected)
{
Util.Out("client connected..");
NetworkStream netStream = new NetworkStream(socketForClient);
StreamWriter writer = new StreamWriter(netStream);
StreamReader reader = new StreamReader(netStream);
string str = "Message from Server : " + DateTime.Now.ToLongDateString();
writer.WriteLine(str);
Util.Out("What meessage do you want to send to client?");
writer.WriteLine(Console.ReadLine());
writer.Flush();
str = reader.ReadLine();
Util.Out(str);
reader.Close();
writer.Close();
netStream.Close();
}
socketForClient.Close();
Util.Out("Exiting...");
}
}
Client Code :
public class MyClient
{
//Connects to the server
public void Connect()
{
TcpClient socketForServer = null;
try
{
socketForServer = new TcpClient("localhost", 10);
Util.Out("Connected to the Server");
}
catch
{
Util.Out("Failed to connecto localhost");
Util.Out("Exiting..");
return;
}
NetworkStream netstream = socketForServer.GetStream();
StreamReader reader = new StreamReader(netstream);
StreamWriter writer = new StreamWriter(netstream);
try
{
string output1, output2;
output1 = reader.ReadLine();
output2 = reader.ReadLine();
Util.Out(output1);
Util.Out(output2);
writer.Flush();
reader.Close();
}
catch
{
Util.Out("Exception Occured! Exiting...");
}
netstream.Close();
}
}
This is small helper class…
public class Util
{
public static void Out(string s)
{
Console.WriteLine(s);
}
}
This is a simple console application. You can create two console application one for the server & one for the client. Run the server first then client app. If you want you can create nice windows applications using this two simple classes to communicate over network.
November 2, 2005
C# 2.0 : String comparison
Class diagrams in VS 2005
October 31, 2005
GMail Drive
You can download it from http://www.viksoe.dk/code/gmail.htm
October 28, 2005
Creating a Screen Saver with Visual Studio 2005
With VS 2005 it’s possible. You can create your own screen saver without any coding. I will explain the basic steps to create your screen saver in minutes. Of course you will get the complete help info from the VS itself. So lets start your RSS feed screen saver.
Open the VS 2005, File > New > Project
New project dialog box will appear. Select the Starter Kits > Screen Saver Starter Kit
Click ok. You can go ahead and change the code for your requirements or else you can keep the default. Build the project & go to the project BIN folder. You will find ssNews.scr file in it. Copy & Paste the file into the %SystemRoot%\system32\ folder.(e.g. WINNT\system32\) Your done!. Great VS has created screen saver for you in just seconds. Select the screen saver (News) from the Screen saver tab from the Display settings & change the RSS feed from the Screen Saver Settings. You can customize the background picture / RSS feed / shortcut keys... whatever since we got the source code. So try it & have fun.
October 19, 2005
I'm @ TechEd
(Im at teched with my very good old friend Sumudu)
October 11, 2005
TechEd ! im sponsered :-)
October 10, 2005
Brute Force Attacks.
Brute Force attacks are closely related to dictionary attacks. Brute force attack generates random user ids and passwords instead of reading them from a dictionary file.
Now suppose a user has a six-character password that consists of upper-and lowercase letters, digits and 32 punctuation characters. There are 689,869,781,056 password combinations. A brute force attack would require 1,093 years on average to find the correct password. This comparison doesn’t mean brute force attacks aren’t a threat, but it does make it clear how much more dangerous dictionary attacks are. I will post a code sample about how to create a dictionary attack & how we can prevent from it. So stay tuned.
October 3, 2005
Visual Studio: What’s in a code Name?
September 28, 2005
Best approach for a 3 tier application ?
September 27, 2005
Discussion About Microsoft Patterns & Practices
September 26, 2005
Share your videos with Google
September 23, 2005
Custom Objects with Web Services
So today im going to explain how to return a custom object through web service. I will explain the scenario from a simple diagram.( banks needs a valid telephone number to issue a credit card its a fact)
In this scenario Telephone Company is offering a web service to its partners to get the customer just by supplying customers telephone number.
Customer class:
public class Customer
{
public Customer()
{
//
// TODO: Add constructor logic here
//
}
string _name;
string _age;
string _company;
public string Name
{
get{return _name;}
set{_name = value;}
}
public string Age
{
get{return _age;}
set{_age = value;}
}
public string Company
{
get{return _company;}
set{_company = value;}
}
}
GetCustomer web service method which returns the customer object
[WebMethod]
public Customer GetCustomer()
{
//can be perform any database functions
Customer customer = new Customer();
customer.Name = "Ludmal de silva";
customer.Age = "25";
customer.Company = "E-Solutions";
return customer;
}
Now we can use this web service by simply adding a web reference to our project.(you guys should know how to add a web reference its really simple).
Finally you can get the customer object which returns from the web service. Code below.
//Customer object
CustomerService.Customer customer = new CustomerService.Customer();
//CustomerService object
CustomerService.Service1 myCustomerService = new CustomerService.Service1();
///Get the customer from the WebService
customer = myCustomerService.GetCustomer();
//Assigning the values to the UI
this.Label1.Text = customer.Name;
this.Label2.Text = customer.Company ;
this.Label3.Text = customer.Age ;
What I was trying to do is to give a basic idea about web services & to use the custom object with web services. I highly appreciate comments. (my writing skills might be poor...) But all the questions /comments are welcome.
September 22, 2005
Custom DataGrid with client side behavior
September 21, 2005
Power of CSS
http://www.csszengarden.com/
September 20, 2005
Using Web User Control
Web user control is playing a major role in asp.net development. Its hardly possible to develop a application without web user controls. But most of developers are not using it properly. In this article I just thought to share some powerful features of web user control. Microsoft .Net framework is fully object oriented implementation. So we have to take advantage of it. We can learn lots of things by looking at the Microsoft class library. So lets start simple sample to show proper use of Web user control.
Scenario: We have to create 3(might be more) Registration forms in different formats. But the Mailing Address section is always stays the same. We need to accomplish this in minimum effort with a Web User Control in OOP manner.
Solutions: So lets start creating simple Web User Control name AddressUI;
In code behind of the AddressUI insert the below code
//AddressUI Properties
public string Street1
{
get {return this.txtStreet1.Text ;}
set {this.txtStreet1.Text = value;}
}
public string Street2
{
get {return this.txtStreet2.Text ;}
set {this.txtStreet2.Text = value;}
}
public string City
{
get {return this.txtCity.Text ;}
set {this.txtCity.Text = value;}
}
public string Country
{
get {return this.txtCountry.Text ;}
set {this.txtCountry.Text = value;}
}
public bool ContactMe
{
get {return this.chkContactMe.Checked ;}
set {this.chkContactMe.Checked = value;}
}
Now you can use this AddressUI control in any page u wanted. Giving u easily maintainable UI. Let me show you how u can use this control in your ASP.net pages.
Drag & drop the control into the page. You can access the controls property. Check the below code.
Declare the AddressUI control
protected AddressUI AddressUI1;
then access its properties, Add this code to a button click event.
Response.Write(AddressUI1.City + AddressUI1.Country );
your done. You can assign its properties to another objetecs properties.. no hassle doing Page.FindControl & no casting at all.
IE Developer Toolbar
Download IE developer Toolbar
To list some of the features:
· View HTML object class names, IDs, and details such as link paths, tab index values, and access keys.
· Outline tables, table cells, images, or selected tags.
· Validate HTML, CSS, WAI, and RSS web feed links.
· Display image dimensions, file sizes, path information, and alternate (ALT) text.
· Immediately resize the browser window to 800×600 or a custom size.
· Selectively clear the browser cache and saved cookies. Choose from all objects or those associated with a given domain.
· Choose direct links to W3C specification references, the Internet Explorer team weblog (blog), and other resources.
· Display a fully featured design ruler to help accurately align objects on your pages.
September 19, 2005
Blog search by Google
Google has unveiled a website that lets people search web journals or blogs. Try your self: http://blogsearch.google.com/
Word verification for comments
September 16, 2005
Hotmail will be replacing by Microsoft Mail
Twenty-Eight Design Aphorisms
2. Use technology, don’t let it use you.
3. Be aware of what you make and what it says, because people live and die through all of the images we create.
4. We need more teamwork.
5. Have your cake and eat it too; participate in design “research.”
6. Have a backup plan.
7. Designers are not monkeys, they do not merely articulate.
8. New ideas are made every single day; unless you repeat yourself, it’s new. Don’t worry about whether or not the person next to you is doing it, or will do it.
9. Trust no one. No matter how original your idea seems, somebody else is looking to do it better, and probably cheaper.
10. Keep your enemies close. (See number 9.)
11. Media allegiance spells limitation. Think first, then choose what tools to use.
12. There’s nothing wrong with design that looks like art.
13. There’s nothing wrong with art that looks like design.
14. Think holistically.
15. Work in a style that maximizes your performance and well being.
16. Appreciate your audiences’ needs and team members’ skills.
17. Establish objectives prior to form.
18. Brainstorm. Fail frequently. Enjoy the element of play.
19. There are no truisms.
20. A connoisseur of design is not a designer.
21. Design history is not a chronicle of style; you cannot truly critique design unless you fully understand its history.
22. Ideology, thought, and agenda are as important as aesthetics.
23. Design without ego.
24. Statements like “Designers Don’t Think” are short-sighted at best.
25. There is always more than one solution.
26. There will always be revisions.
27. The entire process of design is its essence. Without process, we are left with merely style and solutions.
28. Aesthetic biases are and are not the purest form of design.
September 15, 2005
Document your code.
/// <summary>
/// Gets the users age
/// </summary>
/// <param name="name">username</param>
/// <returns>age</returns>
public int GetAge(string name)
{
return 26;
}
I will show you how to document your code using Visual Studio. You can completely generate a standard documentation from the VS ;)
Click on the Tools > Build Comment Web pages >
Then the Build Comment dialog box will appear, you can select the solution that you want to document, give the path & then press ok. Youre done. You will get a nice documentation for your project. For vb developers you can download add in for xml style comments from this url. http://www.gotdotnet.com/team/ide/#original
September 13, 2005
Whidbey and Yukon in November 7
Microsoft is set to release Whidbey and
September 8, 2005
Ajax with Custom objects
First add the HttpHanlders to the webconfig file .
<httpHandlers>
<add verb="POST,GET" path="ajax/*.ashx"
type="Ajax.PageHandlerFactory, Ajax" />
</httpHandlers/>
Then well create a simple customer class.
[Serializable]
public class Customer
{
string _name;
string _address;
int _type;
public string Name
{
get{return _name;}
set{_name = value;}
}
public string Address
{
get{return _address;}
set{_address = value;}
}
public int Type
{
get{return _type;}
set{_type = value;}
}
public Customer(string name, string address, int type)
{
this._name = name;
this._address = address;
this._type = type;
}
}
In the sample webform1.aspx page write the below method. This will return the customer object. You perform any logic here to return the customer object. But for me im just simply instantiate the object.
[Ajax.AjaxMethod()]
public Customer GetCustomer()
{
//You can do some database logic here to get the customer object0
Customer customer = new Customer("Microsoft","Redmond",1);
return customer;
}
To use this method in the client side we have to register class(In this case the page itself) in the Page_Load event.
Ajax.Utility.RegisterTypeForAjax(typeof(WebForm1));
Ok were almost done. Simply create a JavaScript function to get the values from the object.
function BindCustomer()
{
var customer = WebForm1.GetCustomer().value; document.getElementById('lblName').innerText = customer.Name; document.getElementById('lblAddress').innerText = customer.Address; document.getElementById('lblType').innerText = customer.Type;
}
Of course you have to do the html part. (Add some html controls to the page) .so have fun with ajax. Happy coding... & stay tuned for my next post
September 7, 2005
Google's secret Lab
http://www.searchbistro.com/index.php?/archives/19-Google-Secret-Lab,-Prelude.html
September 2, 2005
ASP.Net low level view
August 30, 2005
w.blooger makes blogin easy
download w.Blogger
August 26, 2005
Cut down your development time.
Wanna cut down your development time?? Use macros. Iit’s really cool. I’m using it through out my coding /development process. While we do developing we used to copy n paste some of the code snippets. For example adding comments to your code or assigning getters setters to a class etc..etc.. but with macros you can do those things by using shortcut keys.. let me show you how.. You’ll love macros once you get to know it. I will explain step by step for you to create a simple macro for adding comments to your code.
'Sample code for addComments macro
Sub MyComments()
DTE.ActiveDocument.Selection.Text = "//by " + System.Environment.UserName + " " + Now()
End Sub
August 16, 2005
Managed Code Performance
Today I read a very good article from a guy who works for Microsoft BCL Performance section. I found some good interesting concepts. If your interested about code performance you should read this article.
http://blogs.msdn.com/ricom/
I wrote a very simple performance test for testing the for vs foreach & string vs stringbuilder ..etc..etc.. you can find the code below.
Timer class: This calculates the code execution time.
///
/// To get the elapsed the time
///
public class MyTimer
{
long _start;
long _end ;
long _exeTime ;
public string ElapsedTime
{
get
{
//returns the Elapsed time
_exeTime = _end - _start;
return _exeTime.ToString();
}
}
///
/// Start the timer
///
public void Start()
{
_start = DateTime.Now.Ticks ;
}
///
/// End the timer
///
public void Stop()
{
_end= DateTime.Now.Ticks ;
}
}
Some of my test samples
static void
{
MyTimer m = new MyTimer();
ArrayList a = new ArrayList();
//For Tests
m.Start();
for(int i=0; i<1000;>
{
string sss= "as" + i.ToString();
Console.WriteLine(sss);
a.Add(sss);
}
m.Stop();
Console.WriteLine(m.ElapsedTime);
m.Start();
for(int i=0; i
{
Console.WriteLine(a[i].ToString());
}
m.Stop();
Console.WriteLine(m.ElapsedTime);
//Foreach Tests
m.Start();
foreach(string s in a)
{
Console.WriteLine(s);
}
m.Stop();
Console.WriteLine(m.ElapsedTime);
//String BuilderTest
StringBuilder name = new StringBuilder();
m.Start();
for(int i=0;i<100000;>
{
name.Append(i.ToString());
}
m.Stop();
Console.WriteLine(name.ToString());
Console.WriteLine(m.ElapsedTime);
}
August 12, 2005
Proper user of Interfaces in C#
What we’re trying to do is to write our database method to the interface. Not to the concrete class.
Here is the complete code.
public interface IDataHelper
{
void Connect();
void Execute();
}
//SqlDataHelper - using SQL database
public class SqlHelper :IDataHelper
{
public void Connect()
{
//SqlDataHelper Implementation
Console.WriteLine("Connectiing sql..");
}
public void Execute()
{
//SqlDataHelper Implementation
Console.WriteLine("executing Sql..");
}}
//OracleHelper - using Oracle database
public class OracleHelper : IDataHelper
{
public void Connect()
{
//SqlDataHelper Implementation
Console.WriteLine("Connectiing oracle..");
}
public void Execute()
{
//SqlDataHelper Implementation
Console.WriteLine("executing oracle..");
}}
public class UserDataBase
{
public UserDataBase()
{}
//method implementing to the IDataHelper interface
public static void CheckDB(IDataHelper help)
{
help.Connect();
help.Execute();
}
public static void Main(string[] args)
{
//Use 1
//Oracle as the Database
OracleHelper oraleHelper = new OracleHelper();
CheckDB(oraleHelper);
//Use 2
//Sql as the Database
SqlHelper sqlHelper = new SqlHelper();
CheckDB(sqlHelper);
}}
Facade Design Pattern
It’s an interface for an entire subsystem. It’s a high level layer that makes the subsystem easier to use.
{
Light _light;
TV _tv;
AC _ac;
public HomeTheaterFacade()
{
this._ac = new AC();
this._dvdPlayer = new DVDPlayer();
this._light = new Light();
this._tv = new TV();
}
public void WatchMovie(Movie movie)
{
_light.Dim();
_tv.On();
_ac.Start();
_dvdPlayer.Play(movie);
}
}
Movie movie = new Movie("Matrix Reloaded");
e.WatchMovie(movie);
August 11, 2005
XML Serialization
How to serialize a object to a XML file. code below.
Simply create a User class file.
[Serializable]
public class User
{
public User()
{
}
string _name;
string _age;
public string Name{get{ return _name;}set{_name = value;}}
public string Age{get{ return _age;}set{_age = value;}}
}
To serialize the user object into a xml file add the code below
public void SerializeUser()
{
//creates user object
User user = new User();
user.Name = "Ludmal";
user.Age = "25";
//this will create a xml file in the given location
TextWriter writer = new StreamWriter("C:\\user.xml");
//simply use the Serialize method from the XMLSerializer class
//
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(User));
serializer.Serialize(writer,user);
}
You can open the xml file & change the values easily.
-
To deserialize user object from the xml file simply add the below method
public User DeserializeUser()
{
//Read from the XML file
TextReader reader = new StreamReader("C:\\user.xml");
//Creates a instance of the xmlserializer class by passing the User class
XmlSerializer serializer = new XmlSerializer(typeof(User));
//Creats the user from the XmlSerializer by deserializing
User user = (User)serializer.Deserialize(r);
return user;
}
Its that simple. Try your self. We can easily save settings as XML files. Remember to add the Serializable attribute to all the classes that you want to serialize.
August 10, 2005
Viewstate & object serialization
[Serializable]
public class User
{
public User()
{
//
// TODO: Add constructor logic here
//
}
string _name;
string _age;
string _address;
public string Name{get{ return _name;}set{_name = value;}}
public string Age{get{ return _age;}set{_age = value;}}
public string Address{get{ return _address;}set{_address = value;}}
}
//In the web form page
private void Page_Load(object sender, System.EventArgs e)
{
user = new User();
user.Name = "Ludmal";
user.Age = "25";
}
private void Button2_Click(object sender, System.EventArgs e)
{
ViewState["User"] = user;
}
private void Button1_Click(object sender, System.EventArgs e)
{
user = (User)ViewState["User"];
Response.Write("My Name is " + user.Name);
}
June 2, 2005
developing better wait page.
http://www.codeproject.com/aspnet/wait_page.asp
May 27, 2005
Developing Windows CE Applications
I was kind a busy with some windows ce applications for one of our clients. basically its a Pocket PC device with CSV file reader/writer & some data mining stuff. In this post im not going to tell about my project but i'd like to share some of the similiraties/differences with the .Net Compact Framework vs .Net framework. The .net compact framework has more in common with the full .net framework than it has differences. Both uses the Assemblies , both access portable executable files(PE) which contains the MSIL & metadata that defines the .net application. Compact Framework supports the Multithreaded programing model just likes the .net framework. Design /Develop Windows CE UI has never been easier. Unlike .Net Windows applications, we have to worry about the device we're targeting on & the processor type(for deployment CAB files). Compact Frmework Controls has less features than the .Net windows application. For example if we look at the WinCE Datagrid its really poor compare to .Net windows Grid. Anyhow its fun to work with Windows CE.
May 12, 2005
ASP.Net Cookie Handling
//Page 1
//Page Load Event
if(!IsPostBack)
{
if(Request.QueryString["AcceptCookies"] == null)
{
Response.Cookies["TestCookie"].Value = "ok";
Response.Cookies["TestCookie"].Expires = DateTime.Now.AddMinutes(1);
Response.Redirect("My2.aspx?redirect=" + Server.UrlEncode(Request.Url.ToString()));
}
else
{
//Can Redirect to the page You want
Response.Write(Request.QueryString["AcceptCookies"].ToString());
}
}
//Page2
//Page Load Event
string redirect = Request.QueryString["redirect"];
string acceptCookies = "";
if(Request.Cookies["TestCookie"] == null)
{
//No Cookies
acceptCookies = "0";
}
else
{
//Yes Cookies
acceptCookies = "1";
//Delete the Test Cookies
Response.Cookies["TestCookie"].Expires = DateTime.Now.AddMinutes(1);
}
Response.Redirect(redirect + "?AcceptCookies=" + acceptCookies );
May 10, 2005
Partial Classes
//partial class 1
public partial class Customer
{
private string _name;
private int _age;
}
//partial class 2
public partial class Customer
{
public string Name
{
get{return _name;}
set{_name = value;}
}
public int Age
{
get{return _age;}
set{_age= value;}
}
public void ShowMyName()
{
return Name;
}
}
public class MyBusiness
{
public void ShowCustomers()
{
Customer customer = new Customer();
customer.ShowMyName();
}
}
May 4, 2005
Generate properties automatically
I found this inresting article while i browse the net. its was good Add-in for VS to create get set for properties.
check it out
http://www.codeproject.com/macro/PropertyGenerator.asp
Stored procedure for Custom Paging
we already know that dataGrid control has built in paging feature. but there are some situation that we have to turn our mind to custom paging. Reason is that if we are binding 100000+ records to a DataSet we wont be showing al those records at once. If we use built in paging we are just binding the complete dataset to the datagrid at once. this will lead to a performance overhead becuase we have to bind the dataset al the time. what if we can pull out only the records we need & give options to the user to browse through the pages. All we have to do it write a StoredProcedure which returns required records. Check the out the Article beclow. you find it interesting i bet u do. Happy Programming!
Custom Paging with Stored Procedure
May 3, 2005
Datagrid with client side behavior
http://msdn.microsoft.com/msdnmag/issues/04/01/CuttingEdge/default.aspx
DataSets vs Collections
http://msdn.microsoft.com/asp.net/default.aspx?pull=/library/en-us/dnaspp/html/CustEntCls.asp
I personaly prefer working with collections. it's making my development easy. find out why.