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..

Thursday, March 14, 2013

Fault contract in WCF

I have created one sample project and uploaded on goggle drive. To download click the below click then open the "File" option from the menu and then you will find the "Download" option.
WCFServiceUsingFaultContract Project

What is Fault Contract:

In simple WCF Service errors/Exceptions can be passed to the Client(WCF Service Consumer) by using FaultContract How do you handle errors in ASP.NET? It's very simple just by adding the simple Try & Catch blocks. But when you come to WCF Service if any unexpected error occurred (like SQL server down/Unavailability of data/Divide By Zero) in service then error/Exception details can be passed to Client by using Fault Contract.

Predicted: (Divide By Zero/Channel Exceptions/Application exceptions etc..)
using System;
 public void Divide(float number, float divideBy) 
       {
           If(dividBy ==0)
           {
             myServiceData.Result = false;
             myServiceData.ErrorMessage = "Invalid Operation.";
             myServiceData.ErrorDetails = "Can not divide by 0.";
             throw new FaultException(myServiceData);
           }
           return number/divideBy;
       }

UnPredicted: (which I explained in this article like connection failures/SQL Server down/Transport errors/Business logic errors.)
using System;
try
            {
                SqlConnection con = new SqlConnection(StrConnectionString);
                con.Open();
                myServiceData.Result = true;
             //Your logic to retrieve data & and return it. If any exception occur while opening the connection or any other unexpected exception occur it can be thrown to Client (WCF Consumer) by below catch blocks.
           }
            catch (SqlException sqlEx)
            {
                myServiceData.Result = true;
                myServiceData.ErrorMessage = "Connection can not open this " + 
                   "time either connection string is wrong or Sever is down. Try later";
                myServiceData.ErrorDetails = sqlEx.ToString();
                throw new FaultException(myServiceData, sqlEx.ToString());
            }
            catch (Exception ex)
            {
                myServiceData.Result = false;
                myServiceData.ErrorMessage = "unforeseen error occured. Please try later.";
                myServiceData.ErrorDetails = ex.ToString();
                throw new FaultException(myServiceData, ex.ToString());
            }

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");

          }
     }
}

Saturday, March 9, 2013

Filtering in ASP.NET MVC

In ASP.NET MVC, controllers define action methods that usually have a one-to-one relationship with possible user interactions, such as clicking a link or submitting a form. For example, when the user clicks a link, a request is routed to the designated controller, and the corresponding action method is called. Sometimes you want to perform logic either before an action method is called or after an action method runs. To support this, ASP.NET MVC provides filters. Filters are custom classes that provide both a declarative and programmatic means to add pre-action and post-action behavior to controller action methods. ASP.NET MVC Filter Types ASP.NET MVC supports the following types of:
  1. Authorization filters: These implement IAuthorizationFilter and make security decisions about whether to execute an action method, such as performing authentication or validating properties of the request. The AuthorizeAttribute class and the RequireHttpsAttribute class are examples of an authorization filter. Authorization filters run before any other filter.
  2. Action filters: These implement IActionFilter and wrap the action method execution. The IActionFilter interface declares two methods: OnActionExecuting and OnActionExecuted. OnActionExecuting runs before the action method. OnActionExecuted runs after the action method and can perform additional processing, such as providing extra data to the action method, inspecting the return value, or canceling execution of the action method.
  3. Result filters: These implement IResultFilter and wrap execution of the ActionResult object. IResultFilter declares two methods: OnResultExecuting and OnResultExecuted. OnResultExecuting runs before the ActionResult object is executed. OnResultExecuted runs after the result and can perform additional processing of the result, such as modifying the HTTP response. The OutputCacheAttribute class is one example of a result filter.
  4. Exception filters: These implement IExceptionFilter and execute if there is an unhandled exception thrown during the execution of the ASP.NET MVC pipeline. Exception filters can be used for tasks such as logging or displaying an error page. The HandleErrorAttribute class is one example of an exception filter.
The Controller class implements each of the filter interfaces. You can implement any of the filters for a specific controller by overriding the controller's On<Filter> method. For example, you can override the OnAuthorization method. The simple controller included in the downloadable sample overrides each of the filters and writes out diagnostic information when each filter runs. You can implement the following On<Filter> methods in a controller:
Reference from http://msdn.microsoft.com/en-us/library/gg416513(v=vs.98).aspx

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());

Wednesday, December 26, 2012

Granting execute permission on all stored procedure in SQL

In SQL many times we need to provide execute permission to all stored procedure for specific user for any database. To achieve this you can make the execute statement by below query.

The query for it is just simple:
SELECT 'Grant Execute on ' + name +  ' SQLServerUSERName'FROM sysobjects WHERE xtype IN ('P')

For tables and views:
SELECT 'Grant select,insert,update,delete on ' + name + ' SQLServerUSERName''
from sysobjects where xtype in ('
U','V')'
Enjoy.

Getting Month name from any date

Getting Month name from any date in SQL:

Just use the below query and you will get the result.

SELECT DATENAME(MONTH, DATEADD(MONTH, MONTH(GETDATE()), -1 ))


Example with result:








Done.

Monday, December 24, 2012

Getting Date from Date Time column

While using date time fields in WHERE clause you can face one common problem. Most of time you can't get the records for which you have used the datetime in where clause. For example:
SELECT * FROM tTable WHERE DateTimeColumn='12/24/2012'

In this I don't get the records which have date 12/24/2012, it is because in table the column contains the time also. Then how to GET these records. Its very simple just convert your date time column with below code:

CAST(FLOOR( CAST( SM.DateDownloaded AS FLOAT ) )AS DATETIME) AS DownloadedDate

Converting rows to columns


Using Pivot you can easily convert rows to columns.
USE AdventureWorks
GO
SELECT VendorID, [164] AS Emp1, [198] AS Emp2, [223] AS Emp3, [231] AS Emp4, [233] AS Emp5FROM (SELECT PurchaseOrderID, EmployeeID, VendorIDFROM Purchasing.PurchaseOrderHeader) p
PIVOT(COUNT (PurchaseOrderID)FOR EmployeeID IN( [164], [198], [223], [231], [233] )
) AS 
ORDER BY VendorID

Enjoy.

Finding foriegn key table names which primary key is using in other tables


Finding table names in which a primary key of any table is used as foriegn key.
SELECT
    ConstraintName = fk.name,
    TableName = t.name,
    ColumnName = c.nameFROM
    sys.foreign_keys fkINNER JOIN 
    sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.OBJECT_IDINNER JOIN 
    sys.tables t ON fk.parent_object_id = t.OBJECT_IDINNER JOIN 
    sys.columns c ON fkc.parent_object_id = c.OBJECT_ID AND fkc.parent_column_id = c.column_idINNER JOIN 
    sys.tables tref ON fk.referenced_object_id = tref.OBJECT_IDINNER JOIN 
    sys.columns cref ON fkc.referenced_object_id = cref.OBJECT_ID AND fkc.referenced_column_id = cref.column_idWHERE
    tref.Name = 'tCurrencyCode'
    AND cref.Name = 'CurrencyId'

Enjoy.