Archive

Posts Tagged ‘.Net’

Create UAC Compatible applications in .NET

September 1st, 2010 Anuraj P No comments

In my last project I got an opportunity to make my application compatible with Windows Vista and Windows 7. The main issue I faced was UAC; User Account Control (UAC) which introduced with the launch of Windows Vista; this provides users a better and safer computing experience. If UAC enabled, Windows will prompt every time when Applications try to access File System, like writing / creating Files in Program Files Folder, Windows Folder etc. (It’s not a best practice to write / create files in System directories like Windows, Program Files etc.). It’s also not a best practice to ask the customer to disable the UAC and run the application. The alternate is to make the application compatible with UAC, so that when the customer runs the application the system will prompts the UAC dialog, and run the application with Administrator privileges.
The procedure to make the application compatible with UAC is simple.

  1. Right-click project and add a new item.
  2. From the Add New Item box select Application Manifest File.
  3. In the manifest file un-comment the following line:
    <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
    

Build your application. And when the build is complete you will see the security shield icon accompanying your application icon.

Security shield icon accompanying application icon

Security shield icon accompanying application icon

A dialogue box appears in front of the user to run the application with full administrative privileges.

UAC Dialog box when double clicking on the Application

UAC Dialog box when double clicking on the Application

How to disable Close button of Windows Forms Application

August 25th, 2010 Anuraj P No comments

We can disable the close button of a Windows Form in three ways

  1. Set controlbox property to false – It is most easy way to do this. But it also hides the Minimize and Maximize buttons.
  2. Using WIN32 API – Using Win32 API, we are getting the system menu and removes the close menu item using Remove menu item.
    Here is the Code.

    const int MF_BYPOSITION = 0x400;
    [DllImport("User32")]
    private static extern int RemoveMenu(IntPtr hMenu, int nPosition, int wFlags);
    [DllImport("User32")]
    private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
    [DllImport("User32")]
    private static extern int GetMenuItemCount(IntPtr hWnd);
    
    //In the Form load event
    IntPtr hMenu = GetSystemMenu(this.Handle, false);
    int menuItemCount = GetMenuItemCount(hMenu);
    RemoveMenu(hMenu, menuItemCount - 1, MF_BYPOSITION);
    

    And here is the screenshot

    Using WIN32 API

    Using WIN32 API

  3. By Overriding the CreateParams property – The CreateParams property gets the required creation parameters when the control handle is created. By overriding the property we are removing the close button. You can get more information about CreateParams in MSDN
    Here is the code.

    private const int CS_CLOSE = 0x200;
    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams parms = base.CreateParams;
            parms.ClassStyle |= CS_CLOSE;  //
            return parms;
        }
    }
    

    And here is the screenshot

    By Overriding CreateParams property

    By Overriding CreateParams property

    All of above three methods will work fine. But if you are using Windows 7 none of the above will work or OS will override all these.

    Windows 7 - Close Window

    Windows 7 - Close Window

Tuple in .NET Framework 4.0

August 19th, 2010 Anuraj P No comments

Another new feature in the .NET 4 Framework is support for tuple,which are similar to anonymous classes that you can create on the fly. A tuple is a data structure used in many functional and dynamic languages, such as F# and Iron Python. By providing common tuple types in the BCL, we are helping to better facilitate language interoperability. Many programmers find tuple to be convenient, particularly for returning multiple values from methods.

Here is a code which uses a function that returns two values.

class Program
{
    static void Main(string[] args)
    {
        //Getting the values from the Tuple Function
        Tuple<string, string> details = GetDetails();
        Console.WriteLine("FirstName : {0}, LastName :{1}", details.Item1, details.Item2);
        Console.Read();
    }
    //Tuple function, which reads two values from
    //user and returns to the main
    static Tuple<string, string> GetDetails()
    {
        Console.Write("Enter First Name:");
        string _firstName = Console.ReadLine();
        Console.Write("Enter Last Name:");
        string _lastName = Console.ReadLine();
        return new Tuple<string, string>(_firstName, _lastName);
    }
}

You can find more details about Tuples in MSDN : Tuple Class

Categories: .Net, .Net 4.0 Tags: , , , ,

Creating PDF file using C#

August 17th, 2010 Anuraj P 1 comment

Most of the forums, it’s a common question that how can we create PDF files from C#. Few days back I got a chance to work with iTextSharp library which helps to create PDF files from .Net. You can download the iTextSharp from sourceforge.net. It also supports HTML Parsing too.
Here is the code which converts and HTML File into PDF using iTextSharp libraries.

using System.Collections.Generic;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;

class Program
{
static void Main(string[] args)
    {
        //Creating the instance of the document object.
        Document doc = new Document();
        //Creating the PDF File
StreamWriter streamWriter = new StreamWriter(@"C:\Sample.pdf");
PdfWriter.GetInstance(doc, streamWriter.BaseStream);
        doc.Open();
IEnumerable<IElement> elements;
        //Reading the HTML Contents
using (StreamReader streamReader = new StreamReader(@"C:\SamplePage.htm"))
        {
            //Parsing HTML Contents.
elements = HTMLWorker.ParseToList(streamReader, new StyleSheet());
        }
foreach (IElement item in elements)
        {
            doc.Add(item);
        }
        //Custom Text which will be appended using Paragraph class.
        string paragraph = "This is custom text which will be appended";
        doc.Add(new Paragraph(paragraph));

        //Closing the document.
        doc.Close();
    }
}

Thanks to Rahul for providing initial inputs on iTextSharp library.

Optional Parameters and Named Parameters in C# 4.0

August 16th, 2010 Anuraj P No comments

Last day I got an assignment to explore new features of .Net Framework 4.0. So I thought about writing a few posts with the new features. The first feature I explored was Optional Parameters and Named Parameters, as I am coming from VB background, I missed this feature in C# and yes we can resolve this using Overloading still we missed that feature. In .Net 4.0 Microsoft introduced Optional Parameters and Named Parameters in C#.

Both of these features are almost similar like in VB 6 or in VB.Net, unlike we don’t need an optional keyword.

class Program
{
    static void Main(string[] args)
    {
        //Optional Parameters
        ShowMessage("Hello World");
        //Named parameters
        ShowMessage("HelloWorld", backColor: ConsoleColor.Blue);
        //Normal Function call
        ShowMessage("Hello World", ConsoleColor.Red, ConsoleColor.Blue);

        Console.Read();
    }

    //In .Net 4.0
    static void ShowMessage(string message,
        ConsoleColor foreColor = ConsoleColor.Black,
        ConsoleColor backColor = ConsoleColor.White)
    {
        Console.ForegroundColor = foreColor;
        Console.BackgroundColor = backColor;
        Console.WriteLine(message);
        //Resetting Console colors to default.
        Console.ResetColor();
    }
}

Operator overloading in C#

August 14th, 2010 Anuraj P No comments

Long back one of my cousins Rajesh gives me an introduction to Operator overloading in C++, but at that time I was VB 6.0 guy and I didn’t give much importance to it. But yesterday I got a chance to work on some sample applications where I tried operator overloading on C#.

I overloaded the + operator for adding two persons objects, and here is the code.

//Person class.
public class Person
{
    //Name of the Person
    public string Name
    {
        get;
        set;
    }
    //Operator overloading.
    public static Person operator +(Person first, Person second)
    {
        //Returning person, by adding the Names.
        return new Person()
        {
            Name = first.Name + " " + second.Name
        };
    }
}

And here is the void Main()

static void Main(string[] args)
{
Person firstPerson = new Person()
    {
        Name = "Person 1"
    };

Person secondPerson = new Person()
    {
        Name = "Person 2"
    };
    //Adding Person objects
Person resultPerson = firstPerson + secondPerson;
    //It will return Person 1 Person 2
Console.WriteLine(resultPerson.Name);
}

You can find Operator Overloading Tutorial in MSDN

Categories: .Net, .Net 3.0 / 3.5 Tags: , ,