Difference Between Constant and ReadOnly and Static

Constant and ReadOnly keyword are used to make a field constant which value cannot be modified. Static keyword is used to make members static that can be shared by all the class objects. In this article, I am going to explain the difference among these three.

Constant

Constant fields or local variables must be assigned a value at the time of declaration and after that they cannot be modified. By default constant are static, hence you cannot define a constant type as static.


  1. public const int X = 10;


A const field is a compile-time constant. A constant field or local variable can be initialized with a constant expression which must be fully evaluated at compile time.


  1. void Calculate(int Z)

  2. {

  3. const int X = 10, X1 = 50;

  4. const int Y = X + X1; //no error, since its evaluated a compile time

  5. const int Y1 = X + Z; //gives error, since its evaluated at run time

  6. }


You can apply const keyword to built-in value types (byte, short, int, long, char, float, double, decimal, bool), enum, a string literal, or a reference type which can be assigned with a value null.


  1. const MyClass obj1 = null;//no error, since its evaluated a compile time

  2. const MyClass obj2 = new MyClass();//gives error, since its evaluated at run time


Constants can be marked as public, private, protected, internal, or protected internal access modifiers.
Use the const modifier when you sure that the value a field or local variable would not be changed.

ReadOnly

A readonly field can be initialized either at the time of declaration or with in the constructor of same class. Therefore, readonly fields can be used for run-time constants.


  1. class MyClass

  2. {

  3. readonly int X = 10; // initialized at the time of declaration

  4. readonly int X1;

  5.  

  6. public MyClass(int x1)

  7. {

  8. X1 = x1; // initialized at run time

  9. }

  10. }


Explicitly, you can specify a readonly field as static since, like constant by default it is not static. Readonly keyword can be apply to value type and reference type (which initialized by using the new keyword) both. Also, delegate and event could not be readonly.
Use the readonly modifier when you want to make a field constant at run time.

Static

The static keyword is used to specify a static member, which means static members are common to all the objects and they do not tied to a specific object. This keyword can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes.


  1. class MyClass

  2. {

  3. static int X = 10;

  4. int Y = 20;

  5. public static void Show()

  6. {

  7. Console.WriteLine(X);

  8. Console.WriteLine(Y); //error, since you can access only static members

  9. }

  10. }


Key points about Static keyword

  1. If the static keyword is applied to a class, all the members of the class must be static.
  2. Static methods can only access static members of same class. Static properties are used to get or set the value of static fields of a class.
  3. Static constructor can’t be parameterized and public. Static constructor is always a private default constructor which is used to initialize static fields of the class.

Convert Enum to Dictionary C#

While working through ,I have always faced problems where only of i could convert an enum to Dictionary. Here's how you do it.

Code:
/// <summary>
/// Converts Enumeration type into a dictionary of names and values
/// </summary>
/// <param name="t">Enum type</param>
public static IDictionary<string, int> EnumToDictionary(this Type t)
{
    if (t == null) throw new NullReferenceException();
    if (!t.IsEnum) throw new InvalidCastException("object is not an Enumeration");
    string[] names = Enum.GetNames(t);
    Array values = Enum.GetValues(t);
    return (from i in Enumerable.Range(0, names.Length)
            select new { Key = names[i], Value = (int)values.GetValue(i) })
                .ToDictionary(k => k.Key, k => k.Value);
}

Example:
var dictionary = typeof(UriFormat).EnumToDictionary();
/* returns
key => value
SafeUnescaped => 3
Unescaped => 2
UriEscaped => 1
*/

Creating Custom Validation using IValidatableObject (DataAnnotation) in ASP.NET MVC

.NET Framework provides a set of inbuilt data validation using DataAnnotation. 

But there might be cases where you might need to validate with your custom rules. Example of such case is like when you need to compare two values and one must be greater than (or less than another).

Here’s how you do it. 

You can change your Validate Function as per your need.
public class ViewModel: IValidatableObject
{
    [Required]
    public DateTime StartDate { get; set; }
    [Required]   
    public DateTime EndDate { get; set; }
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
       if (EndDate < StartDate)
       {
           return new ValidationResult(“EndDate must be greater than StartDate”);
       }
    }
}
Happy Coding!

Rebuilding MS SQL Log File

There are situation where you need to rebuild your Microsoft SQL Server’s transaction log file. Today we discuss about such situations and how we can resolve it. In production environments where lot of data is being handled, the possibility of increasing the log file size we can’t control. We can recover the space by running the shrink command. But there will be situations even after running the shrink command the size will not reduce or the total database performance will not improve. One more situation is that log file is getting removed accidentally. So what can we do now? This is where we need to think about rebuilding the log file. DBCC REBUILD_LOG command can be handy to rebuild the SQL log file.
One thing we need to make sure before running this command is that some how we need to have the database exists in SQL Server. Setting the database to emergency recovery mode will solve this problem. Databases which lost its log file accidentally can be directly set to emergency recover mode, but for the first case (log file performance issue) we need to follow the below steps.

  • Stop SQL Server.
  • Delete Log file (.LDF) file.
  • Start the SQL Server


Since the log file got deleted if you try to access the database it will throw error, so don’t try to access still the time it got rebuild. Now we see how we can set the database to emergency recovery mode. Run the following commands to do so. You have to run these commands under master database.

USE Master
GO

EXEC sp_configure 'allow updates', 1
RECONFIGURE WITH OVERRIDE
GO

BEGIN TRAN
UPDATE master..sysdatabases
SET status = status | 32768
WHERE name = 'DATABASE_NAME'
IF @@ROWCOUNT = 1
BEGIN COMMIT TRAN
RAISERROR('Emergency Mode Successfully Set', 0, 1)
END
ELSE
BEGIN ROLLBACK
RAISERROR('Setting Emergency Mode Failed', 16, 1)
END
GO

EXEC sp_configure 'allow updates', 0
RECONFIGURE WITH OVERRIDE
GO

Once you have finished running the above commands start SQL Server. Again don’t forget one thing “Don’t try to access the database.”

Above commands changed the database to emergency mode. Now run the following commands to rebuild the log file.

DBCC REBUILD_LOG(''DATABASE_NAME'','C:\Database\logfilename.ldf')
ALTER DATABASE 'DATABASE_NAME' SET MULTI_USER
GO

DBCC CHECKDB ('DATABASE_NAME')

A brand new transaction log file got created for your existing database from the scratch. You may lose some transactional integrity by using this method, but it is not really a big issue comparing to the situation you have.

Downloading Multiple Files as Zip Using Ionic.ZIp in ASP.NET MVC

We might come across a situation where we need to download multiple files and since a response cannot contain more than one file result; the best way to do is to zip all the content and download the zip file. 
Here's how we do it:
We need Ionic.Zip.Dll

We need 

using System.IO;
using Ionic.Zip;

 byte[] zipContent = null;
            using (var zip = new ZipFile())
            {
                zip.AddFile(Server.MapPath("~/Ionic.Zip1.dll"));
                zip.AddFile(Server.MapPath("~/Ionic.Zip2.dll"));

                //assign all zip content to content
                using (var ms = new MemoryStream())
                {
                    zip.Save(ms);
                    zipContent = ms.ToArray();
                }
            }
            Response.AppendHeader("Content-Disposition"string.Concat("inline; filename=\"""download.zip""\""));
            return File(zipContent, "zip");

Send Email using SMTP with attachments in ASP.NET

Sample Code

In this article I will explain how to send email with attachment in ASP.Net. The file to be send as attachment along with mail will be uploaded using FileUpload control and will be dynamically added as attachment in the MailMessage class object without saving in any folder on disk.
For this example, for sending emails Gmail SMTP Mail Server will be used. To send email with Gmail SMTP Server, you will need to use an email address and password of a valid Gmail account and along with that you will need the Gmail SMTP Mail Server settings.
HTML Markup
The HTML Markup has a form with some fields such as Recipient Email address, Subject, Body, Attachment, Gmail account email address, Gmail account password and a Button to send the email.
<table border=”0″ cellpadding=”0″ cellspacing=”0″>
    <tr>
        <td style=”width: 80px”>
            To:
        </td>
        <td>
            <asp:TextBox ID=”txtTo” runat=”server”></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
            Subject:
        </td>
        <td>
            <asp:TextBox ID=”txtSubject” runat=”server”></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td valign = “top”>
            Body:
        </td>
        <td>
            <asp:TextBox ID=”txtBody” runat=”server” TextMode = “MultiLine” Height = “150” Width = “200”></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
            File Attachment:
        </td>
        <td>
            <asp:FileUpload ID=”fuAttachment” runat=”server” />
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
            Gmail Email:
        </td>
        <td>
            <asp:TextBox ID=”txtEmail” runat=”server”></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
            Gmail Password:
        </td>
        <td>
            <asp:TextBox ID=”txtPassword” runat=”server” TextMode = “Password”></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
        </td>
        <td>
            <asp:Button Text=”Send” OnClick=”SendEmail” runat=”server” />
        </td>
    </tr>
</table
MailMessage Class Properties
Following are the required properties of the MailMessage class.
From – Sender’s email address
To – Recipient(s) Email Address
CC – Carbon Copies (if any)
BCC – Blind Carbon Copies (if any)
Subject – Subject of the Email 
Body – Body of the Email
IsBodyHtml – Specify whether body contains text or HTML mark up.
Attachments – Attachments (if any)
ReplyTo – ReplyTo Email address.
SMTP Class Properties
Following are the properties of the SMTP class.
Host – SMTP Server URL (Gmail: smtp.gmail.com)
EnableSsl – Specify whether your host accepts SSL Connections (Gmail: True)
UseDefaultCredentials – Set to True in order to allow authentication based on the Credentials of the Account used to send emails
Credentials – Valid login credentials for the SMTP server (Gmail: email address and password)
Port – Port Number of the SMTP server (Gmail: 587)
Namespaces
You will need to import the following namespaces
C#
using System.IO;
using System.Net;
using System.Net.Mail;
VB.Net
Imports System.IO
Imports System.Net
Imports System.Net.Mail
Sending email with attachment using Gmail SMTP Account
Below is the code to send email using Gmail account and Gmail SMTP server in ASP.Net, the Recipient email address (to), the Sender email address (from), Subject and Body is fetched from their respective fields.
Then all these values are set into an object of the MailMessage class.
For attaching a File as attachment to the email, one has to select the File to be send as attachment using FileUpload control.
If the FileUpload control has attachment then the attachment is added to the Attachments List of the MailMessage Object.
You will notice that the File is directly added as attachment without saving it on disk, this is possible since the file data is extracted from the FileUpload PostedFile InputStream property which belongs to the type System.IO.Stream. The second parameter supplied is the name of the File that has to be send as attachment which is extracted from the FileUpload control PostedFile FileName property.
After that an object of the SmtpClient class is created, where we need to set the settings of the Mail Server here Gmail is the Mail Server so we will set the Mail Settings of the Gmail SMTP Server.
Note: It is necessary to use the sender’s email address credentials while defining the Gmail SMTP Server Credentials as Gmail the sender’s email address must be equal to Gmail Username specified in credentials.

C#
protected void SendEmail(object sender, EventArgs e)
{
    using (MailMessage mm = new MailMessage(txtEmail.Text, txtTo.Text))
    {
        mm.Subject = txtSubject.Text;
        mm.Body = txtBody.Text;
        if (fuAttachment.HasFile)
        {
            string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
            mm.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, FileName));
        }
        mm.IsBodyHtml = false;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = “smtp.gmail.com”;
        smtp.EnableSsl = true;
        NetworkCredential NetworkCred = new NetworkCredential(txtEmail.Text, txtPassword.Text);
        smtp.UseDefaultCredentials = true;
        smtp.Credentials = NetworkCred;
        smtp.Port = 587;
        smtp.Send(mm);
        ClientScript.RegisterStartupScript(GetType(), “alert”, “alert(‘Email sent.’);”, true);
    }
}

Send Email using SMTP with attachments in ASP.NET

Sample Code

In this article I will explain how to send email with attachment in ASP.Net. The file to be send as attachment along with mail will be uploaded using FileUpload control and will be dynamically added as attachment in the MailMessage class object without saving in any folder on disk.
For this example, for sending emails Gmail SMTP Mail Server will be used. To send email with Gmail SMTP Server, you will need to use an email address and password of a valid Gmail account and along with that you will need the Gmail SMTP Mail Server settings.
HTML Markup
The HTML Markup has a form with some fields such as Recipient Email address, Subject, Body, Attachment, Gmail account email address, Gmail account password and a Button to send the email.
<table border=”0″ cellpadding=”0″ cellspacing=”0″>
    <tr>
        <td style=”width: 80px”>
            To:
        </td>
        <td>
            <asp:TextBox ID=”txtTo” runat=”server”></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
            Subject:
        </td>
        <td>
            <asp:TextBox ID=”txtSubject” runat=”server”></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td valign = “top”>
            Body:
        </td>
        <td>
            <asp:TextBox ID=”txtBody” runat=”server” TextMode = “MultiLine” Height = “150” Width = “200”></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
            File Attachment:
        </td>
        <td>
            <asp:FileUpload ID=”fuAttachment” runat=”server” />
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
            Gmail Email:
        </td>
        <td>
            <asp:TextBox ID=”txtEmail” runat=”server”></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
            Gmail Password:
        </td>
        <td>
            <asp:TextBox ID=”txtPassword” runat=”server” TextMode = “Password”></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
        </td>
        <td>
            <asp:Button Text=”Send” OnClick=”SendEmail” runat=”server” />
        </td>
    </tr>
</table
MailMessage Class Properties
Following are the required properties of the MailMessage class.
From – Sender’s email address
To – Recipient(s) Email Address
CC – Carbon Copies (if any)
BCC – Blind Carbon Copies (if any)
Subject – Subject of the Email 
Body – Body of the Email
IsBodyHtml – Specify whether body contains text or HTML mark up.
Attachments – Attachments (if any)
ReplyTo – ReplyTo Email address.
SMTP Class Properties
Following are the properties of the SMTP class.
Host – SMTP Server URL (Gmail: smtp.gmail.com)
EnableSsl – Specify whether your host accepts SSL Connections (Gmail: True)
UseDefaultCredentials – Set to True in order to allow authentication based on the Credentials of the Account used to send emails
Credentials – Valid login credentials for the SMTP server (Gmail: email address and password)
Port – Port Number of the SMTP server (Gmail: 587)
Namespaces
You will need to import the following namespaces
C#
using System.IO;
using System.Net;
using System.Net.Mail;
VB.Net
Imports System.IO
Imports System.Net
Imports System.Net.Mail
Sending email with attachment using Gmail SMTP Account
Below is the code to send email using Gmail account and Gmail SMTP server in ASP.Net, the Recipient email address (to), the Sender email address (from), Subject and Body is fetched from their respective fields.
Then all these values are set into an object of the MailMessage class.
For attaching a File as attachment to the email, one has to select the File to be send as attachment using FileUpload control.
If the FileUpload control has attachment then the attachment is added to the Attachments List of the MailMessage Object.
You will notice that the File is directly added as attachment without saving it on disk, this is possible since the file data is extracted from the FileUpload PostedFile InputStream property which belongs to the type System.IO.Stream. The second parameter supplied is the name of the File that has to be send as attachment which is extracted from the FileUpload control PostedFile FileName property.
After that an object of the SmtpClient class is created, where we need to set the settings of the Mail Server here Gmail is the Mail Server so we will set the Mail Settings of the Gmail SMTP Server.
Note: It is necessary to use the sender’s email address credentials while defining the Gmail SMTP Server Credentials as Gmail the sender’s email address must be equal to Gmail Username specified in credentials.

C#
protected void SendEmail(object sender, EventArgs e)
{
    using (MailMessage mm = new MailMessage(txtEmail.Text, txtTo.Text))
    {
        mm.Subject = txtSubject.Text;
        mm.Body = txtBody.Text;
        if (fuAttachment.HasFile)
        {
            string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
            mm.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, FileName));
        }
        mm.IsBodyHtml = false;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = “smtp.gmail.com”;
        smtp.EnableSsl = true;
        NetworkCredential NetworkCred = new NetworkCredential(txtEmail.Text, txtPassword.Text);
        smtp.UseDefaultCredentials = true;
        smtp.Credentials = NetworkCred;
        smtp.Port = 587;
        smtp.Send(mm);
        ClientScript.RegisterStartupScript(GetType(), “alert”, “alert(‘Email sent.’);”, true);
    }
}

Source:

Preserve Javasript State of controls after postback asp.net

While working with jquery controls like dynatree, chosen etc, you might have faced problems like once have set init event to controls through jquery and then postback (even in update panel), the control is reset by asp.net .This can be preserved upon postback by using simple jquery of asp.net.
The trick is to add an event ‘endRequest()’ event and initialize the jquery control here.
Below is an example:

    <script type="text/javascript">
        $(function () {
            Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function (sender, e) {
                //initialize your control here
                //example of chosen select
                $(".chosen-select").chosen({ max_selected_options: 5 });
            });
        });
    </script>