November 9, 2005

MSN Sandbox !!!

Guys check this out, Microsoft’s MSN sandbox (that’s how they called it), new MSN technologies, prototypes and many more. It’s really cool!! http://sandbox.msn.com/

November 7, 2005

System.Net.Mail

Seems to me that Microsoft has deprecated the System.Web.Mail, & replaced it with the System.Net.Mail. When I try to send an email using the System.Web.Mail it gives the message obsolete with a warning. Below is the code sample for sending simple SMTP emails with .NET 2.0.

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

November 3, 2005

Socket Programming using .Net 2.0 System.Net.Socket

Socket is a communication mechanism where we use to connect client and the server. Basically the Server will listen to the client connections on specific port number. A client can connect to the Server by using the relevant hostname and the port number. Upon the successful client connection server will gets a new socket bound to a different port. It needs the original socket for listen to other client connections while communicating with the connected client. Below is the simple client /server example done using the .Net 2.0. Review the code & you will find it interesting. (I made it very simple to make you understand) You can modify the code to meet your needs.  

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

While i was reading some of the msdn blogs i found a nice article about string comparison in C# 2.0. Just have a look and it might be helpful to you. http://blogs.msdn.com/abhinaba/archive/2005/11/02/488041.aspx

Class diagrams in VS 2005

One of the loving features of mine in VS 2005 is class diagrams. The ability to draw class diagrams and the same time it will generate the code for us and vice-versa. Once you done the development you can simply generate the class diagram by right clicking on the Project > View Class Diagram. If you want to export the diagram as an image, right click on the diagram and select Export Diagram as Image. Below is the sample diagram I created using VS 2005.

October 31, 2005

GMail Drive

GMail Drive is a Shell Namespace Extension that creates a virtual filesystem around your Google Gmail account, allowing you to use Gmail as a storage medium.

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

It’s been some time that I couldn’t post anything in my blog bocoz of the tight schedule I had. Tech Ed was really great event especially for us as .net developers. There are loads of things to come from the next release of VS 2005 & SQL 2005. What Microsoft is trying to do is to cut down the development time & to focus more on the business requirements. There were some really good sessions about the Yukon(Sql 2005) from the Sql MVP Vinod Kumar & Vineeth Gupta. Vineeth Gupta demonstrated some really good new features like DB Mirroring, Data Encryption and Key Management and so forth. I was really stunned by the new VS Team System. I will post some articles about each & every new feature when the time permits. So I had fun & learn some new cool stuff at Tech Ed & hope to attend to the next year TechEd as well.



















(Im at teched with my very good old friend Sumudu)

October 11, 2005

TechEd ! im sponsered :-)

Im sponsered by my employer(E-Solutions Lanka) for the first teched in sri lanka. There are two developers(including me :-)) going to the teched. Yesterday i went through some of the key enhacnements in VS 2005/ASP.Net. Just a little preparation for the big event tommorow(12th Oct). But im wondering why microsoft didnt list teched sri lanka in their teched worldwide site. any ideas..??? http://www.microsoft.com/events/teched2005/worldwide.mspx

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.

You should be more concerned about dictionary attack than a brute force attack. A typical password dictionary has roughly 1,000,000 entries of common passwords. These include people’s names, common pet names, and ordinary words. Suppose an efficient dictionary attack can generate and analyze 10 guesses per second. If a user’s password is in the dictionary, the attack will succeed in at most 100,000 seconds or approximately 28 hours.

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?

Microsoft Commonly uses the code names for unreleased versions of products it’s developing. The code names for the versions of visual studio since its initial release in February 2002 have followed a geographical pattern. Everett, a town in Washington about 30 miles from Microsoft headquarters in Redmond, was the code name for visual Studio 2003, the currently shipping product Whidbey the next release is named for Whidbey island in Puget sound, offshore from the town of evrett. The Whidbey release is tied to next version of Sql server(code-named Yukon). The VS.net version Microsoft will release around the same time is code-named Orcas. Orcas island in puget sound is even further from Redmond than Whidbey island.

September 28, 2005

Best approach for a 3 tier application ?




















I have read so many articles went through so many blogs, had discussions with professional developers & this is what i got finally,(remember this is not about tierd architecture , this is about passing the data thorugh tiers..) any ideas???

September 27, 2005

Discussion About Microsoft Patterns & Practices

we just thought to have discussion about microsoft patterns & practices if you guys are interested go head & publish your thoughts to this post http://mahasen.blogspot.com/2005/09/talking-about-microsoft-patterns.html

September 26, 2005

Share your videos with Google

One of my colleagues just showed me another googles invention. Its still in beeta. But guys its really worth. You can share your videos over the internet..more.... Goto: http://video.google.com

September 23, 2005

Custom Objects with Web Services

Web Services are not .net specific. Most of them might think its something Microsoft invented. What Microsoft have done is they implemented a common standard. To create a web service in .net is really easy. But you should understand the concept behind it. You can find the public web services which available through Microsoft UDDI service.(http://uddi.microsoft.com/visualstudio/ )

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

while i was digging into the massive microsoft MSDN site i found this interesting article about the data grid. Never thought a datagrid can do this much. Check the article at http://msdn.microsoft.com/msdnmag/issues/04/01/CuttingEdge/default.aspx im working on a article to show how to return a custom object through a web service. I will publish it tommorow. So stay tuned. ;)

September 21, 2005

Power of CSS

You will be amazed of the CSS possibilities. It can completely change the page's layout with no tables at all. CSS is a really a powerful technology for the UI designers. I just went through a site today (one my colleague refer me to this site) its dedicated site to CSS stuff...really cool. I think UI designers should know the real beauty of CSS for designing spectacular sites.
http://www.csszengarden.com/

September 20, 2005

Using Web User Control

Note: Recommend Audience - Asp.net Beginner

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.

The Hundred Greatest Theorems

check this out The Hundred Greatest Theorems

IE Developer Toolbar

I tried MSN tool bar with the tabs option. trust me its damn lazy work. They just wanna do something ... when ever we maximize /minimize the IE window the page get refreshed which makes me pissed off. Sometimes the IE window get stuck which makes it even worse. So personally I hate MSN toolbar. I rather like Firefox tab options. Since were doing asp.net stuff , most of our customers are using IE we have to stick to it. But its not a must..;) anyhow Microsoft has released toolbar for Internet Explorer 6. itsbasically designed to make developing and previewing websites in IE even easier. I think its really good for web designers to see the site layout & so forth. It will show you the image info, site layout info & even we can validate the HTML , CSS etc through W3C site. You can pinned the Developer toolbar to the Internet Explorer browser window or floated separately.

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

i had to put a word verification for comments bcoz of the number of spam comments im getting. So those who are submitting comments accept my regret & use word verification.

September 16, 2005

Hotmail will be replacing by Microsoft Mail

I created my first email with Microsoft Hotmail. It was the best webmail provider in that time. But i didnt log in to my hotmail since 1998. how pity...I'm currently using gmail as my default webmail. I defently like the simple design & the power of ajax. Anyhow microsoft didnt compltly gave up the hotmail. Their fighting back with thier new Microsoft Mail. Its still in beeta only released to small number of beeta testers & for the microsoft employees. You can see some screenshots below. Google Microsoft battle continues....

Twenty-Eight Design Aphorisms

1. Everything in life is ephemeral, don’t expect anything you design to live forever.

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.

Since we're doing some RAD stuff nobody got time to comment their code. But commenting code will be really helpful once we get used to it. If more than one developer is working on the same file it will be advantageous to that developer. As far as I concern every developer should comment their code. We can automatically generate a comments document using a third party tool or by using the Visual Studio. Every method we write should be documented/ commented. Its really helpful to the client developers. If were building a library you must comment your code coz thats the only way a client developer can understand easily how to use the library. Most of the developers already know how to use Microsoft comments.


/// <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 Yukon in November 7. So stay tuned & develop more powerful applications than today. Add this http://blogs.msdn.com/pdc/rss.aspx rss feed to staty updated with the PDC 2005. PDC is more focusing on Windows Vista. I still couldn’t try vista. It’s supporting Sinhala Unicode characters. Cool isn’t it.

September 8, 2005

Ajax with Custom objects

Ajax (Asynchronous JavaScript and XML) is recently become so popular with the google's gmail release. For .net we have an open source Ajax.net library. (for more info goto http://sourceforge.net ) So today I want to explain some cool stuff which we can do using ajax.net. We can now use custom objects with ajax. the best way to explain is from a example.. so lets go to the code.. what we're trying to do is to return a custom object & bind its properties to a HTML controls. We can instantiate the object from the server side code & pass it to the client side. See how simple.. no Postbacks at all ...below is the complete code..ohh I almost forget something, to use custom objects with ajax we must make the object serializable. So don't forget the serializable attribute.(what is does is serializing/deserializing the object ) ok enough talking, i want to show you the example.. (need to keep this article short as possible to improve readability ?)

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

google has a secret search quality lab that utilizing human testers with the goal of improving search quality. They are testing the quality of the search results from the humans all over the world. The're main goal seems to avoid spam & to get the right site on top. You can find more info here
http://www.searchbistro.com/index.php?/archives/19-Google-Secret-Lab,-Prelude.html

September 2, 2005

ASP.Net low level view

Ever thought of ASP.NET low level process..?? We shouldn't know but its worth to take look at the ASP.NET pipeline. ASP.NET is far away from the classic ASP apps. ASP.NET is easier & far superior than the classic ASP. Typically a .net web developer should know how to interact with objects & events in which ASP.NET high level interface provides. The entire ASP.NET engine built in managed code. ASP.NET is request processing engine. It takes the incoming requests & passes to its internal pipeline to an endpoint where a client developer can attach code to process that request. Request with .aspx extension will move to the appropriate HttpHandler by the aspnet_isapi.dll. When the request comes in it process by the ASP.NET runtime. Depending on the extension it routes the request to an appropriate handler that is responsible for picking the request. Likewise we can program to any type of extensions with our own custom Httphandler. To get a clear picture of the underlying process take a look at the image below.

August 30, 2005

w.blooger makes blogin easy

i just installed w.blooger tool. Im using it now for my future posts. its really a nice manage our posts. if anybody intrested download it from the below URL. its totally free..;)
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.

You can record a macro or you can code it using visual basic.

To record a macro press Ctrl+Shift+R & then type what you want to use repeatedly(for recording). Then stop recording by pressing the Ctrl+Shift+R. To save the macro open the macro explorer by pressing Alt+F8. And rename the TemporaryMacro. If you want to edit the macro right click on the macro then click edit. You can later assign to a shortcut key by simply going to Tools > Customize > Keyboards. Its that easy ;)

Here is a sample macro which I’m using to add comments to my code. You can save it as a macro & start using it. Remember you can do lots of thing using macros not just adding code snippts ;). if you need more sample macros just send me a mail to Ludmal at gmail.com. happy coding..

'Sample code for addComments macro

Sub MyComments()
DTE.ActiveDocument.Selection.Text = "//by " + System.Environment.UserName + " " + Now()

End Sub

Project Life cycle


check this out.. typical software project cycle...

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 Main(string[] args)

{

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#

We as software developers must always ...always remember to program to Interfaces NOT to Implementations. I'll tell you why. Everybody who's doing developing should know about software changes. We have to spent time on enhancements rather than the initial implementation. So what we require is a good design. IT IS A MUST, believe me. I had plenty of nightmares programming to bad designs. Check out the below UML design.






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.

//interface to the DataHelper
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);
}}

Later if you want to use MySql as the database simply write a class MySqlHelper & inherit from the IDataHelper class. You don’t have to change anything in the CheckDb() method. Its that simple. So try to program to interfaces whenever possible. Happy coding dudes..

Facade Design Pattern

Design Patterns are recurring solutions for the common software design problems. Knowing design patterns will dramatically improve the way you design your software. These days till late night I’m reading Head First Design Patterns book. Trust me its really good. I think all of the developers out there should have one. ;) So I would like to share some brief explanation to some of the design patters who really took my breath away. I will explain each & every design pattern in my design pattern series. So stay tune. More to come. Today I will explain you the Façade pattern. Its really simple.

What is Façade Pattern?

It’s an interface for an entire subsystem. It’s a high level layer that makes the subsystem easier to use.

Best way to learn is by a sample. So here is the problem. Imagine after hard day work you go home & prepare your self to watch a movie. What are the things that you have to do before you sit down infront of the TV. You have to on the TV, on DVD player, start AC, dim the lights….etc.. What if you can just sit down & do all the things with a remote control. Nice huh.. that’s what exactly façade pattern do.. so the remote control is the façade. You can get the clear picture by a simeple UML diagram & the code below. Comments are highly appreciated. Stay tune for the next design pattern….

HomeTheater facade.

public class HomeTheaterFacade
{

//Has all the objects

DVDPlayer _dvdPlayer;
Light _light;
TV _tv;
AC _ac;

public HomeTheaterFacade()
{
this._ac = new AC();
this._dvdPlayer = new DVDPlayer();
this._light = new Light();
this._tv = new TV();
}

//To watch the movie simply pass the movie
public void WatchMovie(Movie movie)
{
_light.Dim();
_tv.On();
_ac.Start();
_dvdPlayer.Play(movie);
}
}

see how the client use the HometheaterFacade to watch the movie

HomeTheaterFacade e = new HomeTheaterFacade();

Movie movie = new Movie("Matrix Reloaded");
e.WatchMovie(movie);

there more patterns that will imporove your OO designs. so stay tune more to come..

August 11, 2005

XML Serialization

I was just seeking for a topic to post in my blog today. I couldn’t find much. So I thought to tell you something about XMLSerialization. Most of the developers out there already know whats going on under the hood. But for the developers who’s seeking some new stuff gohead.. .net really rocks!!.

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.


-
Ludmal
34


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

Recently i came across a problem which i cant put a object into viewstate. So i did some research on that & found, if we want to put a object into viewstate we have to make the class serializable by adding serializable attribute. Then you can put your object into the view state. code below.

[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.

These days i worked till late night. Doing some CSV datamining project for windows CE & for ASP.net. In ASP.net site basically doing some csv data synchornization. But its takes while to copy bunch of data to the database server. And the page didnt render until job done. So i just planned to have a wait page so that user will get notified abt the process going on in different thread. I found a cool article in ASP.NET site which helped me to overcome the problem. You get a better idea abt it.
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

Recently i came across with a problem with HtttpCookies. I try to save the client information in a cookie. But i couldnt, so i was just trying to check whether cookie is enable or not in the client browser. I simply used Request.Browser.Cookies property. But it didnt gave me the result that i wanted. Then i realized Request.Browser.Cookies is for checking the Browser capability of handling cookies. I coudn't find anything which tells me browser cookies are enable or disable . So what i did was just simply tried to create a cookie & tried to read the value from it. Below u will find the code for the two pages i used to solved the problem. If you guys have better solutions than this pls let me know.

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

How many times we wished if we can work on the same class file while some other developer checkout the same file. Writing two methods by two developers on the same time on the same class file is barely impossible. But now its possible with Partial Classes(new C# Feature). You can split your class file into multiple files. check out the example below.


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

this one is really cool. i played with the sample code & applied to the sample project it was really nice. u should try this. Then you will get to know the capability of the DataGrid. trust me its really worth for you to read.

http://msdn.microsoft.com/msdnmag/issues/04/01/CuttingEdge/default.aspx

DataSets vs Collections

i still think there is a battle between those two. i heard there was some arguments going abt this in my office.. . anyhow i found some interesting artilce about this. worth to read so take ur time to read it.
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.

February 22, 2005

my first blog in the eblogger

hi, this is my first blog in this eblogger... before i used to do blogin in the MSN site.. but it's too complicated.. i just wanna make my blog simple. just like the msdn bloggin.. (.text).. so just finished Business Intelegence .net project.. submit it waiting for the client response.. lets hope for the best. It was tight project but managed deliver it on time.. i couldn't do it without the support of Vs.NET great development tool i have ever used.. but there are some drawback.. few to mention :- the one that really bugging me is the event removing.. after do some desining in the HTML view some of the event it removing from the Init() method.. still got no answer for that.. ohh and yesterday i found out something interesting.. in textbox if set the mode to multiline we cannot set the max length.. i was wondering why..?? am i doing something wrong..?.. need to do some research.. i will put to blog when i came across about vs bugs... doing .net stuff is exciting but sometimes i feel that whether i'm loosing my personal life..(thought i'm not married yet) i will be back with more new .net stuff.. till next time.. cheers.