Got C# Corner MVP Award


Feeling Excited to announce that today i have got the most awaited MVP Award from C# Corner. An online community for computer professionals.

Thanks to C# Corner.

07042016081103AM

Advertisements

ASP.NET Performance Optimization


The Performance of an application from the perspective of the client is very important and if it is degraded from too many round trips, too many resources, too many ajax or server calls, it gives the end user no option other than leaving your useful resource. So to end this problem you must have an eye on ways to boost your application performance by using performance boosters.

Performance of an application is the most important aspect which you need to monitor every day to provide uninterrupted services to your favorite clients and the better approaches your system uses the better results you will get. I will write the series of Optimization and Performance Techniques for SQL, jQuery, Ajax, JavaScript, C#, query optimization, and Website Optimization in upcoming articles but for now I am stating ASP.NET Performance Metrics.

But wait, what are the ways that you can judge how you want optimization of your web / application?

Below is the list of Optimization and performance Metrics that you want to acknowledge.

  1. Speed
  2. Use Logs
  3. Proper Exception Handling
  4. View State
  5. Proper Use of Caching
  6. Avoid Serve Side Validation
  7. Minify and Compress JS, CSS Resources
  8. Session Management
  9. Paging for Large Result set
  10. Avoid Un-necessary RoundTrips to Server
  11. Pages Must be Batch Compiled
  12. Partition Application Logically
  13. HTTP Compression
  14. Resource Management
  15. String Handling

We Can Discuss Each one in detail. So let’s start.

Speed

Speed of your application is the most important factor and you need to keep an eye on this factor. There are many factors involved to boost speed of your application:

Reduce Page Size:

  • By Reducing page size by means of using external css and javascript files instead of inline css and javascript.
  • The other way to reduce page size is to used only the minify version of javascript files and also beautify css and js by online tools.

To beautify Cascading Style Sheet Files Follow this Link.

To beautify Javascript files follow this Link.

To Minify Cascading Style Sheet Files Follow this Link.

To Minify JavaScript files follow this Link.

Beautify means to format the unformatted files (means with white space, comments and without indentation).

Minify means to remove white spaces, comments, non-indent text and the nice feature is to reduce space by giving your functions and variables a single name like function a(b){ if b == ‘4’){ b=’good’}}, move your code to single line of function defined.

  • Its very efficient way to separate the logic of your page as well as we did to crate an application by separating the logic of data access and business layers, so in page level you can separate it by making user controls of header, body and footer.

Reduce No of Requests to Server:

The fewer number of requests served to the server the more efficient your page behavior is.

Reduce the number  of requests by reducing the number of resources, like move your inline css code of all files to single css and like wise with javscripts. The other way is to cache the non static resouces and remove unnecessary headers from requests like version number and asp.net powered by. Use CDN (Content Delivery Network) so that it downloads files from nearest available server and save the concurrent requests if other websites are using same jquery plugin files.

Use Logs

Use IIS Log to trace out issues on weekly or monthly basis of your application, and the best is that you have to watch it on adaily basis, mainly IIS Log contains information about your server , date and time span, Referral page and the original URL and lots more information and also the HTTP Status response codes through which you can understand the nature of the issue.

I have written post on HTTP Status Response code you can read it from Here

The other way you can customize what to log is by creating a database table and inserting the exception detail in this, I have done it this way in my organization and also tracking module which can search, generate report on daily basis, insert the log modules and lots more, so that you don’t need to query the table again and again to check for daily error or for reporting.

There are other best approaches to track the error, one of the best available tools is Elmah Tool, which has a config base setting through which you can track it by configuring it with email option to the responsible person.

ELMAH (Error Logging Modules and Handlers) is an open source debugging tool for ASP.NET web services. When added to a running web application on a machine, exceptions that are thrown trigger event handlers in the ELMAH tool.

You can get it from google code Link OR

You can get it from Nuget Packages Link.

Proper Exception Handling

There are many developers who cannot handle proper exception techniques as a result the final outcomes are not pretty satisfied which means they cannot understand if there is any crashing of the application. The best way is to use try….. catch block appropriately to handle the exception in a right manner. User can use (if statement) to check for open connection if not open close the connection to the database. The other way use can use the (try…. catch block) for the connection if not closed throw an exception. With try…catch it is best approach to use finally block also with try…catch and then block like this to properly dispose off the unused resources if exception occurs or not.

  1.  try
  2.  {
  3.  }
  4.  catch (Exception)
  5.  {
  6.  throw;
  7.  }
  8.  finally
  9. {
  10.  }

Exception handling is the most important technique for finding the original run time unhandled exception in application but it should be wisely and judiciously used.

View State

View state is encrypted component in webforms that maintain the state of pages. It is used to maintain the state of page in post backs, these are the hidden fields and you can check by viewing source of page. iI you are too using the view state to maintain the state behavior of data in web forms in large form it loads your page and as a result you have a performance issue.

The potential issues lies with view state; it has large page load times due to increased number of page states.

So what are the best practices to override these types of headoff.

Here are some performance paradigms that must be accounted for while using view state.

  • Use it whenever needed in a page but limited it to small size as possible.
  • Don’t use multiple forms in a single page having state management enabled.
  • Use it wisely required on page or either in control level to application level.
  • Monitor the size of view state by enabling tracing.
  • Avoid storing large objects as the size is directly proportional to the objects.

Proper Use of Caching

With the proper use of caching you can get a lot of benefits like reducing the round trips to the server, reducing the number of server resources and it renders faster than in routine normal mode. It can improve the performance manyfold by caching the data on multiple Http Requests, it can store the page partially for specified times with some expiration values. It can boost application performance by storing data in memory so that it can be accessed quickly with less time just like CPU RAM. Cache can be accessible in your single application to use in webfarm you can use the distributed cache managers like memcached to share the cache data within the web farm.

Best use of cache is as follows:

  • Use it in all layers DataAccess, Business and UI Layer and use it in a proper way can give you performance boost.
  • caching for large time for static resources or not too used resources and also adding expiration to cache also give best performance.
  • Don’t cache expensive objects in cache like connection and like other resources.
  • use Output cache for static pages with expiration time and location as per your need.
  • Use partial fragment cache to partially cache the page component.

Avoid Server Side Validation

Validating your system is an important part as you filter what you want very clearly in DB because if you have free type text input then chances are that the required data cannot be received that’s why validations are required.

Validations are of two types: Client and server side validation.

Server Side Validation are important by the perspective of securing your sensitive information like saving password and other sensitive information. This is always not required to do server side validation as it always submits request and response back to client which causes in the cost and time of the user. This type of validation occur when submit is Hit.

Best Tips is to use whenever you required to ensure that security is not bypassed otherwise it is better to check the client side validation formats like email, URL , phone number, masking and other required information which need to be correct.

Minify and Compress JS, CSS Resources

The best approach with static content files is to minify which means make them small. Just like in production environment Jqueryis also recommended to use the min.js version file for best operations with their library you need too to include the minified version of your application working javascript files as the number of requests greatly increases the page time as some time size of file doesn’t matter but it can also be reduced by using the minified files for javascript and CSS files.

In IIS there is also setting for Compressing the Static and dynamic content you can too try this to enable compression in website.

This is also the best approach to use the Cascading style sheet files in the head of the webpage while the scripts must be included in the bottom of the page for fast processing of the page.

As you all aware of that we are using bundles of javascript libraries day by day to do our work but we foget about the behavior and impact which they made to our system. To overcome this Microsoft also announced its Microsoft web Optimization framework which is also useful.

You can read more about this framework from Here.

You may refer to section 1 of this article about the speed concerns.

Session Management

Session is an important part for asp.net applications but its effects are adverse if not handled properly.

Here are some best practices to use it intelligently.

  • Do not store a bunch of data in sessions.
  • Store basic types of data not complex types likes object.
  • Use wisely the available session states like in Proc, out of process using state view and out of process using SQL Server.
  • Out of process is the best option as it application did not restart despite of any application configuration changes but it is slow as it is some server of in sql, While the other in proc is fast as it is used same memory as application and their retrieval is also fast.
  • Do not use sensitive data in session state.
  • Always use abandon () method to sign out the user with session enabled.

Paging for Large Result set

Paging on large result sets are an extremely useful approach as we restrict the result to 10 to 30 records per page to be shown and on call of next records we get more records to load it reduces the extra load server bear to fetch all the records and return it which causes increase in page load times and extra cost to your users as well as the whole page goes unresponsive for about large time. So best approach it to make your result sets as less as possible and also use of ROWCOUNT() enhances the paging a lot more.

As your client has low resources either saving the large results set also make impact on your client.

The basic backbone in paging is the use of row_number ranking function. If you can check time with all records versus no of first page records than it show a great improvement.

Avoid Un-necessary Roundtrips to Server

The best method to avoid roundtrips to the server is to ensure that no un-necessary calls sent to the server as number of requests sent to the server increases the page load time increase in the result client suffers.

So it is necessary that you must use client mechanisms to ensure the validity to get data from server as it does not result in post backs and not involve any server callbacks which result in server involvement and it trigger the request response cycle.

You can following metrics to minimize the round trips between web server and browser.

Use Server.Transfer instead of Response.Redirect for redirecting to certain path. Server.Transfer scope is in current application redirection for redirecting to other than your application use Response.Redirect.

If your data is static you can use caching for best performance. Use Output Buffering as it reduces roundtrips by loading whole page and made available to client. If you want to transfer some data and client always connected then use HttpResponse.IsClientConnected as it reduces chances of any missing change not sent to server.

Pages must be Batch Compiled

The more the assemblies grow in a process, there are more chances that process shoots out and it throws out of memory exception. To overcome this pages need to be batch compiled as when first requested is initiated to compile pages all the pages in the same directory batch compiled and it make a single assembly. The basic advantages is thatthe  max number of assemblies that try to load in the process does not load which did not compromise on server load and only single batch compile assembly loaded in the process.

You can also ensure some things while doing this like:

  • Debug property in the configuration file always set to false in the production environment as if it is set to true pages are not batch compiled
  • Pages also did not time out if certain web service of page is not responding at the desired time,
  • Make sure that different languages are not used in same directory as it reduces chances of batch compilation.

Partition Application Logically

This means logically partitioning of your application logic like business, presentation and Data access layers. This is very useful as you have control of anything happening in any one can do their respective work in logic layer. This didn’t mean that you have to write more line of code, proper code with reusability and scalability of the application is the key properties of your application overall performance.

Don’t confuse it with physical separation of logic, as it only separate the code logic.

Below are the key pros of the separate application logic.

  • The main advantage of this is that you have a choice of logic to be separately reside on servers for your easiness in a web farm environment but it increase the latency of calls.
  • The closer is you logical layers the more benefit you have for example the all logic files in bin directory.

HTTP Compression

As the name suggests that http compression means to compress the content mostly in Gzip format or deflate and send with content headers after compression applied. It provides faster transmission time between IIS and browser.

There are two types of compression supported in IIS:

Static Compression:

It compresses cache static content by specifying in the path of directory attribute. After the first request that is compressed followed by requests used the cache compress copy thus decrease the time to furnish the content and increases productivity and performance of application. You should only compress the static content which is not changes not dynamic one.

Dynamic Compression:

Unlike the static content, dynamic content often changes as a result it supports compression by not being able to add in to the cache it only compresses the content.

Resource Management

The resource management is the management of overall resource of your application as it directly related to the performance of the application. Poor resource management decreases the performance and it loads your server CPU.

Below is the list of the most useful techniques for resource management.

  • Good use of pooling
  • Proper use of the connection object.
  • Dispose of unused resources after using them
  • Handling memory leaks.
  • Remove unused variables

String Handling

String management is one of the key to manage the memory of your application.

There are many techniques which is very useful in handling strings, some of them are enlisted:

  • Use Response.Write() to fastest show output to the browser.
  • Use stringBuilder when you don’t know the number of iterations to concatenate strings.
  • Use += operator to concatenate string when you know the number of strings are limited.
  • Do not use .ToLower() while comparing string as it creates temporary string instead use the string.compare to compare two strings because it has built in check for case insensitive data by using cultureinfo class.

Insert Bulk Data From CSV File To Database Table Using SQLBulkCopy Class


In this article we will see how we can Import CSV File data to Database in ASP.NET C# usingSqlBulkCopy.

Let’s start to build the application which will process our required command.

Step 1:

Firstly, create Database if it does not already exist and then create table in which the dat is inserted after importing file data.

I Have Created a table, namely StudentCourses, and created three columns inside it.


Columns are StudentID, Name and Course which is old data after importing.

Here is the Script to create table.

  1. CREATE TABLE [dbo].[StudentCourses](
  2. [StudentID] [intNOT NULL,
  3. [Name] [varchar](500) NULL,
  4. [Course] [varchar](100) NULL,
  5. CONSTRAINT [PK_StudentCourses] PRIMARY KEY CLUSTERED
  6. (
  7. [StudentID] ASC
  8. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]
  9. ON [PRIMARY]
  10. GO

Before inserting Data Here is our empty table.


Step 2:

Let’s Build Interface / Markup of File Upload Control and Button.

I am also using bootstrap to make UI look good.

Here is the Full code of UI.

  1. <%@ Page Language=“C#” AutoEventWireup=“true” CodeFile=“Default.aspx.cs” Inherits=“_Default” %>
  2. <!DOCTYPE html>
  3. <html xmlns=http://www.w3.org/1999/xhtml&#8221;>
  4. <head runat=“server”>
  5. <title></title>
  6. http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js”&gt;
  7. <link rel=“stylesheet” href=http://netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css&#8221; />
  8. http://netdna.bootstrapcdn.com/bootstrap/3.0.2/js/bootstrap.min.js”&gt;
  9. </head>
  10. <body>
  11. <form id=“form1” runat=“server”>
  12. class=“form-horizontal” style=“margin-top:50px”>
  13. class=“form-group”>
  14. class=“col-lg-3 control-label”>Upload CSV File
  15. class=“col-lg-5”>
  16. “fupcsv” runat=“server” />
  • </div>
  • class=“form-group”>
  • class=“col-lg-9 col-lg-offset-3”>
  • “btnimportcsv” runat=“server” Text=“>Import CSV Data to SQL Table” OnClick=“btnimportcsv_Click” />
  • </div>
  • </div>
  • </form>
  • </body>
  • </html>
  • Step 3:

    Before starting we will create the connection string in web.config. Today I will introduce you the best connection string generator method which can reduce the error and it also test the connection as well. Right Click on your PC Desktop it will open the context menu Now Choose New è Text Document, New text documents created now change the extension of text file from .txt to .udl and Hit Enter.

    It will show prompt like this just press to continue and extension of the file has been changed.

    Now double click the file to open it will look like this.

    Now fill in the desired information in respective fields and test the connection it will give you prompt of failure or success.

    Now press ok at the prompt and then finally hit the OK button of Data Link Properties Window. If you have selected check box of Allow saving password it will give you confirmation message” are you sure?”

    After selecting yes it will print the saved password to the file. Now we will check how it looks like our connection string. Right click the data link properties file and open it with Notepad. It will show you this final oledb connection string.

    And that’s all to generate connection string.

    Step 4:

    So we will start to firstly check the valid .csv extension file and Upload to the certain path.

    1. string fileExt = Path.GetExtension(fupcsv.PostedFile.FileName);
    2. if (fileExt == “.csv”)
    3. {
    4. string csvPath = Server.MapPath(“~/CSVFIles/”) + Path.GetFileName(fupcsv.PostedFile.FileName);
    5. fupcsv.SaveAs(csvPath);
    6. }
    7. else
    8. {
    9. lblmessage.Text = “Please upload valid .csv extension file”;
    10. lblmessage.ForeColor = System.Drawing.Color.Red;
    11. }

    Firstly, checked the file Extension by using the Path.GetExtension () Method and the we have save the file to Certain path by using Server.MapPath to assign path and then use SaveAs() Method to upload it to the Path.

    Step 5:

    In this step we will do our code behind functionality to firstly upload to the certain path and then read the file using File.ReadAllText() Method. After that a connection has been established with the database and we will use SqlBulkCopy Class to define our destination table and write to the database using WriteToServer() Method of SqlBulkCopy Class to finish the task.

    Here is the full code which can do our desired task, Code Comments are added for well understanding.

    1. string fileext = Path.GetExtension(fupcsv.PostedFile.FileName);
    2. if (fileext == “.csv”)
    3. {
    4. string csvPath = Server.MapPath(“~/CSVFIles/”) + Path.GetFileName(fupcsv.PostedFile.FileName);
    5. fupcsv.SaveAs(csvPath);
    6. // Add Columns to Datatable to bind data
    7. DataTable dtCSV = new DataTable();
    8. dtCSV.Columns.AddRange(new DataColumn[3] { new DataColumn(“StudentID”typeof(int)),
    9. new DataColumn(“Name”typeof(string)),
    10. new DataColumn(“Course”,typeof(string)) });
    11. // Read all the lines of the text file and close it.
    12. string csvData = File.ReadAllText(csvPath);
    13. // iterate over each row and Split it to New line.
    14. foreach (string row in csvData.Split(‘\n’))
    15. {
    16. // Check for is null or empty row record
    17. if (!string.IsNullOrEmpty(row))
    18. {
    19. // added rows
    20. dtCSV.Rows.Add();
    21. int i = 1;
    22. foreach (string cell in row.Split(‘,’))
    23. {
    24. dtCSV.Rows[dtCSV.Rows.Count – 1][i] = cell;
    25. i++;
    26. }
    27. }
    28. }
    29. // Database connection string
    30. string consString = ConfigurationManager.ConnectionStrings[“GamesConnectionString”].ConnectionString;
    31. using (SqlConnection con = new SqlConnection(consString))
    32. {
    33. // class use to bulk load data from another source
    34. using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
    35. {
    36. // Set the database table name in which data to be added
    37. sqlBulkCopy.DestinationTableName = “dbo.StudentCourses”;
    38. con.Open();
    39. // copy all the rows from dataTable to the destination Database table.
    40. sqlBulkCopy.WriteToServer(dtCSV);
    41. con.Close();
    42. lblmessage.Text = “Bulk Data Successfully dump into the Destination table”;
    43. lblmessage.ForeColor = System.Drawing.Color.Green;
    44. }
    45. }
    46. }
    47. else
    48. {
    49. lblmessage.Text = “Please upload valid .csv extesnion file”;
    50. lblmessage.ForeColor = System.Drawing.Color.Red;
    51. }
    52. }

    After this line of code we get success message which assures us that our data dumped successfully.

    Step 6: Output of the CSV to Database Table.

    Visual C# Built In Code Snippets For Fast Productivity


    Code snippets are ready made, which means they are really useful reusable codes which need to be used and then again used at someother  part of work.

    These snippets are not really of the type which are only used by just placing a cursor and inserting it to the place you want, but some are surrounded with code snippets also in which some line of code has been selected and then surrounded with required if statement, for loop and so on.

    Code Snippets have following Advantages:

    • It saves a lot of your time by saving reusable code in code snippet manager and you can later use it anywhere.
    • It increases productivity by simply inserting code in you desired location.
    • It reduces the chances of less error by re typing your line of code.
    • It helps to stream line your work as per you assigned deadline.

    Code Snippet Manager:

    Firstly, you can check a whole list of code snippets in code snippets manager which you can open by pressing Combination of (Ctrl + K, Ctrl + B).

    You can alternatively open code snippet manager from Visual Studio Menu from Tools è Code Snippets Manager…

    There is another way to open as introduced in latest versions of visual studio which is very beneficial to open the menu items in less time; it is the Quick Launch Search Box Displayed in Top Right of your Visual Studio IDE.

    As you type text it gives you suggestions and suggestions to do more actions also, like it displays the most Recently used items and Nuget Package Manager search for the searched keyword.

    How to Use Code Snippets:

    Basically there are two types of code snippets to be used; First one is by placing cursor at location and typing some code snippet code and secondly by using surround-with code snippets.

    Note: At any time if you do not want to select the desired code snippets Press ESC Button it will dissolve and does not insert the code snippet.

    Cursor Based Code Snippets:

    Usage of code snippets is very simple. Just place cursor at the desired location where you want to insert code snippets, type snippet code and Press TAB Button Twice to insert in the place… we will discuss full list of code snippets in this article after following this but for reference I am quoting here an example of code snippet… for example you want to add for loop, just write for and press twice to check the magic of code snippet inserting and with full syntax and with default values. It Increases your productivity and time by also reducing the risk of human errors while creating complex syntax like for loop.

    You can use it from Keyboard shortcut also by pressing key combination of (Ctrl + K, Ctrl + X) and select the Visual C# Category.

    But if you have to remember the snippet code you can type it.

    Surround-With Code Snippets:

    You can use surround with code snippets by selecting the line of code and press keyboard short cut key combination (Ctrl + K, Ctrl + S) and type the desired code snippet to wrap in the line of code.

    List of Available Code Snippets:

    Now we will move into the using of code snippets inside IDE.

    #region:

    Region directive is used to define certain region in the code which specifies certain functionality or scope of certain work. It is collapsible portion and it is useful for pages which has lengthy code written so that you can collapse the region of code and focus on your work.

    The start #region must be terminated with #endregion directive otherwise it will through the exception.

    #region has a scope of anywhere means you can insert it anywhere you want.

    (~):

    This code snippet has scope only in class as class has destructors.


    As already mentioned that has scope with in class so I checked it with creating outside the scope of class, although it created as it is snippet but it will generate compile error or a namespace cannot directly contain members such as fields or methods, while the other one inside the class scope did not through any exception.

    ctor:

    This code snippet is used to create constructor of a class. It has also scope within class otherwise it generate exception.

    Type ctor and press TAB twice to insert.


    class:

    This snippet will create a declaration of class. It has a scope of namespace (global), class or struct.

    enum:

    This is used to declare enumeration. This is used to build a list of distinct enumerators. It has a scope of inside namespace, class or struct. The default value for initial first enumerator is 0 and the successive items will follow it like 0, 1 and so on. Enums cannot contain whitespaces while declaring their names.

    The approved types of enum are int, long, byte,unit,ulong,ushort,short and sbyte.


    cw:

    Very helpful snippet cw means Console.WriteLine() which can show current line terminator to the output stream. Its scope lies inside method, indexer, property or event accessor.

    It can take string as a parameter and return to output stream. You can align string to New Line also by using Console.Out.NewLine,

    1. Console.WriteLine();

    equals:

    The Equals as the name defined it has behavior to check equal of two objects either they are of same type or of different type and it returns Boolean value, if matched it return true otherwise false.

    Its scope lies only inside class or struct.

    1. // override object.Equals
    2. public override bool Equals(object obj)
    3. {
    4. //
    5. // See the full list of guidelines at
    6. // http://go.microsoft.com/fwlink/?LinkID=85237
    7. // and also the guidance for operator== at
    8. // http://go.microsoft.com/fwlink/?LinkId=85238
    9. //
    10. if (obj == null || GetType() != obj.GetType())
    11. {
    12. return false;
    13. }
    14. // TODO: write your implementation of Equals() here
    15. throw new NotImplementedException();
    16. return base.Equals(obj);
    17. }
    18. // override object.GetHashCode
    19. public override int GetHashCode()
    20. {
    21. // TODO: write your implementation of GetHashCode() here
    22. throw new NotImplementedException();
    23. return base.GetHashCode();
    24. }

    exception:

    Creates a declaration for class that derives from exception by default. Exceptions are errors which are generated by the application. Its scope is inside a namespace, class or struct.

    1. [Serializable]
    2. public class MyException : Exception
    3. {
    4. public MyException() { }
    5. public MyException(string message) : base(message) { }
    6. public MyException(string message, Exception inner) : base(message, inner) { }
    7. protected MyException(
    8. System.Runtime.Serialization.SerializationInfo info,
    9. System.Runtime.Serialization.StreamingContext context)
    10. base(info, context) { }
    11. }

    for:

    for statement is most probably used to run together block of statements in a repeated fashion until you statements return false. The best possible scenario for using for loop having you know number of iterations required to get possible operation.

    1. for (int i = 0; i < length; i++)
    2. {
    3. }
    foreach:
    foreach iterates through for each element in an array or object collection that implements IEnumerable or Generic IEnumerable Interface.
    It just iterate to the collection of items but it does not for adding or removing items. you can use break and continue operation inside foreach loop as per your easness.

    1. foreach (var item in collection)
    2.         {
    3.         }

    for:

    this code snippet is for decrementing values  after each iteration using for loop. Its scope is as same as for loop.
    1. for (int i = length – 1; i >= 0; i–)
    2.        {
    3.        }

    if:

    it is the most important and too many used code snippet in daily work routine. due to its  simplicity its as important as you think you have to include for every block statement to check for. It has scope inside a method, indexer, property or event accessor. by default it has true value like we are checking for check box which is either checked or not so that we can evaluate the if … else condition on the base of it.

    1. if (true)
    2.         {
    3.         }

    Interface:

    by inserting this snippet it create the interface declaration. an interface only contain the signature of methods, indexer,events pr properties. a class which implements the interface must used the members which interface has defined.  An Interface can inherit from one or more base classes. it has scope inside a class, struct or namespace (global).

    1. interface IInterface
    2. {
    3. }

    namespace:

    it declare a scope / set of related objects. inside a namespace you can declare one or more namespace,c lass, struct, enum, interface and delegate.

    it has scope only inside namespace which has global scope.

    1. namespace MyNamespace
    2. {
    3. }

    prop: it created auto-implemented property inside a class or struct.you can initialize certain properties with some initial value.

    1. public int MyProperty { getset; }
    propfull: it can create property declaration with get  and accessors and it has scope only inside a class or struct.
    1. private int myVar;
    2.     public int MyProperty
    3.     {
    4.         get { return myVar;}
    5.         set { myVar = value;}
    6.     }

    switch:

    It is a control statement which selects a switch section and break no succeeding section should be checked. each switch section contains one or more case labels followed by one or more statements depending on the scenario.

    1. switch (switch_on)
    2.         {
    3.             default:
    4.         }

    try:

    create a try….catch block. the most important purpose of try … catch is to catch unhandled exceptions by trying a block of code and it successful it moved to the next section or move out of the method block and if not successful it go to the catch section where customized as well as other exception are thrown to identify the type of breakage caused by the try code.

    1. try
    2.        {
    3.        }
    4.        catch (Exception)
    5.        {
    6.            throw;
    7.        }
    tryf: the basic purpose of using finally with try block is to cleanup the resources which is occupied by try block,
    1. try
    2.         {
    3.         }
    4.         finally
    5.         {
    6.         }
    while:

    It executes block of statements until the expression is not set to false. The executing statement can also be terminated by adding break, go to like statements. It has scope inside a  method, indexer, property or event accessor.
    1. while (true)
    2.        {
    3.        }
    That’s all about some of the useful code snippets but there are some others; you can check full code snippets  manager for full list.

    Create Web Elements In Seconds Using DCodes (The Online CSS Framework)


    In this tutorial I am using the Dcodes (The online CSS Framework) which is very powerful css framework to build website elements in seconds.

    Dcodes have over 1500+ web ready elements (Short codes) with simple copy and paste integration.

    Just like JQuery tag line of (write less, do more)….. Dcodes have a unique tag line also which is (Get more done in less time) which is very elaborated and of course very well said as the integration is very simple; every developer or even simple basic user can even do this with easy to use copy and paste code to be used with best of your requirement, either you are using css buttons, navigation, rss , elements, tooltips and lot of more to choice from 1500+ elements.

    List of Features:

    • With 1500+ short codes, add web ready elements in seconds, just copy and paste code.
    • Having Compatible with popular browsers and devices, so you not need to worry about the compatibility.
    • Fast, Lightweight, Optimized and Minified version with fast page load times.
    • Show a gallery of images in an outstanding way with 30 jQuery sliders.
    • Connect with social network services like Facebook, twitter, google plus, YouTube, Flickr, LinkedIn and lot more in an easy way.
    • 500+ google web fonts suitable for your need.
    • Construct complex layouts and prototypes in minutes.
    • It’s upon you use the local version of scripts or used Cloud CDN Solution for scripts like jQuery CDN.
    • Use only the required file which you want to include, it increase the download and page load time.
    • With our short codes you can use only HTML+CSS+Jquery, no third party plugin required to setup. That’s why easy and robust.

    There are many more similr features. You can read full list from Here

    Let’s start to create something using Dcodes short codes.

    Just think of it that you have startup your Hosting Business and worry about the plans and features and shown on website in Good UI mode. Firstly you should search for Guru Web graphic designer to create a stunning design and it takes a week to approve a well prepared design. It costs you a lot of time and money but what about Dcodes, how does it facilitate you? Within a minute you can choose the required stunning and flashing design and on the next minute you are ready to integrate with your website. It’s not an easy way to do your work?

    Sure, it completely removes the headache for surfing time and cost, its ambition is to get more done in less time and with an  easy way.

    So firstly go to the site and to the concern area.

    Select the pricing table design and after that click on the below table hyperlink View Code. It will open and copy the code and paste to the destination where you want to use the short code. Add the script and css hosted CDN files in the header section and the final output is given below.


    Full source code is given below for reference.

    1. <html>
    2. <head>
    3. <title>Pricing Table Using DCodes</title>
    4. <script src=https://code.jquery.com/jquery-2.2.3.min.js&#8221; integrity=“sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=” crossorigin=“anonymous”></script>
    5. <!– DC Pricing Tables CSS –>
    6. <link type=“text/css” rel=“stylesheet” href=http://cdn.dcodes.net/2/pricingtables/css/dc_pricingtables.css&#8221; />
    7. <!– DC Pricing Tables JS –>
    8. <script type=“text/javascript” src=http://cdn.dcodes.net/2/pricingtables/js/dc_pricingtables.js&#8221;></script>
    9. </head>
    10. <body>
    11. <!– DC Pricing Tables:2 Start –>
    12. <div class=“dc_pricingtable02 pricing_five” style=“width:800px;margin-top:50px”>
    13. <!– use pricing_three for 3 columns, pricing_four = 4 columns, pricing_five = 5 columns, pricing_six = 6 columns –>
    14. <!– Column 1 –>
    15. <ul class=“pricing_column_first gap”>
    16. <li class=“pricing_header1”></li>
    17. <li class=“pricing_header2”><span>Choose a Plan</span></li>
    18. <li class=“odd”> <a class=“tooltip” href=“#”>Disk Storage <span>The amount of disk storage we provide you with every account purchase.</span> </a> </li>
    19. <li class=“even”> <a class=“tooltip” href=“#”>Bandwidth <span>Amount of data transfer bandwidth provided to each account, per month.</span> </a> </li>
    20. <li class=“odd”><span>Domain Names</span></li>
    21. <li class=“even”> <a class=“tooltip” href=“#”>Subdomains <span>Number of subdomain assigned to your account. </a> </li>
    22. <li class=“odd”><span>Site Builder</span></li>
    23. <li class=“even”><span>Backups</span></li>
    24. <li class=“odd”> <a class=“tooltip” href=“#”>CPANEL <span>Web-based control panel system.</span> </a> </li>
    25. <li class=“even”><span>Email Accounts</span></li>
    26. <li class=“odd”><span>MySQL Databases</span></li>
    27. <li class=“pricing_footer”></li>
    28. </ul>
    29. <div class=“pricing_hover_area”>
    30. <!– Column 2 –>
    31. <ul class=“pricing_column glass_orange”>
    32. <!– color options: glass_black, glass_orange, glass_lightblue, glass_blue, glass_green, glass_purple, glass_red, glass_white, glass_aqua, glass_yellow, light_blue, blue, navy, green, yellow, orange, red, maroon, purple, pink, white, paper, silver, grey, black –>
    33. <li class=“pricing_header1”>Starter</li>
    34. <li class=“pricing_header2”>$5 <span>/mo.</span></li>
    35. <li class=“odd”>10GB</li>
    36. <li class=“even”>100GB</li>
    37. <li class=“odd”>1</li>
    38. <li class=“even”>10</li>
    39. <li class=“odd”><span class=“pricing_no”></span></li>
    40. <li class=“even”><span class=“pricing_no”></span></li>
    41. <li class=“odd”><span class=“pricing_yes”></span></li>
    42. <li class=“even”>10</li>
    43. <li class=“odd”>5</li>
    44. <li class=“pricing_footer”>
    45. <a href=“#” class=“dc_pricing_button orange”>Sign Up</a><!– additional options: small, rounded, large, light_blue, blue, green, red, orange, yellow, pink, purple, grey, black –>
    46. </li>
    47. </ul>
    48. <!– Column 3 –>
    49. <ul class=“pricing_column glass_red”>
    50. <li class=“pricing_header1”>Basic</li>
    51. <li class=“pricing_header2”>$10 <span>/mo.</span></li>
    52. <li class=“odd”>50GB</li>
    53. <li class=“even”>500GB</li>
    54. <li class=“odd”>10</li>
    55. <li class=“even”>50</li>
    56. <li class=“odd”><span class=“pricing_yes”></span></li>
    57. <li class=“even”><span class=“pricing_yes”></span></li>
    58. <li class=“odd”><span class=“pricing_yes”></span></li>
    59. <li class=“even”>50</li>
    60. <li class=“odd”>10</li>
    61. <li class=“pricing_footer”><a href=“#” class=“dc_pricing_button red”>Sign Up</a></li>
    62. </ul>
    63. <!– Column 4 –>
    64. <ul class=“pricing_column glass_green”>
    65. <li class=“pricing_header1”>Professional</li>
    66. <li class=“pricing_header2”>$29 <span>/mo.</span></li>
    67. <li class=“odd”>100GB</li>
    68. <li class=“even”>1000GB</li>
    69. <li class=“odd”>Unlimited</li>
    70. <li class=“even”>Unlimited</li>
    71. <li class=“odd”><span class=“pricing_yes”></span></li>
    72. <li class=“even”><span class=“pricing_yes”></span></li>
    73. <li class=“odd”><span class=“pricing_yes”></span></li>
    74. <li class=“even”>Unlimited</li>
    75. <li class=“odd”>50</li>
    76. <li class=“pricing_footer”><a href=“#” class=“dc_pricing_button green”>Sign Up</a></li>
    77. </ul>
    78. <!– Column 5 –>
    79. <ul class=“pricing_column glass_blue”>
    80. <li class=“pricing_header1”>Business</li>
    81. <li class=“pricing_header2”>$39 <span>/mo.</span></li>
    82. <li class=“odd”>500GB</li>
    83. <li class=“even”>Unlimited</li>
    84. <li class=“odd”>Unlimited</li>
    85. <li class=“even”>Unlimited</li>
    86. <li class=“odd”><span class=“pricing_yes”></span></li>
    87. <li class=“even”><span class=“pricing_yes”></span></li>
    88. <li class=“odd”><span class=“pricing_yes”></span></li>
    89. <li class=“even”>Unlimited</li>
    90. <li class=“odd”>200</li>
    91. <li class=“pricing_footer”><a href=“#” class=“dc_pricing_button blue”>Sign Up</a></li>
    92. </ul>
    93. </div>
    94. </div>
    95. <!– DC Pricing Tables:2 End –>
    96. <div class=“dc_clear”></div> <!– line break/clear line –>
    97. </body>
    98. </html>

    Like These snippets, you can add any element you wish.

    Now we will start to add another element to the page in the form of showing the latest feeds from news agencies, blog post, and popular sites.

    But for today I wish to use C-sharp corner Rss Feed to show the latest articles showing on the main page.

    As we have get idea about RSS we can easily integrate in to our page.

    Just go to the Embed ==> RSS Feeds.

    Select the required ticker and copy the header and body section code and also don’t forget to edit the URL from which you want to show RSS feeds. Here is the full code compiled for RSS.

    1. <html>
    2. <head>
    3. <title>RSS Feeds Using DCodes</title>
    4. <!– DC RSS Feeds CSS –>
    5. <link type=“text/css” rel=“stylesheet” href=http://cdn.dcodes.net/2/rssfeeds/css/dc_rssfeed.css&#8221; />
    6. <!– jQuery Library (skip this step if already called on page ) –>
    7. <script type=“text/javascript” src=http://cdn.dcodes.net/2/jquery.min.js&#8221;></script> <!– (do not call twice) –>
    8. <!– DC RSS Feeds JS –>
    9. <script type=“text/javascript” src=http://cdn.dcodes.net/2/rssfeeds/js/dc_rssfeed.js&#8221;></script>
    10. <script type=“text/javascript” src=http://cdn.dcodes.net/2/rssfeeds/js/dc_vticker.js&#8221;></script>
    11. </head>
    12. <body>
    13. <!– DC RSS Feeds Settings –>
    14. <script type=“text/javascript”>
    15. $(document).ready(function () {
    16. // Put your Atom / RSS feed URL
    17. $(‘#rss-ticker2’).rssfeed(‘http://www.c-sharpcorner.com/rss/latestcontentall.aspx&#8217;, {}, function (e) {
    18. $(e).find(‘div.rssBody’).vTicker({ showItems: 10 });
    19. });
    20. });
    21. </script>
    22. <!– DC RSS Feeds Start –>
    23. <div id=“rss-ticker2” style=“width:80%;”></div>
    24. </body>
    25. </html>

    Final Output of RSS Feeds:


    Here is all about Dcodes…. Hope you find it useful and now you can made elements in seconds.

    Powerful Form Field Validator For Jquery And Bootstrap Using Bootstrap Validator


    Client side validation has been growing very fast due to its smaller impact to the server and you can reduce the round trips also by just filtering the required information in the form of form field validations.

    There are many types of form fields which need a strict validation, not a single one, like field mayallow you to only enter only the numbers, characters or both, but also it should requir you to chec that the field should not be empty having a specific format, either for example with password field it should have a check to contain special characters in field followed by single capital case, and a more interesting password strength and length of password should be between 8 to 15 or like this. Would you guess you can do ut in fewer lines of code? The answer to this question is NO.

    Why because you cannot handle it;  you require more time to code and use a lot of things to do the one kind of task to validate proper password standards. So here I want to introduce you to the best validation library which has a lot of more support for not only bootstrap but for Foundation, Pure, Semantic UI, UI Kit and lots more.

    You can read more about the library and its documentation from here.

    Before starting to implement read the getting started guide from here.

    There are many form field validators in the market but what makes it best? Check out the features list.

    Features of form Validator

    • Language packs included supports multiple language pack.
    • Glyph icons to validate input by using icons.
    • Support for multiple frameworks bootstrap, Foundation, Semantic UI and lot of others more.
    • Compatible with HTML5 Input types
    • Compatible with modern Browsers.
    • Supports error message of type tooltip, message and lot of other ways to check validity.
    • Over 51 built in validators for different form fields.
    • having add-ons like multiple language and re-captcha support

    This is all  the features it supports, now let’s move on to use it in web application.

    Step 1:

    For every JQuery Library it is necessary to first include scripts file in to the application and reference it on the page. First make a choice from the supported frameworks and select one you are working with and include it. For tutorial purposes I am using bootstrap here. Firstly, add following basic required jquery and Twitter bootstrap script to the head section of page.

    Note: Form validation requires jquery version => 1.9.1

    Step 2:

    Add bootstrap validator scripts to the head section just below to the firstly added scripts.

    I am using the CDN files here you may download scripts and follow the instructions in getting started panel to integrate with best of you criteria.

    Step 3:

    Let’s build the form which can be validated through bootstrap validator. I am using signup form for this demo as it contains lots of things to cover.

    1. <form id=“SignupForm” method=“post” class=“form-horizontal”>
    2.     
      class=“form-group”> class=“col-lg-3 control-label”>Username
    3.         
      class=“col-lg-5”> “text” class=“form-control” name=“username” /> 
    4.     </div>
    5.     
      class=“form-group”> class=“col-lg-3 control-label”>Email address
    6.         
      class=“col-lg-5”> “text” class=“form-control” name=“email” /> 
    7.     </div>
    8.     
      class=“form-group”> class=“col-lg-3 control-label”>Password
    9.         
      class=“col-lg-5”> “password” class=“form-control” name=“password” /> 
    10.     </div>
    11.     
      class=“form-group”> class=“col-lg-3 control-label”>Retype password
    12.         
      class=“col-lg-5”> “password” class=“form-control” name=“confirmPassword” /> 
    13.     </div>
    14.     
      class=“form-group”> class=“col-lg-3 control-label” id=“captchasignup”>
    15.         
      class=“col-lg-2”> “text” class=“form-control” name=“captcha” /> 
    16.     </div>
    17.     
      class=“form-group”>
    18.         
      class=“col-lg-9 col-lg-offset-3”> “submit” class=“btn btn-primary”>Sign up 
    19.     </div>
    20. </form>

    UI View looks like this after adding form and applying bootstrap.


    I am using Html elements for validating form fields in asp.net, if you are using server side controls then find this Tutorial.

    You can see the classes used in the form fields are all bootstrap for example the class class=”form-horizontal” used in the form tag is specifically used in bootstrap to horizontally align the form fields like label and input control.

    Step 4:

    Now we come to our important work which is validating the form fields section via bootstrap validator script. Before discussing deep about the script section let’s have a look at the syntax of writing script which is given below:

    1. $(formSelector).formValidation
    2. ({
    3.     // Indicate the framework  
    4.     // It can be: bootstrap, foundation, pure, semantic, uikit  
    5.     framework: ‘bootstrap’,
    6.     // … Form settings go here …  
    7.     fields:
    8.     {
    9.         fieldName:
    10.         {
    11.             // … Field settings go here …  
    12.             validators: {
    13.                 specificValidatorName: {
    14.                     // … common validator settings go here …  
    15.                     // … specific validator settings …  
    16.                 }
    17.             }
    18.         }
    19.     }
    20. });

    Syntax contains comments for better understanding.

    We have initialize our script in document. Ready function of jQuery,

    1. “text/javascript”>
    2.     $(document).ready(function()
    3.     {
    4.         // Generate a simple captcha  
    5.         function randomNumber(min, max)
    6.         {
    7.             return Math.floor(Math.random() * (max – min + 1) + min);
    8.         };
    9.         $(‘#captchasignup’).html([randomNumber(1, 100), ‘+’, randomNumber(1, 200), ‘=’].join(‘ ‘));
    10.         $(‘#SignupForm).bootstrapValidator
    11.           ({
    12.             message: ‘This value is not valid’, fields:
    13.             {
    14.                 username: {
    15.                     message: ‘The username is not valid’,
    16.                     validators: {
    17.                         notEmpty: {
    18.                             message: ‘The username is required and can\’t be empty’
    19.                         },
    20.                         stringLength: {
    21.                             min: 6,
    22.                             max: 30,
    23.                             message: ‘The username must be more than 6 and less than 30 characters long’
    24.                         },
    25.                         regexp: {
    26.                             regexp: /^[a-zA-Z0-9_\.]+$/,
    27.                             message: ‘The username can only consist of alphabetical, number, dot and underscore’
    28.                         },
    29.                         different: {
    30.                             field: ‘password’,
    31.                             message: ‘The username and password can\’t be the same as each other’
    32.                         }
    33.                     }
    34.                 },
    35.                 email: {
    36.                     validators: {
    37.                         notEmpty: {
    38.                             message: ‘The email address is required and can\’t be empty’
    39.                         },
    40.                         emailAddress: {
    41.                             message: ‘The input is not a valid email address’
    42.                         }
    43.                     }
    44.                 },
    45.                 password: {
    46.                     validators: {
    47.                         notEmpty: {
    48.                             message: ‘The password is required and can\’t be empty’
    49.                         },
    50.                         identical: {
    51.                             field: ‘confirmPassword’,
    52.                             message: ‘The password and its confirm are not the same’
    53.                         },
    54.                         different: {
    55.                             field: ‘username’,
    56.                             message: ‘The password can\’t be the same as username’
    57.                         }
    58.                     }
    59.                 },
    60.                 confirmPassword: {
    61.                     validators: {
    62.                         notEmpty: {
    63.                             message: ‘The confirm password is required and can\’t be empty’
    64.                         },
    65.                         identical: {
    66.                             field: ‘password’,
    67.                             message: ‘The password and its confirm are not the same’
    68.                         },
    69.                         different: {
    70.                             field: ‘username’,
    71.                             message: ‘The password can\’t be the same as username’
    72.                         }
    73.                     }
    74.                 },
    75.                 captcha: {
    76.                     validators: {
    77.                         callback: {
    78.                             message: ‘Wrong answer’,
    79.                             callback: function(value, validator) {
    80.                                 var items = $(‘#captchaOperation’).html().split(‘ ‘),
    81.                                     sum = parseInt(items[0]) + parseInt(items[2]);
    82.                                 return value == sum;
    83.                             }
    84.                         }
    85.                     }
    86.                 }
    87.             }
    88.         });
    89.     });

    The username has been checked across three ways firstly your username should be between 6 and 30 characters. Secondly it should contain only alphabet letters  no other characters  allowed like numbers. And thirdly, it should not be empty. For email it is necessary that it should not be empty as well as a valid email. The password is a bit complex and tricky to check as it has many cases but validator handles it beautifully. Have a look at the password section, the password should not be empty, and it does not contain your username and it also check the confirm password.

    This is all about demo but this is the start there are many complex things which are handled through the use of this validator script.

    Final Output after implementing bootstrap validator.

    Convert HTML String To PDF Via iTextSharp Library And Download


    In this article we will see how we can convert a string of data to PDF and then send email with attached copy of generated PDF in C#.
    Firstly, we can convert the string of data to PDF by using Popular Library for rendering PDF in ItextSharp. Secondly, we can download / save the converted PDF by using HTTP Response Class which provides response to client and contains information about response in the form of headers and other piece of necessary information.
    So, lets start to  build our first step,
    Step 1: Convert  HTML String to PDF,
    In this step we will first create a button which will do the rest of the work on Click event.
    Let’s create the button to perform the required operation.
    1. <asp:Button ID=“btn_PDFEmail” runat=“server” Text=“Convert HTML to PDF and Send Email with Attachment” OnClick=“btn_PDFEmail_Click” />

    The UI view looks like the following:

     
    So our front end is all set and we need to apply the cs logic to perform operation.
    Let’s start building HTML string.
    1. StringBuilder sb = new StringBuilder();
    2.                    sb.Append(“<header class=’clearfix’>”);
    3.                    sb.Append(“<h1>INVOICE</h1>”);
    4.                    sb.Append(

      );

    5.                    sb.Append(
      Company Name

      “);

    6.                    sb.Append(
      455 John Tower,
       AZ 85004, US

      “);

    7.                    sb.Append(
      (602) 519-0450

      “);

    8.                    sb.Append(

      “);

    9.                    sb.Append(“</div>”);
    10.                    sb.Append(

      );

    11.                    sb.Append(
      PROJECT Website development

      “);

    12.                    sb.Append(
      CLIENT John Doe

      “);

    13.                    sb.Append(
      ADDRESS 796 Silver Harbour, TX 79273, US

      “);

    14.                    sb.Append(

      “);

    15.                    sb.Append(
      DATE April 13, 2016

      “);

    16.                    sb.Append(
      DUE DATE May 13, 2016

      “);

    17.                    sb.Append(“</div>”);
    18.                    sb.Append(“</header>”);
    19.                    sb.Append(“<main>”);
    20.                    sb.Append(“<table>”);
    21.                    sb.Append(“<thead>”);
    22.                    sb.Append(“<tr>”);
    23.                    sb.Append(“<th class=’service’>SERVICE</th>”);
    24.                    sb.Append(“<th class=’desc’>DESCRIPTION</th>”);
    25.                    sb.Append(“<th>PRICE</th>”);
    26.                    sb.Append(“<th>QTY</th>”);
    27.                    sb.Append(“<th>TOTAL</th>”);
    28.                    sb.Append(“</tr>”);
    29.                    sb.Append(“</thead>”);
    30.                    sb.Append(“<tbody>”);
    31.                    sb.Append(“<tr>”);
    32.                    sb.Append(“<td class=’service’>Design</td>”);
    33.                    sb.Append(“<td class=’desc’>Creating a recognizable design solution based on the company’s existing visual identity</td>”);
    34.                    sb.Append(“<td class=’unit’>$400.00</td>”);
    35.                    sb.Append(“<td class=’qty’>2</td>”);
    36.                    sb.Append(“<td class=’total’>$800.00</td>”);
    37.                    sb.Append(“</tr>”);
    38.                    sb.Append(“<tr>”);
    39.                    sb.Append(“<td colspan=’4′>SUBTOTAL</td>”);
    40.                    sb.Append(“<td class=’total’>$800.00</td>”);
    41.                    sb.Append(“</tr>”);
    42.                    sb.Append(“<tr>”);
    43.                    sb.Append(“<td colspan=’4′>TAX 25%</td>”);
    44.                    sb.Append(“<td class=’total’>$200.00</td>”);
    45.                    sb.Append(“</tr>”);
    46.                    sb.Append(“<tr>”);
    47.                    sb.Append(“<td colspan=’4′ class=’grand total’>GRAND TOTAL</td>”);
    48.                    sb.Append(“<td class=’grand total’>$1,000.00</td>”);
    49.                    sb.Append(“</tr>”);
    50.                    sb.Append(“</tbody>”);
    51.                    sb.Append(“</table>”);
    52.                    sb.Append(

      );

    53.                    sb.Append(
      NOTICE:

      “);

    54.                    sb.Append(
      A finance charge of 1.5% will be made on unpaid balances after 30 days.

      “);

    55.                    sb.Append(“</div>”);
    56.                    sb.Append(“</main>”);
    57.                    sb.Append(“<footer>”);
    58.                    sb.Append(“Invoice was created on a computer and is valid without the signature and seal.”);
    59.                    sb.Append(“</footer>”);

    I am using StringBuilder class for generating HTML string and pass to the parser for generating PDF. Before proceeding further add the following references.

    1. using iTextSharp.text;
    2. using iTextSharp.text.html.simpleparser;
    3. using iTextSharp.text.pdf;
    4. using System.Configuration;
    5. using System.IO;
    6. using System.Linq;
    7. using System.Net;
    8. using System.Net.Mail;
    9. using System.Text;
    10. using System.Web;
    Now let’s write the code for generating in-memory PDF from HTML string.
    1. StringReader sr = new StringReader(sb.ToString());
    2.                    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
    3.                    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
    4.                    using (MemoryStream memoryStream = new MemoryStream())
    5.                    {
    6.                        PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
    7.                        pdfDoc.Open();
    8.                        htmlparser.Parse(sr);
    9.                        pdfDoc.Close();
    10.                        byte[] bytes = memoryStream.ToArray();
    11.                        memoryStream.Close();
    12.                    }

    Now let’s understand the Line of code. After building the string we can read from the string as we have passed the generated string.

    1. StringReader sr = new StringReader(sb.ToString());
    We are building the PDF document with default page size of A4 Page size.
    1. Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);

    Parse the HTML string using HTMLWorker of Itextsharp library,

    1. HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

    Use the memory stream to reside the file in-memory.

    1. using (MemoryStream memoryStream = new MemoryStream())
    2.                     {
    3. }
    Now we get the PDF and memory stream to create the instance and write the document. Then first open the document, parse by the html worker and then after completing the work close the document (dispose off the resources) managing the resource properly.
    1. PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
    2.                        pdfDoc.Open();
    3.                        htmlparser.Parse(sr);
    4.                        pdfDoc.Close();

    Now we add the created document to the memory stream and use the bytes of it as a in-memory reference to later attach to the email.

    1. byte[] bytes = memoryStream.ToArray();
    2.                memoryStream.Close();

    This is all about first step which will generate the PDF file and we will later use this as an attachment.

    First Output
    Now let’s proceed to the second step:
    Step 2:

    In the next step we will see how we can download the in memory generated PDF File.
    As we are using the stream so that we use response method to send the information to the client.
    1. // Clears all content output from the buffer stream
    2.                   Response.Clear();
    3.  // Gets or sets the HTTP MIME type of the output stream.
    4.                   Response.ContentType = “application/pdf”;
    5. // Adds an HTTP header to the output stream
    6.                   Response.AddHeader(“Content-Disposition”“attachment; filename=Invoice.pdf”);
    7. //Gets or sets a value indicating whether to buffer output and send it after
      // the complete response is finished processing.
    8.                   Response.Buffer = true;
    9.      // Sets the Cache-Control header to one of the values of System.Web.HttpCacheability.
    10.                   Response.Cache.SetCacheability(HttpCacheability.NoCache);
    11.  // Writes a string of binary characters to the HTTP output stream. it write the generated bytes .
    12.                   Response.BinaryWrite(bytes);
    13. // Sends all currently buffered output to the client, stops execution of the
      // page, and raises the System.Web.HttpApplication.EndRequest event.
    14.                   Response.End();
    15.  // Closes the socket connection to a client. it is a necessary step as you must close the response after doing work.its best approach.
    16.                   Response.Close();

    Final Output: