using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.Collections.Specialized;
using System.Xml;
using System.Diagnostics;
using System.Data.SqlClient; 
using System.Windows.Forms;

namespace InstallerActions.Install
{
	/// <summary>
	/// Summary description for SetupApp.
	/// </summary>
	[RunInstaller(true)]
	public class SetupApp : System.Configuration.Install.Installer
	{
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;
		private IISVirDirCreator virDirCreator;

		public SetupApp()
		{
			// This call is required by the Designer.
			InitializeComponent();

			// TODO: Add any initialization after the InitializeComponent call
		}

		/// <summary> 
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		///<summary>
		///Perform database steps during the install process - Create database and objects, grant permissions and load data
		///</summary>
		public override void Install(IDictionary stateSaver)
		{
			base.Install (stateSaver);
			
			try
			{
	
				if(this.Context!=null)
				{
					StringDictionary parameters = Context.Parameters  ;
					
					string[] keys =new string[parameters.Count];
					parameters.Keys.CopyTo(keys,0); 
					#region "Region 1: Set the StateServer collection values"
					for(int intKeys=0;intKeys<keys.Length;intKeys++)
					{
						if (keys[intKeys].Equals("targetdir"))
						{
							// MessageBox.Show("Target Dir:" + keys[intKeys] + "; Value : " + parameters[keys[intKeys]].ToString());
							stateSaver.Add("targetdir",parameters[keys[intKeys]].ToString()); 	
						}

						if (keys[intKeys].Equals("webserver"))
						{
							// MessageBox.Show("Webserver:" + keys[intKeys] + "; Value : " + parameters[keys[intKeys]].ToString());
							stateSaver.Add("webserver",parameters[keys[intKeys]].ToString()); 	
						}
						
						/* if(keys[intKeys].Equals("database_name"))
						{							
							stateSaver.Add("database_name",parameters[keys[intKeys]].ToString()); 	
						} */
						
						if(keys[intKeys].Equals("db_server_name") )
						{							
							stateSaver.Add("db_server_name",parameters[keys[intKeys]].ToString()); 	
						}
						
						if(keys[intKeys].Equals("db_user_name"))
						{							
							stateSaver.Add("db_user_name",parameters[keys[intKeys]].ToString()); 	
						}
						
						if(keys[intKeys].Equals("db_password"))
						{							
							stateSaver.Add("db_password",parameters[keys[intKeys]].ToString()); 	
						}						

						if ( keys[intKeys].Equals ( "manufacturer_database" ) )
							stateSaver.Add ( "manufacturer_database", parameters[keys[intKeys]].ToString () ) ;

						if ( keys[intKeys].Equals ( "shipping_agent_database" ) )
							stateSaver.Add ( "shipping_agent_database", parameters[keys[intKeys]].ToString () ) ;

						if ( keys[intKeys].Equals ( "receiving_agent_database" ) )
							stateSaver.Add ( "receiving_agent_database", parameters[keys[intKeys]].ToString () ) ;

						if ( keys[intKeys].Equals ( "receiver_database" ) )
							stateSaver.Add ( "receiver_database", parameters[keys[intKeys]].ToString () ) ;

					}
					#endregion

					#region "Evaluate database connection string"
					//can encrypt here...

					// MessageBox.Show("Setting connection string");
					string connectionstring= "Data Source=" + stateSaver["db_server_name"].ToString() ;					
					bool trustedConnection=false;
					string manufacturerConnectionString = connectionstring ;
					string shippingAgentConnectionString = connectionstring ;
					string receivingAgentConnectionString = connectionstring ;
					string receiverConnectionString = connectionstring ;
					// connectionstring+= ";Initial Catalog=" + stateSaver["database_name"].ToString() ;
					manufacturerConnectionString += ";Initial Catalog=" + stateSaver["manufacturer_database"].ToString () ;
					shippingAgentConnectionString += ";Initial Catalog=" + stateSaver["shipping_agent_database"].ToString () ;
					receivingAgentConnectionString += ";Initial Catalog=" + stateSaver["receiving_agent_database"].ToString () ;
					receiverConnectionString += ";Initial Catalog=" + stateSaver["receiver_database"].ToString () ;

					try
					{
						if(stateSaver["db_user_name"]!=null && stateSaver["db_user_name"].ToString().Length!=0)
						{
							//Here you need to test the connection...and proceed.
							SqlConnection conn =new SqlConnection( "Data Source=" + stateSaver["db_server_name"].ToString()
								+ ";Initial Catalog=master;User Id=" + stateSaver["db_user_name"].ToString() +";Password=" + stateSaver["db_password"].ToString());
							conn.Open();
							conn.Close();
							conn.Dispose();

							// connectionstring+= ";User ID=" + stateSaver["db_user_name"].ToString() ;
							// connectionstring+= ";Password=" + stateSaver["db_password"].ToString() ;
							manufacturerConnectionString+= ";User ID=" + stateSaver["db_user_name"].ToString() ;
							manufacturerConnectionString+= ";Password=" + stateSaver["db_password"].ToString() ;
							shippingAgentConnectionString+= ";User ID=" + stateSaver["db_user_name"].ToString() ;
							shippingAgentConnectionString+= ";Password=" + stateSaver["db_password"].ToString() ;
							receivingAgentConnectionString+= ";User ID=" + stateSaver["db_user_name"].ToString() ;
							receivingAgentConnectionString+= ";Password=" + stateSaver["db_password"].ToString() ;
							receiverConnectionString+= ";User ID=" + stateSaver["db_user_name"].ToString() ;
							receiverConnectionString+= ";Password=" + stateSaver["db_password"].ToString() ;
						}
						else
						{
							//Here you need to test the connection...and proceed.
							SqlConnection conn =new SqlConnection( "Data Source=" + stateSaver["db_server_name"].ToString()
								+ ";Initial Catalog=master;trusted_connection=yes");
							conn.Open();
							conn.Close();
							conn.Dispose();

							trustedConnection=true;
							stateSaver.Add("trustedconnection",true);
							// connectionstring+=";Trusted_connection=yes";
							manufacturerConnectionString+=";Trusted_connection=yes";
							shippingAgentConnectionString+=";Trusted_connection=yes";
							receivingAgentConnectionString+=";Trusted_connection=yes";
							receiverConnectionString+=";Trusted_connection=yes";
						}
					}
					catch (Exception ex)
					{
						throw new InstallException("Could not connect to database. " + ex.ToString()); 
					}

					//MessageBox.Show(connectionstring);
					#endregion

					#region "Update Database connection string in web.config"

					XmlDocument doc = new XmlDocument();
					XmlNode wsURLNode;
					doc.Load(stateSaver["targetdir"].ToString()+ "MicrosoftEPCISDemoWeb\\" + @"Web.config");

					/*
					 * //MessageBox.Show("In Update Database Connection string");
					wsURLNode = doc.SelectSingleNode(@"configuration/appSettings/add[@key='ConnectionString']");
					//MessageBox.Show(wsURLNode.ToString());
					if(wsURLNode!=null)
					{						
						wsURLNode.Attributes["value"].Value = connectionstring;						
						doc.Save( stateSaver["targetdir"].ToString()+ "MicrosoftEPCISDemoWeb\\" + @"Web.config");												
						//MessageBox.Show("Saved Web.config 1");
					}
					else
					{						
						//This error will ensure installation is uncomplete...
						throw new InstallException("Configuration file had no node declared for Connection string."); 
					}*/

					wsURLNode = doc.SelectSingleNode ( @"configuration/appSettings/add[@key='ManufacturerString']" ) ;

					if ( wsURLNode != null )
					{
						wsURLNode.Attributes["value"].Value = manufacturerConnectionString ;
						doc.Save ( stateSaver["targetdir"].ToString () + "MicrosoftEPCISDemoWeb\\" + @"Web.config" ) ;
					}

					else
						throw new InstallException ( "Configuration file had no node declared for Manufacturer's connection-string. " ) ;

					wsURLNode = doc.SelectSingleNode ( @"configuration/appSettings/add[@key='ShippingAgentString']" ) ;

					if ( wsURLNode != null )
					{
						wsURLNode.Attributes["value"].Value = shippingAgentConnectionString ;
						doc.Save ( stateSaver["targetdir"].ToString () + "MicrosoftEPCISDemoWeb\\" + @"Web.config" ) ;
					}

					else
						throw new InstallException ( "Configuration file had no node declared for Shipping Agent's connection-string. " ) ;

					wsURLNode = doc.SelectSingleNode ( @"configuration/appSettings/add[@key='ReceivingAgentString']" ) ;

					if ( wsURLNode != null )
					{
						wsURLNode.Attributes["value"].Value = receivingAgentConnectionString ;
						doc.Save ( stateSaver["targetdir"].ToString () + "MicrosoftEPCISDemoWeb\\" + @"Web.config" ) ;
					}

					else
						throw new InstallException ( "Configuration file had no node declared for Receiving Agent's connection-string. " ) ;

					wsURLNode = doc.SelectSingleNode ( @"configuration/appSettings/add[@key='ReceiverString']" ) ;

					if ( wsURLNode != null )
					{
						wsURLNode.Attributes["value"].Value = receiverConnectionString ;
						doc.Save ( stateSaver["targetdir"].ToString () + "MicrosoftEPCISDemoWeb\\" + @"Web.config" ) ;
					}

					else
						throw new InstallException ( "Configuration file had no node declared for Receiver's connection-string. " ) ;

					doc.Load(stateSaver["targetdir"].ToString()+ "MicrosoftEPCISDemoASNGenerationWS\\" + @"Web.config");

					wsURLNode = doc.SelectSingleNode(@"configuration/appSettings/add[@key='ManufacturerString']");
					if(wsURLNode!=null)
					{						
						wsURLNode.Attributes["value"].Value = manufacturerConnectionString ;						
						doc.Save( stateSaver["targetdir"].ToString()+ "MicrosoftEPCISDemoASNGenerationWS\\" + @"Web.config");
						//MessageBox.Show("Saved Web.config 2");
					}
					else
					{						
						//This error will ensure installation is uncomplete...
						throw new InstallException("Configuration file had no node declared for connectiong string."); 
					}

					doc.Load(stateSaver["targetdir"].ToString()+ "ManufacturerWS\\" + @"Web.config");

					wsURLNode = doc.SelectSingleNode(@"configuration/appSettings/add[@key='ManufacturerString']");
					if(wsURLNode!=null)
					{						
						wsURLNode.Attributes["value"].Value = manufacturerConnectionString ;						
						doc.Save( stateSaver["targetdir"].ToString()+ "ManufacturerWS\\" + @"Web.config");
						//MessageBox.Show("Saved Web.config 2");
					}
					else
					{						
						//This error will ensure installation is uncomplete...
						throw new InstallException("Configuration file had no node declared for connectiong string."); 
					}

					doc.Load(stateSaver["targetdir"].ToString()+ "ShippingAgentWS\\" + @"Web.config");

					wsURLNode = doc.SelectSingleNode(@"configuration/appSettings/add[@key='ShippingAgentString']");
					if(wsURLNode!=null)
					{						
						wsURLNode.Attributes["value"].Value = shippingAgentConnectionString ;						
						doc.Save( stateSaver["targetdir"].ToString()+ "ShippingAgentWS\\" + @"Web.config");
						//MessageBox.Show("Saved Web.config 2");
					}
					else
					{						
						//This error will ensure installation is uncomplete...
						throw new InstallException("Configuration file had no node declared for connectiong string."); 
					}

					doc.Load(stateSaver["targetdir"].ToString()+ "ReceivingAgentWS\\" + @"Web.config");

					wsURLNode = doc.SelectSingleNode(@"configuration/appSettings/add[@key='ReceivingAgentString']");
					if(wsURLNode!=null)
					{						
						wsURLNode.Attributes["value"].Value = receivingAgentConnectionString ;						
						doc.Save( stateSaver["targetdir"].ToString()+ "ReceivingAgentWS\\" + @"Web.config");
						//MessageBox.Show("Saved Web.config 2");
					}
					else
					{						
						//This error will ensure installation is uncomplete...
						throw new InstallException("Configuration file had no node declared for connectiong string."); 
					}

					doc.Load(stateSaver["targetdir"].ToString()+ "ReceiverWS\\" + @"Web.config");

					wsURLNode = doc.SelectSingleNode(@"configuration/appSettings/add[@key='ReceiverString']");
					if(wsURLNode!=null)
					{						
						wsURLNode.Attributes["value"].Value = receiverConnectionString ;						
						doc.Save( stateSaver["targetdir"].ToString()+ "ReceiverWS\\" + @"Web.config");
						//MessageBox.Show("Saved Web.config 2");
					}
					else
					{						
						//This error will ensure installation is uncomplete...
						throw new InstallException("Configuration file had no node declared for connectiong string."); 
					}

					#endregion

					MessageBox.Show ( "Creating database. " ) ;
					#region "Create Database"
					DataBaseInstaller dbInstall =null;
					if(trustedConnection)
					{
						/* dbInstall= new DataBaseInstaller(stateSaver["db_server_name"].ToString(),stateSaver["database_name"].ToString(),
							stateSaver["targetdir"].ToString() + "Setup\\Scripts\\");
						dbInstall.CreateDataBase();
						dbInstall.CreateRecords(); */

						dbInstall= new DataBaseInstaller(stateSaver["db_server_name"].ToString(),stateSaver["manufacturer_database"].ToString(),
							stateSaver["targetdir"].ToString() + "Setup\\Scripts\\");
						dbInstall.CreateDataBase();
						dbInstall.CreateRecords();

						dbInstall= new DataBaseInstaller(stateSaver["db_server_name"].ToString(),stateSaver["shipping_agent_database"].ToString(),
							stateSaver["targetdir"].ToString() + "Setup\\Scripts\\");
						dbInstall.CreateDataBase();
						dbInstall.CreateRecords();

						dbInstall= new DataBaseInstaller(stateSaver["db_server_name"].ToString(),stateSaver["receiving_agent_database"].ToString(),
							stateSaver["targetdir"].ToString() + "Setup\\Scripts\\");
						dbInstall.CreateDataBase();
						dbInstall.CreateRecords();

						dbInstall= new DataBaseInstaller(stateSaver["db_server_name"].ToString(),stateSaver["receiver_database"].ToString(),
							stateSaver["targetdir"].ToString() + "Setup\\Scripts\\");
						dbInstall.CreateDataBase();
						dbInstall.CreateRecords();

					}
					else
					{
						/* dbInstall= new DataBaseInstaller(stateSaver["db_server_name"].ToString(),stateSaver["database_name"].ToString(),
							stateSaver["db_user_name"].ToString(),stateSaver["db_password"].ToString(),stateSaver["targetdir"].ToString() + "Setup\\Scripts\\");						
						dbInstall.CreateDataBase();
						dbInstall.CreateRecords(); */

						dbInstall= new DataBaseInstaller(stateSaver["db_server_name"].ToString(),stateSaver["manufacturer_database"].ToString(),
							stateSaver["db_user_name"].ToString(),stateSaver["db_password"].ToString(),stateSaver["targetdir"].ToString() + "Setup\\Scripts\\");						
						dbInstall.CreateDataBase();
						dbInstall.CreateRecords();

						dbInstall= new DataBaseInstaller(stateSaver["db_server_name"].ToString(),stateSaver["shipping_agent_database"].ToString(),
							stateSaver["db_user_name"].ToString(),stateSaver["db_password"].ToString(),stateSaver["targetdir"].ToString() + "Setup\\Scripts\\");						
						dbInstall.CreateDataBase();
						dbInstall.CreateRecords();

						dbInstall= new DataBaseInstaller(stateSaver["db_server_name"].ToString(),stateSaver["receiving_agent_database"].ToString(),
							stateSaver["db_user_name"].ToString(),stateSaver["db_password"].ToString(),stateSaver["targetdir"].ToString() + "Setup\\Scripts\\");						
						dbInstall.CreateDataBase();
						dbInstall.CreateRecords();

						dbInstall= new DataBaseInstaller(stateSaver["db_server_name"].ToString(),stateSaver["receiver_database"].ToString(),
							stateSaver["db_user_name"].ToString(),stateSaver["db_password"].ToString(),stateSaver["targetdir"].ToString() + "Setup\\Scripts\\");						
						dbInstall.CreateDataBase();
						dbInstall.CreateRecords();

					}

					#endregion


					#region "Create IIS Directories"

					//Call the constructor depending upon the web server specified
					if (stateSaver["webserver"].ToString().ToLower() == "localhost")
						virDirCreator = new IISVirDirCreator();					
					else
						virDirCreator = new IISVirDirCreator(stateSaver["webserver"].ToString());					


					virDirCreator.CreateVirtualDirectory("MicrosoftManufacturingEPCISDemo", stateSaver["targetdir"].ToString());
					//MessageBox.Show("Virtual directory 1 created:" + stateSaver["targetdir"].ToString());
					
					virDirCreator.CreateVirtualDirectory("MicrosoftEPCISDemoWeb", "MicrosoftManufacturingEPCISDemo", stateSaver["targetdir"].ToString() + "MicrosoftEPCISDemoWeb\\");
					//MessageBox.Show("Virtual directory 2 created:" + stateSaver["targetdir"].ToString()+ "MicrosoftEPCISDemoWeb\\");
					
					virDirCreator.CreateVirtualDirectory("MicrosoftEPCISDemoASNGenerationWS", "MicrosoftManufacturingEPCISDemo", stateSaver["targetdir"].ToString() + "MicrosoftEPCISDemoASNGenerationWS\\");
					//MessageBox.Show("Virtual directory 3 created:" + stateSaver["targetdir"].ToString()+ "MicrosoftEPCISDemoASNGenerationWS\\");

					virDirCreator.CreateVirtualDirectory("MicrosoftEPCISDemoASNReceivingWS", "MicrosoftManufacturingEPCISDemo", stateSaver["targetdir"].ToString() + "MicrosoftEPCISDemoASNReceivingWS\\");
					//MessageBox.Show("Virtual directory 4 created:" + stateSaver["targetdir"].ToString()+ "MicrosoftEPCISDemoASNReceivingWS\\");
					
					virDirCreator.CreateVirtualDirectory("ManufacturerWS", "MicrosoftManufacturingEPCISDemo", stateSaver["targetdir"].ToString() + "ManufacturerWS\\");

					virDirCreator.CreateVirtualDirectory("ShippingAgentWS", "MicrosoftManufacturingEPCISDemo", stateSaver["targetdir"].ToString() + "ShippingAgentWS\\");

					virDirCreator.CreateVirtualDirectory("ReceivingAgentWS", "MicrosoftManufacturingEPCISDemo", stateSaver["targetdir"].ToString() + "ReceivingAgentWS\\");

					virDirCreator.CreateVirtualDirectory("ReceiverWS", "MicrosoftManufacturingEPCISDemo", stateSaver["targetdir"].ToString() + "ReceiverWS\\");

					#endregion

					#region "Set the Config file's WS URL"	
					
					//MessageBox.Show( "before doc load");
					doc.Load(stateSaver["targetdir"].ToString()+ "MicrosoftEPCISDemoWeb\\" + @"Web.config");
					//MessageBox.Show( "after doc load");
					wsURLNode = doc.SelectSingleNode(@"configuration/appSettings/add[@key='ASNGenerationWSURL']");
					//MessageBox.Show( "after connection node");
					string asnGenerationWSURL = @"http://" + stateSaver["webserver"].ToString() + @"/MicrosoftManufacturingEPCISDemo/MicrosoftEPCISDemoASNGenerationWS/ASNGenerationService.asmx";
					if(wsURLNode!=null)
					{
						//MessageBox.Show( "before setting");
						wsURLNode.Attributes["value"].Value = asnGenerationWSURL;
						//MessageBox.Show( "after setting");
						doc.Save( stateSaver["targetdir"].ToString()+ "MicrosoftEPCISDemoWeb\\" + @"Web.config");
						//MessageBox.Show( "after save");
						//EventLog.WriteEntry("SetupDB","Configuration file processed..."); 					
					}
					else
					{						
						//This error will ensure installation is uncomplete...
						throw new InstallException("Configuration file had no node declared for ASN Generation WS URL."); 
					}

					wsURLNode = doc.SelectSingleNode(@"configuration/appSettings/add[@key='ASNReceivingWSURL']");
					//MessageBox.Show( "after connection node");
					string asnReceivingWSURL = @"http://" + stateSaver["webserver"].ToString() + @"/MicrosoftManufacturingEPCISDemo/MicrosoftEPCISDemoASNReceivingWS/ASNReceivingService.asmx";
					if(wsURLNode!=null)
					{
						//MessageBox.Show( "before setting");
						wsURLNode.Attributes["value"].Value = asnReceivingWSURL;
						//MessageBox.Show( "after setting");
						doc.Save( stateSaver["targetdir"].ToString()+ "MicrosoftEPCISDemoWeb\\" + @"Web.config");
						//MessageBox.Show( "after save");
						//EventLog.WriteEntry("SetupDB","Configuration file processed..."); 					
					}
					else
					{
						//This error will ensure installation is uncomplete...
						throw new InstallException("Configuration file had no node declared for ASN Receiving WS URL."); 
					}

					wsURLNode = doc.SelectSingleNode(@"configuration/appSettings/add[@key='ManufacturerWSURL']");
					//MessageBox.Show( "after connection node");
					string url = @"http://" + stateSaver["webserver"].ToString() + @"/MicrosoftManufacturingEPCISDemo/ManufacturerWS/ManufacturerWebService.asmx";
					if(wsURLNode!=null)
					{
						//MessageBox.Show( "before setting");
						wsURLNode.Attributes["value"].Value = url ;
						//MessageBox.Show( "after setting");
						doc.Save( stateSaver["targetdir"].ToString()+ "MicrosoftEPCISDemoWeb\\" + @"Web.config");
						//MessageBox.Show( "after save");
						//EventLog.WriteEntry("SetupDB","Configuration file processed..."); 					
					}
					else
					{
						//This error will ensure installation is uncomplete...
						throw new InstallException("Configuration file had no node declared for Manufacturer WS URL."); 
					}

					wsURLNode = doc.SelectSingleNode(@"configuration/appSettings/add[@key='ShippingAgentWSURL']");
					//MessageBox.Show( "after connection node");
					url = @"http://" + stateSaver["webserver"].ToString() + @"/MicrosoftManufacturingEPCISDemo/ShippingAgentWS/ShippingAgentWebService.asmx";
					
					if(wsURLNode!=null)
					{
						//MessageBox.Show( "before setting");
						wsURLNode.Attributes["value"].Value = url ;
						//MessageBox.Show( "after setting");
						doc.Save( stateSaver["targetdir"].ToString()+ "MicrosoftEPCISDemoWeb\\" + @"Web.config");
						//MessageBox.Show( "after save");
						//EventLog.WriteEntry("SetupDB","Configuration file processed..."); 					
					}
					else
					{
						//This error will ensure installation is uncomplete...
						throw new InstallException("Configuration file had no node declared for Shipping Agent WS URL."); 
					}

					wsURLNode = doc.SelectSingleNode(@"configuration/appSettings/add[@key='ReceivingAgentWSURL']");
					//MessageBox.Show( "after connection node");
					url = @"http://" + stateSaver["webserver"].ToString() + @"/MicrosoftManufacturingEPCISDemo/ReceivingAgentWS/ReceivingAgentWebService.asmx";
					
					if(wsURLNode!=null)
					{
						//MessageBox.Show( "before setting");
						wsURLNode.Attributes["value"].Value = url ;
						//MessageBox.Show( "after setting");
						doc.Save( stateSaver["targetdir"].ToString()+ "MicrosoftEPCISDemoWeb\\" + @"Web.config");
						//MessageBox.Show( "after save");
						//EventLog.WriteEntry("SetupDB","Configuration file processed..."); 					
					}
					else
					{
						//This error will ensure installation is uncomplete...
						throw new InstallException("Configuration file had no node declared for Receiving Agent WS URL."); 
					}

					//ramesh. bug fix.
					wsURLNode = doc.SelectSingleNode(@"configuration/appSettings/add[@key='ReceiverWSURL']");
					//MessageBox.Show( "after connection node");
					url = @"http://" + stateSaver["webserver"].ToString() + @"/MicrosoftManufacturingEPCISDemo/ReceiverWS/ReceiverWebService.asmx";
					
					if(wsURLNode!=null)
					{
						//MessageBox.Show( "before setting");
						wsURLNode.Attributes["value"].Value = url ;
						//MessageBox.Show( "after setting");
						doc.Save( stateSaver["targetdir"].ToString()+ "MicrosoftEPCISDemoWeb\\" + @"Web.config");
						//MessageBox.Show( "after save");
						//EventLog.WriteEntry("SetupDB","Configuration file processed..."); 					
					}
					else
					{
						//This error will ensure installation is uncomplete...
						throw new InstallException("Configuration file had no node declared for Receiver WS URL."); 
					}

					doc.Load(stateSaver["targetdir"].ToString()+ "ReceivingAgentWS\\" + @"Web.config");
					wsURLNode = doc.SelectSingleNode(@"configuration/appSettings/add[@key='ShippingAgentWSURL']");
					//MessageBox.Show( "after connection node");
					url = @"http://" + stateSaver["webserver"].ToString() + @"/MicrosoftManufacturingEPCISDemo/ShippingAgentWS/ShippingAgentWebService.asmx";
					
					if(wsURLNode!=null)
					{
						//MessageBox.Show( "before setting");
						wsURLNode.Attributes["value"].Value = url ;
						//MessageBox.Show( "after setting");
						doc.Save( stateSaver["targetdir"].ToString()+ "ReceivingAgentWS\\" + @"Web.config");
						//MessageBox.Show( "after save");
						//EventLog.WriteEntry("SetupDB","Configuration file processed..."); 					
					}
					else
					{
						//This error will ensure installation is uncomplete...
						throw new InstallException("Configuration file had no node declared for Shipping Agent WS URL."); 
					}

					#endregion
				
					#region "Display the readme.htm" file
					ProcessStartInfo psi = new ProcessStartInfo();
					string readmeFileURL = @"http://" + stateSaver["webserver"].ToString() + @"/MicrosoftManufacturingEPCISDemo/Setup/Readme.htm";
					psi.FileName = "iexplore";
					psi.Arguments = "-new " + readmeFileURL;
					Process.Start(psi);
					#endregion
				}
			}
				//Bcas the InstallException has been explicitly thrown by our custom code.
			catch(InstallException inst)
			{
				throw (inst);
			}
			catch(Exception generic)
			{
				//Since generic log and then throw the install exception.
				//EventLog.WriteEntry("SetupDB",generic.Message,EventLogEntryType.Error) ;
				throw new InstallException(generic.Message);
			}
		}

		public override void Rollback(IDictionary savedState)
		{
			 Uninstall ( savedState ) ;

		}


		///<summary>
		///Perform database steps during the install process - Create database and objects, grant permissions and load data
		///</summary>
		public override void Uninstall(IDictionary savedState)
		{
			try
			{
				//Drop the database				
				DataBaseInstaller dbInstall =null;
				if(savedState["trustedconnection"]!=null && (bool)savedState["trustedconnection"])
				{
					/* dbInstall= new DataBaseInstaller(savedState["db_server_name"].ToString(),savedState["database_name"].ToString(),
						savedState["targetdir"].ToString()+ "Setup\\Scripts\\");
					dbInstall.DropDataBase(); */

					dbInstall= new DataBaseInstaller(savedState["db_server_name"].ToString(),savedState["manufacturer_database"].ToString(),
						savedState["targetdir"].ToString()+ "Setup\\Scripts\\");
					dbInstall.DropDataBase();

					dbInstall= new DataBaseInstaller(savedState["db_server_name"].ToString(),savedState["shipping_agent_database"].ToString(),
						savedState["targetdir"].ToString()+ "Setup\\Scripts\\");
					dbInstall.DropDataBase();

					dbInstall= new DataBaseInstaller(savedState["db_server_name"].ToString(),savedState["receiving_agent_database"].ToString(),
						savedState["targetdir"].ToString()+ "Setup\\Scripts\\");
					dbInstall.DropDataBase();

					dbInstall= new DataBaseInstaller(savedState["db_server_name"].ToString(),savedState["receiver_database"].ToString(),
						savedState["targetdir"].ToString()+ "Setup\\Scripts\\");
					dbInstall.DropDataBase();

				}
				else
				{
					/* dbInstall= new DataBaseInstaller(savedState["db_server_name"].ToString(),savedState["database_name"].ToString(),
						savedState["db_user_name"].ToString(),savedState["db_password"].ToString(),savedState["targetdir"].ToString()+ "Setup\\Scripts\\");
					dbInstall.DropDataBase () ; */

					dbInstall= new DataBaseInstaller(savedState["db_server_name"].ToString(),savedState["manufacturer_database"].ToString(),
						savedState["db_user_name"].ToString(),savedState["db_password"].ToString(),savedState["targetdir"].ToString()+ "Setup\\Scripts\\");
					dbInstall.DropDataBase () ;

					dbInstall= new DataBaseInstaller(savedState["db_server_name"].ToString(),savedState["shipping_agent_database"].ToString(),
						savedState["db_user_name"].ToString(),savedState["db_password"].ToString(),savedState["targetdir"].ToString()+ "Setup\\Scripts\\");
					dbInstall.DropDataBase () ;

					dbInstall= new DataBaseInstaller(savedState["db_server_name"].ToString(),savedState["receiving_agent_database"].ToString(),
						savedState["db_user_name"].ToString(),savedState["db_password"].ToString(),savedState["targetdir"].ToString()+ "Setup\\Scripts\\");
					dbInstall.DropDataBase () ;

					dbInstall= new DataBaseInstaller(savedState["db_server_name"].ToString(),savedState["receiver_database"].ToString(),
						savedState["db_user_name"].ToString(),savedState["db_password"].ToString(),savedState["targetdir"].ToString()+ "Setup\\Scripts\\");
					dbInstall.DropDataBase () ;

				}
			
			}
			catch (Exception ex)
			{
				MessageBox.Show("Failed to drop database with the following database:\n" + "Server Name: " + savedState["db_server_name"].ToString() + 
					"\nDatabase Name: " + savedState["database_name"].ToString()+ 
					"Exception: " + ex.ToString());
			}

			//Delete the virtual directory
			try
			{
				//Call the constructor depending upon the web server specified
				if (savedState["webserver"].ToString().ToLower() == "localhost")
					virDirCreator = new IISVirDirCreator();					
				else
					virDirCreator = new IISVirDirCreator(savedState["webserver"].ToString());					


				virDirCreator.DeleteVirtualDirectory("MicrosoftManufacturingEPCISDemo", savedState["targetdir"].ToString());
				//MessageBox.Show("Virtual directory 1 created:" + stateSaver["targetdir"].ToString());
					
			}
			catch (Exception ex)
			{
				MessageBox.Show("Failed to delete virtual directory at the following webserver:\n" + "Server Name: " + savedState["webserver"].ToString() + 
					"\nVirtual Directory Name: MicrosoftManufacturingEPCISDemo" + 
					"Exception: " + ex.ToString());
			}
		}
		#region Component Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			components = new System.ComponentModel.Container();
		}
		#endregion
	}
}
