Naveen's Weblog

Bridge to future

Archive for the ‘C#’ Category

Learn better ways to code in C#

Performance difference between For and Parallel.For

Posted by codingsense on October 17, 2009

Hi,
I was really happy when i heard of the concept of Parallel.For that is introduced in new version of .Net. I tried it in framework 4.0 in visual studio 2010.
Here is the sample that i ran to see how the performance will vary on my system ( Core 2 duo).

class Program
    {
        static void Main(string[] args)
        {
            long[] a = new long[1000000];

            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();
            Parallel.For(0, 1000000, delegate(long i)
            {
                a[i] = i * i;
            });

            watch.Stop();
            Console.WriteLine(watch.ElapsedMilliseconds);

            watch.Start();

            for (long I = 0; I < 1000000; I++)
            {
                a[I] = I * I;
            }

            watch.Stop();
            Console.WriteLine(watch.ElapsedMilliseconds);
            Console.Read();
        }
    }

What i saw is always there is a differnce in value depending on the work load on each core. But to my surprise i found that in all the 10-15 cases that i ran, for loop took less time to execute than Parallel.For.
I think there might be some other things that needs to be done to make use of Parallel.For to make it more efficient than For or there might be some specific tasks where Parallel.For should be used.
Will try to find it out and get back to you soon.

Naveen Prabhu

Posted in C# | Tagged: | Leave a Comment »

Create, Execute and delete Macro in excel using C#

Posted by codingsense on May 11, 2009

When we need any specific task to be done in excel through our program, we first do the same task manually in excel and record the macro to have a look how the function should be written in our code.

There are some functions those are hard to find in the Interop.Excel dll, for such things microsoft has given helpful functions which will help us to add the macro in the sheet and execute it. This will help us to reuse the same macro that we generate in excel with record macro.

And later on if the macro is still present in generated excel then while opening it prompts enable/disable macro, so to avoid it, we will see how the macro can be deleted through C#.

Here let me explain you with a sample.

Read Only Or Locked Cell In Excel

Lets imagine a case , we have to generate an excel of employees with their name and salary. We want no employee should alter the salary that is enterd in the sheet i.e we want it to locked or to make it read only.

For the above case we will try to acheive executing a macro.

First we will try to see how a cell can be locked in excel and what macro is generated by excel when we record a new macro.

1) Select a cell
2) Enter some data ( that is to be locked for modification)
3) select Data Menu -> Validation
4) In Allow select custom
5) In formula enter “” and click ok
6) Now check altering the data in that cell, it gives a message and does not let the user change the value.

Wow this is what we need. Fine, since we have recorded the macro we will open the visual basic editor and see what macro has been generated, ok here is what i got.

Sub Macro1()
'
' Macro1 Macro
' Macro recorded 11/05/2009 by naveen
'
    With Selection.Validation
        .Delete
        .Add Type:=xlValidateCustom, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:=""""""
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With
End Sub

now this is for the selection what we have done in the excel, to make more better when executing from external application we will pass a range parameter to the function, so that we can lock the input range of cells, let us also change the macro name to LockRange and change the message that is displayed to the user.

The new macro would look like.

Sub LockRange(oRange As String)
'
' Macro1 Macro
' Macro recorded 11/05/2009 by naveen
'
    Range(oRange).Select
    With Selection.Validation
        .Delete
        .Add Type:=xlValidateCustom, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:=""""""
        .ErrorTitle = "Locked Cell"
        .ErrorMessage = "This cell is locked for modification."
        .ShowError = True
    End With
End Sub

Now since we know what macro to use to make the requirement possible, we just need to implement the same in our C# code, Here comes the code.

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Vbe.Interop;

namespace LockRangeInExcel
{
class Program    
{
static void Main(string[] args)
{
Excel.Application oXL = null;
Excel._Workbook oWB = null;
Excel._Worksheet oSheet = null;
Excel.Range oRng = null;
_VBComponent oModule = null; // VBA Module            
try            
{
//Start Microsoft.Office.Interop.Excel and get Application object.
                oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;

//Get a new workbook.
                oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;

//Add table headers going cell by cell.
                oSheet.Cells[1, 1] = "First Name";
oSheet.Cells[1, 2] = "Salary(Read Only)";

//Format A1:D1 as bold, vertical alignment = center.
                oSheet.get_Range("A1", "B1").Font.Bold = true;
oSheet.get_Range("A1", "B1").VerticalAlignment =
Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;

// Create an array to multiple values at once.                
string[,] saNames = new string[5, 2];

saNames[0, 0] = "Naveen";
saNames[0, 1] = "10000";
saNames[1, 0] = "Girish";
saNames[1, 1] = "20000";
saNames[2, 0] = "Nandish";
saNames[2, 1] = "15000";
saNames[3, 0] = "Rashmi";
saNames[3, 1] = "40000";

//Fill A2:B6 with an array of values (First and Salary).
                oSheet.get_Range("A2", "B6").Value2 = saNames;

//AutoFit columns A:D.
                oRng = oSheet.get_Range("A1", "B1");
oRng.EntireColumn.AutoFit();

//Create macro in excel
                CreateMacro(oWB, oModule);

// Run VBA macro "MakeCellReadOnly" on a range                
string oRange = "B2:B6";
LockRange(oWB, oRange);

//For single cell you can use the function as follows                
//oRange = "C7";                
//MakeCellReadOnly(oWB, oRange);                

//Delete the created Macro
                DeleteMacro(oWB, oModule);

//Make sure Microsoft.Office.Interop.Excel is visible and give the user control                
//of Microsoft Microsoft.Office.Interop.Excel's lifetime.
                oXL.Visible = true;
oXL.UserControl = true;
}
catch (Exception theException)
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, theException.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, theException.Source);

MessageBox.Show(errorMessage, "Error");
}

ReleaseComObj(oSheet);
ReleaseComObj(oWB);
ReleaseComObj(oXL);
}

private static void ReleaseComObj(object o)
{
try            
{
Marshal.ReleaseComObject(o);
}
catch            
{ }
finally            
{
o = null;
}
}

private static void DeleteMacro(Microsoft.Office.Interop.Excel._Workbook oWB, _VBComponent oModule )
{
Object oMissing = System.Reflection.Missing.Value;
oWB.Application.Run("DeleteThisModule"
, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
}

public static void LockRange(Excel._Workbook oWB, string oRange)
{
Object oMissing = System.Reflection.Missing.Value;
//The following command executes the macro by passing the range to the macro
            oWB.Application.Run("LockRange"
, oRange, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
}

public static void CreateMacro(Excel._Workbook oWB,_VBComponent oModule)
{
//Create a macro
            oModule = oWB.VBProject.VBComponents.Add(vbext_ComponentType.vbext_ct_StdModule);

//Create macro for locking the cell and delete the module            
string sCode =
"Sub LockRange(oRange As String)\r\n" +
"Range(oRange).Select\r\n" +
"With Selection.Validation \r\n" +
".Delete\r\n" +
".Add Type:=xlValidateCustom, AlertStyle:=xlValidAlertStop, Operator:= _\r\n" +
"xlBetween, Formula1:=\"\"\"\"\"\"\r\n" +
".ErrorTitle = \"Locked Cell\"\r\n" +
".ErrorMessage = \"This cell is locked for modification.\"\r\n" +
".ShowError = True\r\n" +
"End With\r\n" +
"End Sub\r\n" +
"Sub DeleteThisModule()\r\n" +
"Dim vbCom As Object\r\n" +
"Set vbCom = Application.VBE.ActiveVBProject.VBComponents\r\n" +
"vbCom.Remove VBComponent:= vbCom.Item(\"Module1\")\r\n" +
"End Sub\r\n";

//Add the macro in excel workbook that we have created
            oModule.CodeModule.AddFromString(sCode);

}
}
}

In VB.Net the same implementation can be done as

Module Module1
Sub Main()
Dim oXL As New Microsoft.Office.Interop.Excel.Application
Dim oWB As Microsoft.Office.Interop.Excel.Workbook
Dim OSheet As New Microsoft.Office.Interop.Excel.Worksheet
Dim oModule As Microsoft.Vbe.Interop.VBComponent

Try            

'Start Microsoft.Office.Interop.Excel and get Application object.
            oXL.Visible = True            
'Get a new workbook.
            oWB = oXL.Workbooks.Add()
OSheet = oWB.ActiveSheet

'Add table headers going cell by cell.
            OSheet.Cells(1, 1) = "FirstName"
            OSheet.Cells(1, 2) = "Salary(Read Only)"            

'Format A1:D1 as bold, vertical alignment = center.
            OSheet.Range("A1", "B1").Font.Bold = True
            OSheet.Range("A1", "B1").VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter

'Create an array to multiple values at once.            
Dim saNames(5, 2) As String
            saNames(0, 0) = "Naveen"
            saNames(0, 1) = "10000"
            saNames(1, 0) = "Girish"
            saNames(1, 1) = "20000"
            saNames(2, 0) = "Nandish"
            saNames(2, 1) = "15000"
            saNames(3, 0) = "Rashmi"
            saNames(3, 1) = "40000"            

'Fill A2:B6 with an array of values (First and Salary).
            OSheet.Range("A2", "B6").Value2 = saNames

'AutoFit columns A:D.
            OSheet.Range("A1", "B1").EntireColumn.AutoFit()

'Create macro in excel
            CreateMacro(oWB, oModule)

' Run VBA macro "MakeCellReadOnly" on a range            
Dim oRange As String = "B2:B6"
            LockRange(oWB, oRange)

'For single cell you can use the function as follows            
'oRange = "C7";            
'MakeCellReadOnly(oWB, oRange);            

'Delete the created Macro
            DeleteMacro(oWB)

'Make sure Microsoft.Office.Interop.Excel is visible and give the user control            
'of Microsoft Microsoft.Office.Interop.Excel's lifetime.
            oXL.Visible = True
            oXL.UserControl = True            

Catch        

End Try        

End Sub    

Private Sub DeleteMacro(ByVal oWB As Microsoft.Office.Interop.Excel.Workbook)
oWB.Application.Run("DeleteThisModule")
End Sub    

Private Sub LockRange(ByVal oWb As Microsoft.Office.Interop.Excel.Workbook, ByVal oRange As String)
'The following command executes the macro by passing the range to the macro
        oWb.Application.Run("LockRange", oRange)
End Sub    

Public Sub CreateMacro(ByVal oWB As Microsoft.Office.Interop.Excel.Workbook, ByVal oModule 
As Microsoft.Vbe.Interop.VBComponent)
'Create a macro
        oModule = oWB.VBProject.VBComponents.Add(Microsoft.Vbe.Interop.vbext_ComponentType.vbext_ct_StdModule)
'Create macro for locking the cell and delete the module        
Dim sCode As String = "Sub LockRange(oRange As String)" + Environment.NewLine + _
"Range(oRange).Select" + Environment.NewLine + _
"With Selection.Validation " + Environment.NewLine + _
".Delete" + Environment.NewLine + _
".Add Type:=xlValidateCustom, AlertStyle:=xlValidAlertStop, Operator:=" + _
"xlBetween, Formula1:=""""""""""" + Environment.NewLine + _
".ErrorTitle = ""Locked Cell""" + Environment.NewLine + _
".ErrorMessage = ""This cell is locked for modification.""" + Environment.NewLine + _
".ShowError = True" + Environment.NewLine + _
"End With" + Environment.NewLine + _
"End Sub" + Environment.NewLine + _
"Sub DeleteThisModule()" + Environment.NewLine + _
"Dim vbCom As Object" + Environment.NewLine + _
"Set vbCom = Application.VBE.ActiveVBProject.VBComponents" + Environment.NewLine + _
"vbCom.Remove VBComponent:= vbCom.Item(""Module1"")" + Environment.NewLine + _
"End Sub"        

'Add the macro in excel workbook that we have created
        oModule.CodeModule.AddFromString(sCode)

End Sub
End Module

To execute the above code, copy paste the whole code in your application. You need to add 2 dll’s to make the compilation successful they are,

  • Microsoft.Office.Interop.Excel
  • Microsoft.Vbe.Interop

And make sure you have given access to external application to access Excel. For more details visit

Let us brief on the methods that have been used in the above code:

CreateMacro :
Creates a new module in excel vb project and then adds the methods LockRange and DeleteThisModule in the module.

LockRange :
Accepts the range and locks the cells in the range so that the user will not be able to edit the data in those cell.
If tried to modify the data then prompts a proper message to the user.

DeleteMacro :
Deletes the macro that is created in the Excel VB Project, so that when user opens the excel file he will not be prompted with the message “Enable/Disable Macros”.

Happy Learning :)

Posted in C# | Tagged: , , | 2 Comments »

Clone fields and properties in a abstract class

Posted by codingsense on March 15, 2009

Hi Friends,

In this post we shall see how we can clone the properties of a abstract class.

If there is a normal class and we need to clone it, then we will use the simple method of cloning
1) Create a new object
2) Copy all the properties of this object to the newly created object
3) Return the object

But assume a condition when we have a abstract class in which lot of properties are been defined and it has lot of derived classes. Now if we want all the derived classes to implement clone and clone all the properties of the base class then we need to write clone method in each derived classes. Since we know that we cannot create a instance method in abstract class becuase its instance cannot be created.

What would you do in the following case, here is the solution for it, Its simple and a generic method that can be used in any class that needs to implement clone. Here it goes.

Clone Properties:

abstract class CloneProperties: ICloneable    
{
public int fldi = 0;

int propi = 0;
public int Propi
{
get { return propi; }
set { propi = value; }
}

int propj = 0;
public int Propj
{
get { return propj; }
set { propj = value; }
}

        #region ICloneable Members

public object Clone()
{
//we create a new instance of this specific type.            
object newInstance = Activator.CreateInstance(this.GetType());

//We get the array of properties for the new type instance.            
PropertyInfo[] properties = newInstance.GetType().GetProperties();

int i = 0;

foreach (PropertyInfo pi in this.GetType().GetProperties())
{
properties[i].SetValue(newInstance, pi.GetValue(this, null), null);
i++;
}

return newInstance;
}
        #endregion    
}

To check the output we shall create a dummy class and inherit it from cloneProperties class

class Prop : CloneProperties    
{
}

And in the Main function we shall call the clone and check

class Program    
{
static void Main(string[] args)
{
CloneProperties cloneProp1 = new Prop();
cloneProp1.fldi = 1;
cloneProp1.Propi = 2;
cloneProp1.Propj = 3;
CloneProperties cloneProp2 = (CloneProperties)cloneProp1.Clone();

Console.WriteLine("Cloning Properties");
Console.WriteLine("fldi = {0} , Propi = {1}, Propj = {2}", cloneProp2.fldi, cloneProp2.Propi,cloneProp2.Propj);

Console.Read();
}
}

Output:

Output after cloning Properties

Output after cloning Properties


Well it has worked fine, we can see that only the properties are succesfully cloned so they have got the values 2 and 3 and for fields it dint clone and it has value 0.

Clone Fields:

If you need to clone only the fields then you can replace the above clone function with the below one

public object Clone()
{
//we create a new instance of this specific type.            
object newInstance = Activator.CreateInstance(this.GetType());

//We get the array of properties for the new type instance.            
FieldInfo[] fields = newInstance.GetType().GetFields();

int i = 0;

foreach (FieldInfo fi in this.GetType().GetFields())
{
fields[i].SetValue(newInstance, fi.GetValue(this));
i++;
}

return newInstance;
}

Output:
cloneflieds

Here you can see that only fields are cloned and properties are set to the default vaule.

Happy Learning :)

Posted in C# | Tagged: , | Leave a Comment »

Get All formula from excel cell

Posted by codingsense on March 1, 2009

Hi Friends,

In this topic we shall see how to get the formula from an excel cell. This program lists only the field in which user has entered a formula in excel sheet.
Here let us explore a good feature of exed known as “UsedRange”. Used Range gives only the cells those have been used, this helps us to avoid searcing in whole excel sheet. We can search only the cells in the UsedRange and fetch if the user has given any formula to cells or not, if he has given a formula lets fetch the formula and display the row, col and formula.

Download Project : 9KB

To access the excel file we shall use Late binding method using System.Reflection which helps to invoke any version of excel instance that is installed on my machine.

//Get Instance of excel on the machine
                objClassType = Type.GetTypeFromProgID("Excel.Application");
//Create new instance of Excel
                objExcelApp = Activator.CreateInstance(objClassType);

To get the UsedRange we can run a macro and get the RowCount and ColCount of the UsedRange and loop within the boundary.

//Get the used Rows and Cols from excel                
object UsedRange = objSheet.GetType().InvokeMember("UsedRange",BindingFlags.GetProperty,null,objSheet,null);
object Rows = UsedRange.GetType().InvokeMember("Rows", BindingFlags.GetProperty, null, UsedRange, null);
object objRowCount = Rows.GetType().InvokeMember("Count", BindingFlags.GetProperty, null, Rows, null);
object Cols = UsedRange.GetType().InvokeMember("Columns", BindingFlags.GetProperty, null, UsedRange, null);
object objColCount = Cols.GetType().InvokeMember("Count", BindingFlags.GetProperty, null, Cols, null);

Next we will loop throught each cells within the UsedRange boundary and check if the Cells[i,j].Formula is starting with “=”. If yes then its a formula, Add the row, col and formula into the list and proceed to next cell.

//Get cells object                
object Cells = objSheet.GetType().InvokeMember("Cells", BindingFlags.GetProperty,
null, objSheet, null);
for (int RowIndex = 1; RowIndex <= RowCount; RowIndex++)
{
for (int ColIndex = 1; ColIndex <= ColCount; ColIndex++)
{
object objCellText = Cells.GetType().InvokeMember("Item", BindingFlags.GetProperty, 
null, Cells, new object[] { RowIndex, ColIndex });
string CellText = Convert.ToString(objCellText.GetType().InvokeMember("Formula", 
BindingFlags.GetProperty,null, objCellText, null));
if (CellText.StartsWith("="))
{
FormulaCell cell = new FormulaCell(RowIndex,ColIndex,CellText);
ListOfFormulae.Add(cell);
}
}

After searching each cell within the used range we get the collection of FormulaCells. After finishing our task, the most important is to disposed the Unmanaged object. For disposing let us use Marshal class.

//Invoke the close method of WorkBooks
objBooks.GetType().InvokeMember("Close", BindingFlags.InvokeMethod, null, objBooks, null);
//Release the COM Excel application using Marshal class                
Marshal.ReleaseComObject(objExcelApp);

Now lets display it.

if (ListOfFormulae != null)
{
for (int Index = 0; Index < ListOfFormulae.Count; Index++)
{
Console.WriteLine("Row = " + ListOfFormulae[Index].Row +
", Col = " + ListOfFormulae[Index].Col +
" has the formula " + ListOfFormulae[Index].Value);
}
}

Hope you have understood the following,

  • How Late binding is done in C#.
  • How to use a macro through C#.
  • How Properties of another application can be accessed using a GetType().InvokeMember() and BindingFlags.GetProperty.
  • How Functions of another application are invoked using a GetType().InvokeMember() and BindingFlags.InvokeMethod.
  • The important one is how to dispose the unmanaged object.

If you have any doubts, please comment.

Happy learing :)

Posted in C# | Tagged: , | 2 Comments »

Apply password to existing PDF file

Posted by codingsense on February 26, 2009

Hi friends,

For applying the password to a PDF file, i m using ITextSharp library.

I was searching for the code to apply password to an existing PDF file, but dint find any method in which PDFStamper or PDFWriter would append password for an existing file. So i have used the way of creating an intermediate file and then deleting it.

 private void ApplyPassword(string SourcePath,string UserPassword, string OwnerPassword)
{
//Open the path in reader object            
PdfReader reader = new PdfReader(SourcePath);

//Get the file Information of the source file            
FileInfo finfo = new FileInfo(SourcePath);

//Create a Intermediate path for applying the password            
string path = finfo.DirectoryName + "\" + finfo.Name + "1.pdf";

//Apply the Password            
PdfStamper stamper = new PdfStamper(reader, new FileStream(path, FileMode.Create));
stamper.SetEncryption(PdfWriter.STANDARD_ENCRYPTION_128, UserPassword , OwnerPassword, 
PdfWriter.AllowCopy | PdfWriter.AllowPrinting);
stamper.Close();
reader.Close();

//copy the Intermediate file to source file path            
File.Copy(path, SourcePath, true);

//Delete the Intermediate file            
File.Delete(path);
}

If anybody know how to give password to a PDF file without creating a intermediate file then i will be pleased to know.

Happy learing :)

Thanks,
Naveen Prabhu

Posted in C# | Tagged: , , | Leave a Comment »

Add, Delete and check if Exists WIN32_Printer

Posted by codingsense on February 6, 2009

To work with any WIN32 type like Win32 Logical disk or Win32 Process in .Net, we need to use System.Management.dll.

In system.Management.dll we can find 3 classes that are very important to handle management operations.

1) System.Management.ManagementScope – This class represents a scope for management operations.
2) System.Management.ManagementClass – This class represents a common Information Model (CIM) Management class.
3) System.Management.ManagementObject – Holds the object of the instance of management class.

Printer Operation

To explain about the Management Classes we will take an sample of Printer device. We shall see how to search a printer, install a printer and delete a printer in our system.

First we shall create a class MyPrinter and then fill it with required functions.

Create Printer Class:

public class Printer    
{
private ManagementScope managementScope = null;
//Add Below functions here    
}

Check if printer is Installed or Not:
Here we shall retrieve the printer information by executing a select query using the ManagementObjectSearcher. The search results can be retrived by using the Get() function, and this function returns a collection of printers maching the name. If the collection has any object then we return true or we return false.

public bool IsPrinterInstalled(string PrinterName)
{
managementScope = new ManagementScope(ManagementPath.DefaultPath);
managementScope.Connect();
SelectQuery selectQuery = new SelectQuery();
selectQuery.QueryString = "Select * from win32_Printer where Name = '" + PrinterName + "'";
ManagementObjectSearcher MOS = new ManagementObjectSearcher(managementScope, selectQuery);
ManagementObjectCollection MOC = MOS.Get();
return MOC.Count > 0;
}

Add a new printer:
For adding a printer we will accept the needed parameter i.e Printer Name, Driver Name, Port No and is printer shared or not. After getting all the details we shall create a ManagementClass of type “Win32_Printer” Type and then create its instance. To this instance we add all the properties, and we add the new printer using the Put() method. Here in Put() function we can pass a class of type PutOptions. It contains many options that can be set, we set only the options needed for us ie PutType which will have the value UpdateOrCreate.

public bool AddPrinter(
string PrinterName, string PrinterDriver,
string PortName, bool SharedPrinter)
{
try            
{
//Create new Win32_Printer Class                
ManagementClass printerClass = new ManagementClass(managementScope, new ManagementPath("Win32_Printer"), null);

//create new Win32_Printer object                 
ManagementObject printerObject =
printerClass.CreateInstance();

//set port parameters                 
if (PortName == null || PortName.Length == 0)
printerObject["PortName"] = "LPT1:";
else                
{
if (PortName[PortName.Length - 1] != ':')
printerObject["PortName"] = (PortName + ":");
else
                        printerObject["PortName"] = PortName;
}
//set driver and device names 
                printerObject["DriverName"] = PrinterDriver;

printerObject["DeviceID"] = PrinterName;
//set sharing                 
if (SharedPrinter)
{
printerObject["Shared"] = SharedPrinter;
printerObject["ShareName"] = PrinterName;
}
// specify put options: update or create                 
PutOptions options = new PutOptions();
options.Type = PutType.UpdateOrCreate;

//put a newly created object to WMI objects set 
                printerObject.Put(options);

return true;
}
catch 
{
throw;
}
}

Delete a Printer:
Deleting a printer works in similar fashion like searching a printer, we need to search the printer then just add one more command to delete the printer if found

public bool DeletePrinter(string PrinterName)
{
managementScope = new ManagementScope(ManagementPath.DefaultPath);
managementScope.Connect();
SelectQuery selectQuery = new SelectQuery();
selectQuery.QueryString = "Select * from win32_Printer where Name = '" + PrinterName + "'";
ManagementObjectSearcher MOS = new ManagementObjectSearcher(managementScope, selectQuery);
ManagementObjectCollection MOC = MOS.Get();
foreach (ManagementObject mo in MOC)
{
mo.Delete();
return true;
}
return false;
}

By adding all the three functions in the above created class , we will have ourself 3 functions that deals with Win32 Printer.

Happy Learning :)

Posted in C# | Leave a Comment »

Send Email Using outlook or Gmail

Posted by codingsense on January 23, 2009

Hi friends,

In VB we had to write more complex codes to send a mail but .Net framework gives an easy option to email using any SMTP.

Here is a sample application that helps you to send email using Outlook and Gmail SMTP.

Download project – 41.6 Kb

emailoutlookgmail

In this project you wil find the following keyworks let me brief you on them.

MailMessage: Creates an instance of the message that is to be sent through mail.

MailMessage mailMessage = new MailMessage();

AlternateView: If you want the message to be in a format other than plain text like Image or Rich Text or HTML or XML then we need to use this Alternate view. And the body of the message should be the same format that we specify in the alternate view.

string body = 
@"<b>The linked resouces </b> : <br/> <img src=""cid:DisplayImage""/>";
AlternateView Av1 = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);
mailMessage.AlternateViews.Add(Av1);and the alternate view is added to Mail Message.

 

Linked Resources: Linked resouces accepts the objects those are linked with the messages. For eg if you need to insert an image or any other object within the mail body then the resource has to be linked as

LinkedResource linkResource = new LinkedResource(FileName);
linkResource.ContentId = "DisplayImage";
linkResource.ContentType.Name = FileName;
Av1.LinkedResources.Add(linkResource);

and this resource has to be added into the alternate view.

Attachments: The files can be attached to the mail Message as follows

mailMessage.Attachments.Add(new Attachment(txtAttachment.Text));

SMTPClient The SMTP client is responsible to send the mail Message that we created, this accepts the Host computer Name or IP Address of the computer that is used to send the mail message.
The Network Credentials have to be set to make the person reveal his identity. Enablessl is used if the SMTPClient uses the Secure Socket Layer(SSL) to encrypt the connection. The port no that is used for SMTP transactions is to be set. The send function will be used to send the mail.

SmtpClient theClient = new SmtpClient(txtHostComputer.Text.Trim());
theClient.Credentials = new System.Net.NetworkCredential(txtUsername.Text.Trim(), txtPassword.Text.Trim());
theClient.EnableSsl = true;
theClient.Port = Convert.ToInt32(cmbPort.Text);
theClient.Send(mailMessage);

Happy learning :)

Posted in C# | Tagged: | Leave a Comment »

Whats new in C# 3.5

Posted by codingsense on December 24, 2008

The key features that are intorduced in C# 3.5 are

We will explore them in more depth in coming posts.. Till then let me find some simpler Samples to make you understand concepts better.. :-)

Posted in C# | Tagged: | Leave a Comment »

Object and Collection Initializers

Posted by codingsense on December 24, 2008


This is an interesting feature that will seem more valuable once you go through the below example.

Imagine a class Employee which has the properties like Name and ID To add two employees and to list them required the following code till c# 2.0.

using System;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee emp1 = new Employee("Naveen",1);
            Employee emp2 = new Employee("Jonny", 2);

            Console.WriteLine("Employee List :");
            Console.WriteLine("----------------");
            Console.WriteLine("ID          Name");
            Console.WriteLine("----------------");
            Console.WriteLine("{0}          {1}", emp1.ID, emp1.Name);
            Console.WriteLine("{0}          {1}", emp2.ID, emp2.Name);
            Console.Read();
        }

        public class Employee
        {
            private string name;
            public string Name
            {
                get { return name; }
                set { name = value; }
            }

            private int id;
            public int ID
            {
                get { return id; }
                set { id = value; }
            }

            public Employee(string Name, int ID)
            {
                this.Name = Name;
                this.ID = ID;
            }
        }
    }
}

Now have a look on whats new in c# 3.5. Life is simplified with the the Object Initailizers.

using System;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee emp1 = new Employee() { Name = "Naveen", ID = 1 };
            Employee emp2 = new Employee() { Name = "Jonny" };

            Console.WriteLine("Employee List :");
            Console.WriteLine("----------------");
            Console.WriteLine("ID          Name");
            Console.WriteLine("----------------");
            Console.WriteLine("{0}          {1}", emp1.ID, emp1.Name);
            Console.WriteLine("{0}          {1}", emp2.ID, emp2.Name);
            Console.Read();
        }

        public class Employee
        {
            public string Name { get; set; }
            public int ID{get;set;}
        }
    }
}

The improvements:

  • if we check the employee class you will find it much simpler, with no much code.The constructor is removed, as well as the private variables are missing. Still the code is running smoothly with data.When the C# “Orcas” compiler encounters an empty get/set property implementation like above, it will now automatically generate a private field for you within your class, and implement a public getter and setter property implementation to it.
  • When creating a instance of the Employee class we can see some new things. Here comes the concept of object Initializers. while creating the instance itself we can specify which public property is to be set with what value. This helps to avoid creating overloads for the constructor.

Try some more and explore the concepts.Catch you soon with some other stuffs. :-)

Posted in C# | Tagged: , | Leave a Comment »

Extension methods

Posted by codingsense on December 24, 2008

Here is a small example of Extension methods using C# 3.5

In this example we will put our own function in Frameworks string data type.

This will help user to print the the content of the stirng to console.

using System;
namespace ConsoleApplication1
{
public static class ExtendString
{
public static void PrintToConsole(this string str)
{
Console.WriteLine(str);
}
}
class Program
{
static void Main(string[] args)
{
string s = "Naveen.Prabhu";
s.PrintToConsole();
Console.Read();
}
}
}

Hope this will help you to understand the use of extension methods.

Create your own samples and take maximum use of this feature.

Happy Learning :-)

Posted in C# | Tagged: | Leave a Comment »