Wednesday, 30 October 2013

Print Data Table data into Excel in c#.net

NameSpace--

using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Word;

Source Code--

 private void printExcelReport(DataTable dtFarmDetail)
        {
            //Declare Excel variable

            object misValue = System.Reflection.Missing.Value;
            Excel.Application xlApp = new Excel.Application();
            Excel.Worksheet xlWorkSheet = new Microsoft.Office.Interop.Excel.Worksheet();
            Excel.Workbook xlWorkBook;
            Excel.Range chartRange;

            //Declare value
            xlWorkBook = xlApp.Workbooks.Add(misValue);
            int Rowcount = dtFarmDetail.Rows.Count;
            int Colcount = dtFarmDetail.Columns.Count;

            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            //Write Header
            for (int p = 1; p <= dtFarmDetail.Columns.Count; p++)
            {
                xlWorkSheet.Cells[1, p] = dtFarmDetail.Columns[p - 1].ColumnName;
            }

            //Assing data in array
            object[,] arrFarm = new object[dtFarmDetail.Rows.Count, dtFarmDetail.Columns.Count];
            for (int i = 0; i < dtFarmDetail.Rows.Count; i++)
            {
                for (int j = 0; j < dtFarmDetail.Columns.Count; j++)
                {
                    string cellvalues = dtFarmDetail.Rows[i][j].ToString();
                    string tickcross = "";
                    if (j > 10)
                    {
                        if (cellvalues == "Yes")
                        {
                            tickcross = "ü";
                        }
                        if (cellvalues == "No" || cellvalues == "")
                        {
                            tickcross = "û";
                        }                      
                    }
                    else
                    { tickcross = cellvalues; }

                    arrFarm[i, j] = tickcross;
                }
            }

            //Write data in sheet
            if (dtFarmDetail.Rows.Count > 0)
            {
                xlWorkSheet.Range[xlWorkSheet.Cells[2,1], xlWorkSheet.Cells[dtFarmDetail.Rows.Count, dtFarmDetail.Columns.Count]] = arrFarm;
                dtFarmDetail.Rows.Clear();
            }

            //Color header
            chartRange = xlWorkSheet.get_Range((object)xlWorkSheet.Cells[1, 1], (object)xlWorkSheet.Cells[1, Colcount]);
            chartRange.get_Range((object)xlWorkSheet.Cells[1, 1], (object)xlWorkSheet.Cells[1, Colcount]).Font.Bold = true;
            chartRange.get_Range((object)xlWorkSheet.Cells[1, 1], (object)xlWorkSheet.Cells[1, Colcount]).Font.Size = 12;
            chartRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Silver);
           
            //Set Alingment
            chartRange = xlWorkSheet.get_Range((object)xlWorkSheet.Cells[1, 1], (object)xlWorkSheet.Cells[2 + Rowcount, Colcount]);
            chartRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;

            //Assign font and size
            chartRange = xlWorkSheet.get_Range((object)xlWorkSheet.Cells[1, 1], (object)xlWorkSheet.Cells[11 + Rowcount, Colcount]);
            chartRange.get_Range((object)xlWorkSheet.Cells[2, 12], (object)xlWorkSheet.Cells[11 + Rowcount, Colcount]).Font.Name = "Wingdings";
            chartRange.get_Range((object)xlWorkSheet.Cells[2, 12], (object)xlWorkSheet.Cells[11 + Rowcount, Colcount]).Font.Bold = true;
            chartRange.get_Range((object)xlWorkSheet.Cells[2, 12], (object)xlWorkSheet.Cells[11 + Rowcount, Colcount]).Font.Size = 12;
            chartRange.get_Range((object)xlWorkSheet.Cells[2, 12], (object)xlWorkSheet.Cells[11 + Rowcount, Colcount]).HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;

            //write sheet
            chartRange.Borders.get_Item(Excel.XlBordersIndex.xlEdgeBottom).Weight = Excel.XlBorderWeight.xlThin;
            chartRange.Borders.get_Item(Excel.XlBordersIndex.xlInsideHorizontal).Weight = Excel.XlBorderWeight.xlThin;
            chartRange.Borders.get_Item(Excel.XlBordersIndex.xlInsideVertical).Weight = Excel.XlBorderWeight.xlThin;
            chartRange.Borders.get_Item(Excel.XlBordersIndex.xlEdgeTop).Weight = Excel.XlBorderWeight.xlThin;
            chartRange.Borders.get_Item(Excel.XlBordersIndex.xlEdgeLeft).Weight = Excel.XlBorderWeight.xlThin;
            chartRange.Borders.get_Item(Excel.XlBordersIndex.xlEdgeRight).Weight = Excel.XlBorderWeight.xlThin;
            xlWorkSheet.Cells.EntireColumn.AutoFit();

            xlApp.Visible = true;
            Marshal.ReleaseComObject(xlWorkSheet);
            Marshal.ReleaseComObject(xlWorkBook);
            Marshal.ReleaseComObject(xlApp);
            xlWorkSheet = null;
            xlWorkBook = null;
            xlApp = null;
            System.GC.Collect();
       
        }

Saturday, 19 October 2013

Create Log file in asp.net


On Event--
 string thisDir = Server.MapPath("./ExLogFile");
            //String Format : DateTime,Action,Userid,UserRole,Status,Attempt, FileName,empid,empname, username, adminactivity
            string logMessage = DateTime.Now.ToUniversalTime() + "," + "Logout," + Session["UName"] + "," + Session["user_RoleName"] + "," + "logged out" + "," + "," + "," + "," + "," + "," + "," ;
            writeToLogFile(logMessage, thisDir);


Method-


 public static void writeToLogFile(string logMessage, string thisDir)
    {
        StreamWriter swLog=null;
        try
        {
            string strLogMessage = string.Empty;
            string strLogFile = "" + thisDir + "\\logFile.txt";
         
            //strLogMessage = string.Format("{0}: {1}", DateTime.Now, logMessage);


            strLogMessage = string.Format(logMessage);

            if (Directory.Exists(thisDir)) { }
            else { System.IO.Directory.CreateDirectory(thisDir); }

            if (!File.Exists(strLogFile))
            {
                swLog = new StreamWriter(strLogFile);
            }
            else
            {
                swLog = File.AppendText(strLogFile);
            }

            swLog.WriteLine(strLogMessage);
            swLog.WriteLine();
            swLog.Close();
            swLog.Dispose();
        }
        catch (Exception)
        {
            swLog.Dispose();
            throw;
        }
        finally { swLog.Dispose(); }

    }

Single User login at a time any where with cache in asp.net

On Login Page-
Globle Define--  public System.Data.DataTable dtSessionGlobal = new DataTable();

  if (Cache["UserSessions"] != null)
        {
            dtSessionGlobal = (DataTable)Cache["UserSessions"];
        }
        else
        {
            dtSessionGlobal.Columns.Add("UserName");
            dtSessionGlobal.Columns.Add("SessionID");
            Cache["UserSessions"] = dtSessionGlobal;
        }

        EventArgs ee = new EventArgs();
        if (Session["username"] == null)
        {        
            btnsessionout_Click(sender, ee);
            //Response.Redirect("~/SignIn Users", false);
        }


On Logout Button-

 protected void btnsessionout_Click(object sender, EventArgs e)
    {
        string UserName =Session["UName"]==null ? "" : Session["UName"].ToString();
        Application[UserName] = null;
        if (dtSessionGlobal.Rows.Count > 0)
        {

            System.Data.DataRow[] dr = dtSessionGlobal.Select(" UserName='" + Session["UName"] + "'");// AND SessionID='" + Session.SessionID + "'
            if (dr.Length > 0)
            {
                foreach (DataRow drRow in dr)
                {
                    dtSessionGlobal.Rows.Remove(drRow);
                }
            }
        }
     
        Cache["UserSessions"] = dtSessionGlobal;

    }




At All Pages-

protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dtSessionGlobal = new DataTable();
        if (Cache["UserSessions"] != null)
        {
            dtSessionGlobal = (DataTable)Cache["UserSessions"];
        }
     
        if (!IsPostBack)
        {
            if (dtSessionGlobal.Rows.Count > 0)
            {
                System.Data.DataRow[] dr = dtSessionGlobal.Select(" UserName='" + Session["UName"] + "' AND SessionID<>'" + Session.SessionID + "'");
                if (dr.Length > 0)
                {
                    Response.Redirect("~/SignIn Users");
                }
                else if (dtSessionGlobal.Select(" UserName='" + Session["UName"] + "'").Length == 0)
                {
                    Response.Redirect("~/SignIn Users");
                }
            }
            else
            {
                Session.Abandon();
                Response.Redirect("~/SignIn Users");
            }
}

Restrict to direct access file and folder from url in web.config

<system.webServer>
 <security>
            <requestFiltering>
                <hiddenSegments>
                    <add segment="Folder Name" />
                    <add segment="Folder Name" />
                    <add segment="Folder Name" />
                    <add segment="Folder Name" />
                    <add segment="Folder Name" />
                    <add segment="Folder Name" />
                    <add segment="Folder Name" />
                </hiddenSegments>
            </requestFiltering>
        </security>  

</system.webServer>

Friday, 18 October 2013

Redirect to custom error page when server or application get error 404 or 403 or 405

for Custorm

<system.web>
<customErrors mode="On" defaultRedirect="~/Error-page not found">
     <error statusCode="404"  redirect="~/Error-page not found" />
      <error statusCode="403" redirect="~/Error-page not found" />
      <error statusCode="500" redirect="~/Error-page not found" />
    </customErrors>
</system.web>




for Http-

<system.webServer>
 <httpErrors errorMode="Custom" defaultResponseMode="ExecuteURL">
      <remove statusCode="404" subStatusCode="-1" />
      <error statusCode="404" prefixLanguageFilePath="" path="/RFBij/Error-page not found" responseMode="ExecuteURL" />
      <remove statusCode="403" subStatusCode="-1" />
      <error statusCode="403" prefixLanguageFilePath="" path="/RFBij/Error-page not found" responseMode="ExecuteURL" />
      <remove statusCode="405" subStatusCode="-1" />
      <error statusCode="405" prefixLanguageFilePath="" path="/RFBij/Error-page not found" responseMode="ExecuteURL" />
    </httpErrors>
</system.webServer>

Friday, 4 October 2013

Asp.Net Validation Summary: How to show ValidationSummary using JavaScript

ValidationSummaryOnSubmit(); function exposed at client side.

<script type="text/javascript" language="javascript">

function PerformValidation() {
              ValidatorValidate(document.getElementById('rfvName'));
              ValidationSummaryOnSubmit();
 }



</script>
 
Note:  ValidationSummaryOnSubmit takes an argument as validationGroup. If you want to show ValidationSummary for a particular validation group, then call function passing name of validation group.
If function is called without any arguments, then it will show all ValidationSummary (if error) in page.

How to highlight selected text in notepad++

  –> To highlight a block of code in Notepad++, please do the following steps step-1  :- Select the required text. step-2  :- Right click...