Friday, February 29, 2008

Service Unavailable error while connecting to team foundation server.

         You may receive "Service Unavailable" error while connecting to Team Foundation Server(TFS). I was getting this error from yesterday whenever I was trying to connect to TFS. Finally today I found the reason and solution. I had changed the password of Administrator user which I had used to configure TFS Application Pool. This has stopped the application pool as the account which is running the TFS Application Pool has old password. So one has to change the password in TFS Application pool. To change password in application pool, click Start - Run and type inetmgr. This will open IIS. Now select the TFS application pool.

           Right click on TFS Apppool and select properties. Select Identity tab. Here you have to enter a new password for this account and click ok. Restart the IIS and try to connect to TFS. This time you will not get the "Service Unavailable" error.

       You will get this same error if you have deleted the user which is used to configure TFS Application pool. Here is the good article from Microsoft. 

Happy Programming !!

Friday, February 15, 2008

The media set has 2 media families but only 1 are provided.

      You get this error while restoring the database backup file in SQL Server 2005. This is because when you took the backup your backup file is divided in more than one part and at the time of restoring the database you have not added all the parts.

       Lets do this practically so that you can have better idea. Take the backup of any database you have. To take the backup right click on database and select the task and click on backup. 

         Once you click on Backup you have to select the location for .back file on database. If there are two paths in path selection box as shown in image below, the backup file is generated in two parts and saved at two different locations.

        So in this case, we have two backup files generated for selected database. Now at the time of restoring if you are assigning only one file and try to restore the database, you will get "The media set has 2 media families but only 1 are provided." error.

        To solve this issue you have to add all the files (in our case two files) in file selection box. Once you select all the backup files and click on restore, the database will restore successfully.

For more detail check here.

Happy Programming !!

Friday, February 08, 2008

Query to find all the tables and columns in selected database.

         As a developer, it is really important for us to understand database design and underlying tables used in application. Sometime we do not have direct access to database server so that we can not open the server console and look in to the database.

         In this case we can take help of SysObjects, SysColumns, SysTypes tables of SQL Server 2005. These tables stores the information about each tables and columns and their data types. Using this tables you can write the query to find out all the tables and columns in selected database. Below is the query that gives you all the table and columns for those tables with data types and length.

 

   1: SELECT 
   2:     SysObjects.[Name] as TableName,
   3:     SysColumns.[Name] as ColumnName,
   4:     SysTypes.[Name] As DataType,
   5:     SysColumns.[Length] As Length
   6: FROM
   7:     SysObjects INNER JOIN SysColumns
   8:     ON SysObjects.[Id] = SysColumns.[Id]
   9:     INNER JOIN SysTypes 
  10:     ON SysTypes.[xtype] = SysColumns.[xtype]
  11: WHERE
  12:     SysObjects.[type] = 'U'
  13: ORDER BY 
  14:     SysObjects.[Name]

Fig - (1) Query to find all the tables and columns for those tables.


 


           "Type" columns of SysObjects table represent the different objects available in database (like Table,Trigger,Stored Procedures etc.). Below list explains the different values of "Type" columns.



   1: C = CHECK constraint 
   2: D = Default or DEFAULT constraint
   3: F = FOREIGN KEY constraint 
   4: FN = Scalar function
   5: IF = Inlined table-function
   6: K = PRIMARY KEY or UNIQUE constraint 
   7: L = Log
   8: P = Stored procedure
   9: R = Rule
  10: RF = Replication filter stored procedure
  11: S = System table 
  12: TF = Table function
  13: TR = Trigger
  14: U = User table
  15: V = View
  16: X = Extended stored procedure

Fig - (2) Explanation of different values of "Type" columns in SysObjects table.


 


          For more detail refer SysObjects and SysColumns.  and So in fig - (1) query uses [type] = 'U'. This means query displays al the user tables. You can change the condition in WHERE clause to get different objects. The query shown below displays all the triggers in selected database.


 



   1: SELECT 
   2:     b.[Name] as [Table Name],
   3:     a.[Name] as [Trigger Name],
   4:     a.[crdate] as [Created Date] 
   5: FROM 
   6:     SysObjects a 
   7:     INNER JOIN Sysobjects b
   8:     ON a.[parent_obj] = b.[id]
   9: WHERE 
  10:     a.[type] = 'TR'
  11: ORDER BY 
  12:     b.[Name]

Fig - (3) Query to display all the Triggers for selected database.


 


Happy Programming !!

Monday, January 28, 2008

Internet explorer was not able to open the Internet site. The requested site is either unavailable or can not be found.Please try again later.

       You may receive this error when you write a code that allows user to download a file instead of opening it in IE other browser. In my code I have to show Open/Save dialog for PDF file. I wrote the following code.

   1: Response.Clear();
   2: Response.Buffer = true;
   3: Response.ContentType = "application/pdf";
   4: Response.Cache.SetCacheability(HttpCacheability.NoCache);
   5: Response.AddHeader("content-disposition", "attachment;filename=test.pdf");
   6: Response.Charset = "";
   7: Response.BinaryWrite(bytContent);
   8: Response.End();

 


         When I ran the code I was getting error as "Internet explorer was not able to open the Internet site. The requested site is either unavailable or can not be found.Please try again later."


          To solve this error I just removed line 4 "SetCacheability" and everything works fine. After that I search on net to find the reason and I found really good article here.


          While surfing I found another approach to achieve this an I found it better that I used here. Rick Astral has shown that approach here.


 


Happy Programming !!

Friday, October 19, 2007

Add new document to Document Library in SharePoint using C#

          We are exploring SharePoint 2007 from last few days. Here is the code for adding new document to document library using C#.  I have created a page with a file upload control and a button. When user clicks on button the selected document will be uploaded to specific document library. You need to add reference to Microsoft.SharePoint DLL to make this code running.

if (FileUpload1.PostedFile != null)
{
            if(FileUpload1.PostedFile.ContentLength > 0)
            {
                   System.IO.Stream strm =
                         FileUpload1.PostedFile.InputStream;

                   byte[] byt = new byte[
                          
Convert.ToInt32 (
                  FileUpload1.PostedFile.ContentLength)];

                   strm.Read(byt, 0, Convert.ToInt32
                        (FileUpload1.PostedFile.ContentLength));

                   strm.Close();

                // Open site where document library is created.
                using (SPSite objSite = new SPSite
                                                ("http://server:port/"))
                {
                    using (SPWeb objWeb = objSite.OpenWeb())
                    {
                        SPFolder mylibrary = objWeb.Folders["Name of
                                                     Document Library"
];

                        // Set AllowUnsafeUpdates = true to avoid
                        // security error
                      
                        objWeb.AllowUnsafeUpdates = true;

                        mylibrary.Files.Add(System.IO.Path.GetFileName
                               (FileUpload1.PostedFile.FileName), byt);
                    }
                }
            }
        }

     Above code first reads the uploaded file in Stream and than uploads it on document library.

Happy Programming !!!

Friday, October 12, 2007

Add aspx page to SharePoint 2007

            This post will show how to create aspx (web page) page to SharePoint 2007. You can find  a really good article to add custom page in SharePoint 2007 site. I have shown one approach describe in above article.

            Create a new Web Application Project from Visual Studio 2005. You need to download web application project extension for this. Open Visual Studio 2005 and select Web Application Project as shown below,

NewWebProject

Fig - (1) Create new Web Application

            Name the project "FirstWebProject". Delete Default.aspx page and add new Web Page and name it to "FirstCustomePage.aspx".  You can design this page as you want. Once you are done with designing run the application once to make sure that there is no error.

            Now go to the file path where you have created the Web Application. Here in my case as you can see in figure - (1) file path is "c:\chirag\VortalProject". You have to copy the DLL file from web application's BIN folder to share point site's BIN folder. To Find BIN folder for your share point site, go to IIS and select your share point site. Right click on the site name and click on Open.

LocateBin

Fig - (2) Locate BIN Directory for SharePoint Site.

          This will open physical location where you site resides. Copy web application's DLL file (In my case "FirstWebProject.dll") in BIN directory of SharePoint site.

          Now create a new folder at same level where your SharePoint site's BIN directory resides. Name is "CustomePage". Add the "FirstCustomePage.aspx" page to "CustomPage" folder.

         Open Web.Config file of Share Point site and copy safe control tag shown below to Web.Config file.

<SafeControl Assembly="FirstWebProject" Namespace="FirstWebProject" TypeName="*" />

Fig - (3) Safe Control Tag.

         If you have chosen different namespace and assembly names than you have to use your name instead of this. You have completed 90% of the task.

          The last thing is, you have to add <trustLevel> tag in share point sites's web.Config file. You need to  set trust level to "WSS_Medium"

<trustLevel name="WSS_Medium" policyFile="C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\config\wss_mediumtrust.config" />

Fig - (4) Setting Trust Level.

          Here you have completed all the required configurations !!!! Now open your share point site in browser and check for newly added page. In our case the link will be http://ServerName:PortNumber/CustomePage/FirstCustomePage.aspx

         If you have done all the changes as mentioned above you can see your page running fine in browser.

Happy Programming !!! 

Page Ghosting & UnGhosting And effect of PageGhosting on Performance in SharePoint 2007

           The WSS team created a virtual path provider named SPVirtualPathProvider that is integrated into every Web application. The SPVirtualPathProvider class is integrated into the ASP.NET request handling infrastructure by the SPRequestModule. More specifically, the SPRequestModule component contains code to register the SPVirtualPathProvider class with the ASP.NET Framework as it does its work to initialize a Web application.

image

Fig - (1) Execution flow for SharePoint pages. 

Page Ghosting and UNGhosting

             When a page instance is initially provisioned from a page template, WSS doesn’t need to store a copy of it in the content database because WSS can load the page template from the file system of the Web server and use it to process any request for an uncustomized page instance. Therefore, you can say that page ghosting describes the act of processing a request for an uncustomized page instance by using a page template loaded into memory from the file system of the front-end Web server.

             Page ghosting is valuable because it eliminates the need to transfer the contents of a page definition file from the SQL Server computer with the content database to the front-end Web server computer. Page ghosting also makes it possible to process the home pages for thousands of different

sites by using a single page template that is compiled into an assembly DLL and loaded into memory in the IIS worker process just once per Web application. Both of these optimizations are key factors in the scalability of WSS in high-traffic environments running thousands or tens of thousands of sites.

            When you modify a page and save a customized version of it in the content database using SharePoint Designer, you eliminate the possibility of page ghosting. Instead, the provided SPVirtualPathProvider must retrieve the customized version of the page from the content database, as shown in Figure 2-6. For this reason, customized pages are sometimes referred to as unghosted pages.

            Now that you understand how WSS processes requests for both ghosted and unghosted pages, you should observe the important role that is played by the SPVirtualPathProvider. It is the SPVirtualPathProvider that determines whether the page being requested has been customized. The SPVirtualPathProvider makes the decision whether to process a page as a ghosted or an unghosted page.

             As a developer, your initial reaction to this might be to question why customized pages are processed in no-compile mode. Your instincts likely tell you that compiled pages run faster than no-compile pages. However, no-compile pages can be more efficient and more scalable in certain scenarios. This is especially true in a large WSS environment where the number of customized pages can reach into the thousands or tens of thousands.

              No-compile pages can be loaded into memory and then unloaded in a manner that is not possible for compiled pages because the .NET Framework doesn’t really support the concept of unloading an assembly DLL from memory. The closest equivalent would be to recycle the current Windows process or the current .NET AppDomain. However, this type of recycling involves unloading all assembly DLLs from memory, not just those assembly DLLs that haven’t been used recently. Furthermore, the .NET Framework places an upper limit on the number of assembly DLLs that can be loaded into a .NET AppDomain.

              No-compile pages provide higher levels of scalability because they do not require loading new assembly DLLs or managed classes into memory. Instead, the processing of no-compile pages involves loading control trees into memory. WSS can manage the memory usage for the control trees associated with customized pages more efficiently because they are not compiled into assembly DLLs. For example, once WSS has finished processing a customized page, it can unload the page’s control tree to free up memory for other purposes. Furthermore, no-compile pages eliminate the need to go through the compilation process, which actually provides faster response times for pages upon first access.

NOTE: Reference taken form Inside Microsoft Windows SharePoint Service 3.0

Thursday, September 27, 2007

Parameter Sniffing and SQL Server

        Today I came to know about an interesting point "Parameter Sniffing". I search on net and found some good material and facts about it. First, what is parameter sniffing? Below is the definition which I got from here.

"Parameter sniffing refers to a process whereby SQL Server's execution environment "sniffs" the current parameter values during compilation or recompilation, and passes it along to the query optimizer so that they can be used to generate potentially faster query execution plans. The word "current" refers to the parameter values present in the statement call that caused a compilation or a recompilation."

        When a stored procedure is created, a normalized query tree for the procedure is saved in the SYSPROCEDURES system table. The normalized query tree contains the referenced table/view and column information. The process of normalization parses the SQL statements into a more efficient format and resolves all referenced objects into their internal representations. During this process, table names, for example, are resolved into their object IDs and column names are resolved into column IDs. When the procedure is subsequently executed, the tree is retrieved from SYSPROCEDURES, and based on it, an optimized execution plan is created and stored in the procedure cache.

        For stored procedures that accept parameters that can be used in the WHERE clause, the execution plan in the procedure cache is the optimized path to the data (based on the parameters given during the first execution of the procedure). For such procedures, if the parameters can be significantly different for each execution of the procedure, it is probably worth exploring the use of the WITH RECOMPILE option during execution or even during the creation of the procedure. This does add the overhead of having to generate the execution plan for each execution of the procedure.
        The additional execution plans stay in cache until they are paged out, and could cause one execution to be very different from another. A user has no control or knowledge of which plan will be used. This can sometimes explain unexpectedly different execution times for the same procedure given the same data and parameters.

You can get more information on parameter sniffing at link shown below.

1. http://omnibuzz-sql.blogspot.com/2006/11/parameter-sniffing-stored-procedures.html

2. http://furrukhbaig.wordpress.com/2007/08/22/parameter-sniffing/

3. http://support.microsoft.com/kb/104445

Happy Programming !!

HTTP could not register URL http://+:8000/. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details)

        You may find this error when you try to register WCF service host using HTTP binding in windows vista. I had the same problem and I found the perfect solution here.

Saturday, September 01, 2007

Value does not fall within the expected range exception while using ReportDataSource

           Here is my code which produce "Value does not fall within the expected range" exception. 

 ReportDataSource objReportDataSource 
              = new ReportDataSource("CategoryProduct");
 objReportDataSource.Name = "NewDataSet_CategoryProducts";
 // dsDataSet is DataSet object
 objReportDataSource.Value = dsData;

            After doing some try and error method I found that this exception is due to objReportDataSource.Value = dsData. You need to assign a DataTable to Value property instead of DataSet. Below is the code that is working fine.

 ReportDataSource objReportDataSource 
              = new ReportDataSource("CategoryProduct");
 objReportDataSource.Name = "NewDataSet_CategoryProducts";
 // dsDataSet is DataSet object
 objReportDataSource.Value = dsData.Tables[0];

Happy Programming !!!

Friday, August 31, 2007

Storing and Retrieving doc/pdf/xls files in SQL Server

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

 

 

Thursday, August 30, 2007

Great tool for LINQ Query

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

Happy Programmig !!

Saturday, August 25, 2007

How to use transaction in LINQ using C#

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 own stored procedures and views with LINQ. You may require to use transaction with your own SPs for 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.

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.

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 parameter in SP.

Now, lets look in to 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 !!

Thursday, August 23, 2007

Raise event from user control to main page / Event delegation from user control to aspx page in ASP.NET,C#

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

<
html xmlns="http://www.w3.org/1999/xhtml" >
<
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 !!!

Tuesday, August 21, 2007

Application failed to initialize properly(0xcC000142). Press OK to terminate the application

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

Hide console window in console application

          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

Happy Programming !!!

Thursday, August 16, 2007

Viewpoint content is not displayed OR Mime type for Viewpoint content

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

Wednesday, August 08, 2007

Generate thumbnail image in dotnet

          If you have created any e-commerce site, you must have used thumbnail image to display product. You may have seen many sites which display thumbnail image and product description and when user click on image it shows large image of the product.  You can do this by uploading two different images for each product OR by uploading a single image and runtime generate thumbnail image from that. You can easily do that in dotnet using "GetThumbnailImage" method. Below is the code for that,

function GenerateThumbnailImage()
{

        System.Drawing.Image imgThumbImage;
        System.Drawing.Image imgOriginalImage = 
                 new Bitmap(Server.MapPath(".")
                       + "\\Images\\bike1.jpg");

        using (imgThumbImage = 
            imgOriginalImage.GetThumbnailImage(50, 50, 
            new System.Drawing.Image.GetThumbnailImageAbort 
            (Abort), IntPtr.Zero))
        {
                imgThumbImage.Save(Response.OutputStream, 
                System.Drawing.Imaging.ImageFormat.Jpeg);
        }
}

private bool Abort()
{
        return false;
}

Fig - (1)  Generate thumbnail image

Happy Programming !!

Get height and width of image / Generate image object from byte array

          We are storing image in database in our recent project. We do not store height and width for that image in database.  After few months of deployment the client wants to display the height and width of each image while we display image.  As we do not store height and width in database we need to find that runtime when we load the image from database. Below is the code that we used to solve our issue,

using (SqlConnection cnn = new SqlConnection(ConnectionString))
{
            try
            {
                cnn.Open();
                SqlCommand cmd = new SqlCommand("select
                             [Image] from   tableName where ID = 1"
);
                cmd.Connection = cnn;
                Byte[] bytImage = (Byte[])cmd.ExecuteScalar();

               // Generate Image from Byte array
                System.Drawing.Image img =
                            System.Drawing.Image.FromStream
                            (new System.IO.MemoryStream(bytImage));

                // If you are storing image in specific folder instead
                // of database then you can use following code to
                // generate image

                System.Drawing.Image img = 
                            System.Drawing.Image.FromFile
                            (@"D:\ExampleWeb Projects\Learn2K5
                            \ms.gif"
);

                //  Display Height and Width
                Response.Write("Height : " + img.Height.ToString()
                             + "   Width : " + img.Width.ToString());
            }
            finally
            {
                cnn.Close();
            }
}

Fig - (1) Generate image object from byte array and get height and width

Happy Programming !!!