Archive for the ‘C#’ Category

Get available server names of Sql Server within the local network – SqlDataSourceEnumerator

SqlDataSourceEnumerator is a class in .net framework that gets the available instances of SQL Server within the local network.

DataTable dt = SqlDataSourceEnumerator.Instance.GetDataSources();

SqlDataSourceEnumerator.Instance.GetDataSources() returns a datatable with the available servers in the current network.

The DataTable returned as 4 colunms such as :-

  • ServerName
  • InstanceName
  • IsClustered
  • Version

Popularity: 1% [?]

Sorting Program using C#

namespace SortingNos
{
   class Program
   {
       static void Main(string[] args)
       {
           Console.WriteLine("Enter Numbers :");
           int[] arr = new int[5];
           string arr1 = "";
           for (int i = 0; i < 5; i++)
 {
 arr1 = Console.ReadLine();
 arr[i] = Convert.ToInt32(arr1);            
}
 
 int a, b, temp = 0;
 Console.WriteLine();
 for (a = 0; a < arr.Length; a++)
           {
                               for(b=a+1;b< arr.Length;b++)
               {
                   if (arr[a] > arr[b])
                   {
                       temp = arr[a];
                       arr[a] = arr[b];
                       arr[b] = temp;
                   }
               }             
               Console.WriteLine(arr[a]);              
           }          
          Console.ReadLine();
       }
   }
}

Download

Popularity: 5% [?]

Encrypting text value using MD5 in Dot Net

For example we will have two textboxes such as ‘TextBox1′ and ‘TextBox2′.Now we will encrypt ‘TextBox1′ value using MD5 in Dot Net and display the encrypted value in ‘TextBox2′.

string pwd = “”;
 
pwd = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox1.Text, “MD5″);
 
TextBox2.Text = pwd;

Popularity: 1% [?]

Function To Generate Random Password using C#

usually you would send a random generated password while user does the registration process through your application.You can use the following code to achieve that.

public string Generate_Password()
{
string Password = “”;
byte Cnt, Idx;
string values = “0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ”;
Random rnd = new Random();
for (Cnt = 1; Cnt &lt;= 6; Cnt++)
{
Idx = (byte)rnd.Next(0, values.Length);
Password += values.Substring(Idx, 1);
}
return Password.Trim().ToUpper();
}

To Generate Random Password we have used the Random Class(Namespace:-System).To learn more about Random Class have a look at this MSDN LINK.

Popularity: 4% [?]

What is Delegate?

A delegate is a type that references a method.Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method,with parameters and a return value.

Any method that matches the delegate’s signature,which consists of the return type and parameters,can be assigned to the delegate.

Delegates allow methods to be passed as parameters.It can be used to define callback methods.

Popularity: 1% [?]

How to Embed a Flash File into C# Window Form?

To embed a flash file in C# Windows .Net Application we can use Shockwave Flash Object ActiveX Control.

Follow the Steps to embed flash file:

Step 1: In Tool box right click and select the menu “Choose Items”.

Step 2: From Choose Toolbox Items window select “Com component” tab.

Step 3: Scroll down and make sure “Shockwave Flash Object” is ticked and click ok. The Shockwave Flash Object will now appear in the toolbox.

Step 4: Simply click and drag the Shockwave Flash Object to window Form.

Step 5: Add the Code “Form Load”.

axShockwaveFlash1.LoadMovie(0, Application.StartupPath + “flash.swf”);

These steps embed the flash file and loads “flash.swf” in the application path when window loads.

Popularity: 16% [?]

Confirmation box in c# windows application

To make a confirmation box in c# windows application we can use

MessageBox.Show(string text,string caption,MessageBoxButtons buttons)

Coding :

if (MessageBox.Show(”Do you want to delete?”, “Confirm delete”,MessageBoxButtons.YesNo) == DialogResult.Yes)
{
MessageBox.Show(”Deleted”);
}

In the above coding when a button delete is clicked a condition is checked and confirmation box “Do you want to delete” is arised with two buttons ‘Yes’ and ‘No’.If ‘Yes’ is clicked then another message box “Deleted” is showed.

Popularity: 14% [?]

Creating Excel as Datasource for Mail Merge using C#

We can use excel as datasource for mail merge.We have to write the header and records in excel file which will act as the datasource for word mail merge.

The first row of excel will be treated as the header in the excel.

while using word as datasource and create a the word datasource we get an error “String longer than 255 characters ” when the concatenated fields string length increases 255. To overcome we can use excel as datasource.

Download Zip

Coding :

//Creating Excel file
private void CreateMailMergeExcelDataFile()
{
try
{
string[] fileds,record1;
 
Object oName = "C:\\TempDoc.xls";
string strHeader = "FirstName, LastName, Address, CityStateZip";
string strRecord1 = "John,Roy,31 New street,320009";
 
MSExcel.Application excelapp;
MSExcel.Workbook excelwrbook;
 
excelapp = new Microsoft.Office.Interop.Excel.Application();
excelapp.Visible = true;
MSExcel.Worksheet ws = new MSExcel.WorksheetClass();
 
excelwrbook = excelapp.Workbooks.Add(objMissing);
 
ws = (MSExcel.Worksheet)excelapp.ActiveWorkbook.ActiveSheet;
 
fileds = strHeader.Split(',');
record1 = strRecord1.Split(',');
//writing in excel you Can use datatable and Get the records and loop.here for
sample i have writing keeping two strings 
 
for (int i = 0; i &lt; j =" 0;" style="color: rgb(0, 102, 0);"  
 //saving the excel workbook
excelwrbook.SaveAs(oName, 
MSExcel.XlFileFormat.xlTemplate, objMissing, 
objMissing, objMissing,objMissing, 
MSExcel.XlSaveAsAccessMode.xlExclusive,
objMissing, objMissing, objMissing, 
objMissing, objMissing);
excelapp.Quit();
 
//opening the excel to act as a datasource for word mail merge
wrdDoc.MailMerge.OpenDataSource("C:\\TempDoc.xls", 
ref objMissing, ref objMissing, ref objMissing, ref objMissing, 
ref objMissing,ref objMissing, ref objMissing, 
ref objMissing,ref objMissing, ref objMissing,
ref objMissing, ref oQuery,ref objMissing, ref objMissing,
ref objMissing);
 
}
catch (Exception ex)
{
MessageBox.Show("Error :" + ex);
}
}
 
private void button1_Click(object sender, System.EventArgs e)
{
try
{
Word.Selection wrdSelection;
Word.MailMerge wrdMailMerge;
Word.MailMergeFields wrdMergeFields;
Word.Table wrdTable;
string StrToAdd;
 
wrdApp = new Word.Application();
wrdApp.Visible = false;
 
// Add a new document.
wrdDoc = wrdApp.Documents.Add(ref objMissing, ref objMissing,
ref objMissing, ref objMissing);
wrdDoc.Select();
 
wrdSelection = wrdApp.Selection;
wrdMailMerge = wrdDoc.MailMerge;
 
// Create a MailMerge Data file using excel 
CreateMailMergeExcelDataFile();
// Create a string and insert it into the document.
StrToAdd = "Mail Merge";
wrdSelection.ParagraphFormat.Alignment =
Word.WdParagraphAlignment.wdAlignParagraphCenter;
wrdSelection.TypeText(StrToAdd);
 
InsertLines(2);
 
// Insert merge data.
wrdSelection.ParagraphFormat.Alignment =
Word.WdParagraphAlignment.wdAlignParagraphLeft;
wrdMergeFields = wrdMailMerge.Fields;
wrdMergeFields.Add(wrdSelection.Range, "FirstName");
wrdSelection.TypeText(" ");
wrdMergeFields.Add(wrdSelection.Range, "LastName");
wrdSelection.TypeParagraph();
 
wrdMergeFields.Add(wrdSelection.Range, "Address");
wrdSelection.TypeParagraph();
wrdMergeFields.Add(wrdSelection.Range, "CityStateZip");
 
InsertLines(2);
 
wrdSelection.ParagraphFormat.Alignment =
Word.WdParagraphAlignment.wdAlignParagraphRight;
 
Object objDate = "dddd, MMMM dd, yyyy";
wrdSelection.InsertDateTime(ref objDate, ref oFalse, ref objMissing,
ref objMissing, ref objMissing);
 
InsertLines(2);
 
wrdSelection.ParagraphFormat.Alignment =
Word.WdParagraphAlignment.wdAlignParagraphJustify;
 
wrdSelection.TypeText("Dear ");
wrdMergeFields.Add(wrdSelection.Range, "FirstName");
wrdSelection.TypeText(",");
InsertLines(1);
 
StrToAdd = "Thank you for using Mail Merge.";
wrdSelection.TypeText(StrToAdd);
// Perform mail merge.
wrdMailMerge.Destination = Word.WdMailMergeDestination.wdSendToNewDocument;
wrdMailMerge.Execute(ref oFalse);
 
// Close the original form document.
wrdDoc.Saved = true;
wrdDoc.Close(ref oFalse, ref objMissing, ref objMissing);
 
 // Makes the merged doc visible
wrdApp.Visible = true;
 
// Release References.
wrdSelection = null;
wrdMailMerge = null;
wrdMergeFields = null;
wrdDoc = null;
wrdApp = null;
 
// Clean up temp file.
System.IO.File.Delete("C:\\TempDoc.xls");
}
catch (Exception ex)
{
MessageBox.Show("Error :" + ex);
}
}

Popularity: 1% [?]

To get the path of temp folder in c#

System.Environment.GetEnvironmentVariable("TEMP")
 
or
 
System.IO.Path.GetTempPath()

above syntax gets the TEMP folder path of the system.
have a look about system.environment.getenvironmentvariable from the msdn link.

Popularity: 5% [?]

How to open an application, file Using Shell execute in .net

We can execute any application(any files,notepad,calculator and etc) using C#.net by
System.Diagnostics.Process.Start.

Coding :

private void bt_ShellExecute_Click(object sender, EventArgs e)
{
string strpath = “C:\\sample.xls”;

System.Diagnostics.Process.Start(strpath);
}

Popularity: 5% [?]

Designed by: Business Web Hosting | Thanks to Buy Icons, travel tips and Used Cars