Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, May 1, 2013

How to Select from Data Table in C#

DataTable Object has a Select Method which acts like Where in SQL Server. So if you want to write filter query you write the column name directly without Where and the filter expression you want.

I made a simple example that creates a DataTable and fill it with some data and use Select method:

DataTable dt = new DataTable("MyDataTable");
dt.Columns.Add(new DataColumn("ID", typeof(int)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));

for (int i = 0; i < 10; i++)
{
    DataRow dr = dt.NewRow();
    dr["ID"] = i + 1;
    dr["Name"] = "Name " + (i + 1).ToString();

    dt.Rows.Add(dr);
}

DataRow[] rows = dt.Select("ID = 3");

Friday, February 1, 2013

How to know if a Date is in range between two Dates in C#

Let's say that we have a DateTime = Jan 1, 2012 and we want to check if this date is between 2 other dates.
The following code example Implements IRange interface that can be used with Integers too.
public interface IRange
    {
        T Start { get; }
        T End { get; }
        bool WithInRange(T value);
        bool WithInRange(IRange range);
    }

    public class DateRange : IRange
    {
        public DateTime Start { get; set; }
        public DateTime End { get; set; }

        public DateRange(DateTime start, DateTime end)
        {
            Start = start;
            End = end;
        }

        public bool WithInRange(DateTime value)
        {
            return (Start <= value) && (value <= End);
        }

        public bool WithInRange(IRange range)
        {
            return (Start <= range.Start) && (range.End <= End);
        }
    }

This is how to use this class function:
DateTime startDate = new DateTime(2011, 1, 1);
        DateTime endDate = new DateTime(2013, 1, 1);
        DateTime inRange = new DateTime(2012, 1, 1);
        DateTime outRange = new DateTime(2010, 1, 1);
        DateRange range = new DateRange(startDate, endDate);
        bool yes = range.WithInRange(inRange);
        bool no = range.WithInRange(outRange);

Friday, June 1, 2012

How to Replace the First Instance of a String in C#

Assume that you have a string and you expect that this string might have some duplicated instances.

String.Replace() is very good Function, but it will replace all the instances of the string. So to accomplish this you need to replace the first instance you find.

The next code example can be used as a helper method in your project if you are dealing with strings frequently:

public static string ReplaceFirst(string str, string term, string replace)
{
    int position = str.IndexOf(term);

    if (position < 0)
    {
        return str;
    }

    str = str.Substring(0, position) + replace + str.Substring(position + term.Length);

    return str;
}

Tuesday, May 1, 2012

How to Programmatically create iFrame in ASP.NET

Sometimes we may need to create iFrames and use it within GridView or Repeater, and we want to pass some values to it.
This example will show you how to create iFrame Programmatically and add it to a PlaceHolder.

HtmlGenericControl myFrame = new HtmlGenericControl();

myFrame.TagName = "IFRAME";
myFrame.Attributes["src"] = "MyPagePath";
myFrame.Attributes["id"] = "myFrame1";
myFrame.Attributes["name"] = "myFrame1";
myFrame.Attributes["width"] = "500";
myFrame.Attributes["height"] = "500";
myFrame.Attributes["class"] = "frames";

myPlaceHolder.Controls.Add(myFrame);

Thursday, March 1, 2012

How to Convert SqlDataSource to DataTable and DataView in C#

Sometimes I want to use SqlDataSource  returned data programmatically and here is how you can do this,

In this example I will assume that SqlDataSource  ID is SqlDataSource1 which is the default ID:
DataSourceSelectArguments args = new DataSourceSelectArguments();
DataView view = SqlDataSource1.Select(args) as DataView; 
DataTable dt = view.ToTable();

Wednesday, November 9, 2011

How to Completely Disable Viewstate in ASP.NET

I tried to disable Viewstate of a website by set EnableViewState Page directive to false.
But when I get the Page HTML Source I found the following line:

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"
 value="/wEPDwUKMTY1NDU2MTA1MmRk7eWz8DBE7zF7MW8sS4wNndKCr5gBJPZZ/LOS1KIbBo4=" /> 

protected override void SavePageStateToPersistenceMedium(object viewState)
{

}

protected override object LoadPageStateFromPersistenceMedium()
{
  return null;
}

Wednesday, October 19, 2011

How to Copy some rows from a GridView to another in ASP.NET

A junior developer asked me can I select some rows from a GridView and copy them to another GridView?
I told him sure all you have to do is to create a DataTable and the columns that will be added to it.
Now you will loop for each row in the first GridView then add the selected rows to the DataTable.
Set the DataSource of the other GirdView to DataTable.
Here is the code that would do the trick:
DataTable dt = new DataTable();
DataRow dr;
       
dt.Columns.Add(new DataColumn("FirstName"));
dt.Columns.Add(new DataColumn("LastName"));
      
foreach (GridViewRow row in GridViewEmployees.Rows)
 {            
  if(((CheckBox)row.Cells[3].FindControl("CheckBox")).Checked == true)
   {
    dr = dt.NewRow();
    dr["ColumnName1"] = ((Label)row.Cells[0].FindControl("Label")).Text;
    dr["ColumnName2"] = ((Label)row.Cells[1].FindControl("Label")).Text;
    dt.Rows.Add(dr);
   }
 }
 
GridViewManagers.DataSource = dt;
GridViewManagers.DataBind();

Thursday, September 1, 2011

Select Drop Down List Item After Declarative Databinding

The new declarative controls of ASP.NET 2.0 are really great. However, there are some times, when it may not seem so.
Let's say you have a DropDownList which is bound by a DataSource control. Also, you have other pages hitting this page, with querystrings, and based on the item in the querystring, you'd like the to select that item.
In ASP.NET 1.1, you'd just code it, and select it after the code, or in the Pre-render event.
DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByText(Request.Querystring("YourQuerystring"));

Saturday, January 1, 2011

How to check SQL Server Database is Exists using C#

The following method using sys. schema and views such as sys.databases and sys.tables.
As we know that the old style sysobjects and sysdatabases and those catalog views have been deprecated since SQL Server 2005.
private static bool CheckDatabaseExists(string connectionString, string databaseName)
{
    string sqlQuery;
    bool result = false;

    try
    {
        SqlConnection conn = new SqlConnection(connectionString);
        sqlQuery = string.Format("SELECT database_id FROM sys.databases WHERE Name = '{0}'", databaseName);

        using (conn)
        {
            using (SqlCommand cmd = new SqlCommand(sqlQuery, conn))
            {
                conn.Open();
                int databaseID = (int)cmd.ExecuteScalar();
                conn.Close();
                result = (databaseID > 0);
            }
        }
    }
    catch (Exception ex)
    {
        result = false;
    }
    return result;
}

Saturday, May 1, 2010

How to convert Data Row to Data Row View

Converting Data Row to Data Row View is not possible, but we can go around this by using DefaultView property of the Data Row Table.

The following code example demonstrate how to get Data Row View out of Data Row:
DataTable dt = new DataTable();

dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));

for (int i = 0; i < 10; i++)
{
 DataRow tempDR = dt.NewRow();
 tempDR["ID"] = (i + 1);
 tempDR["Name"] = "Name " + (i + 1).ToString();
 dt.Rows.Add(tempDR);
}

DataRow dr = dt.Rows[1]; 
DataRowView drv = dr.Table.DefaultView[dt.Rows.IndexOf(dr)];

Monday, February 1, 2010

How to remove HTML Tags from string in C#

I will show you three different methods to remove HTML tags from string in C#:

1. By using Regex:
public static string RemoveHTMLTags(string html)
{
 return Regex.Replace(html, "<.*?>", string.Empty);
}

2. By using Compiled Regex for better performance:
static Regex htmlRegex = new Regex("<.*?>", RegexOptions.Compiled);
   
public static string RemoveHTMLTagsCompiled(string html)
{
 return htmlRegex.Replace(html, string.Empty);
}

3. By using Char Array for faster performance for several HTML files:
public static string RemoveHTMLTagsCharArray(string html)
{
 char[] charArray = new char[html.Length];
 int index = 0;
 bool isInside = false;
  
 for (int i = 0; i < html.Length; i++)
  {
   char left = html[i];

   if (left == '<')
    {
     isInside = true;
      continue;
    }

   if (left == '>')
    {
     isInside = false;
     continue;
    }

   if (!isInside)
    {
     charArray[index] = left;
     index++;
    }
   }

 return new string(charArray, 0, index);
}

Tuesday, August 11, 2009

What is the difference between Convert.ToInt32() and Int32.Parse()

Convert.ToInt32(string); and Int32.Parse(string); produce the same results except when the string is actually a null.

In this case, Int32.Parse(null) throws an ArgumentNullException, but Convert.ToInt32(null) returns a zero.

So which one is better to use?

Waiting for your comments...

Tuesday, February 3, 2009

How to Access controls on Master Pages from Content Pages in ASP .NET

We will assume that we have a Label control called "Label1" on your Master Page, you might want to change the text of that Label.
To do that write this code in your content page:
Label lbl = new Label();
lbl = (Label)Master.FindControl("Label1");
lbl.Text = "Text";
Of course, this is all assuming the label is OUTSIDE the ContentPlaceHolder

Thursday, January 29, 2009

Encryption in C# .NET

This class uses a symmetric key algorithm (Rijndael/AES) to encrypt and decrypt data. As long as encryption and decryption routines use the same parameters to generate the keys, the keys are guaranteed to be the same.

In a real-life application, this may not be the most efficient way of handling encryption, so as soon as you feel comfortable with it you may want to redesign this class.
public class Encryption
{
    /// 
    /// Encrypts specified text using Rijndael symmetric key algorithm
    /// and returns a base64-encoded result.
    /// 
    /// 
    /// Plaintext value to be encrypted.
    /// 
    /// 
    /// Passphrase from which a pseudo-random password will be derived. The
    /// derived password will be used to generate the encryption key.
    /// Passphrase can be any string. In this example we assume that this
    /// passphrase is an ASCII string.        
    /// 
    /// 
    /// Salt value used along with passphrase to generate password. Salt can
    /// be any string. In this example we assume that salt is an ASCII string.
    /// 
    /// 
    /// Hash algorithm used to generate password. Allowed values are: "MD5" and
    /// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
    /// 
    /// 
    /// Number of iterations used to generate password. One or two iterations
    /// should be enough.
    ///
    /// 
    /// Initialization vector (or IV). This value is required to encrypt the
    /// first block of plaintext data. For RijndaelManaged class IV must be
    /// exactly 16 ASCII characters long.
    ///
    /// 
    /// Size of encryption key in bits. Allowed values are: 128, 192, and 256.
    /// Longer keys are more secure than shorter keys.
    ///
    /// 
    /// Encrypted value formatted as a base64-encoded string.
    /// 
    public string Encrypt(string plainText, string passPhrase, string saltValue, string hashAlgorithm, int passwordIterations, string initVector, int keySize)
    {
        // Convert strings into byte arrays.
        // Let us assume that strings only contain ASCII codes.
        // If strings include Unicode characters, use Unicode, UTF7, or UTF8
        // encoding.
        byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
        byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);

        // Convert our plaintext into a byte array.
        // Let us assume that plaintext contains UTF8-encoded characters.
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

        // First, we must create a password, from which the key will be derived.
        // This password will be generated from the specified passphrase and
        // salt value. The password will be created using the specified hash
        // algorithm. Password creation can be done in several iterations.
        PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);

        // Use the password to generate pseudo-random bytes for the encryption
        // key. Specify the size of the key in bytes (instead of bits).
        byte[] keyBytes = password.GetBytes(keySize / 8);

        // Create uninitialized Rijndael encryption object.
        RijndaelManaged symmetricKey = new RijndaelManaged();

        // It is reasonable to set encryption mode to Cipher Block Chaining
        // (CBC). Use default options for other symmetric key parameters.
        symmetricKey.Mode = CipherMode.CBC;

        // Generate encryptor from the existing key bytes and initialization
        // vector. Key size will be defined based on the number of the key
        // bytes.
        ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);

        // Define memory stream which will be used to hold encrypted data.
        MemoryStream memoryStream = new MemoryStream();

        // Define cryptographic stream (always use Write mode for encryption).
        CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
        // Start encrypting.
        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);

        // Finish encrypting.
        cryptoStream.FlushFinalBlock();

        // Convert our encrypted data from a memory stream into a byte array.
        byte[] cipherTextBytes = memoryStream.ToArray();

        // Close both streams.
        memoryStream.Close();
        cryptoStream.Close();

        // Convert encrypted data into a base64-encoded string.
        string cipherText = Convert.ToBase64String(cipherTextBytes);

        // Return encrypted string.
        return cipherText;
    }

    /// 
    /// Decrypts specified ciphertext using Rijndael symmetric key algorithm.
    /// 
    /// 
    /// Base64-formatted ciphertext value.
    ///
    /// 
    /// Passphrase from which a pseudo-random password will be derived. The
    /// derived password will be used to generate the encryption key.
    /// Passphrase can be any string. In this example we assume that this
    /// passphrase is an ASCII string.
    ///
    /// 
    /// Salt value used along with passphrase to generate password. Salt can
    /// be any string. In this example we assume that salt is an ASCII string.
    ///
    /// 
    /// Hash algorithm used to generate password. Allowed values are: "MD5" and
    /// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
    ///
    /// 
    /// Number of iterations used to generate password. One or two iterations
    /// should be enough.
    ///
    /// 
    /// Initialization vector (or IV). This value is required to encrypt the
    /// first block of plaintext data. For RijndaelManaged class IV must be
    /// exactly 16 ASCII characters long.
    ///
    /// 
    /// Size of encryption key in bits. Allowed values are: 128, 192, and 256.
    /// Longer keys are more secure than shorter keys.
    ///
    /// 
    /// Decrypted string value.
    /// 
    /// 
    /// Most of the logic in this function is similar to the Encrypt
    /// logic. In order for decryption to work, all parameters of this function
    /// - except cipherText value - must match the corresponding parameters of
    /// the Encrypt function which was called to generate the
    /// ciphertext.
    /// 
    public string Decrypt(string cipherText, string passPhrase, string saltValue, string hashAlgorithm, int passwordIterations, string initVector, int keySize)
    {
        // Convert strings defining encryption key characteristics into byte
        // arrays. Let us assume that strings only contain ASCII codes.
        // If strings include Unicode characters, use Unicode, UTF7, or UTF8
        // encoding.
        byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
        byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);

        // Convert our ciphertext into a byte array.
        byte[] cipherTextBytes = Convert.FromBase64String(cipherText);

        // First, we must create a password, from which the key will be
        // derived. This password will be generated from the specified
        // passphrase and salt value. The password will be created using
        // the specified hash algorithm. Password creation can be done in
        // several iterations.
        PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);

        // Use the password to generate pseudo-random bytes for the encryption
        // key. Specify the size of the key in bytes (instead of bits).
        byte[] keyBytes = password.GetBytes(keySize / 8);

        // Create uninitialized Rijndael encryption object.
        RijndaelManaged symmetricKey = new RijndaelManaged();

        // It is reasonable to set encryption mode to Cipher Block Chaining
        // (CBC). Use default options for other symmetric key parameters.
        symmetricKey.Mode = CipherMode.CBC;

        // Generate decryptor from the existing key bytes and initialization
        // vector. Key size will be defined based on the number of the key
        // bytes.
        ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);

        // Define memory stream which will be used to hold encrypted data.
        MemoryStream memoryStream = new MemoryStream(cipherTextBytes);

        // Define cryptographic stream (always use Read mode for encryption).
        CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);

        // Since at this point we don't know what the size of decrypted data
        // will be, allocate the buffer long enough to hold ciphertext;
        // plaintext is never longer than ciphertext.
        byte[] plainTextBytes = new byte[cipherTextBytes.Length];

        // Start decrypting.
        int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);

        // Close both streams.
        memoryStream.Close();
        cryptoStream.Close();

        // Convert decrypted data into a string.
        // Let us assume that the original plaintext string was UTF8-encoded.
        string plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);

        // Return decrypted string.
        return plainText;
    }
}

Tuesday, January 27, 2009

Cross Page postback in ASP.NET

This is a new feature in ASP .NET 2.0. The IButtonControl Interface contains a new property called PostBackUrl which points to the page to which the current page will postback, Button, ImageButton and LinkButton implements this interface and exposes the cross page postback functionality.

When user clicks the button in the current page will postback to the specified page which can access the source page controls through Page.PreviousPage property which returns the reference of previous page, once got the reference of previous page you can use the FindControl method to get the reference of particular or you can expose public properties from source page to provide the type safe access.

For example:
Label1.Text =((TextBox)this.PreviousPage.FindControl("TextBox1")).Text;

In order to provide the strongly typed access to previous page, you can specify the previous page in PreviousPageType directive; since you have strongly typed reference of previous page you can now easily access its public members without any typecasting.

Example:

Create two aspx pages name the first one step_1.aspx and the other step_2.aspx
In the page step_1.aspx put a Text Box named TextBox1
Expose the following properties in code behind file:
public TextBox MyName { get { return TextBox1; } }

In the step_2.aspx put this code in the aspx code:
<%@ PreviousPageType VirtualPath="~/step_1.aspx" %>
Then in the page load event in step_2.aspx page write this code:
Response.Write(this.PreviousPage.MyName.Text);

Wednesday, October 15, 2008

How to Send email in ASP.NET using C# through Gmail Outgoing Mail Server

SmtpClient oSmtpClient = new SmtpClient();
oSmtpClient.Host = "smtp.gmail.com"; //The Outgoing mail server
oSmtpClient.Credentials = new NetworkCredential("Your Email", "Your password");
oSmtpClient.Port = 587;
oSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
oSmtpClient.EnableSsl = true;
MailMessage msg = new MailMessage("Email From", "Email To");
msg.Subject = "Subject goes here";
msg.Body = "Body goes here";
oSmtpClient.Send(msg);

Thursday, September 25, 2008

How to Make a Captcha Image in C# .NET



What Captcha stand for?
Completely Automated Public Turing test to tell Computers and Humans Apart.
The Captcha technology help you to make sure your site is reasonably secure against automated attacks.

Write the following code in a class named Captcha :
public class Captcha
{
    //make the captcha image for text
    public Bitmap MakeCaptchaImage(string txt, int width, int hight, string fontFamilyName)
    {
        //make the bitmap and the associated Graphics object
        Bitmap bm = new Bitmap(width, hight);
        Graphics gr = Graphics.FromImage(bm);
        gr.SmoothingMode = SmoothingMode.HighQuality;
        RectangleF recF = new RectangleF(0, 0, width, hight);
        Brush br;
        br = new HatchBrush(HatchStyle.SmallConfetti, Color.LightGray, Color.White);
        gr.FillRectangle(br, recF);
        SizeF text_size;
        Font the_font;
        float font_size = hight + 1;
        do
        {
            font_size -= 1;
            the_font = new Font(fontFamilyName, font_size, FontStyle.Bold, GraphicsUnit.Pixel);
            text_size = gr.MeasureString(txt, the_font);
        }
        while ((text_size.Width > width) || (text_size.Height > hight));
        // Center the text.
        StringFormat string_format = new StringFormat();
        string_format.Alignment = StringAlignment.Center;
        string_format.LineAlignment = StringAlignment.Center;

        // Convert the text into a path.
        GraphicsPath graphics_path = new GraphicsPath();
        graphics_path.AddString(txt, the_font.FontFamily, 1, the_font.Size, recF, string_format);

        //Make random warping parameters.
        Random rnd = new Random();
        PointF[] pts = { new PointF((float)rnd.Next(width) / 4, (float)rnd.Next(hight) / 4), new PointF(width - (float)rnd.Next(width) / 4, (float)rnd.Next(hight) / 4), new PointF((float)rnd.Next(width) / 4, hight - (float)rnd.Next(hight) / 4), new PointF(width - (float)rnd.Next(width) / 4, hight - (float)rnd.Next(hight) / 4) };
        Matrix mat = new Matrix();
        graphics_path.Warp(pts, recF, mat, WarpMode.Perspective, 0);

        // Draw the text.
        br = new HatchBrush(HatchStyle.LargeConfetti, Color.LightGray, Color.DarkGray);
        gr.FillPath(br, graphics_path);

        // Mess things up a bit.
        int max_dimension = System.Math.Max(width, hight);
        for (int i = 0; i <= (int)width * hight / 30; i++)
        {
            int X = rnd.Next(width);
            int Y = rnd.Next(hight);
            int W = (int)rnd.Next(max_dimension) / 50;
            int H = (int)rnd.Next(max_dimension) / 50;
            gr.FillEllipse(br, X, Y, W, H);
        }
        for (int i = 1; i <= 5; i++)
        {
            int x1 = rnd.Next(width);
            int y1 = rnd.Next(hight);
            int x2 = rnd.Next(width);
            int y2 = rnd.Next(hight);
            gr.DrawLine(Pens.DarkGray, x1, y1, x2, y2);
        }
        for (int i = 1; i <= 5; i++)
        {
            int x1 = rnd.Next(width);
            int y1 = rnd.Next(hight);
            int x2 = rnd.Next(width);
            int y2 = rnd.Next(hight);
            gr.DrawLine(Pens.LightGray, x1, y1, x2, y2);
        }
        graphics_path.Dispose();
        br.Dispose();
        the_font.Dispose();
        gr.Dispose();
        return bm;
    }
}
Write the following code in the page load event:
Captcha oCaptcha = new Captcha();
Random rnd = new Random();
string[] s = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
int i;
StringBuilder sb = new StringBuilder(4);
for (i = 0; i <= 4; i++)
{
    sb.Append(s[rnd.Next(1, s.Length)]);
}
Bitmap bm = oCaptcha.MakeCaptchaImage(sb.ToString(), 200, 100, "Arial");
string url = Server.MapPath("~/Images/Captcha.bmp");
bm.Save(url);
Image1.ImageUrl = "~/Images/Captcha.bmp";

Friday, September 5, 2008

How To Make Previous Calendar Dates Not Selectable in ASP.NET

In order to make all dates before the current date, not able to be selected, in the onDayRender event for your Calendar:
if (e.Day.Date < DateTime.Today)
{
    e.Day.IsSelectable = false;
}
To make it more obvious to the end user, also add:
e.Cell.BackColor = Drawing.Color.GhostWhite;
e.Cell.ForeColor = Drawing.Color.Gainsboro;

Thursday, August 7, 2008

The string function "EndsWith" is case-sensitive

Did you know that "EndsWith" String function is case-sensitive even in VB.NET?

You need to make sure you are looking for the correct string, since 'abc' with case-sensitivity is different than 'ABC'.

So, if your function is looking for 'abc', you must make sure that you make adjustments to the string, in order to catch things like this.

To do this, you would need to change:
myString.EndsWith("abc");
to
myString.ToLower.EndsWith("abc");

Monday, May 19, 2008

How to Generate Barcode in ASP.NET

I will show you how to generate bar code images using .NET Built-in classes.
You will not need a Third Party tool or external DLL library.
As we all know that Barcodes depends on Fonts, there are plenty of them used for Barcodes.
The most famous font for Barcode is "Code 39" and anyone can download it for free.
After you download the font and install it to Windows Fonts, use the following method to generate Barcode images:
public void GenerateBarcodes(string productCode, string productName, string productPrice)
{
    Font stringFornt = new Font("Arial", 15, FontStyle.Bold, GraphicsUnit.Point);
    Font barcodeFont = new Font("Free 3 of 9", 40, FontStyle.Regular, GraphicsUnit.Point);
    Bitmap barcodeImage = new Bitmap(140, 110);
    Graphics graph = Graphics.FromImage(barcodeImage);

    graph = Graphics.FromImage(barcodeImage);
    graph.Clear(Color.White);
    graph.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;
    graph.DrawString(productName, stringFornt, new SolidBrush(Color.Black), 10, 0);
    graph.DrawString(productCode, barcodeFont, new SolidBrush(Color.Black), 0, 30);
    graph.DrawString(productCode, stringFornt, new SolidBrush(Color.Black), 10, 70);
    graph.DrawString("#CODE#" + productPrice, stringFornt, new SolidBrush(Color.Black), 10, 90);
    graph.Flush();

    barcodeImage.Save(Server.MapPath("~/BarcodeImages/barcode.jpg"), ImageFormat.Jpeg);

    barcodeImage.Dispose();
    graph.Dispose();
    barcodeFont.Dispose();
}