Jun 12, 2009

How to run a C# application as an administrator

To have your C# (or any .NET program) run as Administrator in Windows, you'll have to create a manifest for it.
Step 1:
Add a manifest file to your app.
Solution Explorer>Rightclick>Add>"New Item">"Application Manifest File"




Step2 : Manipulate the default manifest file as follows

Just change the highlighted attribute from a"asInvoked" to "requireAdministrator"



Step 3: Make your app to use the manifest
[If Not using Visual Studio]
1. Rename it to (YourEXEName).manifest. The .NET Framework when executing the file will see the Manifest and handle its contents.
2.Embed the .manifest file into you EXE. This can be done by executing the following command line:
1.mt -manifest YourProgram.exe.manifest -outputresource:YourProgram.exe
2.If your assembly is strong named, you will be unable to embed the manifest into it as it would invalidate the strong naming.
[If using Visual Studio]
1. Dont have to do anything more...
2. Just remember to run the Visual Studio as an Administrator, for future debugging.

Jun 11, 2009

BackgroundWorker Class and usage examples

BackgroundWorker Class:
Brief Defn: Executes an operation on a separate thread(MSDN).
Detailed Defn: The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running. When you want a responsive UI and you are faced with long delays associated with such operations, the BackgroundWorker class provides a convenient solution.

To execute a time-consuming operation in the background, create a BackgroundWorker and listen for events that report the progress of your operation and signal when your operation is finished. You can create the BackgroundWorker programmatically or you can drag it onto your form from the Components tab of the Toolbox. If you create the BackgroundWorker in the Windows Forms Designer, it will appear in the Component Tray, and its properties will be displayed in the Properties window.

To set up for a background operation, add an event handler for the DoWork event. Call your time-consuming operation in this event handler. To start the operation, call RunWorkerAsync. To receive notifications of progress updates, handle the ProgressChanged event. To receive a notification when the operation is completed, handle the RunWorkerCompleted event.

Note:
You must be careful not to manipulate any user-interface objects in your DoWork event handler. Instead, communicate to the user interface through the ProgressChanged and RunWorkerCompleted events.

BackgroundWorker events are not marshaled across AppDomain boundaries. Do not use a BackgroundWorker component to perform multithreaded operations in more than one AppDomain .

If your background operation requires a parameter, call RunWorkerAsync with your parameter. Inside the DoWork event handler, you can extract the parameter from the DoWorkEventArgs..::.Argument property.
---------------------------------------------------
Usage:

This class can be added both by code and also by using the toolbox
Usage 1: Simple invocation
////Declaration and Instantiation
BackgroundWorker Worker = new BackgroundWorker();

////Add the event handlers in the Constructor
public Form2()
{
InitializeComponent();
Worker.DoWork += new DoWorkEventHandler(Worker_DoWork);
Worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Worker_RunWorkerCompleted);
}

/////The Do work method is performed in a Async/multithreaded way when the
////RunWorkerAsync method of the background worker is invoked.
////N.B.: No UI Control manipulation is permitted.
void Worker_DoWork(object sender, DoWorkEventArgs e)
{
// Do not access the form's BackgroundWorker reference directly.
// Instead, use the reference provided by the sender parameter.
BackgroundWorker bw = sender as BackgroundWorker;

// Extract the argument.
int arg = (int)e.Argument;

// Start the time-consuming operation.
e.Result = TimeConsumingOperation(bw, arg);

// If the operation was canceled by the user,
// set the DoWorkEventArgs.Cancel property to true.
if (bw.CancellationPending)
{
e.Cancel = true;
}
}

////This is the method which is automatically called when the async thread has completed its work.
private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
// The user canceled the operation.
MessageBox.Show("Operation was canceled");
}
else if (e.Error != null)
{
// There was an error during the operation.
string msg = String.Format("An error occurred: {0}", e.Error.Message);
MessageBox.Show(msg);
}
else
{
// The operation completed normally.
string msg = String.Format("Result = {0}", e.Result);
MessageBox.Show(msg);
}
}

=============================================================
Usage 2: Implementing BackgroundWorker with Progress Bar
http://msdn.microsoft.com/en-us/library/waw3xexc.aspx


Jun 5, 2009

Consuming and Publishing RSS feeds

1. http://www.code101.com/Code101/DisplayArticle.aspx?cid=48
2. http://www.dotnetcurry.com/ShowArticle.aspx?ID=137&AspxAutoDetectCookieSupport=1
3. http://www.c-sharpcorner.com/UploadFile/pwright/RssFeedProject12062005000807AM/RssFeedProject.aspx
4. http://aspalliance.com/919_Awesome_ASPNET_20_RSS_ToolKit_Released.1 -- (Detailed Tutorial)
5. http://blogs.msdn.com/dmitryr/archive/2006/02/21/536552.aspx

WCF certificate authentication with IIS7

1. http://romualdas.spaces.live.com/blog/cns!DCDC5E439E70339D!1006.entry
2. http://social.technet.microsoft.com/Forums/en-US/winserversecurity/thread/3bfd8974-ac8a-4c53-ade8-e8b71713f92a
3. http://forums.iis.net/
4. http://notgartner.wordpress.com/2007/09/06/using-certificate-based-authentication-and-protection-with-windows-communication-foundation-wcf/

Creating a WSE 3.0 Enabled Web Service (Tutorial)

http://dotnetslackers.com/articles/aspnet/GettingStartedCreatingWSEEnabledWebService.aspx

IIS 7 SSL Certificate Installation

1. http://pro-studio.spaces.live.com/blog/cns!7CEDD8FA2A6B9050!746.entry
2. http://www.experts-exchange.com/Software/Server_Software/Email_Servers/Exchange/Q_23860405.html
3. http://help.godaddy.com/article/4801

N.B.: If you are going to install a certificate which has a p7b extension, then rename it to .cer before u start.

Jun 2, 2009

Create Digital Signature for your App

If your application does not have a digital signature and has uiAccess=true in its manifest, it will fail with "A referral was returned from the server."

Applications that request uiAccess=true must have a valid, trusted digital signature to execute.

Also, applications by default must reside in a trusted location on the hard drive (such as windows or program files) to receive the uiAccess privilege. They will still run if they are not in one of these locations, but they will not receive the privilege. You can disable this security feature through the local security policy mmc snap-in.

If you want to create a trusted "test" certificate to sign your application with so that you can use your application on your current machine, here's how:

NOTE: These instructions assume you have visual studio installed and are using a command prompt that has all the environment variables set to find SDK utilities such as makecert and signtool. If not, you will need to find these tools on your hard drive before running them.

***

1) Open an elevated command prompt

- Click start

- Find Cmd Shell or command prompt

- Right-click, click Run As Administrator

2) Create a trusted root certificate

- Browse to the folder that you wish to contain a copy of the certificate

- In the command shell, execute the following commands:

makecert -r -pe -n "CN=Test Certificate - For Internal Use Only" -ss PrivateCertStore testcert.cer

certmgr.exe -add testcert.cer -s -r localMachine root

3) Sign your file

- In the command shell, browse to the location of your exe

- In the command shell, type:

SignTool sign /v /s PrivateCertStore /n "Test Certificate - For Internal Use Only" /t http://timestamp.verisign.com/scripts/timestamp.dll APP.exe

Where APP.exe is your application.

Feb 26, 2009

.Net 3.0 - C# - Features and Additions

Some of the interesting and intruiging additions were:
  • Implicitly typed local variables
  • Anonymous types
  • Extension methods
  • Object and collection initializers
  • Lambda expressions
  • Query expressions
  • Expression Trees
  • Linq
Links:
1 http://blah.winsmarts.com/2006/05/17/demystifying-c-30--part-1-implicitly-typed-local-variables-var.aspx
2. Lambda Expressions:
http://blogs.msdn.com/ericwhite/pages/Lambda-Expressions.aspx
3. Lambda Expressions:
http://www.developer.com/net/csharp/article.php/3598381

Feb 9, 2009

C# "Orcas" Language Features (from Scott Guthrie's blog)

Automatic Properties, Object Initializers, and Collection Initializers
-------------------------------------------------------------------------------------------
Automatic Properties
If you are a C# developer today, you are probably quite used to writing classes with basic properties like the code-snippet below:
public class Person

{
private string _firstName;
private string _lastName;
public string FirstName
{
get
{
return rn _firstName;
}
set
{
_firstName = value;
}
}

public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
}
}
}
Note about that we aren't actually adding any logic in the getters/setters of our properties - instead we just get/set the value directly to a field. This begs the question - then why not just use fields instead of properties? Well - there are a lot of downsides to exposing public fields. Two of the big problems are: 1) you can't easily databind against fields, and 2) if you expose public fields from your classes you can't later change them to properties (for example: to add validation logic to the setters) without recompiling any assemblies compiled against the old class.
The new C# compiler that ships in "Orcas" provides an elegant way to make your code more concise while still retaining the flexibility of properties using a new language feature called "automatic properties". Automatic properties allow you to avoid having to manually declare a private field and write the get/set logic -- instead the compiler can automate creating the private field and the default get/set operations for you.
For example, using automatic properties I can now re-write the code above to just be:
public class Person

{
public string FirstName
{
get;
set;
}
public string LastName
{
get;
set;
}
}
Or If I want to be really terse, I can collapse the whitespace even further like so:
public class Person

{
public string FirstName { get; set; }
public string LastName { get; set;
}

How does this work?
Well if I try to decompile the code using Reflector then we would see that we have this following code for the class Personinternal

class Person
{
// Fields
[CompilerGenerated
private string k__BackingField;

[CompilerGenerated]
private string k__BackingField;
// Methods
public Person();
// Properties
public string FirstName
{
[CompilerGenerated]
get;
[CompilerGenerated]
set;
}

public string LastName
{
[CompilerGenerated]
get;
[CompilerGenerated]
set;
}
}
Looks the like the following code was generated by the compiler ... I am still not clear how the "k__BackingField" expression is used in sync with the compiler generated attribute, but I am happy that I have such a shortcut.

N.B.: Those Automatic Properties are even faster to type, when you use Code Snippets:Type "prop", press TAB twice and then just type in the datatype and identifier to the placeholders.
I like also that the classes (typically DTOs) stay clean when using the Automatic Properties.
It is also very easy to copy the properties to interface specifications (or vice versa): just delete or add the access modifiers.

Object Initializers

When the C# "Orcas" compiler encounters an empty get/set property implementation like above, it will now automatically generate a private field for you within your class, and implement a public getter and setter property implementation to it. The benefit of this is that from a type-contract perspective, the class looks exactly like it did with our first (more verbose) implementation above. This means that -- unlike public fields -- I can in the future add validation logic within my property setter implementation without having to change any external component that references my class.
Bart De Smet has a great write-up on what happens under the covers when using automatic properties with the March CTP release of "Orcas". You can read his excellent blog post on it here.
New C# and VB Language Feature: Object Initializers
Types within the .NET Framework rely heavily on the use of properties. When instantiating and using new classes, it is very common to write code like below:
Person person = new Person();
person.FirstName = "Scott";
person.LastName = "Guthrie";

Have you ever wanted to make this more concise (and maybe fit on one line)? With the C# and VB "Orcas" compilers you can now take advantage of a great "syntactic sugar" language feature called "object Initializers" that allows you to-do this and re-write the above code like so:
Person person = new Person { FirstName="Scott", LastName="Guthrie" };


The compiler will then automatically generate the appropriate property setter code that preserves the same semantic meaning as the previous (more verbose) code sample above.
In addition to setting simple property values when initializing a type, the object initializer feature allows us to optionally set more complex nested property types. For example, assume each Person type we defined above also has a property called "Address" of type "Address". We could then write the below code to create a new "Person" object and set its properties like so:
Person person = new Person {
FirstName = "Scott",
LastName = "Guthrie",
Address = new Address
{
Street = "One Microsoft Way",
City = "Redmond",
State = "WA",
Zip = 98052
}
};
Bart De Smet again has a great write-up on what happens under the covers when using object initializers with the March CTP release of "Orcas". You can read his excellent post on it here.

Collection Initializers

New C# and VB Language Feature: Collection Initializers
Object Initializers are great, and make it much easier to concisely add objects to collections. For example, if I wanted to add three people to a generics-based List collection of type "Person", I could write the below code:
List people = new List();
people.Add( new Person { FirstName = "Scott", LastName = "Guthrie" } );
people.Add( new Person { FirstName = "Bill", LastName = "Gates"} );
people.Add( new Person { FirstName = "Susanne", LastName = "Guthrie"} );

Using the new Object Initializer feature alone saved 12 extra lines of code with this sample versus what I'd need to type with the C# 2.0 compiler.
The C# and VB "Orcas" compilers allow us to go even further, though, and also now support "collection initializers" that allow us to avoid having multiple Add statements, and save even further keystrokes:
List people = new List
{
new Person { FirstName = "Scott", LastName = "Guthrie"},
new Person { FirstName = "Bill", LastName = "Gates"},
new Person { FirstName = "Susanne", LastName = "Guthrie"}
};
When the compiler encounters the above syntax, it will automatically generate the collection insert code like the previous sample for us.

Jan 15, 2009

EventLog: Exploring Event Logs, Event Sources, and Entries


1. To create the custom log

// Source cannot already exist before creating the log.
if (System.Diagnostics.EventLog.SourceExists("Source1"))
{
System.Diagnostics.EventLog.DeleteEventSource("Source1");
}
// Logs and Sources are created as a pair. System.Diagnostics.EventLog.CreateEventSource("Source1", "NewLog1");
// Associate the EventLog component with the new log.

eventLog1.Log= "NewLog1"; eventLog1.Source = "Source1";

2. To delete a custom log
if (System.Diagnostics.EventLog.Exists("NewLog1"))
{
System.Diagnostics.EventLog.Delete("NewLog1");
}

3. To write entries to the log
eventLog1.WriteEntry("This is an informational message");
eventLog1.WriteEntry("This is an error message", System.Diagnostics.EventLogEntryType.Error);


4. To clear log entries
eventLog1.Clear();

5. To verify that the custom log exists
bool logExists = System.Diagnostics.EventLog.Exists("NewLog1");
MessageBox.Show("Does the log exist? " + logExists.ToString());


6. To verify that the source exists
bool sourceExists = System.Diagnostics.EventLog.SourceExists("Source1");
MessageBox.Show("Does the source exist? " + sourceExists.ToString());


7. To remove the event source you created
if (System.Diagnostics.EventLog.SourceExists("Source1"))
{
System.Diagnostics.EventLog.DeleteEventSource("Source1");
}


8. To read entries from the custom log you created
if(eventLog1.Entries.Count > 0)
{
foreach (System.Diagnostics.EventLogEntry entry in eventLog1.Entries)
{
MessageBox.Show(entry.Message);
}
}

{
MessageBox.Show("There are no entries in the log.");
}