Archive

Archive for the ‘.Net’ Category

Retain the value of a dynamic control on post back

January 25th, 2010 14 comments

I heard this question several time that how you can retain the value of dynamically created controls on postbacks. You might see this before that when you create dynamic controls either in GridView or page. When you do postback, you cannot find the controls in page or GridView.

If you want your dynamic controls to work you can create them on page_load or page_init methods. But in some cases you have to create controls on some control event other than page_laod or page_init. In these cases you can follow my blog to retain the values of dynamic controls on postbacks.

In my case I have a button named btnSetParameters. On click event I’m creating controls in a GridView column. I have an ASP .Net panel in that column. My code is creating dynamic controls and then adding them to panel. But on postback I couldn’t found these controls in GridViewRow by their IDs. I need their values on postback.

For this I have created an ArrayList to keep controls.

Private objControlsList As New ArrayList

Then on RowDataBound where I was creating dynamic controls I added some code to add these controls in ArrayList. Here is an example of adding a TextBox in ArrayList. ASP Panel in GridViewRow name is pnlControls.

Dim txtValue As New TextBox
txtValue.ID = “txtValue1″
CType(e.Row.FindControl(“pnlControls”), Panel).Controls.Add(txtValue)
objControlsList.Add(txtValue)

Do the same for all the dynamic controls and add them on ArrayList. You can even put custom controls in this ArrayList. After adding all the controls, put this ArrayList in Session.

Session.Add(“ControlsList”, objControlsList)

Now on page postback, use the controls from the ArrayList. Use the UniqueID to pick the values from the ViewState for orginal controls.

Dim txtSaved As TextBox = CType(objControlsTempList(counter), TextBox)
txtValue.Text = Request.Form(txtSaved.UniqueID).ToString()
counter += 1

For dynamic DropDownlist control you can use this piece of code.

Dim ddlSaved As DropDownList = CType(objControlsTempList(counter), DropDownList)
ddlSaved.SelectedValue = Request.Form(ddlSaved.UniqueID).ToString()
counter += 1

For radio buttons you can use this piece of code. You must define a group name while creating the radio buttons to use this code.

Dim rdSaved As RadioButton = CType(objControlsTempList(counter), RadioButton)
Dim radioName As String = (rdSaved.ClientID).Remove(rdSaved.ClientID.LastIndexOf(“_”)).Replace(“_”, “$”) + “$” + rdSaved.GroupName
If Request.Form(radioName) <> Nothing Then
        selectedValue = Request.Form(radioName).ToString()
End If

Now you can match this selectedValue with radio buttons in the Panels, to find the selected radio button.

For CheckBoxe controls you can use this code.

Dim chSaved As CheckBox = CType(objControlsTempList(counter), CheckBox)
If Request.Form(chSaved.UniqueID) <> Nothing Then
        chSaved.Checked = True
Else
        chSaved.Checked = False
End If

Finally, you can use this code for dynamic custom control. It’s a bit tricky to find the value. I know the structure of my custom user control. It is a custom date control. It is actually creating two DropDownList controls for day and month part of date. And it is also creating a TextBox control for Year part of the date. Here is the piece of code I use to get the selected value of dynamic custom control on postback.

Dim dtSaved As CustomDate = CType(objControlsTempList(counter), CustomDate)
Dim cntlName As String = “”
Dim selectedDate As String = “”
cntlName = (dtSaved.ClientID + “_ddlDay”).Replace(“_”, “$”)
selectedDate = Request.Form(cntlName).ToString()

cntlName = (dtSaved.ClientID + “_ddlMonth”).Replace(“_”, “$”)
selectedDate += “/” + Request.Form(cntlName).ToString()

cntlName = (dtSaved.ClientID + “_txtYear”).Replace(“_”, “$”)
selectedDate += “/” + Request.Form(cntlName).ToString()

dateCtrl.DateValue = Date.Parse(selectedDate)
counter += 1

Hope it will help someone, creating dynamic controls and retain the values on postbacks.

Cheers

Disable submit button from client side

October 30th, 2009 5 comments

It seems very easy to disable ASP .Net submit button, but there are a lot of complications to perform this seemingly small thing. Usually when you disable ASP .Net submit button, it stops further processing. So if you disable button from JavaScript onclick function, it will not do postback. Sometime you want to disable submit button before page postback, for example if you have a file upload form and your code take some time to upload a big file, you might like to disable submit button. There are different solutions to solve this issue.
First solution is you can call the postback from client side JavaScript. For this I will prefer to write the JavaScript code from code behind file. You can attach an attribute like this

submit.Attributes.Add(“onclick”, “this.disabled=true;” + Page.ClientScript.GetPostBackEventReference(submit, “”));

But the problem with this solution is, if you have ASP .Net validation implemented on the controls. Even if it fails validation it fires post back event. In my form I also had ASP .Net validator. So I choose another option.
Solution is very simple, create another button with same text value and keep hidden. On client click of actual submit button hide submit button and show the hidden button. Make sure hidden button should be disabled. You can disable it from JavaScript as well. In this way user will not get idea that it’s a different button and it will also give an effect of disabled button.
Now if you are using ASP .Net validation, you would probably like to disable submit button when page validation is successful. So here is the code you can use.

protected override void OnInit(EventArgs e)
{
Button Submit = (Button)FindTemplateControl(“submit”);
Button Cancel = (Button)FindTemplateControl(“cancel”);
Button HiddenSubmit = (Button)FindTemplateControl(“hiddensubmit”);

string script = “if (!(typeof (ValidatorOnSubmit) == \”function\” && ValidatorOnSubmit() == false))”;
script += “{ “;
script += @”document.getElementById(‘” + Submit.ClientID + “‘).style.display=’none’;”;
script += @”document.getElementById(‘” + HiddenSubmit.ClientID + “‘).style.display=’inline’;”;
script += @”document.getElementById(‘” + HiddenSubmit.ClientID + “‘).disabled=true;”;
script += @”document.getElementById(‘” + Cancel.ClientID + “‘).disabled=true;”;
script += @” } “;
script += @”else “;
script += @”return false;”;

Page.ClientScript.RegisterOnSubmitStatement(Page.GetType(), “DisableSubmitButton”, script);
}

Have fun :)

Success message using ASP .Net validators

October 29th, 2009 2 comments

Recently we have implemented a form containing file upload controls. We have used ASP .Net validators to validate fields. In ASP .Net validation you can display error message in Recently we have implemented a form containing file upload controls. We have used ASP .Net validators to validate fields. In ASP .Net validation you can display error message in ValidationSummary control, but you can’t display success message. My case was I had to display a message to users before file upload start. And obviously this message needs to appear after successful page validation and before page do a post back. So in case file upload take some time, user can see a message that file upload processing has been started.
Here how I achieve it. When you use ASP .Net validator in page, your ASP .Net validator generates some JavaScript code in page. If you see the source of html page you can see this function.

function WebForm_OnSubmit()
{
    if (typeof(ValidatorOnSubmit) == “function” && ValidatorOnSubmit() ==false)
        return false;
    return true;
}

Now you need to write some code for on submit function. Create a div in your page and add your message in it. Set the display as  none in style property. Here is the div I used for my file upload form.

<div id=”successmessage” style=”display:none; color:Red>
“Please wait for your confirmation message while we upload your files (for large files this may take a few minutes)”
</div>

Now add this piece of code in cs file.

protected override void OnInit(EventArgs e)
{
    string script = “if (typeof (ValidatorOnSubmit) == \”function\” && ValidatorOnSubmit() == false)”;
    script += @”return false;”;
    script += @”else “;
    script += @”document.getElementById(‘successmessage’).style.display=’block’”;
    Page.ClientScript.RegisterOnSubmitStatement(Page.GetType(), “SuccessMessage”, script);
}

That’s all, now when you press submit button, it validates page and display success message if successful. After implementing this code your html page source will be like this

function WebForm_OnSubmit()
{
    if (typeof (ValidatorOnSubmit) == “function” && ValidatorOnSubmit() == false)
        return false;
    else
        document.getElementById(‘successmessage’).style.display=’block’;

    if (typeof(ValidatorOnSubmit) == “function” && ValidatorOnSubmit() == false)
        return false;
    return true;
}

Maintain scroll position in postbacks

October 15th, 2009 9 comments

It’s a very small thing but some time you want to maintain the scroll position after postback. I recently had the same requirement. We have a control in the depth of the page and we have to maintain the position of the scroll after the postback. Thanks to .Net developers, it’s very simple now. You can set the page property like this

MaintainScrollPositionOnPostback=”true” in aspx page directive or

Page.MaintainScrollPositionOnPostback = true;  in c# code for page_load

I hope you enjoy this easiness of .Net.

Date handy fundtions

September 6th, 2009 Comments off

This is a very small thing, but sometimes it helps. I had a date and then I had to find the starting and end date of that month. Here how you can do this small thing in VB .Net. In this case ‘day’ is the date. 

Dim startDate As Date = Date.Parse(“01/” + day.Month.ToString() + “/” + day.Year.ToString())
Dim endDate As Date = startDate.AddMonths(1)
endDate = endDate.AddDays(-1)

you can also use the available functions AddYears and AddMonths.

Cheers

Categories: .Net Tags: , , ,

Convert Infix To Postfix Using C#

August 31st, 2009 Comments off

I remember in mid 2007 I was looking for some CSharp code to convert from infix to postfix. Unfortunately I couldn’t found any readymade code to so. At that time I have written this code. It might be of any help to you. It’s the conversion of algorithm to convert from infix to postfix. If you need any further understanding about this code you are welcome to ask me.

 

private void infixToPostfix(string strExpression)
{
  try

  {
    string strExp = strExpression;
    string
outputExp = string.Empty;
    string
strRevExp = reverseString(strExp);
    string temp = string
.Empty;    while (strRevExp.Length > 0)
    {
      if (strRevExp.IndexOf(” “
) != -1)
        temp = strRevExp.Substring(0, strRevExp.IndexOf(
” “
));
      else

        temp = strRevExp;
      if (!isOperator(temp) && temp != “(“ && temp != “)”)
        outputExp +=
” “
+ temp;
      else if (temp == “)”
)
        sExp.Push(temp);
      else if
(isOperator(temp))
      {
        while (true
)
        {
          if
(sExp.Count == 0)
          {
            sExp.Push(temp);
            break
;
          }
          else if (sExp.Peek() == “)”
)
          {
            sExp.Push(temp);
            break
;
          }
          else if
(isGreaterEqual(temp, sExp.Peek()))
          {
            sExp.Push(temp);
            break
;
          }
          else

            outputExp +=
” “ + sExp.Pop();
        }
      }
      else if (temp == “(“
)
      {
        while (sExp.Peek() != “)”
)
          outputExp +=
” “
+ sExp.Pop();
        sExp.Pop();
      }
      if (strRevExp.IndexOf(” “
) != -1)
        strRevExp = strRevExp.Remove(0, strRevExp.IndexOf(
” “
) + 1);
      else

        strRevExp =
“”;
    }
    while
(sExp.Count != 0)
      outputExp +=
” “
+ sExp.Pop();  catch (Exception ex)
  {
    WriteException(
“infixToPostfix”
, ex);
  }
}

Private string reverseString(string actualString)
{
  string reverseString = string
.Empty;
  try

  {
    string[] strRevExpArray = actualString.Split(‘ ‘);
    for (int
i = strRevExpArray.Length – 1; i >= 0; i–)
      reverseString +=
” “
+ strRevExpArray[i];
    reverseString = reverseString.TrimStart();
  }
  catch (Exception
ex)
  {
    WriteException(
“reverseString”
, ex);
  }
  return
reverseString;
}

Cheers.

Categories: .Net Tags: , , ,

Create a Web Service Installer (Part – 2)

May 25th, 2009 5 comments

If you are using Visual Studio 2005 to create an installer you will see that your installer is a bit different as I said in first part. First of all you might have to foloow almost the same steps but with minor changes.
Secondly in the end you can see that the Installer created by VS 2005 does not provide the option to select the Application pool to the user at the time of Installation. Also it doesn’t set the required ASP .Net version.
It keeps the same ASP .Net version as the parent application.
It’s not a big deal you can change them manually, but sometime as in my case my client would be more happy to see all the things done through installer. So I oppt the ‘Custom Actions’ to handle this scenerio. Even if you
are a user of VS 2008 you can get benefit from this post by get some idea about ‘Custom Actions’ in Windows Installers.
To add the custom action you have to use the installer class. For this we will add another project in the solution. This will be a Class Library project. And then we will add a new ‘Installer Class’ in new project.
Code listing
 

normal;mso-layout-grid-align:none;text-autospace:none”>
using style=”font-size:10.0pt;font-family:”Courier New”;mso-no-proof:yes”>
System.Collections.Generic;

 

normal;mso-layout-grid-align:none;text-autospace:none”>
using style=”font-size:10.0pt;font-family:”Courier New”;mso-no-proof:yes”>
System.Text;

 

normal;mso-layout-grid-align:none;text-autospace:none”>
using style=”font-size:10.0pt;font-family:”Courier New”;mso-no-proof:yes”>
System.Configuration;

 

normal;mso-layout-grid-align:none;text-autospace:none”>
using style=”font-size:10.0pt;font-family:”Courier New”;mso-no-proof:yes”>
System.Configuration.Install;

 

normal;mso-layout-grid-align:none;text-autospace:none”>
using style=”font-size:10.0pt;font-family:”Courier New”;mso-no-proof:yes”>
System.ComponentModel;

 

normal;mso-layout-grid-align:none;text-autospace:none”>
using style=”font-size:10.0pt;font-family:”Courier New”;mso-no-proof:yes”>
System.Diagnostics;

 

normal;mso-layout-grid-align:none;text-autospace:none”>
using style=”font-size:10.0pt;font-family:”Courier New”;mso-no-proof:yes”>
System.IO;

 

normal;mso-layout-grid-align:none;text-autospace:none”>
using style=”font-size:10.0pt;font-family:”Courier New”;mso-no-proof:yes”>
System.DirectoryServices;

 

normal;mso-layout-grid-align:none;text-autospace:none”>
 

 

normal;mso-layout-grid-align:none;text-autospace:none”>
namespace style=”font-size:10.0pt;font-family:”Courier New”;mso-no-proof:yes”>
MyCustomActions

 

normal;mso-layout-grid-align:none;text-autospace:none”>
{

 

normal;mso-layout-grid-align:none;text-autospace:none”>
  �
[RunInstaller( style="color:blue">true
)]

 

normal;mso-layout-grid-align:none;text-autospace:none”>
  �
public partial
class
CustomActionInstaller
: Installer

 

normal;mso-layout-grid-align:none;text-autospace:none”>
  �
{

 

normal;mso-layout-grid-align:none;text-autospace:none”>

      
public CustomActionInstaller()

 

normal;mso-layout-grid-align:none;text-autospace:none”>
      �
{

 

normal;mso-layout-grid-align:none;text-autospace:none”>
          �
InitializeComponent();

 

normal;mso-layout-grid-align:none;text-autospace:none”>
      �
}

 

normal;mso-layout-grid-align:none;text-autospace:none”>
 

 

normal;mso-layout-grid-align:none;text-autospace:none”>
      �
public override
void Install(System.Collections. style=”color:#2B91AF”>IDictionary
stateSaver)

 

normal;mso-layout-grid-align:none;text-autospace:none”>
      �
{

 

normal;mso-layout-grid-align:none;text-autospace:none”>
          �
base.Install(stateSaver);

 

normal;mso-layout-grid-align:none;text-autospace:none”>
 

 

normal;mso-layout-grid-align:none;text-autospace:none”>
          �
// Retrieve configuration settings

 

normal;mso-layout-grid-align:none;text-autospace:none”>
          �
string targetSite = Context.Parameters[ style="color:#A31515">"targetsite"
];

 

normal;mso-layout-grid-align:none;text-autospace:none”>
          �
string targetVDir = Context.Parameters[ style="color:#A31515">"targetvdir"
];

 

normal;mso-layout-grid-align:none;text-autospace:none”>
          �
string targetDirectory =
Context.Parameters["targetdir"];

 

normal;mso-layout-grid-align:none;text-autospace:none”>
          �
string appPoolName = Context.Parameters[ style="color:#A31515">"apn"
];

 

normal;mso-layout-grid-align:none;text-autospace:none”>
 

 

normal;mso-layout-grid-align:none;text-autospace:none”>
          �
if (targetSite ==
null)

 

normal;mso-layout-grid-align:none;text-autospace:none”>
              �
throw new
InstallException(“IIS
Site Name Not Specified!”
);

 

normal;mso-layout-grid-align:none;text-autospace:none”>
 

 

normal;mso-layout-grid-align:none;text-autospace:none”>
          �
if (targetSite.StartsWith( style=”color:#A31515″>”/LM/”
))

 

normal;mso-layout-grid-align:none;text-autospace:none”>
              �
targetSite = targetSite.Substring(4);

 

normal;mso-layout-grid-align:none;text-autospace:none”>
 

 

normal;mso-layout-grid-align:none;text-autospace:none”>
          �
RegisterScriptMaps(targetSite, targetVDir);

 

normal;mso-layout-grid-align:none;text-autospace:none”>
          �
AssignVDirToAppPool(“IIS://localhost/”
+ targetSite + “/Root/” + targetVDir,
appPoolName);

 

normal;mso-layout-grid-align:none;text-autospace:none”>
      �
}

 

normal;mso-layout-grid-align:none;text-autospace:none”>
 

 

normal;mso-layout-grid-align:none;text-autospace:none”>
      �
void RegisterScriptMaps( style=”color:blue”>string
targetSite, string
targetVDir)

 

normal;mso-layout-grid-align:none;text-autospace:none”>
      �
{

 

normal;mso-layout-grid-align:none;text-autospace:none”>
  �
        
// Calculate Windows path

 

normal;mso-layout-grid-align:none;text-autospace:none”>
          �
string sysRoot = System. style=”color:#2B91AF”>Environment
.GetEnvironmentVariable( style=”color:#A31515″>”SystemRoot”);

 

normal;mso-layout-grid-align:none;text-autospace:none”>
 

 

normal;mso-layout-grid-align:none;text-autospace:none”>
          �
// Launch aspnet_regiis.exe utility to
configure mappings

 

normal;mso-layout-grid-align:none;text-autospace:none”>
          �
ProcessStartInfo info =
new ProcessStartInfo();

 

normal;mso-layout-grid-align:none;text-autospace:none”>
   �
       
info.FileName = Path.Combine(sysRoot,

@”Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe”
);

 

normal;mso-layout-grid-align:none;text-autospace:none”>
          �
info.Arguments = string.Format( style=”color:#A31515″>”-s {0}/ROOT/{1}”
, targetSite, targetVDir);

 

normal;mso-layout-grid-align:none;text-autospace:none”>
          �
info.CreateNoWindow = true;

 

normal;mso-layout-grid-align:none;text-autospace:none”>
          �
info.UseShellExecute = false;

 

normal;mso-layout-grid-align:none;text-autospace:none”>
 

 

normal;mso-layout-grid-align:none;text-autospace:none”>
          �
Process.Start(info);

 

normal;mso-layout-grid-align:none;text-autospace:none”>
      �
}

 

normal;mso-layout-grid-align:none;text-autospace:none”>
 

 

normal;mso-layout-grid-align:none;text-autospace:none”>
      �
static void
AssignVDirToAppPool(string vdirPath,
string appPoolName)

 

normal;mso-layout-grid-align:none;text-autospace:none”>
      �
{

 

normal;mso-layout-grid-align:none;text-autospace:none”>
          �
// 
vdirPath is of the form “IIS://<servername>/<siteID>/Root[/<vDir>]” style=”mso-spacerun:yes”>          �

 

normal;mso-layout-grid-align:none;text-autospace:none”>
          �
// 
appPoolName is of the form “<name>”, for example, “MyAppPool”

 

normal;mso-layout-grid-align:none;text-autospace:none”>
 

 

normal;mso-layout-grid-align:none;text-autospace:none”>
          �
try

 

normal;mso-layout-grid-align:none;text-autospace:none”>
          �
{

 

normal;mso-layout-grid-align:none;text-autospace:none”>
              �
DirectoryEntry vDir =
new DirectoryEntry(vdirPath);

 

normal;mso-layout-grid-align:none;text-autospace:none”>
              �
string className =
vDir.SchemaClassName.ToString();

 

normal;mso-layout-grid-align:none;text-autospace:none”>
              �
if (className.EndsWith( style=”color:#A31515″>”VirtualDir”
))

 

normal;mso-layout-grid-align:none;text-autospace:none”>
              �
{

 

normal;mso-layout-grid-align:none;text-autospace:none”>
                  �
object[] param = { 0, appPoolName,
true };

 

normal;mso-layout-grid-align:none;text-autospace:none”>
                  �
vDir.Invoke(“AppCreate3″, param);

 

normal;mso-layout-grid-align:none;text-autospace:none”>
                  �
vDir.Properties["AppIsolated"][0] =
“2″;

 

normal;mso-layout-grid-align:none;text-autospace:none”>
                  �
Console.WriteLine( style=”color:#A31515″>” Done.”
);

 

normal;mso-layout-grid-align:none;text-autospace:none”>
              �
}

 

normal;mso-layout-grid-align:none;text-autospace:none”>
          �
}

 

normal;mso-layout-grid-align:none;text-autospace:none”>
          �
catch (Exception
ex) { }

 

normal;mso-layout-grid-align:none;text-autospace:none”>
      �
}

 

normal;mso-layout-grid-align:none;text-autospace:none”>
  �
}

}

 

I’m not going into the details of the methods, these are pretty staright
forward methods. you can understand them easily. In ‘SetFrameWorkForApps’ we are
doing the framework check and then update it as required. In ‘AssignVDirToAppPool’
we set the application pool. which we get from the suer as input through the
custom UI in windows installer.

But this time on Step 3 you have your own custom UI. Here user can give the
Application Pool name, like I use the application pool name as i required for my
application.

Amazingly when you go in IIS Manager you will be happy to see that your new
application is created with the defined ‘Application Pool’ and Framework is also
set as required to the application.
Summary
I’m sure this will be a helpful article to start with Setup projects both in Visual Studio 2005 and Visual Studio 2008. If you need any further help kindly do write to me.

 

normal;mso-layout-grid-align:none;text-autospace:none”>
using style=”font-size:10.0pt;font-family:”Courier New”;mso-no-proof:yes”>
System;

Add a new project and give it some name. To add a Installer Class, right click
on the Class Library Project and then select ‘New Item’.

Choose ‘Installer Class’ and give it some name. Now we have to add this class
library in Installer Project. Go back to the Web Installer Project and repeat
the same step. Right Click the ‘bin’ under ‘Web Application Folder’ in ‘File
System’ view and then select the ‘Add’ ‘Project Output’, this time you will have
two projects in project drop down. Select the Class Library Project and choose
‘Primary Output’ from the list, click the Ok button.

Now if you are a VS 2005 user, you will see the difference with VS 2008
installer here. As in VS 2008 the bin folder only contains the executable dlls.
Whereas in VS 2005 solution you have to add your ‘Primary Output’ in bin folder,
this also copy highlighted two files in bin folder rather you can see these
files in ‘Web Application Folder’ in VS 2008.

To change the application pool on user input we have to add some custom UI in
Windows Installer. For this right click on the Setup Project and select View ->
User Interface. Here you will see all the forms use by installer.

Right click on Start and select ‘Add Dialog’, then Choose a dialog from the
predefined templates.

Now open the properties of the newly created dialog. and change them as per
required as I have made a few changes for my installer.

Change the order of the forms.

You are done with the UI.  Your new UI is ready to be display in the
installer steps. But now you have to use the user input in installer class to
set the Application Pool. Right click on the Project and select the View ->
Custom Actions.

Now right click on Install and select Add Custom Action.  Select the
‘Primary Output from the ‘MyCustiomAction’ project. I will add the project
output as Custom Action for Install process.

Open the properties of added ‘Primary Output … ‘ and set the CustomActionData
as

/targetdir=”[TARGETDIR]\” /apn=”[APNAME]” /targetvdir=”[TARGETVDIR]”
/targetsite=”[TARGETSITE]”

Here actually we set the variables we use in future in code. As we defined the
text box name to APNAME in the custome form we added to get the user input for
Application Pool. No we set the variable for this field to ‘apn’. So in code now
we use this ‘apn’ as user input.

Now first we will add some code in out installer class and then come back to
further configuration in setup project. As I discussed before if you are using
Visual Studio 2005 your application installer will not set ‘Application Pool’
and ‘ASP .Net’ version for you. Now we are going to write code for these two to
make this possible through custom actions. Open your Installer Class and copy
and paste the following code there.

Ok we are pretty much done. Now if you want to make some mroe customization with
the Installer UI, you can do it. But keep in mind the that there are very
limited options to customize the Installer UI.

OK now build the main application if required, then Class Library Project and
then the Setup Project. Your installer is ready for you. Run the installer and
you will see that on Step 2 you don’t have any option to select the application
pool like the users of the Visual Studio 2008 have. 

Add ‘Custom Actions’ to the Visual Studio 2005 Installer


If you are not creating a very simple installer. You must have to use ‘Custom Actions’. As there could be a lot of scenerios, like you have to set application pool(For VS 2005 users), you might have to set some
registry informations, set the ASP .Net version as required(For VS 2005 users), you might have to set the database connection string at the time of installation. Luckily you can do all these things through custom actions.
You can define custom actions for different stages for installer. Like before install, install, after install, same for uninstall.
Categories: .Net Tags:

Create a Web Service Installer (Part – 1)

May 24th, 2009 13 comments
I’m writing this article because I read a lot fo articles on the internet to create an installer for web applications. But none of them was comprehensive. In recent days I have to create a setup project for Web Services project and I couldn’t find any thing helpfull.

To add a Web Setup Project in your solution, just right click the solution and select Add -> ‘New Project’

It will be in ‘Other Project Types’ -> ‘Setup and Deployment’ -> ‘Web Setup Project’.

Name it whatever you want and hit ok. It will then show up in your solution explorer as a separate project.

Our next step will be to configure the web setup project to take the compiled assemblies (\bin directory contents) + content markup (.aspx, .config, etc files) from our Web Application Project and use them as inputs within our setup project. To-do this, right-click on the web setup project and choose the ‘Add -> Project Output’ from the menu.

It will appear a dialog, select ‘Primary Output’ and ‘Content Files’ from the list and press ‘Ok’.

This will add concerned files in their respective locations. The good thing about the Windows Installer is this that now you shouldn’t be worry about any changes occur in your web services application. As whenever the dll for web services application has been change, you just compile the setup project and it will add the new dll from the source directory.

Below is the view of ‘Web Application Folder’ after last step.

Now here is the view of ‘Bin’ folder, you can see that it copies all the required dlls to run the application. As in my case it copied the dlls of Sharepoint as well.


Ok, before doing the build action, we can make small configurations for the application. Right click on the ‘Web Application Folder’ in Setup project and select Properties. Now change the ‘DefaultDocument’ to one you want as default, like in my case I choose ‘GetSharePointData.asmx’. Also change the ‘VirtualDirectory’ name to ‘MySharePointServices’. You can change the name of Virtual Directory from the Installer.

When i was working on it i was creating web services for a sharepoint site, but this is a generic installer and you can use it anywhere. We can achieve the deployment work in other ways as well like using XCopy but doing deployment using Windows Installer is a much better way and you can leave deployment and configuration on normal users.

Alright now lets start to play with visual studio and .Net, consider we have already created a web service application and now we want to deploy these web services on live or staging servers.
Add a Web Setup Project to the Solution

 Now build the Setup Project, for this right click on the ‘MyApplicationInstaller’ and choose ‘Build’. It will create the Installer for your web services project. It create a MSI file. You observed that compilation of the Setup project is a bit slower. It because of the fact that it add all the content files and dlls in package, so if you have number of things in your application it will take more time to create a Installer.

One more thing to remeber that you have to build the Setup project seprately,
because by default Visual Studio does not include the Setup project in build
process. So if you are doing build action from solution. it will just build the
main application and not the Setup project.

Thats all your Installer is ready, just pick the MSI file from the ‘Debug’ folder in ‘MyApplicationInstaller’ project directory and place it on the cleint machine and just run the ‘MSI’.

Here you can select the application pool for your web application. As my
application need to run under the same application pool as of SharePoint site. I
select the required one. You can also set the Virtual Directory name here.

Now if you open the IIS Manager, you can open it by using the command ‘inetmgr’ in ‘Run’ console. You can see the new web application created by your own installer in the ‘Default Web Site’ node.
If you right click on the application and open the ‘Properties’, you will see the it set the application pool you selected in Installer and it also set the ASP .Net version for your application. As my application required ASP .Net 2.0, so it sets it to ASP .Net 2.0.

Note: I have developed the whole Installer using Visual Studio 2008. If your are using Visual Studio 2005, you have to set application pool and ASP .Net version your self. Here is a small difference between the VS 2005 and VS 2008 Installers. But don’t you worry in my next step I’m doing this using ‘Custom Actions’. So you can also get the understanding of using ‘Custom Actions’ for Windows Installer.

Part – 2

Categories: .Net Tags: , ,