Sunday, May 27, 2007

Ways of using Web service from JavaScript


1. Client side <--> ASPX page <--> Web service.
2. Client side <--> HTC file <--> Web service.
3. Client side <--> AJAX <--> Web service.
4. Client side <--> SOAP Request/Response <--> Web service.


1. Create a dummy aspx page that is used by JavaScript to use Web Service functions. JavaScript class calls aspx page and in turn aspx page calls Web Service. Here aspx page use Web Service by adding a Web Reference in project and create a object of Web Service class and process it as normal function calling.


2. HTC Usage –


HTML Page ----



<body>
<div id="service" style="behavior: url(webservice.htc)">

-------------
-------------

</body>





Java Script File ----



function asyncWSCall(strMethodName, strCountryName, boolAsync)
{
strMethodName == "getCurrentPositionData" ; //WebService function name

// Establish the friendly name "WS" for the WebServiceURL
//service.useService("http://localhost/DemoApp/SampleWebService.asmx?WSDL","WS");

// The following uses a callback handler named " processgetCurrentPositionData"
iCallID = service.WS.callService(processgetCurrentPositionData,
strMethodName, strCountryName, boolAsync);
}


function processgetCurrentPositionData(result)
{
-------
-------

document.getElementById('txtAr').value = result.value.xml;
}




Web Service ----


[WebMethod]
public XmlDocument getCurrentPositionData(string countryName, bool boolAsync)
{
------
------
}




3. AJAX Usage –

HTML Page ----


<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="scriptManagerId">
<services>
<asp:ServiceReference Path="WSForAJAX.asmx" />
</services>
</asp:ScriptManager>

-----
-----

</body>




Java Script File ----



function wsCallForCurrentPostion()
{
WSForAJAX.getCurrentPositionData(OnSucceededWithContext, OnFailed,"XmlDocument");
}



// This is the callback function invoked if the Web service succeeded.
// It accepts the result object, the user context, and the calling method name as parameters.
function OnSucceededWithContext(result, userContext, methodName)
{
var RsltElem = document.getElementById('txtAr').value;

var readResult;
if (userContext == "XmlDocument")
{
if (document.all)
readResult = result.documentElement.firstChild.text;
else // Firefox
readResult = result.documentElement.firstChild.textContent;

RsltElem.innerHTML = "XmlDocument content: " + readResult;
}
}



// This is the callback function invoked if the Web service failed.
// It accepts the error object as a parameter.
function OnFailed(error)
{
// Display the error.
var RsltElem = document.getElementById("ResultId");
RsltElem.innerHTML = "Service Error: " + error.get_message();
}




Web Service ----



[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public XmlDocument getCurrentPositionData(string countryName, bool boolAsync)
{
----
----
}




4. SOAP Usage –


Java Script File ----



//Function to create parameter for WebService method.
function createWSParam()
{
var strMethodName = 'getCurrentPositionData' ;
var strSoapContent = '<countryName>' + count4WSCall + '</ countryName >\n'
+ '<boolAsync>' + strCountryName + '</ boolAsync >\n' ;
}





//Function to create SOAP data packet.
function createSOAPData(strMethodName, strSoapContent)
{
var soapAction = 'http://tempuri.org/' + strMethodName ;
var url = 'http://localhost/DemoApp/SampleWebService.asmx' ;
var data = '<?xml version=\'1.0\' encoding=\'utf-8\'?>\n'
+'<soap:Envelope xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-
instance\' xmlns:xsd=\'http://www.w3.org/2001/XMLSchema\'
xmlns:soap=\'http://schemas.xmlsoap.org/soap/envelope/\'>\n'
+ '<soap:Body>\n'
+ '<' + strMethodName + ' xmlns=\'http://tempuri.org/\'>\n'
+ strSoapContent
+ '</' + strMethodName + '>\n'
+ '</soap:Body>\n'
+'</soap:Envelope>' ;
}





//Function to create XMLHttpRequest.
function getXmlHttpObject()
{
var xmlhttp ;
if(window.ActiveXObject)
{
try
{
xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (ex)
{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
}
else if (window.XMLHttpRequest) //For Non-IE
{
xmlhttp = new XMLHttpRequest();
}
}





//Function to send the SOAP Request.
function sendSOAPDataToWebService(xmlhttp, url, data, soapAction)
{
xmlhttp.open('POST', url, true);
xmlhttp.onreadystatechange = processgetSOAPResponseData ;
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.setRequestHeader('SOAPAction', soapAction);
xmlhttp.send(data);
}





//Function to process the SOAP Response.
function processgetSOAPResponseData()
{
if (xmlhttp.readyState == 4)
{
if (xmlhttp.status == 200) // only if "OK"
{
try
{
if (window.ActiveXObject) // code for IE
{
doc = new ActiveXObject("Microsoft.XMLDOM");

doc.async="false";
doc.loadXML(xmlhttp.responseText);
}
else // code for Mozilla, Firefox, Opera, etc.
{
var parser=new DOMParser();
doc = parser.parseFromString(xmlhttp.responseText,"text/xml");
}

var rootNode = doc.documentElement;
// documentElement always represents the root node

if( rootNode.childNodes[0].childNodes[0].childNodes[0].nodeName
== "getCurrentPositionDataResult" )
{
//Method to process the SOAP data
getCurrentPositionData(rootNode) ;
}
}
catch (ex)
{
}
}
}
}



Web Service ----



[WebMethod]
public XmlDocument getCurrentPositionData(string countryName, bool boolAsync)
{
------
------
}








Suggested Links:

AJAX Example
http://ajax.asp.net/docs/ViewSample.aspx?sref=Sys.Net.SimpleWebService/cs/SimpleWebService.asmx

Use of Xml in AJAX
http://ajax.asp.net/docs/tutorials/CreateSimpleAJAXApplication.aspx
http://ajax.asp.net/docs/ViewSample.aspx?sref=EnhancingJavaScript/cs/Inheritance.aspx

HTC -
http://msdn.microsoft.com/archive/default.asp?url=/archive/en-us/samples/internet/behaviors/library/webservice/default.asp

HTC Example -
http://msdn2.microsoft.com/en-us/library/ms531033.aspx

HTC Result Object example --
http://msdn2.microsoft.com/en-us/library/ms531058.aspx

Debugging of Javascript

1) In IE –
Simply use external .js file


<script language="javascript" src="JavaScripts/WSCallViaHTC.js" type="text/javascript"></script>



2) In Mozilla –

a) FireBug enables you to step through client script and examine HTML DOM elements.
It also provides a script console, a command line, and other tools.




b) The JavaScript Debugger (also known as "Venkman") provides a JavaScript
debugging environment that includes a source-code browser and other features.




c) Web Developer Extension enables you to inspect the DOM and CSS styles.
 
Suggested Link:
Debugging Javascripts --
http://ajax.asp.net/docs/overview/92684ea0-7bb4-4a34-9203-3aa6394ce375.aspx

Issues related to multiple browser compatibility

Following are the issuses that i faced while developing a multiple browser compatible application:

1. Web service call should be SOAP Request/Response.



var strMethodName = 'getCurrentPositionData' ;
var strSoapContent =
'<counter4RouteID>' + count4WSCall + '</counter4RouteID>\n'
+ '<countryName>' + strCountryName + '</countryName>\n' ;



var soapAction = 'http://tempuri.org/' + strMethodName ;
var url = 'http://localhost/VEVistaMashUp/VEVistaMashUpService.asmx' ;
var data = '<?xml version=\'1.0\' encoding=\'utf-8\'?>\n'
+'<soap:Envelope xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-instance\'
xmlns:xsd=\'http://www.w3.org/2001/XMLSchema\'
xmlns:soap=\'http://schemas.xmlsoap.org/soap/envelope/\'>\n'
+ '<soap:Body>\n'
+ '<' + strMethodName + ' xmlns=\'http://tempuri.org/\'>\n'
+ strSoapContent
+ '</' + strMethodName + '>\n'
+ '</soap:Body>\n'
+'</soap:Envelope>' ;





2. To use SOAP Request/Response we have to create the xmlHttp object. In IE we use ActiveXObject while in Non-IE we use XMLHttpRequest ().



var xmlhttp ;
if(window.ActiveXObject)
{
try
{
xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (ex)
{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
}
else if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}





3. SOAP request should be Asynchronous in case of Mozilla while IE support both Synchronous and Asynchronous web service call.



xmlhttp.open('POST', url, true);
xmlhttp.onreadystatechange = processgetCurrentPositionData ;
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.setRequestHeader('SOAPAction', soapAction);
xmlhttp.send(data);





4. IE support both xmlHttpObject.responseXml and xmlHttpObject.responseText while Mozilla supports only xmlHttpObject.responseText.


xmlhttp .responseText




5. For using xmlDocument in JavaScript we have use Microsoft.xmlDom in IE and DomParser in case of Non-IE browser.



if (xmlhttp4CurrentPos.readyState == 4)
{
if (xmlhttp4CurrentPos.status == 200) // only if "OK"
{
try
{
if (window.ActiveXObject) // code for IE
{
doc = new ActiveXObject("Microsoft.XMLDOM");

doc.async="false";
doc.loadXML(xmlhttp4CurrentPos.responseText);
}
else // code for Mozilla, Firefox, Opera, etc.
{
var parser=new DOMParser();
doc = parser.parseFromString(xmlhttp4CurrentPos.responseText,"text/xml");
}

var rootNode = doc.documentElement; // documentElement always represents the root node

if( rootNode.childNodes[0].childNodes[0].childNodes[0].nodeName == "getCurrentPositionDataResult" )
{
getCurrentPositionData(rootNode) ;
}
}
catch (ex)
{
}
}
}




6. Mozilla require ‘px’ to every points while IE assume unit without any ‘px’ or ‘%’ as ‘px’.



objMenu.style.left = vLeft + 'px';
objMenu.style.top = vTop + 'px';




7. In IE ‘event ‘ is a global variable that always refer to the current event while in Mozilla you have to explicitly specified the event with method.



onmouseover="displayInfo(event);"

function displayInfo(evt)
{
......
......
var e = (window.event) ? window.event : evt;
......
......
}




8. Mozilla don’t support document.all [‘tagID’], while document.getElementById (‘tagID’) is supported by every browser.


document.getElementById("flashObj")


9. Require to set the z-index in case of Opera to see the some object over another object.


z-index: 2


10. To insert some html as string during runtime requires '<div> …</div>’ tags in Non-IE while its work fine in IE. Also IE require some width of control. In case of button – it has some default height width but if your page consists of only DIV tag then we have to specify some height and width to it.



var strMediaPlayerContent = "<div>" ;

......
......

var objMediaPlayer = document.getElementById('div4MediaPlayer') ;
objMediaPlayer.innerHTML = strMediaPlayerContent + "</div>" ;


11. We have to create graphic object in case of Non-IE when we are using Virtual Earth APIs.


map = new VEMap( "USMap" );

if( typeof( window.innerWidth ) == 'number' ) //Non IE
Msn.Drawing.Graphic.CreateGraphic=function(f,b) { return new Msn.Drawing.SVGGraphic(f,b) }

map.LoadMap(new VELatLong(lat4USAirCraft, long4USAirCraft), 10 ,'h' ,true);

map.HideDashboard();


12. In JavaScript Debugger of Mozilla – after code execution cursor move to catch line (even if the code is correct).

13. In Mozilla use ‘\\’ instead of ‘/’ to specify file Path while using Query string.



"Videos\\Sample.MPG";


14. JavaScript debuggers in case of Mozilla are – Fire Bug, JavaScript Debugger and Error Console.


Ways of using object in HTML

1) Following code snippet displays the use Window Media player in HTML page ---




<object id="Player" width="320" height="300" classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6">
<param name="bgcolor" value="#FF9900" />
<param name="Volume" value="50" />
<param name="AutoStart" value="True" />
<embed type='application/x-mplayer2' id='Player' name='mediaPlayer' width="100%" height="100%" autostart='True' src='Videos/Sample.MPG' showcontrols='0' showtracker='0' showdisplay='0' showstatusbar='0' videoborder3d='0'>
</embed>
</object>




2) Following code snippet displays the use Flash object in HTML page ---




<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="100%" height="100%" id="sample" align="middle">
<param name="movie" value="externalinterface.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<param name="allowScriptAccess" value="always" />
<embed src="externalinterface.swf" allowscriptaccess="always" quality="high" bgcolor="#ffffff" width="100%" height="100%" name="sample" align="middle" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>






In IE we use ‘<object>……</object>’ tag while in Non-IE we use ‘<embed>……</embed>’ tag.

Friday, May 25, 2007

How to use WIX's ServiceInstall to install Windows Service?

In continuation of my previos post ( How to create an installer using WIX ... )...
Following is code snippet for using ServiceInstall in WIX...



<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
<Product Id="832B8322-6349-4ddd-8AC6-CF18E7A05509" Name="DotNetService"
Language="1033" Version="1.0.0.0" Manufacturer="Persistent"
UpgradeCode="6493A097-BA2D-482b-9EDD-2BDBC3E5463E">
<Package InstallerVersion="200" Compressed="yes" />
<Media Id="1" Cabinet="WixServiceInstaller.cab" EmbedCab="yes" />
<Directory Id='TARGETDIR' Name='SourceDir'>
<Directory Id='ProgramFilesFolder' Name='PFiles'>
<Directory Id='DOTNETSERVICE' Name='DotNet'>
<Component Id="InstallService" Guid='AAA67783-EEF0-453f-BBAF-E02B1341E3BC'>
<File Id="WindowsService" Name="WixServiceInstaller.exe"
Source="WixServiceInstaller.exe" KeyPath="yes"/>
<ServiceInstall Id="ABC"
Name="WixServiceInstaller"
DisplayName="WixServiceInstaller"
Type="ownProcess"
Start="auto"
ErrorControl="normal"
Description="WixServiceInstaller"
Account="[SERVICEACCOUNT]"
Password="[SERVICEPASSWORD]" />
<ServiceControl Id="StartWixServiceInstaller"
Name="WixServiceInstaller" Start="install" Wait="no" />
<ServiceControl Id="StopWixServiceInstaller" Name="WixServiceInstaller"
Stop="both" Wait="yes" Remove="uninstall" />
</Component>
</Directory>
</Directory>
</Directory>
<Feature Id='TheOnlyFeature' Description='Feature contains the single component'
Level='1'>
<ComponentRef Id='InstallService'/>
</Feature>
</Product>
</Wix>



Suggested Link:
Installing Services using Wix-
http://blogs.madtechnology.net/blogs/chris/archive/2007/05/04/684.aspx

Thursday, May 24, 2007

How to create an installer using WIX which installs a Windows Service?

This tutorial walks you through how to create an installer using WIX which installs a Windows Service.

1) Create a configuration file that specifies the supported frameworks, named it WixWinServiceConfig.xml.



<?xml version="1.0"?>
<configuration>
<startup>
<supportedRuntime version="v2.0.50727"/>
</startup>
</configuration>

2) Put your InstallUtilLib.dll, SampleWindowsService.exe (EXE of Windows Service) and WixWinServiceConfig.xml in a folder (I placed these files in folder that contains candle.exe and light.exe for simplicity). You can find the InstallUtilLib.dll in your %windir%\Microsoft.NET\Framework\v2.0.50727\ directory. Once you have these three files, you can start coding the WXS file.

3) Create a wxs file named WindowsServiceWixProject.wxs. For full code refer Appendix.
InstallUtilLib.dll added in wxs file as a binary. This file does all the works of installing the services.

To perform a managed install of the service, you need four custom actions - two deferred custom actions for installing and uninstalling, one commit custom action and one rollback custom action. As these custom actions execute in the higher security context, you need to pass data to these custom actions using four separate 'Set Property' custom actions.

To maintain the sequence of actions, <installexecutesequence> is used in wxs file.

4) After creating the WindowsServiceWixProject.wxs file, compile it with candle.exe. After compilation WindowsServiceWixProject.wixobj file gets created. Then link the WindowsServiceWixProject.wixobj file with light.exe. This results in the creation of WindowsServiceWixProject.msi file.


Figure 1: Compliation and Link of Wix's files

5) To install the msi installer, run following command
msiexec /i WindowsServiceWixProject.msi


Figure 2: Installation of msi file

6) To uninstall the msi installer, run following command
msiexec /uninstall WindowsServiceWixProject.msi


Figure 3: Uninstallation of msi file


Figure 4: Uninstallation of msi file


Figure 5: Uninstallation of msi file

Appendix


WindowsServiceWixProject.wxs




<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
<Product Id="182a4509-6086-4eed-b1e7-b155aa1e7ea5" Name="DotNetService"
Language="1033" Version="1.0.0.0" Manufacturer="Persistent"
UpgradeCode="49c8c75a-5210-4944-b2b8-69814e6a874d">
<Package InstallerVersion="200" Compressed="yes" />

<Media Id="1" Cabinet="WindowsServiceWixProject.cab" EmbedCab="yes" />

<Directory Id='TARGETDIR' Name='SourceDir'>
<Directory Id='ProgramFilesFolder' Name='PFiles'>
<Directory Id='DOTNETSERVICE' Name='DotNet'>
<Component Id='TheService' Guid='a464e2d9-a75e-4996-9f54-fd5155c3c35a'>
<File Id='WindowsService' Name='SampleWindowsService.exe'
KeyPath='yes' DiskId='1' Source='SampleWindowsService.exe' />
<File Id='ConfigFile' Name='WixWinServiceConfig.xml' DiskId='1'
Source='WixWinServiceConfig.xml' CompanionFile='WindowsService'/>
</Component>
</Directory>
</Directory>
</Directory>

<Feature Id='TheOnlyFeature' Description='Feature contains the single component' Level='1'>
<ComponentRef Id='TheService'/>
</Feature>

<!-- Including the InstallUtilLib.dll. This file does all
the works of installing the services. -->
<Binary Id='InstallUtil' SourceFile='InstallUtilLib.dll' />

<!--Write custom actions to install, uninstall, commit and rollback the changes-->
<CustomAction Id='InstallServiceSetProp' Property='InstallService' Value='/installtype=notransaction /action=install /LogFile= "[#WindowsService]" "[DOTNETSERVICE]WixWinServiceConfig.xml"'/>
<CustomAction Id='InstallService' BinaryKey='InstallUtil'
DllEntry='ManagedInstall' Execute='deferred' />

<CustomAction Id='UnInstallServiceSetProp' Property='UnInstallService' Value='/installtype=notransaction /action=uninstall /LogFile= "[#WindowsService]" "[DOTNETSERVICE]WixWinServiceConfig.xml"'/>
<CustomAction Id='UnInstallService' BinaryKey='InstallUtil'
DllEntry='ManagedInstall' Execute='deferred' />

<CustomAction Id='CommitServiceSetProp' Property='CommitService' Value='/installtype=notransaction /action=commit /LogFile= "[#WindowsService]" "[DOTNETSERVICE]WixWinServiceConfig.xml"'/>
<CustomAction Id='CommitService' BinaryKey='InstallUtil'
DllEntry='ManagedInstall' Execute='commit' />

<CustomAction Id='RollbackServiceSetProp' Property='RollbackService' Value='/installtype=notransaction /action=rollback /LogFile= "[#WindowsService]" "[DOTNETSERVICE]WixWinServiceConfig.xml"'/>
<CustomAction Id='RollbackService' BinaryKey='InstallUtil'
DllEntry='ManagedInstall' Execute='rollback' />

<!-- Now to sequence these Custom Actions in the execute sequence -->

<InstallExecuteSequence>

<Custom Action='UnInstallServiceSetProp' After='MsiUnpublishAssemblies'>$TheService=2</Custom>
<Custom Action='UnInstallService' After='UnInstallServiceSetProp'>$TheService=2</Custom>

<Custom Action='InstallServiceSetProp' After='StartServices'>$TheService>2</Custom>
<Custom Action='InstallService' After='InstallServiceSetProp'>$TheService>2</Custom>

<Custom Action='RollbackServiceSetProp' After='InstallService'>$TheService>2</Custom>
<Custom Action='RollbackService' After='RollbackServiceSetProp'>$TheService>2</Custom>

<Custom Action='CommitServiceSetProp' After='RollbackService'>$TheService>2</Custom>
<Custom Action='CommitService' After='CommitServiceSetProp'>$TheService>2</Custom>

</InstallExecuteSequence>
</Product>
</Wix>






WixWinServiceConfig.xml





<?xml version="1.0"?>
<configuration>
<startup>
<supportedRuntime version="v2.0.50727"/>
</startup>
</configuration>




Suggested Links:

1) Installing Windows Services (Created with .NET) with WIX---

http://blog.vagmim.com/2004/09/installing-windows-services-created.html

How to create a Windows Service?

This tutorial walks you through how to and use your Windows Service. This Service writes some text to a text file when you start and stop the Windows Service.

1) To create a new Windows Service, pick Windows Service option from your Visual C#/Windows Projects. Name your Windows Service project as SampleWindowsService (you can write any nameJ) and click OK.


Figure 1: Windows Service Project

2) Name the Window Service as WixService in solution explorer, then go to the WixService.cs file to add functionalities to Windows Service.

In WixService.cs, there are two overridden functions OnStart and OnStop. The OnStart function executes when you start your Windows Service and the OnStop function gets execute when you stop your Windows Service. Here to check the Windows Service, you can write some text to a text file when you start and stop the service.



protected override void OnStart(string[] args)
{
// TODO: Add code here to start your service.
FileStream fs = new FileStream(@"C:\WIX_Work\SampleWindowsService\WixService.txt",
FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine("WixService: Service Started \n");
sw.Flush();
sw.Close();
}
protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
FileStream fs = new FileStream(@"C:\WIX_Work\SampleWindowsService\WixService.txt",
FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine("WixService: Service Stopped \n");
sw.Flush();
sw.Close();
}


3) Now to add an installer to SampleWindowsService project. Go back to the design surface for WixService and right-click on it. Select Add Installer, which creates a new component called ProjectInstaller and adds it to the project.

4) Select the ServiceProcessInstaller1 control on the ProjectInstaller design surface. Change the Account property in its Properties window to LocalSystem. Then select the ServiceInstaller1 control. In its Properties window, change the ServiceName property to WixService. Now build the project. This creates SampleWindowsService.exe for the service.

5) Now you're ready to install the service. To install the Windows Service, open the Visual Studio 2005 Command Prompt. Run the installutil.exe by providing the path of SampleWindowsService.exe path.


Figure 2: Installation of Windows Service

6) After installing the Windows Service, open the Services. To open Services, use services.msc in Run command prompt. Services display the newly installed Windows Service i.e. WixService.


Figure 3: WixService in Services Window

7) To uninstall the Windows Service, use /u with installutill.exe in command prompt.


Figure 4: Uninstallation of WixService

8) To Start/Stop the Windows Service, select the service, click Start/Stop button present in the toolbar or select the appropriate menu by right-clicking on selected service.


Figure 5: WixService Start/Stop

9) When you Start/Stop the Windows Service, text entries occurs in the specified text file.


Figure 6: Text file that contains text, when Windows Service Start/Stop

Appendix

WixService.cs



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.IO;

namespace SampleWindowsService
{
public partial class WixService : ServiceBase
{
public WixService()
{
InitializeComponent();
}

protected override void OnStart(string[] args)
{
// TODO: Add code here to start your service.

FileStream fs = new FileStream(
@"C:\WIX_Work\SampleWindowsService\WixService.txt",
FileMode.OpenOrCreate, FileAccess.Write);

StreamWriter sw = new StreamWriter(fs);
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine("WixService: Service Started \n");
sw.Flush();
sw.Close();
}

protected override void OnStop()
{
// TODO: Add code here to perform any tear-down
//necessary to stop your service.

FileStream fs = new FileStream(
@"C:\WIX_Work\SampleWindowsService\WixService.txt",
FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine("WixService: Service Stopped \n");
sw.Flush();
sw.Close();
}
}
}





Google