Feeds:
Posts
Comments

Archive for August, 2007

         I have explained how to store and retrieve image file in SQL Server in my previous post. I received many comments mentioning that how can we store and retrieve doc or pdf or excel (or any type of file) in SQL Server. Few friends (developers) have also posted comment that they receive only 13 byte when they retrieve stored image or doc or xls or pdf or rtf file. So I thought let be write another blog for them. Sorry friends I am bit late in writing this article and mean while you also have solved your issues. However this may help some new friends.

         In this example I have used a table which has four fields. Below is the script for table,

CREATE TABLE [TestTable]
(
         [ID] [int] IDENTITY(1,1) NOT NULL,
         [FileName] [nvarchar](15) NOT NULL,
         [Extension] [nvarchar](5) NOT NULL,
         [Content] [image] NULL
)

Fig – (1) Scrpit for Table

         In my demo project I have used one file Upload control (to upload the file), one Textbox (where user can enter ID for uploaded file to retrieve it) and 2 buttons (one for uploading file and other for retrieving).

         When user select the file and click on Upload button the code stores the selected file in database. Below is the code for that,

    using (SqlConnection cnn = new SqlConnection(“Connection String”))
    {
                    cnn.Open();
                    SqlCommand cmd = new SqlCommand(“InsertFile”, cnn);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add(new SqlParameter(“@FileName”, “Name of 
                                                               Uploaded File”
));
                    cmd.Parameters.Add(new SqlParameter(“@Extension”, “Extension of
                                                               Uploaded File”
));
                    cmd.Parameters.Add(new SqlParameter(“@Content”, “byte array
                                                               (byte[]) of uploaded file”
));
                    cnn.Close()
     }

   Fig – (2) Code for inserting selected file in database.    

          Now when user enter FileID for uploaded file in textbox and click on retrieve button we will get the Content and extension field from database for that file id. You can use FillDataSet method to retrieve the byte array. Below code shows how to send retrieved file to user depending on the extension.

                string strExtenstion = “extension of retrieved file”;
                byte[] bytFile =  “Byte array retrieved from database”;

                Response.Clear();
                Response.Buffer = true;

                if (strExtenstion == “.doc” || strExtenstion == “.docx”)
                {
                        Response.ContentType = “application/vnd.ms-word”;
                        Response.AddHeader(“content-disposition”,
                                                          “attachment;filename=Tr.doc”);
                }
                else if (strExtenstion == “.xls” || strExtenstion == “.xlsx”)
                {
                         Response.ContentType = “application/vnd.ms-excel”;
                         Response.AddHeader(“content-disposition”,
                                                         “attachment;filename=Tr.xls”
);
                }
                else if (strExtenstion == “.pdf”)
                {
                         Response.ContentType = “application/pdf”;
                         Response.AddHeader(“content-disposition”,
                                                        “attachment;filename=Tr.pdf”
);
                }

                Response.Charset = “”;
                Response.Cache.SetCacheability(HttpCacheability.NoCache);

                // If you write,
               
// Response.Write(bytFile1);
               
// then you will get only 13 byte in bytFile.
                Response.BinaryWrite(bytFile);

                Response.End();

Fig – (3) Code to retrieve the file from database.

Happy Programming !!!

 

 

Advertisements

Read Full Post »

             Joseph Albahari has created a great tool for LINQ query expression. You can dwnload it  from here.

Happy Programmig !!

Read Full Post »

           I installed VS 2008 beta 2 before few days and started exploring it. I looked in to the LINQ and found very interesting.  LINQ generates DataContext class which provides classes and methods which is used in OR-Mapping. You can also use your stored procedures and views with LINQ. You may require to use transaction with your SPs during Insert, Delete or Update operations.

           System.Data.Common.DbTransaction class provides the Transaction object. I have used Northwind database in this example. Lets start with new project, you can select new project from Start -> All Programs ->  Microsoft Visual Studio 2008 Beta 2  and click on Microsoft Visual Studio 2008 Beta 2. Create new Asp.net website. Right click on website from solution explorer and select LINQ to SQL classes from Add New Item as shown below.

Fig – (1)  LINQ to SQL classes 

           This will generate dbml file in App_Code folder. Select the tables, views, stored procedures and function from server explorer and drag it on dbml file. DataContext class generates methods for each SPs, functions and views. 

           I have used Category and Product tables in this example. I have created two SPs InsertCategory and InsertProduct for inserting records in appropriate tables. You can see your SPs when you create the object of DataContext class.

Fig – (2) DataContext class shows the methods generated for SPs 

          I will first insert the category and then insert product for newly created category. If you have used some parameters as OUT parameters in your SP, you need to pass these parameters as Ref in calling method. In my SPs I have used CategoryID and ProductID as OUT parameters. 

          Now, lets move towards the transaction. I want that either category and product both will be added in database or none of them will be inserted. Below is the code for that,

System.Data.Common.DbTransaction trans = null;
DataClassesDataContext objDataClass = new DataClassesDataContext
                
(ConfigurationManager.ConnectionStrings
                                       [Constants.ConnectionString].ConnectionString);
try
{

                // Nullable data type as the methods generated for SP will use Nullable
                // type
                int? intCategoryID =0;
                int? intProductID =0;

                // Open the connection
                objDataClass.Connection.Open();

                // Begin the transaction
                trans = objDataClass.Connection.BeginTransaction();
               
                // Assign transaction to context class
                // All the database operation perform by this object will now use
                //transaction
 
                objDataClass.Transaction = trans;

                // Insert Category
                // I have to use Ref keyword CategoryID of newly added category will
                // be assign to this variable

                objDataClass.InsertCategory
                                          (
                                            ref intCategoryID, 
                                            txtName.Text.Trim().Replace(“‘”, “””), 
                                            txtDescription.Text.Trim().Replace(“‘”, “””),
                                            new byte[0]
                                          );
                               

                // Insert Product
                // I have to use Ref keyword as ProductID of newly generated product will
                // be assign to this variable

                objDataClass.InsertProduct
                                          (
                                            ref intProductID,
                                            txtProductName.Text.Trim().Replace(“‘”,“””),
                                            null,
                                            intCategoryID,
                                            txtQuantityPerUnit.Text.Trim().Replace(“‘”, “””),
                                            Convert.ToDecimal(
                                                      txtUnitPrice.Text.Trim().Replace(“‘”, “””)
                                                                                  ),
                                             null,
                                             null,
                                             null,
                                             0);
               

                // Commit transaction
                trans.Commit();

               
            }
            catch (Exception ex)
            {                

                    // Rollback transaction
                    if (trans != null)
                                 trans.Rollback();
            }
            finally
            {

                      // Close the connection
                      if (objDataClass.Connection.State == ConnectionState.Open)
                                 objDataClass.Connection.Close();
            }

     Fig – (3) Code for Transaction in LINQ using  C#

Happy Programming !!

Read Full Post »

          “What is delegate?” we all have faced this question in one or more interview. 🙂 and the most common answer is “Function pointer”. Here I am showing a simple example of delegate. I have one user control and one aspx page. The user control contains one button. When user click on this button I will call a method on main page using delegate. Here is my user control,

<%@ Control Language=”C#” AutoEventWireup=”true” CodeFile=”WebUserControl.ascx.cs” Inherits=”Dalegate_WebUserControl” %>

<asp:Button ID=”btnTest” runat=”server” Text=”I am Inside User Control” OnClick=”btnTest_Click” />

Fig – (1) WebUserControl.ascx

            On WebUserControl.ascx.cs I have written simple delegate and event handler as shown below,

public partial class Dalegate_WebUserControl : System.Web.UI.UserControl
{

    // Delegate declaration
    public delegate void OnButtonClick(string strValue);

    // Event declaration
    public event OnButtonClick btnHandler;
   
    // Page load
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }

    protected void btnTest_Click(object sender, EventArgs e)
    {
           // Check if event is null
           if (btnHandler != null)
               btnHandler(string.Empty);

           // Write some text to output
           Response.Write(“User Control’s Button Click <BR/>”);
    }
}

Fig – (2) WebUserControl.ascx.cs

          Above code first check whether btnHandler is not null and than raise the event by passing argument. You can pass any number of argument in event. You need to change public delegate void OnButtonClick(string strValue) and btnHandler(string.Empty) lines for changing number of arguments. Now take a look at aspx page,

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”Dalegate_Default” %>

<%@ Register Src=”WebUserControl.ascx” TagName=”WebUserControl” TagPrefix=”uc1″ %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml&#8221; >
<
head runat=”server”>
    <title>Untitled Page</title>
</
head>
<
body>
    <form id=”form1″ runat=”server”>
    <div>
        <asp:Label ID=”lblText” Text=”I am On Main Page : “
                   runat
=”server”></asp:Label>
        <asp:DropDownList ID=”ddlTemp” runat=”server”>
            <asp:ListItem>Chirag</asp:ListItem>
            <asp:ListItem>Dipak</asp:ListItem>
            <asp:ListItem>Shailesh</asp:ListItem>
        </asp:DropDownList>
        <br />
        <br />
        <uc1:WebUserControl ID=”WebUserControl1″ runat=”server” />
   
    </div>
    </form>
</
body>
</
html>

Fig – (3) Default.aspx

          Default.aspx has one drop down list and a user control as shown in above code. Lets look at cs file,

public partial class Dalegate_Default : System.Web.UI.Page
{
      protected void Page_Load(object sender, EventArgs e)
      {
             // Declare and Define Event of User Control. When User Clicks on button
             (which is inside UserControl)
             // below event is raised as I have called raised that event on Button Click
             WebUserControl1.btnHandler += new 
             Dalegate_WebUserControl
.OnButtonClick(WebUserControl1_btnHandler);
       
      }

      void WebUserControl1_btnHandler(string strValue)
      {
             Response.Write(“Main Page Event<BR/>Selected Value: “ +
                                     ddlTemp.SelectedItem.Text + “<BR/>”);
      }   
}

 Fig – (4) Default.aspx.cs

            Now when you run the application and clicks on button you can see that when user click on button the user control raise the click event and calls the WebUserControl1_btnHandler(string strValue) method on main page.

Happy Programming !!!

Read Full Post »

Hi,

            I am having a small issue. I am calling a console application from ASP.NET 2.0 website. Below is my code,

string strPassword = Convert.ToString(“Password”);

System.Security.SecureString ssPassword = new System.Security.SecureString();
foreach (char chr in strPassword)
{
          ssPassword.AppendChar(chr);
}

System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo(“Path of EXE”);
info.UseShellExecute = false;
info.Arguments = “ARGUMENTS”;
info.UserName = Convert.ToString(“UserName”);
info.Password = ssPassword;
info.Domain = Convert.ToString(“Domain”);

System.Diagnostics.Process.Start(info);

Fig – (1) code for calling exe from asp.net

            When I run (by pressing F5 from VS) it works fine and console application loads. However once I have deployed the application console application does not load and gives error “Application failed to initialize properly(0xcC000142). Press OK to terminate the application“.
                   I have used proper credential(Machine’s Admin User Name and Password on which web application is deployed. Console application is on same machine).

Early response is highly appreciated.   🙂

Read Full Post »

          As you all know when you execute an console application it will load command prompt and shows out put. There are amny situation in which you do not want this console window to be dislayed to user while your application runing. You can do that by calling some unmanaged functions. I have used following method to do that which is posted by Brendan Grant on MSDN.

using System.Runtime.InteropServices;

[DllImport(“user32.dll”)]
public static extern IntPtr
FindWindow(string lpClassName, string lpWindowName);

[DllImport(“user32.dll”)]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

IntPtr hWnd = FindWindow(null, title);

 if (hWnd != IntPtr.Zero)
 {
                if (!visible)
                    //Hide the window                   
                    ShowWindow(hWnd, 0); // 0 = SW_HIDE               
                else
                    //Show window again                   
                    ShowWindow(hWnd, 1); //1 = SW_SHOWNORMA          
}

Fig – (1) Code to hide console window in console application

Read Full Post »

        We are using Viewpoint 3-D content in our LMS (Learning Management System). The content is working fine in my local machine. However when I uploaded the LMS on deployment server the contect stopped working. The content loads perfectly. User can listen the sound and can change the step and steps, however 3-D content is not visible. After doing dome google search I found about Mime type settings in IIS. Viewpoint content requires Mime type added in IIS. Once I added required Mime type content it start working.

        Viewpoint require “.mts”, “.mtx”, “.mtz” and “.mzv” mime types. You have to add these mime types in IIS to make viewpoint content working. You can add Mime type by,

        1. Click on Start Menu
        2. Select Run.
        3. Type inetmgr and press enter.
        4. Select perticular Website or Virtual directory to add mime
            type for that website/Virtual directory. If you want to
            add for all the sites select Default Website and click on
            Property.
        5. Click on HTTP Headers and select Mime type.
        6. In the Extension field, type .mts.
        7. In the Content Type field, type application/metastream, 
           and then click OK.
        8. Repeat for .mtx, .mtz, and .mzv files.

Happy Programming !!

Read Full Post »

Older Posts »