Windows Phone Developers

Sunday, May 6, 2012

Using Directive in C#, Create an alias in C#

Before you can use the classes in a given namespace in a C# program, you must add a using directive for that namespace to your C# source file. In some cases, you must also add a reference to the DLL that contains the namespace


The using directive has two uses:
· To allow the use of types in a namespace so that you do not have to qualify the use of a type in that namespace:


using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

· To create an alias for a namespace or a type.

using Excel = Microsoft.Office.Interop.Excel

The using keyword is also used to create using statements, which help ensure that IDisposable objects such as files and fonts are handled correctly. See using Statement for more information.
The scope of a using directive is limited to the file in which it appears.
Create a using alias to make it easier to qualify an identifier to a namespace or type.

Big Statements like the following

oXL = new Microsoft.Office.Interop.Excel.application();

can be replaced with

using Excel = Microsoft.Office.Interop.Excel
oXL = new Excel.application();

Create a using directive to use the types in a namespace without having to specify the namespace. A using directive does not give you access to any namespaces that are nested in the namespace you specify.
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Calculating Time taken for an operation using VB.NET (in Milliseconds)

Calculate Processing Time for a Vb.NET Subroutine (accuracy to millisecond)


Not every project will have the luxury of having rational analyzer to check the process time for every subroutine/function. In those cases we can use the StopWatch to determine the time taken for a program

Imports System.Diagnostics

Sub Get_Accurate_ProcessTime()

Dim oWatch As New Stopwatch

oWatch.Start()

Process_database()

oWatch.Stop()

MsgBox("Total Time Taken for Database Operation := " & oWatch.ElapsedMilliseconds.ToString)


End Sub
A Stopwatch instance can measure elapsed time for one interval, or the total of elapsed time across multiple intervals. In a typical Stopwatch scenario, you call the Start method, then eventually call the Stop method, and then you check elapsed time using the Elapsed property.
A Stopwatch instance is either running or stopped; use IsRunning to determine the current state of a Stopwatch. Use Start to begin measuring elapsed time; use Stop to stop measuring elapsed time. Query the elapsed time value through the properties Elapsed, ElapsedMilliseconds, or ElapsedTicks. You can query the elapsed time properties while the instance is running or stopped. The elapsed time properties steadily increase while the Stopwatch is running; they remain constant when the instance is stopped.


By default, the elapsed time value of a Stopwatch instance equals the total of all measured time intervals. Each call to Start begins counting at the cumulative elapsed time; each call to Stop ends the current interval measurement and freezes the cumulative elapsed time value. Use the Reset method to clear the cumulative elapsed time in an existing Stopwatch instance.
The Stopwatch measures elapsed time by counting timer ticks in the underlying timer mechanism. If the installed hardware and operating system support a high-resolution performance counter, then the Stopwatch class uses that counter to measure elapsed time. Otherwise, the Stopwatch class uses the system timer to measure elapsed time. Use the Frequency and IsHighResolution fields to determine the precision and resolution of the Stopwatch timing implementation.


The Stopwatch class assists the manipulation of timing-related performance counters within managed code. Specifically, the Frequency field and GetTimestamp method can be used in place of the unmanaged Win32 APIs QueryPerformanceFrequency and QueryPerformanceCounter.
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Regular Expression to Check Zip Code

Regular Expression to Match Zip Code

Imports System.Text.RegularExpressions
Function IsValidZip(ByVal sZipCode As String)
Return Regex.IsMatch(sZipCode, "^\d{5}(\-\d{4})?$")
End Function
The above will check for U.S . Zip codes like 55001-2434. 94941-3232 etc
To Check Indian Zip codes use
Imports System.Text.RegularExpressions
Function IsValidZip(ByVal sZipCode As String)
Return Regex.IsMatch(sZipCode, "^\d{6}$")
End Function
Matches 600040, 400123 etc
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Check if Path is Absolute or Relative Path using C# (.NET)


IsPathRooted method of Path class returns a value indicating whether the specified path string contains absolute or relative path information.

if (Path.IsPathRooted(@"c:\temp\") == true)

{

Console.WriteLine("Path is absolute");

}

else

{

Console.WriteLine("Path is relative");

}

How to find absolute path using C# (.NET), How to find relative path using C# (.NET), C# (.NET) Path Class, C# (.NET) IsPathRooted method
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Insert CSV File to Array using C#

Read Text File to Array C#/ Insert CSV File to Array using C# / C# Array from Text/CSV Files
ReadAllLines method can be used to read the contents of a CSV file to array. Each line of the text file will become the elements of the array
public void ReadFile2Array()
{
String[] FileContent = File.ReadAllLines(@"C:\Temp\vba.csv");
int LineNo = 0;
foreach (string Line in FileContent)
{
LineNo +=1;
Console.WriteLine("Line " + LineNo.ToString() + " " + Line);
}
}
ReadAllLines method opens a text file, reads all lines of the file into a string array, and then closes the file.
The input file is shown below



The output will be like


Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

The type or namespace name 'ComVisible' could not be found (are you missing a using directive or an assembly reference?)

The type or namespace name 'ComVisibleAttribute' could not be found (are you missing a using directive or an assembly reference?)
This error occurs when you are trying to use ComVisibleAttribute in a class without a reference to System.Runtime.InteropServices namespace
[ComVisible(true)]
public interface IAddinVSTO
{
void SayHello();
}
Should have a reference to System.Runtime.InteropServices namespace like shown below
using System.Runtime.InteropServices;
[ComVisible(true)]
public interface IAddinVSTO
{
void SayHello();
}



ComVisibleAttribute Error

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

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.



Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Excel Runtimes not removed by Excel.Quit / Application.Quit

How to delete the leftover Excel object using VB.NET / Vb.NET delete Excel from memory



Excel runtimes that remain after the program is a nemesis. Many times this might be due to the leftover Excel objects in the program that causes Excel to remain in memory even after Application.Quit. Workbooks that are modified and left open often causes this problem. We have tried out one method to get rid of the Excel in memory using Vb.NET. We assumed that the programs that used Excel has been terminated and if any Excel remains in the memory it should be of the ‘legitimate’ application that the user has opened or the left over Excel.


We checked the presence of Title for Excel Application, which was present in all cases for the open instance of Excel. Left over instances didn’t had the title. The following code ‘kills’ the instances of Excel in memory that don’t have a WindowTitle.





Public Sub KillUnusedExcelProcess()

Dim oXlProcess As Process() = Process.GetProcessesByName("Excel")

For Each oXLP As Process In oXlProcess

If Len(oXLP.MainWindowTitle) = 0 Then


oXLP.Kill()


End If


Next


End Sub




Try if it works for you and post your suggestions or modifications




Keywords : automation does not close microsoft excel, Application.Quit not closing Excel Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon