Thursday, October 12, 2006

Crank! I will watch that soon!

This article supposedly will help good developers develop good design for their websites. I have always had this problem. I always felt I lacked this "good designing capability".

http://peterkellner.net/2006/08/28/msprofcsshowto/

I did not go through it yet. But once I am home I would study that and make some observations.

Speed launch of Studio products

Its been around 6 months since I used Visual Studio and worked on any .NET application. So I am having problem of amensia - memory loss!! :D I have been using the /nosplash option with Visual Studio since long, since I started real coding on .NET! But sitting idle in my office and browsing the internet, it took me a long time to recall "what was the option that I used to quickly launch Visual Studio?". It is the "/nosplash option, which you can give in the TARGET of your Visual Studio project. For example, you can launch the Visual Studio from Start->Run and type "devenv". You can see the usual Splash screen. Its very elegantly designed, but still I dont want to see it everytime I start Visual Studio(I used to launch Visual Studio around 20-30 times a day!) So you can use this handy tip. Type
"devenv /nosplash" and press enter. And Splash!!! your Visual Studio is straight up! and working fine!

This post is just to make sure that incase I forget that myself, I know where to look out !

Signing a weak assembly in .NET 2.0

Just came across this post on MSDN Blogs. It says "Signing an unsigned assembly in .NET 2.0". Usually I dont find such things interesting, but gone are those student days and being a professional, there are some "corporate" things to be learnt. So recently I borrowed a book from library "Introducing .NET Framework" by O'Rielly. It was an old book, dated .NET 1.0 beta 2 release!! but still I felt I learnt a lot of new details regarding .NET Framework, especially about the CLR and stuff like that. So I found this one interesting. I have made some notes which I would post it in the future.
For now, take a look at this.
http://blogs.msdn.com/neerajag/archive/2006/10/12/signing-a-existing-net-assembly.aspx

Wednesday, October 11, 2006

Height of Sincerity!

well the title would not make any sense for another two to three days. Thanks to my colleagues that I am nominated for the Best Learner and Best Guide awards for the FLP batch. Friday, the 13th! is a big day for us, FLPites. Its our Graduation day and the day when we get a hint of our "what next?"

Old habits die hard and my taste for .NET still remains. So I often keep browsing about Microsoft and .NET. In that process I read some excellent blogs. One such blog is here. Its an index of Various "How-to-deploy" on Visual Studio. It is a must-look!
http://blogs.msdn.com/astebner/articles/574618.aspx

I would not change the heading of my blog. But I would like to post few comments on the currently technology I am working on! Surprisingly, inspite of not liking the platform, I am doing pretty well on Mainframes! As a developer who fine tuned his programming skills among OBJECTS, working on COBOL, developing applications with CICS appears awful. But still, you have to do it.

One thing that we should appreciate about coding Cobol on Mainframes is, with the tools I used so far, I now feel that I can survive coding without the help of Visual Studio or Eclipse or any IDE for that matter. If you can manage a project on TSO, trust me, you can do wonders with Visual Studio and other IDEs.

There is a lot to learn about Mainframes - CICS, COBOL and JCL! But still somehow I feel I dont belong here. I plan to move to .NET professionally too....

More insights later. I also plan to post tips/guide for mainframe beginners! Now - I aint a beginner anymore and I do have valuable suggestions and tips on Mainframes too!

Friday, September 29, 2006

After a long time

Well hi to those non-existent visitors of my blog ! :)

Lots of work got updated on the Microsoft development front(in my unfortunate absence). Anyway this post is to just store a link about UpdateControl, an aTlas how-to. Wonderful job done, i find it pretty soothing as i have just completed reading Atlas At Last:MSDN Mag article. Take a look at the how-to :
http://blogs.msdn.com/trobbins/articles/678575.aspx

Wish I had a PC at the place I stay :(

Wednesday, May 03, 2006

Step by step guide to Web Services

Firstly, this is no documentation for Web Services and neither do i wish to make any. I dont discuss any inernals on how web services work. It is just a step-by-step guide to develop Web Services and consuming them in .NET. I prefer VB.NET for this tutorial. I use layman terms and if you have some problem with my language, visit MSDN and learn-dont bother to visit again.
What are Web Services??
I would say a Web Service is a DLL that is referenced through the internet using HTTP protocol. Instead of shipping your business logic along with the application, as a DLL, we can make it a web service and host it as a website. But all it does is to provide the same services as a DLL - i.e no presentation involved.
How to create a web Service?
1. Start Visual Studio 2003. Go to VB Projects -> ASP.NET Web Service -> Give a project name and click OK.
2. Click on Switch to code view on the designer view you get. We dont need a designer so we go to the code view.
3. You can notice a Hello World method commented. Copy the same and paste it and this time uncomment it. That is your code file should look like this.

_
Public Class Service1
Inherits System.Web.Services.WebService

#Region " Web Services Designer Generated Code "

' WEB SERVICE EXAMPLE
' The HelloWorld() example service returns the string Hello World.
' To build, uncomment the following lines then save and build the project.
' To test this web service, ensure that the .asmx file is the start page
' and press F5.
'
' _
'Public Function HelloWorld() As String
' Return "Hello World"
'End Function

<WebMethod()>
Public Function HelloWorld() As String
Return "hello world"
End Function
End class

4. Ok your web service is ready. Just "Build" the project clicking on CTRL + f5). It starts up IE showing a sample page. That looks like the one shown below!

Service1
The following operations are supported. For a formal definition, please review the Service Description.

HelloWorld

5. Click on the "HelloWorld" and you are taken to a page that has the SOAP Headers and HTTP Post descriptions along with a Invoke button. Click on the "Invoke" button. the output you get is as follows.

<xml version="1.0" encoding="utf-8" ?>
<string> xmlns="http://tempuri.org/LearnWebServices/Service1">hello world</string>
The webservice is working perfectly. I dont intend to discuss the above XML, its self explanatory.

How do you consume a Web Service?
1. The above described way is to check if a webservice is working properly. It is not the actual way to use a Web Service. In order to use a web service in Visual Studio, add a new Windows project to the same solution. Right-click on the newly added project and click on "Add Web Reference.." and in the page you get, click on the "Web Services on the Local Machine".
2. Then you get a list of the webservices that are available on your machine. Click on the one which you just created(i renamed my .asmx file in the web services project to SampleService, so i ll click on the SampleService in the window). Give some proper "Web Reference Name" above the button - "Add Reference". Click on the button to add the reference.( I gave the Web reference name as "LearnWebServices" )
3. Reference has been added. It actually checks to see if the service is upto date without any errors. Only then it adds the reference. You can then see a web References folder inside the Solution Explorer for the WindowS application project.
4. Now add a button to the form in the win app project. In the click event, write the following code.

Dim s As New LearnWebServices.Service1
MsgBox(s.HelloWorld())

5. When you run the Windows application and click on the button you get a "
hello world" message displayed. The first execution is always slow, but later on you see the message displayed immediately. What i did in the above code is to instantiate the Service1 class and then call the method on its object. You can notice that its just as if you are using a Local library!

Some Issues?
The coverage is not complete. There are books on writing Web services and i dont have any intention for competiting them. I discuss few more issues as days pass by but for now, some notes follows.
1. You can write as many classes inside the web service, just the methods should have the <WebMethod()> attributes. There could a non-webmethods inside the webservice, but they cannot be accessed directly like the Web methods.
2. Method overloading is not directly supported. in order to overload methods we need to use specific attributes. If we overload Helloworld() method and try to test the web service, we get this exception -

Overloaded methods

<WebMethod()> _
Public Function HelloWorld() As String
Return "hello world"
End Function

<WebMethod()> _
Public Function HelloWorld(ByVal name As String) As String
Return "hello world " + name
End Function


The exception we get when we try to run the web service is
Both System.String HelloWorld(System.String) and System.String HelloWorld() use the message name 'HelloWorld'. Use the MessageName property of the WebMethod custom attribute to specify unique message names for the methods.

The correction needed is to add a MessageName property to the web Method!! As shown.

<WebMethod()> _
Public Function HelloWorld() As String
Return "hello world"
End Function

<WebMethod(MessageName:="HelloWorldWithParamter")> _
Public Function HelloWorld(ByVal name As String) As String
Return "hello world " + name
End Function

As you can notice we use the named paramters in VB.NET. Figure it out on how to use this in C#.

3. Another difference with Web Methods is that Parameters when reference types are passed as paramters and changes are to be reflected, then ByRef has to be used unlike in the case of local methods where ByVal and ByRef mean the same for the reference types.

4. When you make a changes and compile the Web Service again, you shoud REBUILD the web service project. Also you should "update web reference". For this right click on the Web references/LearnWebServices in the solution explorer and click on Update Web reference.

Well thats all for now. See you later with more tutorials.

Wednesday, April 26, 2006

ASP.NET Boom!

Its been quite a long time since i posted an entry here. I was busy with all my work, exams, projects, jobwork, learning, movies and a lot more :)
Well ASP.NET 2.0 is too good to work with. We can make excellent and very powerful controls by mixing some of the already existing controls. And yeah! I did try and made one. I worked recently on "making a Tab Control in asp.net 2.0" and also a "Scrollable Datagrid". In the later entries i would post some tutorial on both.
Also Microsoft is giving great support for ASP.NET, probably ignoring the Windows Applications a bit. And trust me, I am seeing more and more Asp.NET 2.0 website projects everyday and very soon we get to see as many asp.net 2.0 projects as that in PHP! Definitely an excellent technology to learn and not only that Microsoft has provided excellent video tutorials for free ! there are two sets of tutorials - one "How do I?" series and the other is a Visual Web Developer Express tutorials. Both of them are available for free download at
http://msdn.microsoft.com/asp.net/learning/learn/newtodevelopment/default.aspx#Multimedia

http://msdn.microsoft.com/vstudio/express/vwd/learning/default.aspx

more links available at
http://msdn.microsoft.com/asp.net/reference/multimedia/#aspnetHowTo

And guess what they are giving more publicity for VWD than that for Visual Studio 2005 and that too when VWD is for free. They have seriously had some tough competition from Eclipse which is no doubt an excellent IDE and is for free. So they probably want to give something for free which would not effect the sales of VS 2005 and at the time is as powerful as that.

Even I got to watch those videos and once i get the time, i would love to watch and learn more about ASp.NET 2.0

Next post i would talk about servlets and their issues. A bit depricated but really good like any other Java Technologies!

Saturday, March 18, 2006

Newbies guide to Servlets.

I better kiss ASP.NET and bang the heck out of servlets. Agreed, servlets are easy to program to a certain extent, but when it is for presentation oriented applications they are terrible to work with. They just mess up your code so much that you begin to hate it yourself.
Anyway, for those who doesnt know servlets - heres a sample servlet and steps.

1. Download Apache Tomcat Server(the best for servlets) and install it.

2. In the installation folder you can see " webapps " folder which is the root folder for your server. You copy your applications into this folder.

3. Write your servlet and compile it. Take a look at sample servlet.
import javax.servlet.http.*;
import java.io.*;
public class SampleServlet extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse resp) throws Exception
{
doPost(req,resp); //call post method handler
}

public void doPost(HttpServletRequest req,HttpServletResponse resp) throws Exception
{
PrintWriter out=resp.getWriter();//obtain the stream to the output - to the browser
//we need to render html content as shown below.doesnt this suck???
out.println("
<html><head><title>Sample Servlet</title></headgt;<body>");
out.println("Bhargava's blog rocks!!!</body></html>");
}
}

How to compile??
Nothing different, but make sure you add path to the Servlet-api.jar which is present in the common/lib folder of Apach tomcat installation folder. How do you do that? well figure it out yourself. otherwise mail me.

4. Now that the servlet is ready, compile it and keep the .class file aside. Now Create a folder, say TestServlet and create a WEB-INF folder inside this folder. Inside the WEB-INF Folder, create a "classes" folder and copy your servlet class into the file. I shall give you a web.xml which is to be placed inside the WEB-INF Folder. Copy the TestServlet folder to webapps directory of the Tomcat installation folder. The following is the directory structure you should get as a result.
Apache installation path.....\webapps |-TestServlet
|-WEB-INF (-> web.xml is also present in web-inf)
|-classes
|-SampleServlet.class

5. Actually the better way is to create a .war archive. Create WEB-INF and place web.xml in it. Also classes directory with SampleServlet .class inside it. Go to command line and navigate to the folder which has this WEB-INF and type the following
jar cvf TestServlet .war WEB-INF
You can just copy the generated war archive into the webapps folder of Tomcat and restart Tomcat.
6. The web.xml is the configuration file that tells the container what servlets are available and other information(i dont know !! ) create the web.xml as it is. Try to understand what it says.

<?xml version="1.0" encoding="ISO-8859-1"?>


<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">

<!-- SERVLETS INFORMATION STARTS HERE -->
<!-- sample servlet for testing -->
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>TestServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/TestServlet</url-pattern>
</servlet-mapping>

<!-- end sample servlet-->
</web-app>


Notice the value. It says when ever SampleServlet is called from browser , invoke the servlet whose name is SampleServlet whcih inturn loads the servlet whose class is mapped to this servlet, throuh

Assuming apache runs on localhost, and that you have deployed your servlet(by the way the web.xml is called Deployment Descriptor) you should type the following URL on browser

http://localhost/TestServlet/SampleServlet



You should get
Bhargav 's blog rocks!!


In case you dont get the output and get a 404 Error(resource not found) please verify if you have created the directory as i mentioned and most importantly the web.xml is correct or not. I once got stuck up with this problem and no where on the internet you can find solution for the problem!(not now cos i posted it on my blog! isnt my blog informative?) The problem was that i did not specify the schema to follow in the element inside web.xml, that is even the following portion is very important.



<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">



I hope this brief tutorial gives a kick start for those interested in learning servlets. Actually there is more of servlets than what i just covered(what i told is simply about Deployment in Tomcat, nothing else)? Just google out and if you have any questions , feel free to contact me at krishnabhargav@yahoo.com. I am not bad at J2EE, though not as good as .NET. Anyway i can help you out.

Next on this servlets issue, i would post a tutorial on Forms based authentication using Servlets and Apache Tomcat container. Again there is no proper step-by-step tutorial for this online, so meanwhile please go through some sample servlets code. All the best. And please hate servlets :)) cos compared to servlets Asp.NEt is veryyyyy easy to work with.


Krish.

Wednesday, March 15, 2006

Long ago ..... System.Web.Mail

Hi all,
Its been quite a while since i posted on my blog. I was terribly busy(emotionally disturbed, so took a two week break and i did nothing but "eat,sleep,watch movie,freak with friends"). Anyway the following is the steps you need to do, to send email from .NET application using System.Web.Mail.
1. Add reference to System.Web.dll if it its not already added(for asp.net applications, its already added, so you can skip this)
2. Import the namespace System.Web.Mail
3. Customize the following code
'a) Prepare your message
Dim msg as new MailMessage
msg.To = "to@email.com"
msg.From = "from@email.com"
msg.Subject = "Your subject goes here"
msg.Body = "Body of email"
'b) Send your message
SmtpMail.SmtpServer="smtpserveraddress"
SmtpMail.Send(msg) 'sending the mail.

As you notice, its pretty simple to work with!! But it isnt as simple as it appears. Just for information, Web.Mail uses CDOSYS internally to communicate with SMTP server and this is considered bad(i dont have enough experience to tell why, but its bad from what i read) .
Also another question is "What if my SMTP Server needs authentication?" Well this question has haunted me for two years and have now found out the answer. Just check out this cool support topic from MSDN.
http://support.microsoft.com/default.aspx?scid=kb;en-us;555287

Well there are sooo many issues with System.Web.Mail that there is a dedicated site for the namespace !!! check out www.systemwebmail.com !!! Cool

Also for your information, for .NET 2.0 use System.Net.Mail namespace - which actually makes sense. That is all for now and i have another problem to figure out. I noticed that Query Strings end when they encounter "#" I mean if actual string is Pa=1&Pg=2&Name=C#&Value=CS,when you read that string inside the asp.net applicaiton using "Request.QueryString", all you can see is that its only Pa=1&Pg=2&Name=C and #&Value=CS is skipped!!! Any solution for this?? Comment on my blog.

Tuesday, February 28, 2006

Road Trip to developing a forum : Goal accomplished

I was really busy since three days to make any update on this blog. I was working on writing a forum board from scracth on, and guys it was too hectic. My good buyer was very cooperative and inspite of having a very tough deadline, he took me with patience. Finally after around 30 hours of coding,testing,evaluation,correcting and what not, i successfully completed the Message Board, say Pre-Release of Message Board. :)) It was written in ASP.NET from scratch, i basically tested it thoroughly with Ms Access Database and later ported to SQL Server DB. This is really cool, cos with just few classnames changed, the code for works for any DB!!! Isnt that good? Ofcourse i did not make use of any Stored Procedures, which i really dont know how to write. Well guys, it was really great experience, and i would say its a dream come true. I implemented Forms Authentication too and beleive me, it is not as tough as it looks in the online articles. Very soon, i would post an article here on my blog or in my upcoming site.

Well apart from this news, we four friends are soon forming a software freelancers team.(names not disclosed :)) ). Well once we get moderate success, we shall think of expanding the unit by adding few more of my taleneted friends. But for now no vacancies :)) Wish us all the best for Embryo Software Services(well i shall change the name in another day, changed the name twice till now)

I dont have moood to talk about .NET technical issue, i am fed up and i worked for around 16 hrs each day since sunday, and it was all .NET, right now i need to relax and start Servlets Programming tomorrow. And dont expect any code segments for the forum board from me, it is the property of my buyer :)) So i cannot disclose any code here. Thanks for visiting. See you later.

Wednesday, February 22, 2006

Good Will Hunting : Tweleve Performance Tips

This is an extract from MSDN article.

Twelve Performance tips
  • Load fewer modules at startup
  • Precompile assemblies using NGen
  • Place strong-named assemblies in the GAC
  • Avoid base address collisions
  • Avoid blocking on the UI thread
  • Perform lazy processing
  • Populate controls more quickly
  • Exercise more control over data binding
  • Reduce repainting
  • Use double buffering
  • Manage memory usage
  • Use reflection wisely
You can read the article at
http://msdn.microsoft.com/msdnmag/issues/06/03/WindowsFormsPerformance/default.aspx#Tips

Lot of information available in it. Check it out for sure.

Tuesday, February 21, 2006

Fast and Furious:Make .NET apps a hare that wins

The future is all virtual machine based-i mean to say every platform would become more and more managed. But at the cost of performance. C++ is still favorite of many because machine code is directly generated but not any MSIL or a bytecode. This makes the applications very fast to executed. But the managed environments provides developer a lot many comforts for which they are ready to give up performance to some extent. But with recent research in optimized JIT compilers, even Managed applications could be faster(not as much as native code). Well let me not drag the topic - i aint writing any book! I wanted to share some information which could be used to make your applications a bit faster(by applications i mean .NET apps)
  • Firstly, create as many less objects as possible - if your application runs for longer durations. Then also make sure to set the object reference to "nothing"/"null" when you are done while using it.
  • Read FxCop rules and also PMD rules from pmd.sourceforge.net, though PMD is for Java the rules are well applicable to .NET since both of them rely about the same basics of runtime.
  • Make sure that you save unnecessary loops, reducing loops always saves you CPU time. Also read this article on MSDN about performance of .NET applications. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpag/html/scalenetchapt13.asp
  • One thing is that, avoid Boxing/UnBoxing as much as possible - the lesser the work for CLR for type-casting, better the performance.
Well, these so called tips are almost useless, not many want to learn something extra to improve the performance of their code. Do we??? Well, when using Visual Studio you can improve the performance. Select Project in Solution Explorer, go to project properties, then go to Build Tab. There you can see "Optimize Performance" and "Integer Overflow checks". Check the Optimize Performance and also if you dont wish to perform any integer overflow checks, make that setting too.

There is also a tool called NGen that ships along with .NET SDK. Ngen.exe could be used to generate JIT compiled code and it saves the compiled code in GAC. Make a note that even this compiled code is managed, but when the application whose NGEN code is available in the GAC, JIT is no more functional at runtime- performance improves drastically. The documentation for NGen is really stupid and overly complex. Very soon i shall be working with Ngen and then i would post a simple tutorial on how to use it. Till then those interested can refer MSDN article here :
http://msdn.microsoft.com/msdnmag/issues/05/04/NGen/
Also there are more articles on Ngen and none of them are cool :( unfortunately they arent meant for you and me, they are for advanced geeks.

Monday, February 20, 2006

I got a Date with DateTimePicker

Well, Recently i came across one cool problem. Yes! the problem is really cool and what makes me blog here is that there is no simple solution available online, for what i encountered.Thanks for Visual Studio.NET I could rectify the problem myself.

DateTimePicker is a good control that solves most of our calender problems. It could be customized in different ways. Like we can customize the format in which the date appears. Also the look could be changed. Inorder to change the look from ComboBox style to updown-style just change the property "ShowUpDown" to true. It would give you two small updown arrows, that could be used to change the value.

Each of us have our own taste for the way the date should appear, not only taste sometimes our requirements makes us change the display to something else. For example, at times we might need something like :
1/1/2005 10:05:00 AM
and sometimes just :
Jan 1 2005 10:05 AM
What i mean is that there are numerous ways in which DateTimePicker should display the value. So how do you tell the control what format it should display?
The answer is simple, you have the Format property on the DataTimePicker, which can take different values like Long,Short,Time and Custom(Clearly it is an enumeration).Programatically you can change the value as

dtp1.Format=DateTimePickerFormat.Long or
dtp1.Format=DateTimePickerFormat.Short and so on.

The most powerful of these Format values is Custom, which gives us fine grain control about the display. Working with Custom format is complex at first for those who havent worked with it till now. But it is simple then on. The steps are simple.
1. Set the Format property to "Custom"
2. You have another property "CustomFormat" on the DateTimePicker control which gets into action when Custom format is applied.
3. It is a string, so you can set a format as a string here. For example in order to display the date/time as February 21 10:00:00 PM, you can set the custom format as :

dtp1.Format=DateTimePickerFormat.Custom
dtp1.CustomFormat="MMMM dd hh:mm:ss tt"

4. Its over!!! Apply changes, check it out. You see exactly what i showed above.

There are really numerous ways to customize like - you can also display the Day name like Friday, sat or Sun, more and more control is possible. You can even specify 24 hour format, i.e., if its 2 pm it could be shown as 14:00 . How do you do that?
See the following statement :
dtp1.CustomFormat="MMMM dd HH:mm:ss"
The display would be then February 21 14:00:00 ( its in 24 hour format now)

Well i am done with my date, you need further details about the Customformat take a look at this link on MSDN
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemwindowsformsdatetimepickerclasscustomformattopic.asp

Now let me come to the cool problem i was talking about !!!
Cool Problem - very hot!!
My requirement was that as soon as i load the form which has a DatetimePicker control, the control shoud display the current time ! Well it is rather simple, could be done in two ways.
1. dont set any default value during design time. OR
2. In the form load property, you can work this out as :
a) first set the MaxDate property of dtp to DateTime.Max or anything else you wish. But not that if you set MaxDate as 2004 and you try to set the value greate than the MaxDate, say 2005, you ll encounter an exception. What i do usually is :

dtp1.MaxDate=DateTime.MaxValue.AddDays(-2)

I subtracted -2 because, the DateTimePicker cannot support anything that is after 12/31/9998 12:00:00 AM. if you say

dtp1.MaxDate=DateTime.MaxValue

You encounter this exception:
"DateTimePicker does not support dates after 12/31/9998 12:00:00 AM. Paramter name:value"

And if you know, DateTime.MaxValue is "12/31/9999 11:59:59 PM. That is what DateTimePicker can support is exactly 1 year 1 sec less than the MaxValue. So you can Add -1 year and then add -1 second, but I wanted to be on safer side, so i directly add -2 years(means i remove 2 years from MaxValue which makes it 12/31/9997 11:59:59 PM, which is totally fine.
b) setting the MaxDate is really important because, if you dont do it and then say
dtp1.Value=Date.Now
you shall encounter this exception :
'1/21/2006 1:06:00 PM' is not a valid value for 'Value'. 'Value' should be between MinDate and MaxDate.

Now one can ask if i need to even set MinDate, well it is not actually needed, but what you set at default value is applied as MinDate. So most of the times not needed, incase you set something other than Date.Now to the value of dtp and if you get an exception, you better set even the MinDate property to something else.

All code at single place :
In Form load event

dtp1.MaxDate=DateTime.Now.AddYears(-2)
dtp1.Value=DateTime.Now ' you can set the value.

If you take the exception message 'Value' should be between...... and search in google - all you get is about DataBinding and databases. Well I havent worked on DataBinding much, so no idea about it. But there was no solution for this simple problem, atleast i did not find it.

So I thought it would add my blog little value, if i present some article on how to work with DateTimePicker and a general problem when using it- along with my solution.

Hope you .NET guys find it useful as much as i do. See you soon with another article.