Surendra Sharma

Surendra Sharma

Search This Blog

Thursday, July 11, 2013

How to check temporary table is exist or not in SQL Server

IF OBJECT_ID('tempdb..#tempEmployee') IS NOT NULL DROP TABLE #tempEmployee
     
--    Create temp table #tempEmployee
CREATE TABLE #tempEmployee  
(   
      ID   INTEGER NOT NULL,    
      EmpName     VARCHAR(50)  NOT NULL
);   

INSERT INTO #tempEmployee(ID, EmpName)
SELECT 1, 'AAA'
UNION
SELECT 2, 'BBB'

SELECT * FROM #tempEmployee -- Get two records

DROP TABLE #tempEmployee

SELECT * FROM #tempEmployee -- Error : Invalid object name '#tempEmployee'


Please leave your comments if it is useful for you.

Wednesday, July 10, 2013

How to download file async in ASP.NET

While developing ASP.NET site, its common feature to allow download of a file.
Along with download large file, site should allow user to do other tasks on the page i.e. allow user to download file async.

Here are the guidelines for doing it

  • Create two web page - default.aspx and Download.aspx
  • On default.aspx take one hidden frame and button to download as below

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
 <script type="text/javascript" language="javascript">

     function DownLoadFile(uid) {
         var iframe = document.getElementById("ifrmDownloadframe");
            iframe.src = uid;
            return false;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <iframe style="display: none" id="ifrmDownloadframe"></iframe>
    <div>
    Current Date Time is <asp:Label ID="Label1" runat="server" ></asp:Label>
    <br />
        <asp:Button ID="btnDateTime" runat="server" Text="Show Date Time"
            onclick="btnDateTime_Click" />
        <asp:Button ID="btnDownload" runat="server" Text="Download" />
    </div>
    </form>
</body>
</html>

  • Set Download.aspx page with required query string as a frame source as below from default.aspx

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            Label1.Text = DateTime.Now.ToString();
            btnDownload.Attributes.Add("onclick", DownloadShippedFile(100));
        }
    }

    protected void btnDateTime_Click(object sender, EventArgs e)
    {
        Label1.Text = DateTime.Now.ToString();
    }

    private string DownloadShippedFile(int Id)
    {
        string result = string.Empty;

        try
        {

            string key = string.Format("Type=DownloadEmpFile&EmployeeId={0}", Id);
            string strURL = Request.ApplicationPath + "/Download.aspx?" + key;
            result = "return DownLoadFile('" + strURL + "');";
        }
        catch (Exception ex)
        {
            result = string.Format("alert('{0}');return false;", ex.Message);
        }

        return result;
    }
}


  • On Download.aspx, get filepath from query string and force file to download on browser

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString.Count > 0 && Request.QueryString["EmployeeId"] != null)
        {
            //Based upon id get file name from database or from some where else. I am considering direct file name
            string filePathFromDatabase = @"\\xyz\abc.zip";
            DownloadFile(filePathFromDatabase);
        }
    }


    private void DownloadFile(string sFileName)
    {
        FileStream fileStream = new FileStream(sFileName, FileMode.Open, FileAccess.Read);

        byte[] buffer = new byte[(int)fileStream.Length];
        fileStream.Read(buffer, 0, (int)fileStream.Length);
        fileStream.Close();

        Response.Clear();
        Response.ClearContent();
        Response.ClearHeaders();
        if (sFileName.EndsWith(".html"))
            Response.ContentType = "text/html";
        else
            Response.ContentType = "application/octet-stream";

        Response.AddHeader("Content-Length", buffer.Length.ToString());
        Response.AddHeader("Content-Disposition", "attachment;filename=\"" + sFileName + "\"");
        Response.BinaryWrite(buffer);
        Response.Flush();
        Response.End();
    }



Please leave your comments if it is useful for you.

Tuesday, July 9, 2013

Income Tax In India

Most of the engineers don’t understand the financial terms. Every year they have to face income tax, deductions and investment related problems.

Here is link to which simply explain the basic terms of income tax

Monday, July 8, 2013

How to create the 3 tier / layer architecture application in .NET

Most of the projects in .NET are developed using tier / layer architecture. Though tier and layer have different meaning, but for all .NET beginners I am using same term.
Below is typical diagram of 3 tier architecture.


  1. Presentation Layer: It’s a User Interface Layer (UIL) where users are interacting with an application. It also contains additional application logic. This layer may be ASP.NET, windows or mobile application. This layer interacts with middle layer. It never directly access data layer.

2.     Business Layer: It’s a Business Logic Layer (BLL) which communicates both to Presentation layer or Data Layer.

3.     Data Layer: It’s a Data Access Logic Layer (DAL) which interacting with database.

Steps to create in Visual Studio using C#
  1. Create one window / web project.
  2. Right click on your solution, Add one new project as shown below


  1. Select one class library project, specify its name as “DataAccessLayer”, as shown below


  1. Similarly create another class library name as “BusinessLogicLayer”
  2. Create classes in DataAccessLayer for StudentInfo table as shown below
using System;
using System.Data;
using System.Collections.Generic;
using System.Text;

namespace DataAccessLayer
{
    class StudentInfo
    {
        public DataTable LoadAll()
        {
            //Write code to load all the records of studentinfo Table
            DataTable objDataTable = new DataTable();
            return objDataTable;
        }

        //Write rest of the code for each SP - Insert, Update, delete
    }
}

  1. Build DataAccessLayer Project.
  2. Add the reference of DataAccessLayer in BusinessLogicLayer project as shown below

 



  1. Try to access the DataAccessLayer’s StudentInfoDAL class in BusinessLogicLayer as shown below
using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
using DataAccessLayer;

namespace BusinessLogicLayer
{
    public class StudentInfoBLL
    {
        /// <summary>
        /// Call the StudentInfoDAL class of DataAccessLayer
        /// </summary>
        /// <returns></returns>
        public DataTable LoadAll()
        {
            StudentInfoDAL objStudentInfoDAL = new StudentInfoDAL();
            return objStudentInfoDAL.LoadAll();
        }

        //Write rest of the code to call the Insert, Update, delete method of StudentInfoDAL
    }
}

  1. Build BusinessLogicLayer Project.
  2. Similarly Add the reference of BusinessLogicLayer in your window / web project.
  3. Try to access the BusinessLogicLayer’s StudentInfoBLL class.
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using BusinessLogicLayer;

namespace _3TierDemo
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindStudentInfoData();
            }
        }

        public void BindStudentInfoData()
        {
            StudentInfoBLL objStudentInfoBLL = new StudentInfoBLL();
            DataTable objDataTable = objStudentInfoBLL.LoadAll();
            GridView1.DataSource = objDataTable;
            GridView1.DataBind();
        }
    }
}


Finally your 3-Tier application look like.




 

Hope this is helpful. Please leave your comments for any help / suggestion.

Unable to copy file "obj\Debug\xyzproj.exe" to "bin\Debug\xyzproj.exe". The process cannot access the file 'bin\Debug\xyzproj.exe' because it is being used by another process.

If you come across the error in visual studio like “Unable to copy file "obj\Debug\xyzproj.exe" to "bin\Debug\xyzproj.exe". The process cannot access the file 'bin\Debug\xyzproj.exe' because it is being used by another process.

Solution: - It simply means that your EXE is already running. Close already running exe or window, then build / rebuild and run your application.

Thursday, July 4, 2013

Daily Yoga Chart

I was involved with different kind of exercise - heavy weight, Cardio, running, jogging, Karate, cycling, dance etc.

Now I am doing YOGA from DEC 2012. It’s my personal experience that YOGA is the best among all the exercises.

Here you can find daily YOGA Chart for reference.

It covers daily Aaasans, Pranayam, Dhayan.

Aasans - It includes different body parts exercise which makes body flexible and healthy
Pranayama - It includes different breathing exercises
Dhayan - It includes Meditation which improve mind peace

If you want more details about any Aasans, Pranayama or Dhayan, please leave comments here.




Please share with your friends and leave your valuable feedback.

Wednesday, July 3, 2013

The application domain in which the thread was running has been unloaded

If you are getting error “The application domain in which the thread was running has been unloaded.” while building .NET project in Visual Studio.

Solution 1:  Rebuild the whole solution

Solution 2:  Rebuild individual class libraries and project.