Saturday, August 21, 2010

Creating a Setup file/deployment (interface to install a application)

Creation of the interface for installing a windows application or a windows service.
------------------------------------------------------------------------------------

Step1:
--------
Be ready with your .exe file for which you want to create the installation interface/wizard.

Then open VisualStudio and go for new project-->Other projects type -->setup and deployment




Step2:
---------
Then you see the following interface after entering the project............this depends on the version of visual studio you are using.



Step3:
---------



Step4:
--------
Now select the exe file and the config file.
If you dont have any config file then choose only the exe file.


Step5:
---------



Step6:
---------



Step7:
--------



Step8:
--------


Step9:
--------

The final setup exe files are ready in the bin folder.

Creating a perfect sample Windows Service......

Below you can find how to create a windows service and handling all its events for writing a perfect working service and proper CPU consumption by the windows service.


Summary:

The below service is used for creating a file in a specified location and write the time into it at a specific time interval continiously untill you stop the service.




Step1:
-------
Open Visualstudio-->New project-->windows-->service/windowsservice.


Step2:
-------

Now you see the below screen as


step3:
-------
RightClick and choose the add Installer



Step4:
--------
Now you can see the following



Step5:
--------
Now you need to change the properties of the installers..........

Step6:
--------
Now start the coding.


SERVICE1.VB
code:






Imports System
Imports System.IO
Imports System.Configuration

Public Class Service1

'Declaring the global variables
Dim tmTimer As System.Timers.Timer = Nothing

Protected Overrides Sub OnStart(ByVal args() As String)
' Add code here to start your service.
' in motion so your service can do its work.
'Declaring the variable here
Dim itimeInterval As Integer = -1
Try
'geting time interval from app.config file
itimeInterval = CType(ConfigurationManager.AppSettings("TimeInterval"), Integer)
'initialiasing
tmTimer = New Timers.Timer(itimeInterval)
'starting the timer
tmTimer.Start()
'calling the function when timer finished
AddHandler tmTimer.Elapsed, AddressOf GenerateFile
'again resetting the properties
With tmTimer
.AutoReset = True
.Enabled = True
.Start()
End With
Catch ex As Exception
WriteEventlog(ex.ToString)
End Try
End Sub

Public Sub GenerateFile()
'Declaring the variables
Dim Fs As FileStream = Nothing
Dim Sw As StreamWriter = Nothing
Try
'Creating the objects to the variables
Fs = New FileStream("D:\NewtextFile.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite)
WriteEventlog("Done creating the file")
Sw = New StreamWriter(Fs)
Sw.WriteLine(DateTime.Now)
WriteEventlog("Done writing the data.")
Sw.Close()
Fs.Close()
Catch ex As Exception
WriteEventlog(ex.ToString)
Finally
Sw.Close()
Fs.Close()
If Sw IsNot Nothing Then Sw = Nothing
If Fs IsNot Nothing Then Fs = Nothing
End Try
End Sub

Private Sub WriteEventlog(ByVal tMsg As String)
'--------------------------------------------------------------------------------------------------
'Description : Logs the entries.
'------------------------------------------------------------------------------------------
Dim MyLog As New EventLog() ' create a new event log

Try
' Check if the the Event Log Exists
If Not Diagnostics.EventLog.SourceExists("File Writing") Then
Diagnostics.EventLog.CreateEventSource("File Writing", "File Writing Log")
End If
MyLog.Source = "File Writing"
' Write the Log
Diagnostics.EventLog.WriteEntry("File Writing Log", tMsg, EventLogEntryType.Information)
Catch ex As Exception

Finally
If MyLog IsNot Nothing Then MyLog = Nothing
End Try
End Sub

Protected Overrides Sub OnStop()
'The event is fired when the service is stopped.
tmTimer.Stop()
' Add code here to perform any tear-down necessary to stop your service.
End Sub

Protected Overrides Sub OnPause()
MyBase.OnPause()
'Handling the paused event of the serivce
tmTimer.Stop()
End Sub
Protected Overrides Sub OnContinue()
MyBase.OnContinue()
''Handling the on continue action of service
tmTimer.Start()
End Sub

Protected Overrides Sub OnShutdown()
MyBase.OnShutdown()
tmTimer.Stop()
End Sub
End Class






*Make sure you write all the events like the onshutdown, onpaused, onstop, onstart for the proper usage of the CPU memory.




The app.config file entry:
---------------------------



here the time is in milliseconds.................so to convert it into minutes, multiply the time with * 60000 and give the value in the below config key


< key ="TimeInterval" value="1">






now build the service. Now your service is ready for installing in services.

Thursday, August 19, 2010

Handling windows services from the code(c#)..........

Wondering how to start, stop, or to get the status of the windows services which are available at SERVICES.MSC.


ASPX CODE:
----------------


.CS code:
-------------

protected void btnStatus_Click(object sender, EventArgs e)
{//declaring the variables
ServiceController scObj = null;
try
{
//creating the object for the service cotroller.
scObj = new ServiceController();
//the service name can be viewed from the: goto RUN->SERVICES.MSC->select a //service->properties->service name.
scObj.ServiceName = "AppHostSvc";

//for stopped state
if (scObj.Status == ServiceControllerStatus.Stopped)
{
lblMsgg.Text = "The service is stopped";
//now we are starting the service
scObj.Start();
}//for running state
else if (scObj.Status == ServiceControllerStatus.Running)
{
lblMsgg.Text = "The service is running.";
//now we are stopping the service
scObj.Stop();
}//for paused state
else if (scObj.Status == ServiceControllerStatus.Paused)
{
lblMsgg.Text = "The service is Paused.";
}

}
catch (Exception Ex)
{
throw Ex;
}
finally
{//clearing the memory
if (scObj != null) scObj = null;
}
}

Monday, August 16, 2010

Directory creation in c# in the selected drives available in your system

Creating a directory in c# in the selected drives available in your system.
----------------------------------------------------------------------------
The below code is used to list all the drives available in your system and allow you to create a directory in the drive you choose.


ASSSUMPTIONS MADE: THE VALIDATION ARE TO BE TAKEN CARE BY YOU.

code:
--------
ASPX:
--------



.cs code
------------

PageLoad event code:


protected void Page_Load(object sender, EventArgs e)
{

//now we need to get the list of the directories of the system
DriveInfo[] diDrive = null;
try
{
if (!IsPostBack)
{
//tdrive = new string[System.IO.DriveInfo.GetDrives().Length];
diDrive = System.IO.DriveInfo.GetDrives();

//arrDrives = System.IO.DriveInfo.GetDrives().ToArray();
ddlDrivesList.Items.Clear();


//here we are adding the drive letters to the dropdown list
foreach (DriveInfo iDrives in diDrive)
{
ddlDrivesList.Items.Add(iDrives.ToString());
}
}
}
catch (Exception)
{

throw;
}
finally
{
if (diDrive != null) diDrive = null;

}


}




Button Click code:



protected void btnCreateDirectory_Click(object sender, EventArgs e)
{
//Declaring the variables here.

try
{
lblerror.Text = string.Empty;
//verifying whether the direactory exists or not
if (System.IO.Directory.Exists(Path.Combine(ddlDrivesList.SelectedItem.ToString(), txtDirectoryName.Text)) == true)
{
lblerror.Text = "Already Exists";
}
else
{
//creating the directory
System.IO.Directory.CreateDirectory(Path.Combine(ddlDrivesList.SelectedItem.ToString(), txtDirectoryName.Text));
lblerror.Text = "directory created";
}
}
catch (Exception EX)
{
throw EX ;
}
}

Sunday, August 15, 2010

Reading Data from the the file (.txt or .csv)

Using the File stream objects to read the data from a file
------------------------------------------------------------
ASSUMPTIONS MADE ARE: THE FILE NAME YOU ARE ENTERING IS EXISTING IN THE ROOT FOLDER OF YOUR APPLICATION. AND VALIDATIONS ARE TAKEN CARE BY YOU.


Code in the .ASPX file
------------------------


Code in .cs file
----------------
protected void btnReadFromFile_Click(object sender, EventArgs e)
{
//declaring the variables required

//we need to use System.IO name space for this.
System.IO.FileStream Fs = null;
System.IO.StreamReader Sr = null;
string tFilePath = string.Empty;
try
{
//gettting the file name as entered by the user
tFilePath = string.Concat(txtFileName.Text.ToString(), ".Txt");

//creating the file stream object
Fs = new System.IO.FileStream(Path.Combine(Server.MapPath("~/"), tFilePath), System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Read);

//Reading the data into the file
Sr = new System.IO.StreamReader(Fs);
TxtTextToRead.Text = Sr.ReadToEnd();
//closing the streams
Sr.Close();
Fs.Close();

}
catch (Exception ex)
{
throw ex;
}
finally
{
//clearing the memory in the finally block
//Here first we need to close the streams and then make the objects to null
//other wise we get the error some times that the file is accessed by another program
Sr.Close();
Fs.Close();
if (Sr != null) Sr = null;
if (Fs != null) Fs = null;

}

}

How to write data into a Txt or Csv File in C#.NET.

Using the file stream objects for writing the data into the txt file
-----------------------------------------------------------------------------

ASSUMPTIONS MADE ARE:
THE VALIDATIONS ARE NOT DONE HERE, IT MUST BE TAKEN CARE BY YOU.


Code in the .ASPX page
-------------------------





Code in the .cs page
-----------------------
protected void btnWriteIntoFile_Click(object sender, EventArgs e)
{
//declaring the variables required

//we need to use System.IO name space for this.
System.IO.FileStream Fs = null;
System.IO.StreamWriter Sw = null;
string tFilePath = string.Empty;
try
{
//gettting the file name as entered by the user
tFilePath = string.Concat(txtFileName.Text.ToString(),".Txt"); //Change the ext as like(.Txt)

//creating the file stream object
Fs = new System.IO.FileStream(Path.Combine(Server.MapPath("~/"),tFilePath), System.IO.FileMode.CreateNew, System.IO.FileAccess.ReadWrite);

//writing the data into the file
Sw = new System.IO.StreamWriter(Fs) ;
Sw.Write(TxtTextToWriteData.Text.ToString());

//closing the streams
Sw.Close();
Fs.Close();

}
catch (Exception ex)
{
throw ex;
}
finally
{
//clearing the memory in the finally block
//Here first we need to close the streams and then make the objects to null
//other wise we get the error some times that the file is accessed by another program
Sw.Close();
Fs.Close();
if (Sw != null) Sw = null;
if (Fs != null) Fs = null;

}
}

Friday, August 6, 2010

Publish Blog from Word 2007

Publish Blog from Word 2007
Did you know that you can publish directly to your blog from Word 2007? Well, that’s one of the new features of Word 2007! You can publish to popular services such as Blogger, Typepad, Wordpress, Windows Live Spaces and others. All that you need, is internet connection to publish the posts which you have prepared, directly from Word! To start with, you have to create and configure an account in Word and start blogging. You will be able to insert pictures, links, and formatted text as well!
To create and configure an account in Word 2007:
• Click the Office button > Publish > Blog .
• As this is the first time the Blog account is set up, click the Register Now button in the Register a Blog Account dialog.


• In the New Blog Account dialog, select your blog provider- Blogger or WordPress or whatever, from the drop down menu.




* Provide the login details.


* If you would like Word to upload pictures for you, click the Picture Options button.




* You can choose to have Word publish images directly to your blog provider or to your server, if you or a host is serving your site.


Now, you will notice that the Ribbon has changed to blogging mode! You can Publish, Publish as draft, Insert your categories , Open existing posts, set up new blogs and even insert HTML objects like pictures, links and much more! You can even create image effects and drop shadows! Cool!
Now create your blog post and when done, click the Publish button. Your post has been published and live!