Wednesday, December 24, 2008

How to use F8 in C# or VB.NET

Use F8 for debugging in C# or VB.NET

Programmers migrating from VB 6.0 will like to hang on to the good old F8 function key in C#/VB.NET. One can do that by changing the settings from Visual Studioà Tools Menu -- > Options -- > Environment -- > Keyboard and select Visual Basic 6 as the Mapping scheme




Tuesday, December 16, 2008

Get Built-in Property of Word Document using C# (.NET)

Retrieve Built-in Property of Word Document using C# (.NET)

Here is a simple code that uses System.Reflection class’s methods to extract the builtin document properties of a Word document

Declarations

using System.Reflection;

using Microsoft.VisualBasic;

using Office = Microsoft.Office.Core ;

using Word = Microsoft.Office.Interop.Word;

Code:

private static void GetBuiltInProperty_CSharp(Object sFileName )

{

Word.Application oWA;// Word Application Object

Word.Document oWD;// Word Document Object

Object missing = Missing.Value ;

Object bSaveChanges = false ;

Object oBuiltProps;

try

{

oWA = new Word.Application();

oWA.Visible = true;

oWD = oWA.Documents.Open(ref sFileName , 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);

oBuiltProps = oWD.BuiltInDocumentProperties;

string sProperty = "Author";

Type typeBuiltProps = oBuiltProps.GetType();

Object oDocProp = typeBuiltProps.InvokeMember("Item", BindingFlags.DefaultBindingFlags.GetProperty, null, oBuiltProps, new object[] {sProperty});

string sPropValue;

Type typeAutValue = oDocProp.GetType();

sPropValue = typeAutValue.InvokeMember("Value", BindingFlags.Default BindingFlags.GetProperty, null, oDocProp, new object[] { }).ToString();

oWD.Close(ref bSaveChanges, ref missing, ref missing);

oWA.Quit(ref bSaveChanges, ref missing, ref missing);

}

catch (Exception)

{

throw;

}

}

Remove DOCTYPE declaration from XML Files using C#

How to remove Document Type Definition (DTD) declarations from XML Files using C#

XMLSchema is fast replacing DTD. If you have old XML files that link to DTD, you might want to remove the Doctype declarations. The following code should help you in that

private static void Remove_DTD_From_XML(String sXMLFile)

{

try

{

XmlDocument XDoc = new XmlDocument();

XDoc.Load(sXMLFile);

XmlDocumentType XDType = XDoc.DocumentType;

XDoc.RemoveChild(XDType);

XDoc.Save(sXMLFile + ".changed");

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

}

}

}

How to Get All Elements of an XML using C# (.NET)

Loop through XML and retrieve all elements using C# (.NET)

XML is a wonderful invention readily accepted by the programming community. Nowadays, you will find most of the data as XML. How to make it in a readable / printable form. The obvious answer would be a XML transformation (using XSLT).

But here we will look into a simple way to extract contents of XML using C#

The XML File looks like the following:

< ?xml version="1.0" encoding="us-ascii" standalone="yes"? >

< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "C:\ShasurData\ForBlogger\OldData\Sample.DTD" >

< !--Sample Invoice for GP GmbH-- >

< Invoice INVNo="INT03456" InvDate="15-09-2008 08:41:42" xmlns:d1p1="InvDate" >

< Items >

< Item >

< Name >Hex Socket Screw< /Name >

< Price >$4.25< /Price >

< Quantity >1000< /Quantity >

< /Item >

< Item >

< Name >Roll Bearing< /Name >

< Price >$6.15< /Price >

< Quantity >1200< /Quantity >

< /Item >

< /Items >

< /Invoice >

We use the following code to loop through the nodes and extract the elements

private static void ReadXMLEXample()

{

XmlDocument XDoc = new XmlDocument();

XDoc.Load(@"C:\ShasurData\ForBlogger\OldData\Sample.xml");

XmlNodeList XNodeList = XDoc.SelectNodes("//Items/Item");

Console.WriteLine("{0}\t{1}", "Name","Price");

foreach (XmlElement XElement in XNodeList)

{

Console.WriteLine("{0}\t{1}", XElement["Name"].InnerText.ToString(), XElement["Price"].InnerText.ToString());

}

}

The output will be :




Beep in C# Console Application

How to Alert the user in C# console application

You can use “\a” to alert the user with the system beep sound. The following example alerts the user for input

private static void KeywordExample()

{

Console.Write("\a Your name please" );

string @MyString = Console.ReadLine();

Console.Write(@MyString);

}

How to use Reserved Words in .NET (C#)

How to use Keywords in .NET (C#)

If you can use tens and thousands of words as identifier, why should one use the few keywords reserved by C#?

private static void KeywordExample()

{

string string = "Some String";

}

Might be you still want to use ‘bool’, ‘string’ etc. But using this will throw “identifier expected, 'keyword' is a keyword - Compiler Error CS1041”

A reserved word for the C# language was found where an identifier was expected. Replace the keyword with a user-specified identifier.

To overcome this error, prefix the identifier with “@”. The character @ is not actually part of the identifier, so the identifier might be seen in other languages as a normal identifier, without the prefix. An identifier with an @ prefix is called a verbatim identifier.

private static void KeywordExample()

{

string @string = "Some String";

Console.Write(@string);

}

Wednesday, December 10, 2008

How to get Built-in Property of a Word Document using VB.NET

VB.NET Retrieve Built-in Property / VB.NET Extract Built-in Property

Some differentiable information can be stored in a built-in property, for example, keywords in a Word document. The following VB.NET code uses System.Reflection members to get the Built-in property

The code needs the following directives

Imports Office = Microsoft.Office.Core

Imports Word = Microsoft.Office.Interop.Word

Imports System.Reflection

It also needs the following declarations

Dim oWA As Word.Application = New Word.Application

Dim oWD As Word.Document

The following code that extracts the value stored in ‘Subject’ property:

Sub GetBuiltInProp()

Try

Dim oBuiltProps As Object

oWA.Visible = True

oWD = oWA.Documents.Open("C:\ShasurData\DND_DEC_2008.doc")

oBuiltProps = oWD.BuiltInDocumentProperties

Dim oTypeBuiltProps As Type = oBuiltProps.GetType

Dim sPropertyName As String = "Subject"

Dim oProperty As Object = oTypeBuiltProps.InvokeMember("Item", BindingFlags.Default Or BindingFlags.GetProperty, Nothing, oBuiltProps, New [Object]() {1})

Dim oTypeProp As Type = oProperty.GetType

Dim sPropertyValue As String = oTypeProp.InvokeMember("Value", BindingFlags.Default Or BindingFlags.GetProperty, Nothing, oProperty, New [Object]() {})

Catch ex As Exception

Console.WriteLine(ex.Message)

Finally

oWD.Close(False)

oWA.Quit()

End Try

End Sub

Here we are retrieving the built-in property of the document using

oWD = oWA.Documents.Open("C:\ShasurData\DND_DEC_2008.doc")

oBuiltProps = oWD.BuiltInDocumentProperties

Then using the System.type class’s GetType and InvokeMethod to get to the built-in property

Dim oTypeBuiltProps As Type = oBuiltProps.GetType

Dim sPropertyName As String = "Subject"

Dim oProperty As Object = oTypeBuiltProps.InvokeMember("Item", BindingFlags.Default Or BindingFlags.GetProperty, Nothing, oBuiltProps, New [Object]() {1})

The builtindocument property collection has many Items. Hence we get the Item first through InvokeMember and then use the object to retrieve the value of that particular item

Dim oTypeProp As Type = oProperty.GetType

Dim sPropertyValue As String = oTypeProp.InvokeMember("Value", BindingFlags.Default Or BindingFlags.GetProperty, Nothing, oProperty, New [Object]() {})

The above method overcomes the "Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Core.DocumentProperties'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{2DF8D04D-5BFA-101B-BDE5-00AA0044DE52}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE))." error

Please feel free to modify and suggest improvements

See also How to Insert Document Properties in Word Document

How to Set Built-In Properties of Word Document using VB.NET

VB.NET Set Built-in Properties

With more collaboration happening across offices, document properties have gained more importance. Word properties can be categorised as a)Custom Property b) Built-in property

Some common built-in properties are

· Title

· Subject

· Author

· Keywords

· Comments

The following code can be used to get the built-in property of the given word document.

Here are the directives necessary for the program

Imports Office = Microsoft.Office.Core

Imports Word = Microsoft.Office.Interop.Word

Imports System.Reflection

System.Reflection looks an odd man here right! Yes, we will be using the Reflection class to retrieve the properties of the Word document

The following variables initialize the Word Application

Dim oWA As Word.Application = New Word.Application

Dim oWD As Word.Document

The code uses System.Type class’s members like InvokeMember, Gettype etc. Type is the root of the System.Reflection functionality and is the primary way to access metadata.

The following code opens a Word document and sets its ‘Subject’ property.

Sub SetBuiltInProp()

Try

Dim oBuiltProps As Object

oWA.Visible = True

oWD = oWA.Documents.Open("C:\ShasurData\DND_DEC_2008.doc")

oBuiltProps = oWD.BuiltInDocumentProperties

Dim TypBuiltProps As Type = oBuiltProps.GetType

Dim sPropertyName As String = "Subject"

Dim oProp As Object = TypBuiltProps.InvokeMember("Item", BindingFlags.Default Or BindingFlags.GetProperty, Nothing, oBuiltProps, New [Object]() {sPropertyName})

Dim sPropValue As String = "VSTO Examples"

Dim TypSubject As Type = oProp.GetType

TypSubject.InvokeMember("Value", BindingFlags.Default Or BindingFlags.SetProperty, Nothing, oProp, New [Object]() {sPropValue})

Catch ex As Exception

Console.WriteLine(ex.Message)

Finally

oWD.Save()

oWD.Close()

oWA.Quit()

End Try

End Sub

The GetType method returns a Type object that represents the type of an instance.

Setting other built-in properties will be the same as above.

Monday, December 8, 2008

How to sign an Assembly in Visual Studio 2008

To sign an assembly using VS 2008 open the Project Designer from Project - - > Properties of from Solution Explorer - - > Right Click - - > Properties -- > Signing tab
The Signing table enables to sign the assembly. Select the Sign the Assembly checkbox to indicate generating a strong name.





To create a new key file Select from the Dropdown box


Enter a filename for the Key and (and password). This dialog box specifies a new key file with which to sign the assembly. If you specify a password, a Personal Information Exchange (.pfx) file is created; if you do not specify a password, a strongly named key (.snk) file is created.









Signing the assembly by providing a strong name to the compiled application or component makes easy for the administrators to apply a security policy.

Friday, December 5, 2008

How to get the Built-in Properties of a Word Document using VSTO

BuiltinDocumentProperties returns the entire collection of Built-in document properties. Use the Microsoft.Office.Core.DocumentProperties.Item(System.Object) property to return a single member of the collection (a Microsoft.Office.Core.DocumentProperties object) by specifying either the name of the property or the collection index (as a number).

private static void WordBuiltinPropExample(Word.Document oWD)

{

// Built-in Document Properties for a Word Document

Office.DocumentProperties oBuiltProps = (Office.DocumentProperties)oWD.BuiltInDocumentProperties;

foreach (Office.DocumentProperty oBuiltProp in oBuiltProps)

{

MessageBox.Show(oBuiltProp.Name + " " + oBuiltProp.Value);

}

}

How to get the Custom Properties of a Word Document using VSTO

How to get the Custom Properties of a Word Document using .NET (C#)

CustomDocumentProperties returns the entire collection of custom document properties. Use the Microsoft.Office.Core.DocumentProperties.Item(System.Object) property to return a single member of the collection (a Microsoft.Office.Core.DocumentProperties object) by specifying either the name of the property or the collection index (as a number).

private static void WordCustPropertyExample(Word.Application wAP )

{

// Custom Property Extraction For Word Document

Office.DocumentProperties oCusProps = (Office.DocumentProperties)wAP.ActiveDocument.CustomDocumentProperties;

foreach (Office.DocumentProperty oCusProp in oCusProps)

{

// MessageBox.Show( oCusProp.Name);

}

}

To add a custom property to the Word document using VSTO, use the add method as shown below

//Adding a Custom Property for Word Document

oCusProps.Add("CopyEdited By", false, Office.MsoDocProperties.msoPropertyTypeString, "Santa Barbara", false);

Operator '&' cannot be applied to operands of type 'string' and 'string' - CS0019

Operator '&' cannot be applied to operands of type 'string' and 'string' - CS0019



MessageBox.Show("Hello " & "World");


should be



MessageBox.Show("Hello " + "World");



Try stringbuilder also

Specify initial values of the array in .NET (C#)

Initial values of the array elements can be specified using an array initializer, which is a list of expressions written between the delimiters { and }

static void ArrayExample()

{

int[] Marks = {56, 78, 45};

int[,] Matrix = new int[5, 5];

string[] Students = {"George Kutty", "Madhavan Nair", "Haneef Iqbal"} ;

for (int i=0;i

{

Console.WriteLine("Student Name: {0} - Marks {1}" , Students[i], Marks[i]);

}

}

Array – X is a 'variable' but is used like a 'method' Error in .NET (C#) - CS0118

The compiler detected a situation in which a construct was used in some erroneous way or a disallowed operation was tried on a construct. Some common examples include the following:

  • A try to instantiate a namespace (instead of a class)
  • A try to call a field (instead of a method)
  • A try to use a type as a variable
  • A try to use an extern alias as a type.

One possible cause is use of parenthesis ‘()’ in Arrays

static void ArrayExample()

{

int[] Marks = new int[5];

string[] Students = new string[5];

for (int i=0;i

{

Console.WriteLine("Student Name: {0} - Marks {1})" , Students(i), Marks(i));

}

}

To resolve this error, replace parenthesis with square brackets

Console.WriteLine("Student Name: {0} - Marks {1}" , Students[i], Marks[i]);


Automatic initialization of arrays in .NET (C#)

When you declare an array of particular type, the new operator automatically initializes the elements of an array to their default value, which, for example, is zero for all numeric types and null for all reference types.

The following example shows the automatic initialization of arrays in C#:

static void ArrayExample()

{

int[] Marks = new int[5];

string[] Students = new string[5];

for (int i=0;i

{

Console.WriteLine("Student Name: {0} - Marks {1}" , Students[i], Marks[i]);

}

}

The output will be:

Auto Initialization of Arrays in C#

Auto-implemented properties in .NET (C#)

Auto-implemented properties are created using set and get accessor without any attributes.

class AccessorExample

{

private string _ProdName;

public string ProdName

{

get

{

return _ProdName;

}

set

{

_ProdName = value;

}

}

public double CostPrice;

//Auto-implemented property

public double discount { get; set; }

//Read-only property

public double EmpDisc { get; private set; }

}

The statement public double discount { get; set; } sets / gets the discount

and can be accessed by

AccessorExample AEx = new AccessorExample();

AEx.ProdName = "T-Shirt";

AEx.CostPrice = 12.34;

AEx.discount = 10;

Console.WriteLine(AEx.ProdName + " Costs " + AEx.CostPrice.ToString() + " before " + AEx.discount + "% discount" );

A property that has both a get accessor and a set accessor is a read-write property, a property that has only a get accessor is a read-only property, and a property that has only a set accessor is a write-only property.

public double EmpDisc { get; private set; } is a read-only property; value of EmpDisc cannot be set. Assigning a value to this property will throw the following exception

AEx.EmpDisc = 15;

The property or indexer 'CSharpSample.AccessorExample.EmpDisc' cannot be used in this context because the set accessor is inaccessible

[The property or indexer 'property/indexer' cannot be used in this context because the set accessor is inaccessible - CS0272]

For auto-implemented properties, the compiler creates a private, anonymous backing field can only be accessed through the property's get and set accessors.





Abstract Methods in .NET (C#)

An abstract method is a virtual method with no implementation. The actual implementation of the abstract method will be from a overridden method of the derived class.

An abstract method is declared with the abstract modifier and is permitted only in a class that is also declared abstract.

public abstract class AbsExample {

public abstract string AbsMethod();

}

An abstract method must be overridden in every non-abstract derived class.

class AbsImplementor : AbsExample

{

public override string AbsMethod()

{

return "AbsMethod Implemented!!!";

}

}

The method can be invoked by

AbsImplementor a1 = new AbsImplementor();

Console.WriteLine(a1.AbsMethod());

Base Class Constructors in C#

Base-class constructor can be called when creating instances of the derived class using the base keyword as shown below

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace CSharpSample

{

class CBaseProduct : Object

{

public string ProductSKU ;

public string ProductName ;

public CBaseProduct(string SKUID, string ProdName)

{

this.ProductSKU = SKUID;

this.ProductName = ProdName;

}

}

class CSpecProduct : CBaseProduct

{

public string ProductRate;

public CSpecProduct(string SKUID, string ProdName, string ProdRate)

: base(SKUID, ProdName)

{

this.ProductRate = ProdRate;

}

}

}

A base class access is permitted only in a constructor, an instance method, or an instance property accessor.

The following code calls the derived class constructor, which in turn calls the base class constructor

CSpecProduct c1 = new CSpecProduct("00123", "Tata Tea", "45.00");

What is rank of an array?

What is rank of an array (.NET)?

Rank of the array is nothing but the number of dimensions of an array.

int[] Marks = new int[5];

int[,] Matrix = new int[5, 5];

Marks is a single dimensional array (Rank 1) and Matrix is two-dimensional array (Rank 2) containing (5 X 5) elements

kbAlertz.com :: Visual Studio 2005

kbAlertz.com :: Visual Studio 2008

kbAlertz.com :: Visual Basic 2005