For Developers
Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Copy-Paste to and from clipboard using c#

To make the operations such as copy paste using c#,we have to use the Clipboard Class which provides methods to place data on and retrieve data from the system Clipboard.

Example :-

Copy the text from txtCopy to clipboard


System.Windows.Forms.Clipboard.SetDataObject(txtCopy.Text, true);

Paste the text from clipboard to txtPaste

IDataObject clipData = Clipboard.GetDataObject();
if (clipData.GetDataPresent(DataFormats.Text))
{
txtPaste.Text = clipData.GetData(DataFormats.Text).ToString();
}
else
{
txtPaste.Text = "Could not retrieve data from the clipboard.";
}


Download


Get Clients IP Address Using ASP.NET

We can get the clients IP address using the Request object's(The Request object retrieves the values that the client browser passed to the server during an HTTP request. ) property Request.ServerVariables Collection.
Request.ServerVariables Collection gets the values of predetermined environment variables.

"REMOTE_ADDR" gets the IP address of the remote host making the request. 


string ipaddr;

ipaddr = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];



here the string "ipaddr" stores the clients ip.


List Of other Request.ServerVariables Object
VariableDescription

AUTH_TYPE

The authentication method that the server uses to validate users when they attempt to access a protected script.

CONTENT_LENGTH

The length of the content as given by the client.

CONTENT_TYPE

The data type of the content. Used with queries that have attached information, such as the HTTP queries POST and PUT.

GATEWAY_INTERFACE

The revision of the CGI specification used by the server. Format: CGI/revision.


HTTP_<HeaderName>

The value stored in the header HeaderName. Any header other than those
listed in this table must be prefixed by "HTTP_" in order for the
ServerVariables collection to retrieve its value.



Note: The server interprets any underscore (_) characters in
HeaderName as dashes in the actual header. For example if you specify
HTTP_MY_HEADER, the server searches for a header sent as MY-HEADER.



LOGON_USER

The Windows NT® account that the user is logged into.

PATH_INFO

Extra path information as given by the client. You can access scripts
by using their virtual path and the PATH_INFO server variable. If this
information comes from a URL it is decoded by the server before it is
passed to the CGI script.

PATH_TRANSLATED

A translated version of PATH_INFO that takes the path and performs any necessary virtual-to-physical mapping.

QUERY_STRING

Query information stored in the string following the question mark (?) in the HTTP request.

REMOTE_ADDR

The IP address of the remote host making the request.

REMOTE_HOST

The name of the host making the request. If the server does not have
this information, it will set REMOTE_ADDR and leave this empty.

REQUEST_METHOD

The method used to make the request. For HTTP, this is GET, HEAD, POST, and so on.

SCRIPT_MAP

Gives the base portion of the URL.

SCRIPT_NAME

A virtual path to the script being executed. This is used for self-referencing URLs.

SERVER_NAME

The server's host name, DNS alias, or IP address as it would appear in self-referencing URLs.

SERVER_PORT

The port number to which the request was sent.

SERVER_PORT_SECURE

A string that contains either 0 or 1. If the request is being handled
on the secure port, then this will be 1. Otherwise, it will be 0.

SERVER_PROTOCOL

The name and revision of the request information protocol. Format: protocol/revision.

SERVER_SOFTWARE

The name and version of the server software answering the request (and running the gateway). Format: name/version.

URL

Gives the base portion of the URL.




Convert Text to Image using c#

We can Convert text to image in c# using System.Drawing namespace.
Here we create a bitmap image and use its Graphics property to convert text passed to image and place the image in a picture box.


private void TextToImage()
{
Color BackColor = Color.White;
String FontName = "Times New Roman";
int FontSize = 25;
int Height = 50;
int Width = 300;

//creating bitmap image
Bitmap
bitmap = new Bitmap(Width, Height);

//FromImage method creates a new Graphics from the specified Image.
Graphics graphics = Graphics.FromImage(bitmap);
Color color = Color.Gray;
Font font = new Font(FontName, FontSize);

SolidBrush BrushBackColor = new SolidBrush(BackColor);
Pen BorderPen = new Pen(color);

Rectangle displayRectangle = new Rectangle(new Point(0, 0), new Size(Width - 1, Height - 1));
//Drawing a rectangle and filling the background as white
graphics
.FillRectangle(BrushBackColor, displayRectangle);
graphics.DrawRectangle(BorderPen, displayRectangle);

//giving the font and color to the string passed

graphics.DrawString(txtEnter.Text,font,Brushes.Red, 0, 0);
pictureBox1.Image = bitmap;

}


Download

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

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

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;

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 <= 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.

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.

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.

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.

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 < 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);
}
}

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.

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);
}

How to use Spit Container in c#.net

SpitContainer is windows .net control which consists of a movable bar that divides a container's display area into two resizable panels.

we can use the Orientation property to specify Orientation to be horizontal or vertical. The default orientation of the SplitContainer is vertical.

we can use the split container for the features such as collapse,expand.

Coding :

int LastSplitterDistance = 0;

int tmp = this.splitContainer1.SplitterDistance;
this.splitContainer1.SplitterDistance = LastSplitterDistance;
LastSplitterDistance = tmp;

Here we make the splitter distance property of spitcontanier to 0 to collapse.Making the splitter distance to 0 will collapse panel1 only.

You cannot change the heigth of each panel explicitly.If you do you get a error as below.

"The SplitterPanel's height cannot be set explicitly. Set the SplitterDistance on the SplitContainer instead."

Sample : DownloadZip

Create New Folder Using C#.Net


System.IO.Directory.CreateDirectory("D:\\TempFolder");

This will create a new folder by name "TempFolder" in D drive.

Mail Merge Using C#

I was looking for doing a mail merge application and went through the web and found a good article from Microsoft link .This automates Microsoft Word to perform Mail Merge using C#.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Word = Microsoft.Office.Interop.Word;

namespace mailmersamp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

Word.Application wrdApp;
Word._Document wrdDoc;
Object oMissing = System.Reflection.Missing.Value;
Object oFalse = false;

private void InsertLines(int LineNum)
{
int iCount;

// Insert "LineNum" blank lines.
for (iCount = 1; iCount <= LineNum; iCount++)
{
wrdApp.Selection.TypeParagraph();
}
}

private void FillRow(Word._Document oDoc, int Row, string Text1, string Text2, string Text3, string Text4)
{
// Insert the data into the specific cell.
oDoc.Tables[1].Cell(Row, 1).Range.InsertAfter(Text1);
oDoc.Tables[1].Cell(Row, 2).Range.InsertAfter(Text2);
oDoc.Tables[1].Cell(Row, 3).Range.InsertAfter(Text3);
oDoc.Tables[1].Cell(Row, 4).Range.InsertAfter(Text4);
}

private void CreateMailMergeDataFile()
{
Word._Document oDataDoc;
int iCount;
Object oName = "C:\\TempDoc.doc";
Object oHeader = "FirstName, LastName, Address, CityStateZip"; wrdDoc.MailMerge.CreateDataSource(ref oName, ref oMissing,ref oMissing, ref oHeader, ref oMissing, ref oMissing,ref oMissing, ref oMissing, ref oMissing);

// Open the file to insert data.

oDataDoc = wrdApp.Documents.Open(ref oName, ref oMissing,ref oMissing, ref oMissing, ref oMissing, ref oMissing,ref oMissing, ref oMissing, ref oMissing, ref oMissing,ref oMissing, ref oMissing, ref oMissing, ref oMissing,ref oMissing, ref oMissing);


for (iCount = 1; iCount <= 1; iCount++)
{
oDataDoc.Tables[1].Rows.Add(ref oMissing);
}
// Fill in the data.

FillRow(oDataDoc, 2, "Roy", "John","45 Main Street", "Chennai, IND 6399873");
FillRow(oDataDoc, 3, "Jan", "Mike","34 cross Street", "Trichy, IND 620006");

// Save and close the file.
oDataDoc.Save();
oDataDoc.Close(ref oFalse, ref oMissing, ref oMissing);
}

private void button1_Click(object sender, System.EventArgs e)
{
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 oMissing, ref oMissing,ref oMissing, ref oMissing);
wrdDoc.Select();

wrdSelection = wrdApp.Selection;
wrdMailMerge = wrdDoc.MailMerge;

// Create a MailMerge Data file.
CreateMailMergeDataFile();

// 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);

// Right justify the line and insert a date field
// with the current date.
wrdSelection.ParagraphFormat.Alignment =
Word.WdParagraphAlignment.wdAlignParagraphRight;

Object objDate = "dddd, MMMM dd, yyyy";
wrdSelection.InsertDateTime(ref objDate, ref oFalse, ref oMissing,
ref oMissing, ref oMissing);

InsertLines(2);

// Justify the rest of the document.
wrdSelection.ParagraphFormat.Alignment =
Word.WdParagraphAlignment.wdAlignParagraphJustify;

wrdSelection.TypeText("Dear ");
wrdMergeFields.Add(wrdSelection.Range, "FirstName");
wrdSelection.TypeText(",");
InsertLines(1);

// Create a string and insert it into the document.
StrToAdd = "Thank you for using Mail Merge.";
wrdSelection.TypeText(StrToAdd);

InsertLines(2);

// Insert a new table with 3 rows and 4 columns.
wrdTable = wrdDoc.Tables.Add(wrdSelection.Range, 3, 4,
ref oMissing, ref oMissing);

// Set the column widths.
wrdTable.Columns[1].SetWidth(100, Word.WdRulerStyle.wdAdjustNone);
wrdTable.Columns[2].SetWidth(100, Word.WdRulerStyle.wdAdjustNone);
wrdTable.Columns[1].SetWidth(100, Word.WdRulerStyle.wdAdjustNone);
wrdTable.Columns[2].SetWidth(100, Word.WdRulerStyle.wdAdjustNone);

// Set the shading on the first row to light gray.
wrdTable.Rows[1].Cells.Shading.BackgroundPatternColorIndex =
Word.WdColorIndex.wdGray25;

// Bold the first row.
wrdTable.Rows[1].Range.Bold = 1;

// Center the text in Cell (1,1).
wrdTable.Cell(1, 1).Range.Paragraphs.Alignment =
Word.WdParagraphAlignment.wdAlignParagraphCenter;

// Fill each row of the table with data.
FillRow(wrdDoc, 1, "Number", "Name","Dept","Note");
FillRow(wrdDoc, 2, "100", "abc","Cse","New");
FillRow(wrdDoc, 3, "101", "def","Ece","New");

// Go to the end of the document.
Object oConst1 = Word.WdGoToItem.wdGoToLine;
Object oConst2 = Word.WdGoToDirection.wdGoToLast;
wrdApp.Selection.GoTo(ref oConst1, ref oConst2, ref oMissing, ref oMissing);


// Create a string and insert it into the document.
StrToAdd = "\n For additional information regarding the " +
"Mail Merge, " + "you can visit our Web Site at ";
wrdSelection.TypeText(StrToAdd);

// Insert a hyperlink to the Web page.
Object oAddress = "http://www.fordevs.com";
Object oRange = wrdSelection.Range;
wrdSelection.Hyperlinks.Add(oRange, ref oAddress, ref oMissing,
ref oMissing, ref oMissing, ref oMissing);

// Create a string and insert it into the document
StrToAdd = ". Thank you for your interest in Mail Merge. \r\n\r\n" +
"Sincerely,\r\n" + "Jack\r\n";
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 oMissing, ref oMissing);

// 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.doc");
}
}
}


Download Zip

Note :

We get a error when the concatenated fields string length exceeds 255. To Overcome we can use excel as datasource instead of word.

Using Excel as Datasource