Showing posts with label c==. Show all posts
Showing posts with label c==. Show all posts

Friday, 17 February 2012

C# - Select XML Nodes by Name

To find nodes in an XML file you can use XPath expressions. Method XmlNode.Selec­tNodes returns a list of nodes selected by the XPath string. Method XmlNode.Selec­tSingleNode finds the first node that matches the XPath string.

Suppose we have this XML file.

[XML]
<Names>
<Name>
<FirstName>John</FirstName>
<LastName>Smith</LastName>
</Name>
<Name>
<FirstName>James</FirstName>
<LastName>White</LastName>
</Name>
</Names>

To get all <Name> nodes use XPath expression /Names/Name. The first slash means that the <Names> node must be a root node. SelectNodes method returns collection XmlNodeList which will contain the <Name> nodes. To get value of sub node <FirstName> you can simply index XmlNode with the node name: xmlNode["FirstName"].InnerText. See the example below.

[C#]
XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Names>...</Names>"

XmlNodeList xnList = xml.SelectNodes("/Names/Name");
foreach (XmlNode xn in xnList)
{
string firstName = xn["FirstName"].InnerText;
string lastName = xn["LastName"].InnerText;
Console.WriteLine("Name: {0} {1}", firstName, lastName);
}

The output is:
Name: John Smith
Name: James White

C# Format the date and time

using C = System.Console;
...
static void Main() {
DateTime dateTime = DateTime.Now;
C.WriteLine ("d = {0:d}", dateTime ); // mm/dd/yyyy
C.WriteLine ("D = {0:D}", dateTime ); // month dd, yyyy
C.WriteLine ("f = {0:f}", dateTime ); // day, month dd, yyyy hh:mm
C.WriteLine ("F = {0:F}", dateTime ); // day, month dd, yyyy HH:mm:ss AM/PM
C.WriteLine ("g = {0:g}", dateTime ); // mm/dd/yyyy HH:mm
C.WriteLine ("G = {0:G}", dateTime ); // mm/dd/yyyy hh:mm:ss
C.WriteLine ("M = {0:M}", dateTime ); // month dd
C.WriteLine ("R = {0:R}", dateTime ); // ddd Month yyyy hh:mm:ss GMT
C.WriteLine ("s = {0:s}", dateTime ); // yyyy-mm-dd hh:mm:ss (Sortable)
C.WriteLine ("t = {0:t}", dateTime ); // hh:mm AM/PM
C.WriteLine ("T = {0:T}", dateTime ); // hh:mm:ss AM/PM

// yyyy-mm-dd hh:mm:ss (Sortable)
C.WriteLine ("u = {0:u}", dateTime );

// day, month dd, yyyy hh:mm:ss AM/PM
C.WriteLine ("U = {0:U}", dateTime );

// month, yyyy (March, 2006)
C.WriteLine ("Y = {0:Y}", dateTime );
C.WriteLine ("Month = " + dateTime.Month); // month number (3)

// day of week name (Friday)
C.WriteLine ("Day Of Week = " + dateTime.DayOfWeek);

// 24 hour time (16:12:11)
C.WriteLine ("Time Of Day = " + dateTime.TimeOfDay);

// (632769991310000000)
C.WriteLine("DateTime.Ticks = " + dateTime.Ticks);
// Ticks are the number of 100 nanosecond intervals since 01/01/0001 12:00am
// Ticks are useful in elapsed time measurement.
}


Date and time formatting example (program output)


d = 3/3/2006

D = Friday, March 03, 2006

f = Friday, March 03, 2006 4:20 PM

F = Friday, March 03, 2006 4:20:26 PM

g = 3/3/2006 4:20 PM

G = 3/3/2006 4:20:26 PM

M = March 03

R = Fri, 03 Mar 2006 16:20:26 GMT

s = 2006-03-03T16:20:26

t = 4:20 PM

T = 4:20:26 PM

u = 2006-03-03 16:20:26Z

U = Friday, March 03, 2006 10:20:26 PM

Y = March, 2006

Month = 3

Day Of Week = Friday

Time Of Day = 16:20:26.1406250

DateTime.Ticks = 632769996261406250


Connection String C# - VB.NET

Using C#:

using System.Data.SqlClient;
...
SqlConnection oSQLConn = new SqlConnection();
oSQLConn.ConnectionString = "Data Source=(local);" +
"Initial Catalog=mySQLServerDBName;" +
"Integrated Security=SSPI";
oSQLConn.Open();


Using VB.NET:

Imports System.Data.SqlClient
...
Dim oSQLConn As SqlConnection = New SqlConnection()
oSQLConn.ConnectionString = "Data Source=(local);" & _
"Initial Catalog=mySQLServerDBName;" & _
"Integrated Security=SSPI"
oSQLConn.Open()


If connection to a remote server (via IP address):

oSQLConn.ConnectionString = "Network Library=DBMSSOCN;" & _
"Data Source=xxx.xxx.xxx.xxx,1433;" & _
"Initial Catalog=mySQLServerDBName;" & _
"User ID=myUsername;" & _
"Password=myPassword"
Where:
- "Network Library=DBMSSOCN" tells SqlConnection to use TCP/IP Q238949
- xxx.xxx.xxx.xxx is an IP address.
- 1433 is the default port number for SQL Server.  Q269882 and Q287932
- You can also add "Encrypt=yes" for encryption


 OLE DB .NET Data Provider (System.Data.OleDb)
The OLE DB .NET Data Provider uses native OLE DB through COM interop to enable data access. 


To use the OLE DB .NET Data Provider, you must also use an OLE DB provider (e.g.  SQLOLEDB, MSDAORA, or Microsoft.JET.OLEDB.4.0).

For IBM AS/400 OLE DB Provider

' VB.NET
Dim oOleDbConnection As OleDb.OleDbConnection
Dim sConnString As String = _
"Provider=IBMDA400.DataSource.1;" & _
"Data source=myAS400DbName;" & _
"User Id=myUsername;" & _
"Password=myPassword"
oOleDbConnection = New OleDb.OleDbConnection(sConnString)
oOleDbConnection.Open()


For JET OLE DB Provider

' VB.NET
Dim oOleDbConnection As OleDb.OleDbConnection
Dim sConnString As String = _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\myPath\myJet.mdb;" & _
"User ID=Admin;" & _
"Password="
oOleDbConnection = New OleDb.OleDbConnection(sConnString)
oOleDbConnection.Open()


For Oracle OLE DB Provider

' VB.NET
Dim oOleDbConnection As OleDb.OleDbConnection
Dim sConnString As String = _
"Provider=OraOLEDB.Oracle;" & _
"Data Source=MyOracleDB;" & _
"User ID=myUsername;" & _
"Password=myPassword"
oOleDbConnection = New OleDb.OleDbConnection(sConnString)
oOleDbConnection.Open()


For SQL Server OLE DB Provider

' VB.NET
Dim oOleDbConnection As OleDb.OleDbConnection
Dim sConnString As String = _
"Provider=sqloledb;" & _
"Data Source=myServerName;" & _
"Initial Catalog=myDatabaseName;" & _
"User Id=myUsername;" & _
"Password=myPassword"
oOleDbConnection = New OleDb.OleDbConnection(sConnString)
oOleDbConnection.Open()


For Sybase ASE OLE DB Provider

' VB.NET
Dim oOleDbConnection As OleDb.OleDbConnection
Dim sConnString As String = _
"Provider=Sybase ASE OLE DB Provider;" & _
"Data Source=MyDataSourceName;" & _
"Server Name=MyServerName;" & _
"Database=MyDatabaseName;" & _
"User ID=myUsername;" & _
"Password=myPassword"
oOleDbConnection = New OleDb.OleDbConnection(sConnString)
oOleDbConnection.Open()
For more information, see:  System.Data.OleDb Namespace and .NET Data Providers


 ODBC .NET Data Provider (System.Data.ODBC)
The ODBC .NET Data Provider is an add-on component to the .NET 1.0 Framework SDK. It provides access to native ODBC drivers the same way the OLE DB .NET Data Provider provides access to native OLE DB providers.


For SQL Server ODBC Driver

' VB.NET
Dim oODBCConnection As Odbc.OdbcConnection
Dim sConnString As String = _
"Driver={SQL Server};" & _
"Server=MySQLServerName;" & _
"Database=MyDatabaseName;" & _
"Uid=MyUsername;" & _
"Pwd=MyPassword"
oODBCConnection = New Odbc.OdbcConnection(sConnString)
oODBCConnection.Open()


For Oracle ODBC Driver

' VB.NET
Dim oODBCConnection As Odbc.OdbcConnection
Dim sConnString As String = _
"Driver={Microsoft ODBC for Oracle};" & _
"Server=OracleServer.world;" & _
"Uid=myUsername;" & _
"Pwd=myPassword"
oODBCConnection = New Odbc.OdbcConnection(sConnString)
oODBCConnection.Open()


For Access (JET) ODBC Driver

' VB.NET
Dim oODBCConnection As Odbc.OdbcConnection
Dim sConnString As String = _
"Driver={Microsoft Access Driver (*.mdb)};" & _
"Dbq=c:\somepath\mydb.mdb;" & _
"Uid=Admin;" & _
"Pwd="
oODBCConnection = New Odbc.OdbcConnection(sConnString)
oODBCConnection.Open()


For Sybase System 11 ODBC Driver

// C#
string myConnStr = "Driver={Sybase System 11};" +
"SRVR=mySybaseServerName;" +
"DB=myDatabaseName;" +
"UID=myUsername;" +
"PWD=myPassword";
OdbcConnection myConnection = new OdbcConnection(myConnStr);
myConnection.Open();


For all other ODBC Drivers

' VB.NET
Dim oODBCConnection As Odbc.OdbcConnection
Dim sConnString As String = "Dsn=myDsn;" & _
"Uid=myUsername;" & _
"Pwd=myPassword"
oODBCConnection = New Odbc.OdbcConnection(sConnString)
oODBCConnection.Open()
For more information, see:  ODBC .Net Data Provider


 .NET Framework Data Provider for Oracle (System.Data.OracleClient)
The .NET Framework Data Provider for Oracle is an add-on component to the .NET Framework that provides access to an Oracle database using the Oracle Call Interface (OCI) as provided by Oracle Client software. 


Using C#:

using System.Data.OracleClient;

OracleConnection oOracleConn = new OracleConnection();
oOracleConn.ConnectionString = "Data Source=Oracle8i;" +
"Integrated Security=SSPI";
oOracleConn.Open();


Using VB.NET:

Imports System.Data.OracleClient

Dim oOracleConn As OracleConnection = New OracleConnection()
oOracleConn.ConnectionString = "Data Source=Oracle8i;" & _
"Integrated Security=SSPI";
oOracleConn.Open()
Note: You must have the Oracle 8i Release 3 (8.1.7) Client or later installed in order for this provider to work correctly.


Note: You must have the RTM version of the .NET Framework installed in order for this provider to work correctly.

Note: There are known Oracle 7.3, Oracle 8.0, and Oracle9i client and server problems in this beta release. The server-side issues should be resolved in the final release of the product.  However, Oracle 7.3 client will not be supported.

 MySQL .NET Native Provider
The MySQL .NET Native Provider is an add-on component to the .NET Framework that allows you to access the MySQL database through the native protocol, without going through OLE DB.


Using C#

using EID.MySqlClient;

MySqlConnection oMySqlConn = new MySqlConnection();
oMySqlConn.ConnectionString = "Data Source=localhost;" +
"Database=mySQLDatabase;" +
"User ID=myUsername;" +
"Password=myPassword;" +
"Command Logging=false";
oMySqlConn.Open();


Using VB.NET

Imports EID.MySqlClient

Dim oMySqlConn As MySqlConnection = New MySqlConnection()
oMySqlConn.ConnectionString = "Data Source=localhost;"  & _
"Database=mySQLDatabase;"  & _
"User ID=myUsername;"  & _
"Password=myPassword;"  & _
"Command Logging=false"
oMySqlConn.Open()

Tuesday, 3 January 2012

The Split Method C#

The Split method is used to split a string of text and put the words into an array. For example, you could grab a line of text from a text file. Each position in the array would then hold a word from the line of text. An example may clear things up.

Add another button to your form. Double click the button to get at the code, and add the following:

C# code for the Split Method


Run the programme and click your button. You should see each word from the line of text display.

In the first line of the code, we're setting up a string with three items in it. Each item is separated by a comma. (Comma separated files from software like Excel are quite common, and so too is parsing each line of text.)

For the second line, we have this:

string[] wordArray = lineOfText.Split( ',' );

The first part sets up a string array that we've called wordArray. After the equals sign, we have this:

lineOfText.Split( ',' );

The variable called lineOfText is obviously the line of text we want to examine. For the round brackets of Split, we've typed a comma surrounded by single quotes. That's because C# needs to know what character in your line of text you are using to separate the words. This is known as the delimiter. If our line of text were this instead:

string lineOfText = "item1 item2 item3";

we'd use a blank space as a delimiter. Like this:

string[] wordArray = lineOfText.Split( ' ' );

This time, we've typed a blank space between the single quotes.

But C# will split the line, and put each part into the array we've set up. (It won't include the delimiter.) For our line of text we only have three words. So the Message box in our code displays what is at position 0, position 1, and position 2 in our array.

If you don't know how many position there are in the array (if you have lines of text that vary in size, for example), the you can loop through each position:

foreach (string s in wordArray)
{
MessageBox.Show( s );
}

The Split method can take other parameters, and get a bit complex. So we'll leave it there in this beginners book!

 

The Join Method


You can join the pieces of your arrays back together again. Join, however, is not a method available to ordinary strings. Instead, you can access it through the String class. Like this:

C# code for the Join Method


In the code above, we've used Split to split the line of text and put the words into an array. We've then used Join to create a single line of text again. This time, though, the words are separated with hyphens and not commas.

To use Join, first type the word String (with a capital letter). After a dot, you should then see the Join method appear on the IntelliSense list. In between the round brackets of Join, you first need the character your want to use as a delimiter. Note that this is surrounded by double quotes. If you use single quotes, C# will think it is the char variable type. But you need to use the string variable type, so you'll get an error. After a comma, you type the name of the array you want to Join together

Monday, 19 December 2011

Select XML Nodes by Name in C#

To find nodes in an XML file you can use XPath expressions. Method XmlNode.Selec­tNodes returns a list of nodes selected by the XPath string. Method XmlNode.Selec­tSingleNode finds the first node that matches the XPath string.

Suppose we have this XML file.

[XML]
<Names>
<Name>
<FirstName>John</FirstName>
<LastName>Smith</LastName>
</Name>
<Name>
<FirstName>James</FirstName>
<LastName>White</LastName>
</Name>
</Names>

To get all <Name> nodes use XPath expression /Names/Name. The first slash means that the <Names> node must be a root node. SelectNodes method returns collection XmlNodeList which will contain the <Name> nodes. To get value of sub node <FirstName> you can simply index XmlNode with the node name: xmlNode["FirstName"].InnerText. See the example below.

[C#]
XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Names>...</Names>"

XmlNodeList xnList = xml.SelectNodes("/Names/Name");
foreach (XmlNode xn in xnList)
{
string firstName = xn["FirstName"].InnerText;
string lastName = xn["LastName"].InnerText;
Console.WriteLine("Name: {0} {1}", firstName, lastName);
}

The output is:
Name: John Smith
Name: James White

Friday, 16 December 2011

C# String Functions and Manipulation

C# and VB.NET have a whole set of string functions to trim, find, search, replace and split strings. It's also simple to convert to upper case or title case

Trim Function


The trim function has three variations Trim, TrimStart and TrimEnd. The first example show how to use the Trim(). It strips all white spaces from both the start and end of the string.

//STRIPS WHITE SPACES FROM BOTH START + FINSIHE
string Name = " String Manipulation " ;
string NewName = Name.Trim();
//ADD BRACKET SO YOU CAN SEE TRIM HAS WORKED
MessageBox.Show("["+ NewName + "]");

TrimEnd


TrimEnd works in much the same way but u are stripping characters which you specify from the end of the string, the below example first strips the space then the n so the output is String Manipulatio.

//STRIPS CHRS FROM THE END OF THE STRING
string Name = " String Manipulation " ;
//SET OUT CHRS TO STRIP FROM END
char[] MyChar = {' ','n'};
string NewName = Name.TrimEnd(MyChar);
//ADD BRACKET SO YOU CAN SEE TRIM HAS WORKED
MessageBox.Show("["+ NewName + "]");

TrimStart


TrimStart is the same as TrimEnd apart from it does it to the start of the string.

//STRIPS CHRS FROM THE START OF THE STRING
string Name = " String Manipulation " ;
//SET OUT CHRS TO STRIP FROM END
char[] MyChar = {' ','S'};
string NewName = Name.TrimStart(MyChar);
//ADD BRACKET SO YOU CAN SEE TRIM HAS WORKED
MessageBox.Show("["+ NewName + "]");

Find String within string


This code shows how to search within a string for a sub string and either returns an index position of the start or a -1 which indicates the string has not been found.

string MainString = "String Manipulation";
string SearchString = "pul";
int FirstChr = MainString.IndexOf(SearchString);
//SHOWS START POSITION OF STRING
MessageBox.Show("Found at : " + FirstChr );

Replace string in string


Below is an example of replace a string within a string. It replaces the word Manipulatin with the correct spelling of Manipulation.

string MainString "String Manipulatin";
string CorrectString = MainString.Replace("Manipulatin", "Manipulation");
//SHOW CORRECT STRING
MessageBox.Show("Correct string is : " + CorrectString);

Strip specified number of characters from string


This example show how you can strip a number of characters from a specified starting point within the string. The first number is the starting point in the string and the second is the amount of chrs to strip.

string MainString = "S1111tring Manipulation";
string NewString = MainString.Remove(1,4);


//SHOW OUTPUT
MessageBox.Show(NewSring);

Split string with delimiter


The example below shows how to split the string into seperate parts via a specified dilemeter. The results get put into the Split array and called back via Split[0].

string MainString = "String Manipulation";
string [] Split = MainString.Split(new Char [] {' '});
//SHOW RESULT
MessageBox.Show(Convert.ToString(Split[0]));
MessageBox.Show(Convert.ToString(Split[1]));

Convert to title (proper) case


This is a simple extension method to convert a string to Proper Case or Title Case (ie the first character of each word is made upper case).
public static string ToTitleCase(this string title)
{
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
return textInfo.ToTitleCase(title);
}

Microsoft Word Template for Reoport Using ASP.NET C#

private void GenerateWords(string sPO, string sSup)

{

Object oMissing = System.Reflection.Missing.Value;

Object oTrue = true;

Object oFalse = false;

Object savechanges = true;

Word.ApplicationClass oWord = new Word.ApplicationClass();

Word.Document oWordDoc = new Word.Document();

oWord.Visible = true;

Object oTemplatePath = Server.MapPath("Reports/Word/PurchaseOrder.docx");

 

oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);

oWordDoc.Activate();

 

foreach (Word.Field myMergeField in oWordDoc.Fields)

{

iTotalFields++;

Word.Range rngFieldCode = myMergeField.Code;

String fieldText = rngFieldCode.Text;

 

// Start filling information in Word file

if (fieldText.StartsWith(" MERGEFIELD"))

{

Int32 endMerge = fieldText.IndexOf("\\");

Int32 fieldNameLength = fieldText.Length - endMerge;

String fieldName = fieldText.Substring(11, endMerge - 11);

 

fieldName = fieldName.Trim();

 

if (fieldName == "PONo")

{

myMergeField.Select();

oWord.Selection.Font.Color = Word.WdColor.wdColorBlue;

oWord.Selection.TypeText(sPO);

}

 

if (fieldName == "SupNo")

{

myMergeField.Select();

oWord.Selection.Font.Color = Word.WdColor.wdColorBlue;

oWord.Selection.TypeText(sSup);

}

 

if (fieldName == "VendorID")

{

myMergeField.Select();

oWord.Selection.Font.Color = Word.WdColor.wdColorBlue;

oWord.Selection.TypeText(dtPOSup(sPO, sSup).Rows[0]["VendorID"].ToString().Trim());

}

 

if (fieldName == "VName")

{

myMergeField.Select();

oWord.Selection.Font.Color = Word.WdColor.wdColorBlue;

oWord.Selection.TypeText(dtPOSup(sPO, sSup).Rows[0]["Name"].ToString().Trim());

}

 

if (fieldName == "Contact")

{

myMergeField.Select();

oWord.Selection.Font.Color = Word.WdColor.wdColorBlue;

oWord.Selection.TypeText(dtPOSup(sPO, sSup).Rows[0]["Contact"].ToString().Trim());

}

 

if (fieldName == "Designation")

{

myMergeField.Select();

oWord.Selection.Font.Color = Word.WdColor.wdColorBlue;

oWord.Selection.TypeText(dtPOSup(sPO, sSup).Rows[0]["Designation"].ToString().Trim());

}

 

if (fieldName == "Tel")

{

myMergeField.Select();

oWord.Selection.Font.Color = Word.WdColor.wdColorBlue;

oWord.Selection.TypeText(dtPOSup(sPO, sSup).Rows[0]["Tel"].ToString().Trim());

}

 

if (fieldName == "Fax")

{

myMergeField.Select();

oWord.Selection.Font.Color = Word.WdColor.wdColorBlue;

oWord.Selection.TypeText(dtPOSup(sPO, sSup).Rows[0]["Fax"].ToString().Trim());

}

 

if (fieldName == "PODate")

{

myMergeField.Select();

oWord.Selection.Font.Color = Word.WdColor.wdColorBlue;

oWord.Selection.TypeText(dtPOSup(sPO, sSup).Rows[0]["PODate"].ToString().Trim());

}

 

if (fieldName == "ClientName")

{

myMergeField.Select();

oWord.Selection.Font.Color = Word.WdColor.wdColorBlue;

oWord.Selection.TypeText(dtPOSup(sPO, sSup).Rows[0]["ClientName"].ToString().Trim());

}

 

if (fieldName == "JobDescription")

{

myMergeField.Select();

oWord.Selection.Font.Color = Word.WdColor.wdColorBlue;

oWord.Selection.TypeText(dtPOSup(sPO, sSup).Rows[0]["JobDescription"].ToString().Trim());

}

 

if (fieldName == "JobNo")

{

myMergeField.Select();

oWord.Selection.Font.Color = Word.WdColor.wdColorBlue;

oWord.Selection.TypeText(dtPOSup(sPO, sSup).Rows[0]["JobNo"].ToString().Trim());

}

 

if (fieldName == "CostCode")

{

myMergeField.Select();

oWord.Selection.Font.Color = Word.WdColor.wdColorBlue;

oWord.Selection.TypeText(dtPOSup(sPO, sSup).Rows[0]["CostCode"].ToString().Trim());

}

 

if (fieldName == "SchDlvy")

{

myMergeField.Select();

oWord.Selection.Font.Color = Word.WdColor.wdColorBlue;

oWord.Selection.TypeText(dtPOSup(sPO, sSup).Rows[0]["SchDlvy"].ToString().Trim());

}

 

if (fieldName == "DlvyPoint")

{

myMergeField.Select();

oWord.Selection.Font.Color = Word.WdColor.wdColorBlue;

oWord.Selection.TypeText(dtPOSup(sPO, sSup).Rows[0]["DlvyPoint"].ToString().Trim());

}

 

if (fieldName == "Amount")

{

myMergeField.Select();

oWord.Selection.Font.Color = Word.WdColor.wdColorBlue;

oWord.Selection.TypeText(dtPOSup(sPO, sSup).Rows[0]["Amount"].ToString().Trim());

}

 

if (fieldName == "tbl")

{

myMergeField.Select();

oWord.Selection.Font.Color = Word.WdColor.wdColorBlue;

oWord.Selection.TypeParagraph();

Word.Table tbl = oWordDoc.Tables.Add(rngFieldCode, 1, 5, ref oMissing, ref oMissing);

//oWordDoc.Tables.Add(rngFieldCode, dtItems(sPO, sSup).Rows.Count, 5, ref oMissing, ref oMissing);

 

//SET HEADER

SetHeadings(tbl.Cell(1, 1), "Item No.");

SetHeadings(tbl.Cell(1, 2), "Description");

SetHeadings(tbl.Cell(1, 3), "Unit");

SetHeadings(tbl.Cell(1, 4), "Unit Price");

SetHeadings(tbl.Cell(1, 5), "Amount");

//END SET HEADER

 

//Add Row

for (int i = 0; i < dtItems(sPO, sSup).Rows.Count; i++)

{

Word.Row newRow = tbl.Rows.Add(ref oMissing);

newRow.Range.Font.Bold = 0;

newRow.Range.Underline = 0;

newRow.Range.ParagraphFormat.Alignment =

Word.WdParagraphAlignment.wdAlignParagraphCenter;

 

newRow.Cells[1].Range.Text = dtItems(sPO, sSup).Rows[i][3].ToString();

newRow.Cells[2].Range.Text = dtItems(sPO, sSup).Rows[i][4].ToString();

newRow.Cells[3].Range.Text = dtItems(sPO, sSup).Rows[i][8].ToString();

newRow.Cells[4].Range.Text = dtItems(sPO, sSup).Rows[i][10].ToString();

newRow.Cells[5].Range.Text = dtItems(sPO, sSup).Rows[i][11].ToString();

}

//END ROW

 

oWord.Selection.TypeParagraph();

}

 

if (fieldName == "TItems")

{

myMergeField.Select();

oWord.Selection.Font.Color = Word.WdColor.wdColorBlue;

oWord.Selection.TypeText(dtTotal(sPO, sSup).Rows[0]["Unit"].ToString().Trim());

}

 

if (fieldName == "Discount")

{

myMergeField.Select();

oWord.Selection.Font.Color = Word.WdColor.wdColorBlue;

oWord.Selection.TypeText(dtTotal(sPO, sSup).Rows[0]["Discount"].ToString().Trim());

}

 

if (fieldName == "TAmount")

{

myMergeField.Select();

oWord.Selection.Font.Color = Word.WdColor.wdColorBlue;

oWord.Selection.TypeText(dtTotal(sPO, sSup).Rows[0]["Amount"].ToString().Trim());

}

 

if (fieldName == "Summary")

{

myMergeField.Select();

oWord.Selection.Font.Color = Word.WdColor.wdColorBlue;

oWord.Selection.TypeText(dtPOSup(sPO, sSup).Rows[0]["Amount"].ToString().Trim());

}

 

if (fieldName == "ReqNo")

{

myMergeField.Select();

oWord.Selection.Font.Color = Word.WdColor.wdColorBlue;

oWord.Selection.TypeText(dtPOSup(sPO, sSup).Rows[0]["ReqNo"].ToString().Trim());

}

 

if (fieldName == "RevNo")

{

myMergeField.Select();

oWord.Selection.Font.Color = Word.WdColor.wdColorBlue;

oWord.Selection.TypeText(dtPOSup(sPO, sSup).Rows[0]["RevNo"].ToString().Trim());

}

}

}

// End filling information in Word file

 

Object oSaveAsFile = (Object)Server.MapPath("Reports/Word/tmp2.docx");

oWordDoc.SaveAs(ref oSaveAsFile, 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);

 

oWordDoc.Close(ref savechanges, ref oMissing, ref oMissing);

oWord.Application.Quit(ref savechanges, ref oMissing, ref oMissing);

 

//foreach (Process p in System.Diagnostics.Process.GetProcessesByName("winword"))

//{

// try

// {

// if (p.ProcessName == "WINWORD")

// {

// if (!p.HasExited)

// {

// p.Kill();

// p.WaitForExit(); // possibly with a timeout

// }

// }

// else

// {

// lblMessage.Text = "cannot kill. try again!";

// }

// }

// catch (Win32Exception winException)

// {

// //process was terminating or can't be terminated - deal with it

// Session["error"] = winException.Message;

// Response.Redirect("MessageBoard.aspx");

// }

// catch (InvalidOperationException invalidException)

// {

// //process has already exited - might be able to let this one go

// Session["error"] = invalidException.Message;

// Response.Redirect("MessageBoard.aspx");

// }

//}

 

Response.ClearContent();

Response.ClearHeaders();

Response.ContentType = "application/msword";

Response.WriteFile(Server.MapPath("Reports/Word/tmp2.docx"), false);

Response.Flush();

Response.Close();

}

 

 

Different ways how to escape an XML string in C#

Different ways how to escape an XML string in C#


XML encoding is necessary if you have to save XML text in an XML document. If you don't escape special chars the XML to insert will become a part of the original XML DOM and not a value of a node.

Escaping the XML means basically replacing 5 chars with new values.

These replacements are:




























<->&lt;
>->&gt;
"->&quot;
'->&apos;
&->&amp;

 

Here are 4 ways you can encode XML in C#

1. string.Replace() 5 times

This is ugly but it works. Note that Replace("&", "&amp;") has to be the first replace so we don't replace other already escaped &.

 
string xml = "<node>it's my \"node\" & i like it<node>";
encodedXml = xml.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\"", "&quot;").Replace("'", "&apos;");

// RESULT: &lt;node&gt;it&apos;s my &quot;node&quot; &amp; i like it&lt;node&gt;

 

 

2. System.Web.HttpUtility.HtmlEncode()

Used for encoding HTML, but HTML is a form of XML so we can use that too. Mostly used in ASP.NET apps. Note that HtmlEncode does NOT encode apostrophes ( ' ).
string xml = "<node>it's my \"node\" & i like it<node>";
string encodedXml = HttpUtility.HtmlEncode(xml);

// RESULT: &lt;node&gt;it's my &quot;node&quot; &amp; i like it&lt;node&gt;

3. System.Security.SecurityElement.Escape()

In Windows Forms or Console apps I use this method. If nothing else it saves me including the System.Web reference in my projects and it encodes all 5 char.


string xml = "<node>it's my \"node\" & i like it<node>";

string encodedXml = System.Security.SecurityElement.Escape(xml);

 

// RESULT: &lt;node&gt;it&apos;s my &quot;node&quot; &amp; i like it&lt;node&gt;



4. System.Xml.XmlTextWriter

Using XmlTextWriter you don't have to worry about escaping anything since it escapes the chars where needed. For example in the attributes it doesn't escape apostrophes, while in node values it doesn't escape apostrophes and qoutes.



string xml = "<node>it's my \"node\" & i like it<node>";

using (XmlTextWriter xtw = new XmlTextWriter(@"c:\xmlTest.xml", Encoding.Unicode))

{

xtw.WriteStartElement("xmlEncodeTest");

xtw.WriteAttributeString("testAttribute", xml);

xtw.WriteString(xml);

xtw.WriteEndElement();

}

 

// RESULT:

/*

<xmlEncodeTest testAttribute="&lt;node&gt;it's my &quot;node&quot; &amp; i like it&lt;node&gt;">

&lt;node&gt;it's my "node" &amp; i like it&lt;node&gt;

</xmlEncodeTest>

*/



 

Each of the four ways is different, so use each one where you fell appropriate. You can't go wrong with SecurityElement though. :)

MS Word Office Automation - Filling Text Form Fields And Check Box Form Fields And Mail Merge

The first one is using MailMerge and the second is using bookmarks.

The word file looks like this:

Using MailMerge (Insert - > Quick Parts -> Field -> Mail merge -> Merge field) First name: «firstName» Last name: «lastName»

Using Bookmarks( Insert -> BookMark) First name: (<- the bookmark is here, it’s not visible) Last name:

And the code is following:

  1. Using bookmarks
     

    Open("D:/Doc1.doc");

    if (oDoc.Bookmarks.Exists("bkmFirstName"))

    {

    object oBookMark = "bkmFirstName";

    oDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = textBox1.Text;

    }

    if (oDoc.Bookmarks.Exists("bkmLastName"))

    {

    object oBookMark = "bkmLastName";

    oDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = textBox2.Text;

    }

     

     

    SaveAs("D:/Test/Doc2.doc"); Quit();

    MessageBox.Show("The file is successfully saved!");

     

  2. Using MailMerge
       

    Open("D:/Doc1.doc");

    foreach (Field myMergeField in oDoc.Fields)

    {

    //iTotalFields++;

    Range rngFieldCode = myMergeField.Code;

    String fieldText = rngFieldCode.Text;

     

     

    // GET only MAILMERGE fields

    if (fieldText.StartsWith(" MERGEFIELD"))

    {

    Int32 endMerge = fieldText.IndexOf("\\");

    Int32 fieldNameLength = fieldText.Length - endMerge;

    String fieldName = fieldText.Substring(11, endMerge - 11);

     

     

    fieldName = fieldName.Trim();

    if (fieldName == "firstName")

    {

    myMergeField.Select();

    oWordApplic.Selection.TypeText("This Text Replaces the Field in the Template");

    }

    }

    }

    SaveAs("D:/Test/Doc2.doc"); Quit();

    MessageBox.Show("The file is successfully saved!");

     




 

Method in C#

ApplicationClass oWordApplic = new Microsoft.Office.Interop.Word.ApplicationClass();

private Microsoft.Office.Interop.Word.Document oDoc = new Document();

 

public void Open(string strFileName)

{

object fileName = strFileName;

object readOnly = false;

object isVisible = true;

object missing = System.Reflection.Missing.Value;

 

oDoc = oWordApplic.Documents.Open(ref fileName, ref missing, ref readOnly,

ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,

ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing);

 

oDoc.Activate();

}

 

public void SaveAs(string strFileName)

{

object missing = System.Reflection.Missing.Value;

object fileName = strFileName;

 

oDoc.SaveAs(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,

ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);

}

 

public void Quit()

{

object missing = System.Reflection.Missing.Value;

oWordApplic.Application.Quit(ref missing, ref missing, ref missing);

}

 

Tuesday, 10 August 2010

Matrix Output in C

user will just enter number of rows and cols and your program will generate following result.....
for eg.
for n=3 your output should be

4 9 2
3 5 7
8 1 6

each number is used only once....addition of numbers in rows,cols and on diagonals are same. So, now try this, first of all just for the odd values of n...then think about the even values of n.....first of all is there any pattern ??? then and then you can write logic for this.... Lets see how much time it will take????

void main()
{
int a=3;
int b;
b=(++a)+(++a)+(++a);
a=3;
printf("%d",(++a)+(++a)+(++a));
}

Tuesday, 2 February 2010

Export Tablular data in CSV format in C#

protected void Page_Load(object sender, EventArgs e)
{
string strconn = "server=192.168.1.1;database=db;uid=sa;pwd=sa";
SqlConnection conn = new SqlConnection(strconn);
SqlDataAdapter da = new SqlDataAdapter("select * from tablename", conn);
DataSet ds = new DataSet();
da.Fill(ds, "Tablename");
DataTable dt = ds.Tables["Tablename"];
CreateCSVFile(dt, "D:csvData.csv");
}
public void CreateCSVFile(DataTable dt, string strFilePath)
{

StreamWriter sw = new StreamWriter(strFilePath, false);
int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
sw.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
// Now write all the rows.
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();

/*
string mFileName = @"E:SonarishWeights_updation";
string filename = "Products_YPT_All Items.csv";
string conn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " + mFileName + "; Extended Properties='text;HDR=Yes'";
OleDbConnection ExcelConnection = new OleDbConnection(conn);
OleDbCommand ExcelCommand = new OleDbCommand("SELECT * FROM [" + filename + "]", ExcelConnection);
OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ExcelCommand);
ExcelConnection.Open();
System.Data.DataSet dataSetFromCSV = new DataSet();
ExcelAdapter.Fill(dataSetFromCSV);
ExcelConnection.Close();
if (dataSetFromCSV.Tables[0].Rows.Count > 0)
{

for (int i = 0; i < dataSetFromCSV.Tables[0].Rows.Count; i++)
{
DataRow drexcel = dataSetFromCSV.Tables[0].Rows[i];

string itemname = drexcel[0].ToString();
string weight = drexcel[27].ToString();
if (weight == "")
{
weight = "NULL";
query = "UPDATE InventoryUnitMeasure SET WeightInKilograms=" + weight + " FROM InventoryItem where InventoryItem.ItemCode=InventoryUnitMeasure.ItemCode and InventoryItem.ItemName='" + itemname + "'";
}
else
{
query = "UPDATE InventoryUnitMeasure SET WeightInKilograms=" + weight + " FROM InventoryItem where InventoryItem.ItemCode=InventoryUnitMeasure.ItemCode and InventoryItem.ItemName='" + itemname + "'";
}
SqlCommand com = new SqlCommand(query, con);
com.ExecuteNonQuery();
}

}*/
}

Tuesday, 12 January 2010

C++ Syntax: Switch

C++ Syntax: switch
Description
The switch statement provides a convenient alternative to the if when dealing with a multi-way branch. Suppose we have some integer value called test and want to do different operations depending on whether it has the value 1, 5 or any other value, then the switch statement could be employed:-
switch ( test ) {

case 1 :
// Process for test = 1
...
break;

case 5 :
// Process for test = 5
...
break;

default :
// Process for all other cases.
...

}

It works as follows:-
The expression, just test in this case, is evaluated.
The case labels are checked in turn for the one that matches the value.
If none matches, and the optional default label exists, it is selected, otherwise control passes from the switch compound statement
If a matching label is found, execution proceeds from there. Control then passes down through all remaining labels within the switch statement. As this is normally not what is wanted, the break statement is normally added before the next case label to transfer control out of the switch statement. One useful exception occurs when you want to do the same processing for two or more values. Suppose you want values 1 and 10 to do the same thing, then:-
case 1 :
case 10:
// Process for test = 1 or 10
break;

works because the test = 1 case just "drops through" to the next section