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

Monday, June 24, 2013

Export Datatable to Excel in C#

First, add the "Microsoft.Office.Interop.Excel" assembly reference in your project. Please make sure your project uses .Net Framework 4.0

Microsoft.Office.Interop.Excel.Application ExcelApp =
            new Microsoft.Office.Interop.Excel.Application();
            ExcelApp.Application.Workbooks.Add(Type.Missing);

            // Change properties of the Workbook 

            ExcelApp.Columns.ColumnWidth = 20;

            // Storing header part in Excel
            for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
            {
                ExcelApp.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
            }

            // Storing Each row and column value to excel sheet
            for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
            {
                for (int j = 0; j < dataGridView1.Columns.Count; j++)
                {
                    ExcelApp.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
                }
            }
            MessageBox.Show("Excel file created , you can find the file D:\\Employee Data.xlsx");
            ExcelApp.Visible = true;
            ExcelApp.ActiveWorkbook.SaveCopyAs("D:\\Employee Data.xlsx");
 ExcelApp.ActiveWorkbook.Saved = true;
 Marshal.FinalReleaseComObject(ExcelApp);

Enjoy..

Sunday, March 10, 2013

Action Filters in C# (MVC)

The goal of this tutorial is to explain action filters. An action filter is an attribute that you can apply to a controller action -- or an entire controller -- that modifies the way in which the action is executed. The ASP.NET MVC framework includes several action filters:


  • OutputCache – This action filter caches the output of a controller action for a specified amount of time.
  • HandleError – This action filter handles errors raised when a controller action executes.
  • Authorize – This action filter enables you to restrict access to a particular user or role.
You also can create your own custom action filters. For example, you might want to create a custom action filter in order to implement a custom authentication system. Or, you might want to create an action filter that modifies the view data returned by a controller action.
In this tutorial, you learn how to build an action filter from the ground up. We create a Log action filter that logs different stages of the processing of an action to the Visual Studio Output window..


Using an Action Filter



An action filter is an attribute. You can apply most action filters to either an individual controller action or an entire controller.
For example, the Data controller in Listing 1 exposes an action named Index() that returns the current time. This action is decorated with the OutputCache action filter. This filter causes the value returned by the action to be cached for 10 seconds.
using System;
using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
     public class DataController : Controller
     {
          [OutputCache(Duration=10)]
          public string Index()
          {
               return DateTime.Now.ToString("T");

          }
     }
}

Thursday, March 7, 2013

Profiling Database activity in Entity Framework

Profiling Database activity in Entity Framework

In Entity framework the LINQ to entities query can be traced by method, ToTraceString. For doing this first it needs to be converted in ObjectQuery.
var objQuery = from c in context.Customers where c.CustomerID == 3 select c;

var objectQuery=objQuery as System.Data.Objects.ObjectQuery;

Console.WriteLine(objectQuery.ToTraceString());

Saturday, March 31, 2012

Machine Key for Load Balancing

In my project there is requirement to change the field length eg CompanyCode. Problem is with this field name there are many tables who not created the foriegn keys and this field is used in many procedures and functions. To find the text company code I found this simple code:
/// <summary>
/// Version arguments to MachineKey.Generate() method.
/// </summary>
public enum MachineKeyVersion
{
    /// <summary>
    /// .NET version 1.1.
    /// </summary>
    Net1,

    /// <summary>
    /// .NET version 2.0 and up.
    /// </summary>
    Net2,
}

public class MachineKey
{
    /// <summary>
    /// Generates the contents of a machineKey element suitable for use in
    /// an ASP.NET web.config file.
    /// </summary>
    /// <param name="version">Indicates if keys should be generated for
    /// ASP.NET 1.1 or 2.0 and later.</param>
    public static string Generate(MachineKeyVersion version)
    {
        // Generate keys
        string validationKey = GenerateKey(64);
        string decryptionKey;
        if (version == MachineKeyVersion.Net1)
            decryptionKey = GenerateKey(24);
        else
            decryptionKey = GenerateKey(32);

        // Construct <machineKey> tag
        StringBuilder builder = new StringBuilder();
        builder.Append("<machineKey");
        builder.AppendFormat(" validationKey=\"{0}\"", validationKey);
        builder.AppendFormat(" decryptionKey=\"{0}\"", decryptionKey);
        builder.Append(" validation=\"SHA1\"");
        if (version == MachineKeyVersion.Net2)
            builder.Append(" decryption=\"AES\"");
        builder.Append(" />");
        return builder.ToString();
    }

    /// <summary>
    /// Generates a string of random hex digits of the specified
    /// number of bytes.
    /// </summary>
    /// <param name="length">Number of bytes to generate</param>
    protected static string GenerateKey(int length)
    {
        RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();
        byte[] buff = new byte[length];
        rngCsp.GetBytes(buff);
        StringBuilder sb = new StringBuilder(buff.Length * 2);
        for (int i = 0; i < buff.Length; i++)
            sb.Append(string.Format("{0:X2}", buff[i]));
        return sb.ToString();
    }
}
Now just call the MachineKey.Generate method
private void btnGenerate_Click(object sender, EventArgs e)
{
    MachineKeyVersion version;

    if (radNet1.Checked)
        version = MachineKeyVersion.Net1;
    else
        version = MachineKeyVersion.Net2;

    txtMachineKey.Text = MachineKey.Generate(version);
}

Reference: http://www.blackbeltcoder.com/Articles/asp/generating-a-machinekey-element 

Tuesday, March 20, 2012

Password in C# Console Application

Today my friend ask me how to make password field in C# Console Application.
I found the simple solution:
class PasswordExample
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Pls key in your Login ID");
            var loginid = Console.ReadLine();
            Console.WriteLine("Pls key in your Password");
            var password = ReadPassword();
            Console.Write("Your Password is:" + password);
            Console.ReadLine();
        }

      
     public static string ReadPassword()
        {
            string password = "";
            ConsoleKeyInfo info = Console.ReadKey(true);
            while (info.Key != ConsoleKey.Enter)
            {
                if (info.Key != ConsoleKey.Backspace)
                {
                    Console.Write("*");
                    password += info.KeyChar;
                }
                else if (info.Key == ConsoleKey.Backspace)
                {
                    if (!string.IsNullOrEmpty(password))
                    {
                        // remove one character from the list of password characters
                        password = password.Substring(0, password.Length - 1);
                        // get the location of the cursor
                        int pos = Console.CursorLeft;
                        // move the cursor to the left by one character
                        Console.SetCursorPosition(pos - 1, Console.CursorTop);
                        // replace it with space
                        Console.Write(" ");
                        // move the cursor to the left by one character again
                        Console.SetCursorPosition(pos - 1, Console.CursorTop);
                    }
                }
                info = Console.ReadKey(true);
            }
            // add a new line because user pressed enter at the end of their password
            Console.WriteLine();
            return password;
        }
    }

That's it.