Store Page ViewState in Session with asp.net

  • 4

As we all know we any web page on the internet is state less. We have to write our own mechanism to maintain state between httprequest and httpresponse. Asp.net has great features called viewstate to maintain state during page postback. It will store the element state in hidden variables with _VIEWSTATE. It will look like below.

image

If you are having large amount of controls then you will have larger viewstate on the page and it will increase your html kb as well as your performance. So to increase the performance of our application we need to store this viewstate in other place. ASP.NET 2.0 has nice new class called SessionPagePersister which will store the viewstate in the session. You just need to override the PageStatePersister property in your page and your viewstate will be on the page.

Here is the code.



Code Snippet


  1. protected override PageStatePersister PageStatePersister
  2. {
  3. get
  4. {
  5. return new SessionPageStatePersister(this);
  6. }
  7. \



If you are having so many pages then you have to write that cod manually Instead of doing this you can use inheritance features of C#.NET to write the code in just one way and then inherit your page from that class. Following is the code for that. You can create a class called MyPage that class into all the pages here is the code for class MyPage .


Code Snippet


  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;

  6. namespace TestBlogApplication
  7. {
  8. public class MyPage:System.Web.UI.Page
  9. {
  10. protected override PageStatePersister PageStatePersister
  11. {
  12. get
  13. {
  14. return new SessionPageStatePersister(this);
  15. }
  16. }

  17. }
  18. \



and Then inherit the class in your page like following.



Code Snippet


  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;

  7. namespace TestBlogApplication
  8. {
  9. public partial class Page1 : MyPage
  10. {
  11. protected void Page_Load(object sender, EventArgs e)
  12. {

  13. }
  14. }
  15. }




So that's it that way you can increase your application performance via maintaining the viewstate in session. Happy Codding..

Extend your existing classes with extension method in asp.net 3.5

  • 0
In asp.net 3.5 there is one good features called extension method now you can extend your functionality without modifying existing classes. Extension method allow developers to add own functionality to any existing classes. You don't need to create subclass or don't need to recompile existing classes and still you can extend that class with extension methods. Let's create an example to extend existing string classes to convert a simple string to bold html string.
public static class MyExtensions
{
public static string ConvertToBold(this string mystring)
{
System.Text.StringBuilder myBoldString =new System.Text.StringBuilder(string.Empty);
myBoldString.Append("<strong>");
myBoldString.Append(mystring);
myBoldString.Append("</strong>");
return myBoldString.ToString();  
}
}
So now our extension method is ready. Following the sample code to use this extension method.
protected void Page_Load(object sender, EventArgs e)
{
string helloWorld = "Hello World";
Response.Write(helloWorld.ConvertToBold());
}
While running application you can out like below.
Extension 

What's new in sql server 2008

Microsoft SQL Server are one of the popular RDBMS(Relational Database Management System) all over world. Before some time Microsoft has launched the new version of SQL Server 2008. SQL Server 2008 provides the highest levels of security, reliability, and scalability for your business-critical applications. . Following are the some of new features of SQL Server 2008.

  1. Policy based management.
  2. Performance Data Collection.
  3. Data compression.
  4. Resource Generator.
  5. Transparent Data Encryption.
  6. External Key Management/Extensible Key Management.
  7. Data Auditing.
  8. Hot-Add CPU and Hot-Add Memory.
  9. Streamlined Installation.
  10. Server Group Management.
  11. Upgrade Advisor.
  12. Partition aligned indexed views.
  13. Backup Compression.
  14. Extended Events.
  15. Grouping Set.
  16. Merge Operator.
  17. Greater Support for LINQ and Entity Framework.
  18. Change Data Capture.
  19. Table Valued Parameters.
  20. Entity data model for entity framework.
  21. Synchronization Server with ADO.NET.
  22. CLR Improvements.
  23. Conflict detection between peer to peer Replication
  24. Service Broker Priorities and Diagnostics.
  25. Spatial Data with Geography and Geometry data types.
  26. Virtual Earth Integration.
  27. Sparse Column.
  28. Filtered Indexes.
  29. Integrated full text search.
  30. File stream data.
  31. Large user defined types.
  32. Large user defined aggregates.
  33. Date/Time Data Types.
  34. Improved XML Support.
  35. ORDPATH.

and many more features are there. It's great rdbms to use in your future projects. Please visit following link to explore above features in great details.

http://www.microsoft.com/sqlserver/2008/en/us/whats-new.aspx

You can download SQL server 2008 Express database for free from following link.

http://www.microsoft.com/express/sql/download/

How to remove white spaces between tags and lines of html render by asp.net page

When asp.net page loaded in to browser there are lots of white spaces between tags and in tags that will increase your html kb. For example if your page around 300 kb then it will take 3 second to load on 100 kbps internet connection and in dial up connection it will still take time. So if you want to load your site fast on dial up internet connection then you need to decrease html kb as much you can and removing white spaces from the html will be good idea for that.

Following is the code for the page on which you want to remove white spaces from the html. It will decrease your html kb by 30 percentage.

private static readonly Regex REGEX_FOR_TAGS = new Regex(@">s+<", RegexOptions.Compiled);

private static readonly Regex REGEX_FOR_BREAKS = new Regex(@">[\s]*<",
RegexOptions.Compiled);
protected override void Render(HtmlTextWriter writer)
{
using (HtmlTextWriter writer = new HtmlTextWriter(new System.IO.StringWriter()))
{
base.Render(writer);
string htmlkb = writer.InnerWriter.ToString();
htmlkb = REGEX_FOR_TAGS.Replace(htmlkb, "> <");
htmlkb= REGEX_FOR_BREAKS .Replace(htmlkb, "><");
writer.Write(html.Trim());
}
}

Here in the above code there are two regular expression one for white space in tag and another for whitespace between tag and by just overriding the render event of event you can replace the whitespace.

Happy Coding...

Technorati Tags: ,,,

Sending mail with secure service layer in asp.net 3.5/2.0

  • 1

In earlier post i have mentioned that how to send the email using new System.Net.Smtpmail with asp.net 2.0 or higher version. Now lets learn how to send the mail with the secure service layer in the asp.net.

Security is the one of the most important requirement in today’s world as you are doing your business online you have keep secure from other wrong elements. Secure service layer add an

extra layer of security to your web application and sending mail with the SSL with tighten your security for mails. Your emails are more secure then ever and your valuable information will not going to wrong hands.

Here is the code from which we can send the email with the secure service layer. As i have mentioned in earlier post you need to to send email with authentication to use SSL. So you need to write following code. First you need to create message like following..

MailAddress fromAddress = new MailAddress("from@site.com","Nameofsendingperson");
message.From = @”fromAddress”;//here you can set address
message.To.Add("mailto:to@site.com%22%29;//");//
message.Subject = "Sending email with ssl";
message.CC.Add("cc@site.com");//ccing the same email to other email address
message.Bcc.Add(new MailAddress("bcc@site.com"));//here you can add bcc address
message.IsBodyHtml = true;//To determine email body is html or not
message.Body =@"Plain or HTML Text";
Then you have to sent message with following code.
System.Net.Mail.SmtpClient mailClient =
 new System.Net.Mail.SmtpClient("your smptp","ssl port");
//This object stores the authentication values
System.Net.NetworkCredential basicCrenntial = 
new System.Net.NetworkCredential("username", "password");
mailClient.Host = "Host";
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = basicCrenntial;
// You have to add one other properties for SSL
mailClient.EnableSSL=true;
mailClient.Send(message);

Client Id of a control in ASP.NET 4.0.

  • 2

Client Id is used to store the id of a server control in client side. ASP.NET Engine creates a very long client id to unique identify each element on the same page. If you are having so many inner controls hierarchy then asp.net will generate very long client id like “ctl00_Ctl001_ctl02_BM_Login_btnSave” here i i have used control name like ctrl00,ctr001,bm etc. If you are having long control name then it will more longer then this. This will increase html kilobytes for the pages and if you are having so many server controls in the page then it will take time to load in browser and will decrease performance of application . To overcome this problem we have to override existing asp.net controls like textbox,label etc and then you have override client id from server side with server side id. Now with asp.net 4.0 you can control client id generated by .net framework. In asp.net 4.0 there is one another property called ClientIdMode which will control the behavior of client id generated by .net framework. Like following.

<asp:Button ID="btnSave" runat="server" ClientIDMode="[Mode]" />

There are four types of different mode for ClientIdMode property.

  1. Legacy- This is the same as in old version. It will generate client like like “ctl00_Ctl001_ctl02_BM_Login_btnSave” in old fashion.

  2. Inherit-This is the default mode for every control . It will refer parent control to have its clientidmode. If you want to change it then you have to specify your client id mode for that control.

  3. Static –This mode will put client id as static if you set server id like “btnSave” then it will generate the same ld like “btnSave”. So if you want to use this mode then you have to make sure that you are having all unique name in one pages. Otherwise it will be a mess for ids.

  4. Predictable- This mode will used when the framework needs to ensure uniqueness of each control in particular way. The framework traverse from the control to parent controls and put hierarchy of parent control id with control id like ‘”ctrl0_btnsave” and for another btnsave its like “ctrl0_ctrl1_btnsave” etc.

  5. Technorati Tags: ,

Javascript is not working with update panel- Microsoft Ajax

  • 17
As an asp.net developer we all must have to use update panel for the ajaxifying our application in today’s ajax world. No one likes postaback now. But when we add the some content with the java script under update panel then some times it’s stop working because of the update panel server side behavior. So what we should do? … Here is the trick. Normally we code java script in the asp.net page like following…

string alertScript = "javascript:alert('Alter From asp.net page')";
ClientScript.RegisterStartupScript(typeof(Page),"alertscript", alertScript);
Instead of this you should use.

string alertScript = "javascript: alert('This is aler from asp.net page')";
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertScript",
                                alertScript,true);
This will work. Happy coding..

Technorati Tags: ,,,,

Page.MetaDescription and Page.MetaKeywords in asp.net 4.0

  • 0

As i have in my earlier post Search Engine optimization is necessary for every sites otherwise site will not have more users and viewers. For search engine meta tag are very important one Search engine crawler get information from this meta tags. There lots of meta tag but most important meta tag are keyword and description. From keyword meta tag search engine crawler get information about keyword for which they list this site page and from the description tag they will get descriptive information about particular page.

ASP.NET 4.0 introduces support for this. Now you can create your own meta tag keyword and description with the help of Page.MetaDescription and Page.MetaKeywords. It will render as same description and keyword meta tags in simple HTML Page. For example if you write following in your page_load event.

protected void Page_Load(object sender, EventArgs e)
{
Page.MetaDescription = "This page contains information about asp.net 4.0";
Page.MetaKeywords = "ASP.NET 4.0,Search Engine Optimization";
}
It will render meta tag as following.
<meta name="description" content="This page contains information about asp.net 4.0" />

<meta name="keywords" content="asp.net 4.0, Search Engine Optimization" />

So now with asp.net 4.0 you can do your site search engine optimization very easily and you don’t have to write code for that.

Permanent redirection in asp.net 4.0

We all need search engine optimization in our sites. With web 2.0 site its necessary that our site is search engine friendly because if i write this blog but nobody comes to read my blog then what is the worth of it. So for every thing we need to have search engine optimization whether its a blog,site or any thing on web.

For Search Engine Optimization one of the most important thing is the permanent redirection with 301 headers. Now all you say what is 301 headers lets explore this thing in greater details.

301 Header in SEO:

Every dot net programmer does comes along Response.Redirect – It will redirect from one page to another page which causes 302 redirect. For search engine optimization 302 redirection is document is temporary moved from one location to another location so it will keep indexing the other document as well from which we have redirected. In 301 header it will stop the response from older page. So that search engine can index new location permanently.

We can achieve this functionality in asp.net 4.0 directly with permanent redirect method. Like following. It will create 301 headers for search engines/

Response.PermanentRedirect(“http://jalpesh.blogspot.com”);

With the help of this now you can redirect your 302 pages to 301 which will be more search engine friendly then the older one.

IIS 7.0 URL Rewrite Module 2.0 Beta Version is out now.

  • 1

Url rewriting is an important feature that will enable application to be search engine friendly and make url more readable. IIS 7.0 comes with built in url rewriting module so you don’t need to write more code for url rewriting module. URL Rewriting module will do following for you.

  1. Replace the URLs generated by a web application in the response HTML with a more user friendly and search engine friendly equivalent
  2. Modify the links in the HTML markup generated by a web application behind a reverse proxy.
  3. Fix up the content of any HTTP response by using regular expression pattern matching

You can download IIS 7.0 URL Rewrite Module 2.0 Beta Version from the following.

http://www.iis.net/downloads/default.aspx?tabid=34&i=1904&g=6

It is containing following features.

  1. Rule base url rewriting Engine
  2. Regular Expression Pattern Matching.
  3. Wild card pattern matching.
  4. Global and Distributed rewrite rules.
  5. Access to server variable and http headers.
  6. Various Rule Actions
  7. String manipulation features.
  8. Support for IIS kernel mode and user mode output caching
  9. Failed Request Tracing Support
  10. Rule Templates
  11. UI for testing of regular expression and wildcard patterns
  12. UI for managing rewrite rules and rewrite maps
  13. GUI tool for importing of mod_rewrite rules

For more details about IIS 7.0 Url Rewriting modules visit following links.

http://learn.iis.net/page.aspx/460/using-url-rewrite-module/

http://ruslany.net/2009/07/url-rewrite-module-2-0-for-iis-7-beta/

http://www.15seconds.com/issue/081205.htm

Microsoft SilverLight 3.0 is out now-What’s new in Silverlight 3.0?

  • 0
Microsoft Silvelight 2.0 has been great success for the Microsoft. There lots of rich user friendly animated application is designed with Microsoft Silvelight 2.0. Now with Microsoft has added some new features to Silverlight 3.0. It includes major media enhancement,allowing web applications to view on desktop, Graphic improvement for 3D Support, GPU Acceleration and H-264 Support etc. Following is new feature list for silvelight 3.0
  1. Live and on demand true HD Smooth streaming.
  2. More format Choice.
  3. True HD Playback.
  4. Extensible media format support
  5. Perceptive 3D Graphics
  6. Pixel shader effects.
  7. Bitmap Caching.
  8. Animation Effect.
  9. Enhance control skinning.
  10. Improve text rendering and font support.
  11. Search Engine Optimization
  12. Data Forms and Data Validation.
  13. Application library caching
  14. Binary Xml.
  15. Adobe Photoshop and Illustrator import support
  16. Fully compatible with visual studio 2010.
There are many more features. To know more about him please visit following link. http://silverlight.net/getstarted/silverlight3/default.aspx
If you have any question then you can ask here in silverlight community.http://silverlight.net/Community/
You can get started with silvelight 3.0 with following. Its will be great help and tools available on following link. http://silverlight.net/GetStarted/

Partial Types, Class and Method in C#.NET 3.0/2.0

With C# 2.0 Microsoft has added partial keyword in C#. So what is partial keyword used for. Lets go through the partial keyword in greater detail.

First and foremost use of the partial keyword is the you can declare one class or method with more then one declaration and at the compilation time it will have one complete class.So now you can declare a class more then one file at the compile time it will be treated as one class.

For example this is one class

//first file Patial Class
public class partial PartialClass
{
   public void First()
   {
     //First function
   }
}
 Here is the another class
public class partial PartialClass
{
   public void Second()
   {
      // Logic...
   }
}
Now at the compile time it will be treat as single class like following.
public class PartialClass
{
   public void First()
   {
      // Logic...
   }
   public void Second()
   {
      // Logic...
   }
}
Same way you can use partial method it will treated as one method as compile time. Partial method will only available with C# 3.0. It will not be available to C# 2.0.

Practical Usage Of Partial Class:

There are lots of way where partial class is useful like many developer can work on same class via creating different files. There are lost of code generators available in market so you can extend the class functionality via marking them partial. Partial class can also be used for the manage code in separate files instead of creating large files. With C# 3.5 linq to sql designer uses this concept to split custom behaviors outside mapping class.

My blog post is in Microsft TechEd Online Editors Pick List

  • 0

Microsoft TechEd online is a great community and always been best to learn new thing. I have been proud of associating my self with great community. It’s a great thing to get acknowledgement from community. Recently one of my blog post-Sending email through System.Net.Mail.Smtpmail in asp.net 3.5/2.0 got place in Microsoft Teched editors pick list. It all because of my blog readers thank you for having faith in me. It’s a great honor to have this post is a part of community. Thanks Again………

TechEd

Here is the link for all blog of Microsoft Tech Ed Online..

http://www.msteched.com/online/blogs.aspx

Subsonic 3.0 is out now- Next Generation Object Relational Mapper

There lots of ORM(Object Relational Mapper) is available now like entity framework,nhibernate, linq, dlinq but i choose subsonic 3.0 for my next application which will be a question answer site for the following reason

  1. Now subsonic 3.0 is with linq support so you can write your lambda expression and linq queries along with the subsonic
  2. It comes with simple repository.
  3. Built in T4 Templates for 4.0
  4. Linq to subsonic.
  5. Subsonic 3.0 templates.
  6. Can handle thousand of queries at a times.
  7. Full support with asp.net 3.5 features.
  8. Ease of Use.
  9. Great support with asp.net mvc

And another great news is that Rob Conery is hired by the Microsoft and subsonic will official ORM for ASP.net Applications.

You can download subsonic 3.0 from here.

http://www.subsonicproject.com/Download

Happy Coding..

Photoshop and CSS Tutorials.

I am creating a web template for my forthcoming question answer asp.net mvc site. I need a web 2.0 rich template for my site for that i have search on web and found some great photoshop and css links. Here is collection for that.

Photoshop link:

  1. First is the my link who created design for my blog. http://psdvibe.com/- Its a great resource to learn Photoshop and create professional template. Thanks you for giving me the best template free of charge.
  2. http://www.webdesignbooth.com/32-useful-portable-apps-for-web-designers-and-developers/
  3. http://hv-designs.co.uk- A Great Resource for Photoshop design
  4. http://creativenerds.co.uk/tutorials/70-tutorials-using-photoshop-to-design-a-website/
  5. http://pelfusion.com/
  6. http://bestdesignoptions.com/
  7. http://www.smashingmagazine.com/2009/07/15/clever-png-optimization-techniques/
  8. http://sixrevisions.com/tutorials/web-development-tutorials/coding-a-clean-illustrative-web-design-from-scratch/
  9. http://speckyboy.com/2009/07/06/40-free-and-essential-web-design-and-development-books-from-google/
  10. http://webdesignledger.com
  11. http://sixrevisions.com/
  12. http://photoshoptutorials.ws/
  13. http://www.tutorialized.com/tutorials/Photoshop/1
  14. http://www.absolutecross.com/tutorials/photoshop/
  15. http://www.photoshopsupport.com/tutorials.html

CSS Link:

  1. http://www.freecsstemplates.org/ One of the greatest tutorial i have seen for free.
  2. http://www.free-css-templates.com/
  3. http://www.free-css.com/
  4. http://www.csstemplatesforfree.com/
  5. http://www.westciv.com/style_master/house/
  6. http://www.w3.org/Style/CSS/learning
  7. http://www.jasonbartholme.com/101-css-resources-to-add-to-your-toolbelt-of-awesomeness/
  8. http://speckyboy.com
  9. http://designreviver.com
  10. http://thecssblog.com/tips-and-tricks/image-slicing-and-css-being-smart-with-file-formats/
  11. http://line25.com/articles/15-must-read-articles-for-css-beginners
  12. http://www.smashingmagazine.com/2009/06/25/35-css-lifesavers-for-efficient-web-design/
  13. http://designreviver.com/tips/13-training-principles-of-css-everyone-should-know/
  14. http://arbent.net/blog/40-outstanding-css-techniques-and-tutorials

Happy designing…

Sending email through System.Net.Mail.Smtpmail in asp.net 3.5/2.0

  • 19

For any web application or website the sending email is a necessity for newsletter, invitation or reset password for everything we have to sent a mail to the people. So we need to see how we can send mail. In 1.1 we are sending emails with System.Web.Mail.SmtpMail which is now obsolete. Now in asp.net 2.0 or higher version there is a namespace called System.Net.Mail.Smtpmail in asp.net 3.5. With this namespace we can easily write a code to send mail within couple of minutes.

If you want to sent a mail first thing you need is smtpserver. Smtpserver is a server which will route and send mail to particular system. To use smtpserver we need to configure some settings in web.config following is the setting for the web.config.

<system.net>

    <mailsettings>

       <smtp deliveryMethod="Network">

         <network host="stmp server address or ip"

           port="Smtp port" defaultCredentials="true"/>

        </smtp>     

    </mailsettings>

</system.net>


Here you need to set the all the smtp configuration. This will be used by the smptclient by default. Here is the code for sending email in asp.net 3.5

SmtpClient smtpClient = new SmtpClient();

MailMessage message = new MailMessage();

try

{

   MailAddress fromAddress = new MailAddress("from@site.com","Nameofsendingperson");

   message.From = fromAddress;//here you can set address

   message.To.Add("to@site.com");//here you can add multiple to

   message.Subject = "Feedback";//subject of email

   message.CC.Add("cc@site.com");//ccing the same email to other email address

   message.Bcc.Add(new MailAddress("bcc@site.com"));//here you can add bcc address

   message.IsBodyHtml = false;//To determine email body is html or not

   message.Body =@"Plain or HTML Text";

   smtpClient.Send(message);

}

catch (Exception ex)

{

   //throw exception here you can write code to handle exception here

}


So from above simple code you can add send email to anybody
Adding Attachment to the email:If you want to attach some thing in the code then you need to write following code.

message.Attachments.Add(New System.Net.Mail.Attachment(Filename));


Here file name will the physical path along with the file name. You can attach multiple files with the mail.

Sending email with Authentication: If you want to sent a email with authentication then you have to write following code.

System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient();

     //This object stores the authentication values

     System.Net.NetworkCredential basicCrenntial = 
          new System.Net.NetworkCredential("username", "password");

     mailClient.Host = "Host";

     mailClient.UseDefaultCredentials = false;

     mailClient.Credentials = basicCrenntial;

     mailClient.Send(message);



Happy Coding…

Google SMS Channel –Subscribe my post via SMS

  • 0

Mobile has been very useful device since its launched. Now days we can not live without mobile. Think if you have your own sms channel and you can send message to your subscribers about your thought your blogs. It seems like a dream but now dream comes true. Google has launched new sms channel through which you can sent any thing to your subscribers. Now you guys can have my blog post via sms. I have created my channel at Google sms channel. You just need to subscribe that channel that’s it. You will have all my updates of blog on your mobile.

Here is the link for subscribing my blog post.

http://labs.google.co.in/smschannels/subscribe/DotNetJaps

Click this link and subscribe this channel and you will have all my blog updates on your mobile. Its free any one can create his/here channel. Go to http://labs.google.co.in/smschannels and try create new channel link and that’s it you are having your own sms channel.

GoogleLabs

Wave.Google.com –A new communication tool.

  • 0

Google wave is a new communication and sharing tool coming this year. With wave people can do lots of this things in a single browser like communication,videos,map link sharing, rich formatted text etc.

You can have a group chat and any participant can reply anywhere in message. edit content and add participant at any point any time.

You can also do lots of things like created gadgets thanks to wave api available on wave.Google.com.wave.Google.com is having key technologies like natural language processing, Real time conversation etc. Here is the some video for that.

Natural Language Processing:

Another one live collaborative editing.

If you want to play with wave google api then here is the link for that.

http://code.google.com/apis/wave/

And here is the Google developer preview video.

Happy surfing…

Windows Live Writer 2009 Available for download now.

I am using windows live writer more then a year for blogging. Its a great tool to blog the things. There lots of inbuilt features are there. Like you can insert videos,Format HTML, Insert hyperlink, insert picture directly from the desktop etc.

BlogPost_thumb1

A new version of window live writer is having all this functionality. As well as its having plug ins that can be very use full when you are professionally blogging the things. There lots of plug in available like twitter update,dig this and flicker

As well as all this you can directly insert videos from YouTube,soapbox etc.

Here is the link for the downloading the windows live writer.

http://windowslivewriter.spaces.live.com/