Archive

Archive for the ‘Visual Studio’ Category

.Net 4.0 and Visual Studio 2010 Released

April 14th, 2010 Anuraj P No comments

Download a full trial version at http://www.microsoft.com/visualstudio/en-us/download

Free Visual Studio 2010 Express editions available at http://www.microsoft.com/express/downloads/

Free e-book “Moving to Visual Studio 2010″ – Download from here http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=12a6de81-c633-4f2c-a35f-cea6fe772712

Exploring IL Assembler

January 18th, 2010 Anuraj P No comments

One of colleague once asked a question to me, like what is the risk by distributing the windows application without obfuscating it. The only problem I found is user can use some tools like .Net Reflector and explore our assemblies. But few days before I found some nice .Net Framework tools, ildasm.exe and ilasm.exe, IL Disassembler and IL Assembler respectively. These tools are available with .Net Framework SDKs. These tools can used to generate IL code for .Net assemblies and re-create assemblies from IL code. You can achieve it in code via .Net Reflection.Emit namespace. (In Community Techdays @ Cochin, one session is on Reflection.Emit. Don’t miss it.) As it is a vast topic I am only explaining basics ;)

Generate IL code using ILDASM.exe

  1. First create a HelloWorld.cs and compile it to HelloWorld.exe
  2. using System;
    
    public class HelloWorld
    {
    static int Main(string[] args)
    	{
    Console.WriteLine("Hello World");
    		return(0);
    	}
    }
    
  3. Use csc.exeto compile the cs file to exe. – csc HelloWorld.cs
  4. Use ildasm.exe HelloWorld.Exe to view the IL Code. You can find ILDASM in the Microsoft .Net SDK Path

    ILDASM - Exploring HelloWorld.exe

    ILDASM - Exploring HelloWorld.exe

  5. To generate the IL code use Select Dump option from File Menu or Press Ctrl+D. It will asks for a location to save the IL code.

    IL Code Generated

    IL Code Generated

  6. Use any Editor to modify the IL code. You can find all the string values ( “Hello World” in this example ) as it is in the IL code. Modify it.( I am modifying it as “Hello World from IL Code”).

    IL Code - Notepad

    IL Code - Notepad

So we created the IL code and modified.
Generate Assembly from IL code using ILASM.exe

  1. Invoke the ILASM.exe with IL file as the parameter. ilasm helloworld_il.il
  2. It will show some details about assembling the IL code to assembly. And if the operation is successful you will get an exe in the location with HelloWorld_IL.exe.

    Assembling the IL code to EXE

    Assembling the IL code to EXE

  3. If you invoke the exe from command prompt it will display the modified string instead of Hello World.(In this example “Hello World from IL Code”).

You can do more if you know how IL works. Happy IL Programming ;)

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

Implementing Custom Paging in DataRepeater using C# and SQL Server

October 22nd, 2009 Anuraj P No comments

Normally DataRepeater doesn’t have a paging feature; and you can implement it using LINQ, if you are using .Net 3.5. Here is an implementation which is using SQL Server 2005 feature ROW_NUMBER(). You can get more information about ROW_NUMBER() from MSDN.

Stored Procedure – xsp_GetPersons

CREATE PROCEDURE xsp_GetPersons
@StartIndex INT, @Count INT
AS
BEGIN
DECLARE @EndIndex INT
SET @StartIndex = @StartIndex * @Count
SET @EndIndex = @StartIndex + @Count
SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY UserId DESC) AS SlNo, UserId, FirstName, LastName, Email, ISNULL(DOB, GETDATE()) AS DOB FROM U_MyRegistration)Registration WHERE Registration.SlNo BETWEEN @StartIndex AND @EndIndex
END

And I added a DataRepeater control, with Next and Previous buttons in the Footer.

<tr>
    <td colspan="3" align="left">
        <asp:LinkButton CommandName="Navigation" CommandArgument="Prev" runat="server" ID="linkPrevious"
            Text="<< Previous" />
    </td>
    <td colspan="3" align="right">
        <asp:LinkButton CommandName="Navigation" CommandArgument="Next" runat="server" ID="linkNext" Text="Next >>" />
    </td>
</tr>

Code behind. As it is a sample code, I am not added any validations.

int count = 10;
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        BindData(); //Binding Data.
    }
}

private void BindData()
{
    int startIndex = Convert.ToInt32(this.hidCurrentIndex.Value);
    Persons p = new Persons();
    this.Repeater1.DataSource = null;
    this.Repeater1.DataSource = p.GetPersons(startIndex, count);
    this.Repeater1.DataBind();
}

protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
    if (e.CommandName.Equals("Navigation",
StringComparison.CurrentCultureIgnoreCase))
    {
        if (e.CommandArgument.ToString().Equals("Prev",
StringComparison.CurrentCultureIgnoreCase))
        {
            this.hidCurrentIndex.Value = (Convert.ToInt32
(this.hidCurrentIndex.Value) - 1).ToString(); //Decrementing the count
            this.BindData();
        }
        else
        {
            this.hidCurrentIndex.Value = (Convert.ToInt32
(this.hidCurrentIndex.Value) + 1).ToString(); //Incrementing the count
            this.BindData();
        }
    }
}

And the implementation of Persons class from App_Code

using System;
using System.Collections.Generic;
using System.Data.SqlClient;

public class Persons : List<Persons.Person>
{
    public class Person
    {
        public int UserId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public DateTime DOB { get; set; }
    }

    public Persons GetPersons(int startIndex, int count)
    {
        Persons persons = new Persons();
        using (SqlConnection connection = new SqlConnection ("Server=.\SQLEXPRESS;User Id=sa;Password=sapwd;Database=myDatabase"))
        {
            connection.Open();
            using (SqlCommand command = new SqlCommand("xsp_GetPersons",

connection))
            {
                command.CommandType = System.Data.CommandType.StoredProcedure;
                command.Parameters.AddWithValue("@StartIndex", startIndex);
                command.Parameters.AddWithValue("@Count", count);
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    persons.Add(new Person()
                    {
                        DOB = Convert.ToDateTime(reader["DOB"].ToString()),
                        Email = reader["Email"].ToString(),
                        FirstName = reader["FirstName"].ToString(),
                        LastName = reader["LastName"].ToString(),
                        UserId = Convert.ToInt32(reader["UserId"].ToString()),
                    });
                }
            }
        }
        return persons;
    }
}

The core thing is stored procedure, which will return the results based on the given index. Thanks to Aneesh for the details of ROW_NUMBER() function.

TreeView Population without recursive function

October 20th, 2009 Anuraj P No comments

If you want to display hierarchical data in a Treeview normally we are using recursion. I was looking for code which helps to avoid recursion using a Single query. But that code was using VB.Net and it was using a class called “Collection”, which is not available in C#. So I was looking for a compatable code in C# for long time and today I got the chance to re-write it using C#, but I am using Lamda expressions for this.

Here is the Table structure I want to display in Treeview


CREATE TABLE [dbo].[tblEmployees](
[EmployeeId] [int] IDENTITY(1,1) NOT NULL,
[EmployeeName] [nvarchar](50) NOT NULL,
[Parent] [int] NOT NULL)

And I inserted following Data in it.

Table Data

Table Data

And the Stored Procedure for getting employees using Common Table Expressions.

-- usp_GetEmployees
CREATE PROCEDURE [dbo].[usp_GetEmployees]
AS
BEGIN
	WITH SimpleRecursive AS
	(SELECT EmployeeName, EmployeeId, Parent, 0 AS Depth FROM dbo.tblEmployees
	WHERE (EmployeeId IN(SELECT EmployeeId FROM dbo.tblEmployees AS Recursion1
	WHERE (Parent = 0)))
	UNION ALL
	SELECT P.EmployeeName, P.EmployeeId,P.Parent, A.Depth + 1 AS Depth
	FROM dbo.tblEmployees AS P INNER JOIN SimpleRecursive AS A ON A.EmployeeId = P.Parent)
	SELECT EmployeeName, EmployeeId, CONVERT(INT, Parent) AS Parent, Depth
	FROM SimpleRecursive AS SimpleRecursive_1
	ORDER BY Depth
END

And the code in C# which adding nodes to Treeview.

private void PopulateTreeview()
{
    this.tvEmployees.Nodes.Clear();
    Employees employees = new Employees();
    using (SqlConnection connection = new SqlConnection(@"Server=.\SQLEXPRESS; User Id=SQLUser;Password=SQLPassword;Database=Database"))
    {
        connection.Open();
        using (SqlCommand command = new SqlCommand("usp_GetEmployees", connection))
        {
            command.CommandType = System.Data.CommandType.StoredProcedure;
            SqlDataReader reader = command.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
            while (reader.Read())
            {
                employees.Add(new Employees.Employee()
                {
                    Depth = int.Parse(reader["depth"].ToString()),
                    EmployeeId = int.Parse(reader["EmployeeId"].ToString()),
                    Parent = int.Parse(reader["Parent"].ToString()),
                    EmployeeName = reader["EmployeeName"].ToString(),
                });
            }
        }
    }

    foreach (Employees.Employee employee in employees)
    {
        Employees.Employee parentEmp = employees.Find(o => o.EmployeeId == employee.Parent);
        if (parentEmp != null)
        {
            this.tvEmployees.Nodes.Find(parentEmp.EmployeeId.ToString(), true)[0].Nodes.Add(employee.EmployeeId.ToString(), employee.EmployeeName);
        }
        else
        {
            this.tvEmployees.Nodes.Add(employee.EmployeeId.ToString(), employee.EmployeeName);
        }
    }
    this.tvEmployees.ExpandAll();
}

And the employees class

public class Employees : List<Employees.Employee>
{
    public class Employee
    {
        public int EmployeeId
        {
            get;
            set;
        }
        public string EmployeeName
        {
            get;
            set;
        }
        public int Parent
        {
            get;
            set;
        }
        public int Depth
        {
            get;
            set;
        }
    }
}

And here is the screenshot

Treeview Demo - Screenshot

Treeview Demo - Screenshot


Thanks to Aneesh and Anas for their valuable comments.
Happy Programming :)

Application development using Gtk# in .Net

October 17th, 2009 Anuraj P No comments

When I started my software development career, I got introduced to some cool tools for GUI application development in Linux. I was using Glade and the library was Gtk. Then later I become a MS fan and started working on ASP, VB and .Net. Yesterday I got a chance to download Mono and Monodevelop. And the Gtk for Windows and .Net called Gtk#. I explored in Mono Develop(I was downloaded MonoDevelop-2.2 beta 2) a little, but it was crashed for me two time. :( Then I started using Gtk# in VC# Express. And I created a simple Text File Viewer using C#, with Gtk# for UI. Most of the things in Gtk# is pretty different from .Net Windows Forms development. And I like the concept to in built support for predefined MenuItems, Icons etc. I think MS took the idea of commands in WPF from this.

I created a Windows Application Project and Added reference of the following libraries

atk-sharp.dll
gdk-sharp.dll
glade-sharp.dll
glib-sharp.dll
gtk-dotnet.dll
gtk-sharp.dll

And I deleted the Form1. And modified the Program.cs; the Program.cs

namespace HelloGtk
{
    using System;
    using Gtk;

    public class Program
    {
        private MainWindow mainWindow = null;

        public Program()
        {
            Application.Init();
            mainWindow = new MainWindow();
            Application.Run();
        }

        static void Main()
        {
            new Program();
            return;
        }
    }
}

And the added a class MainWindow.cs, and wrote the code

namespace HelloGtk
{
    using Gtk;
    using System.IO;

    public class MainWindow : Gtk.Window
    {
        private string title = "Text File Viewer";
        private VBox vbox;
        private MenuBar menubar;
        private Statusbar statusbar;
        private TextView textView;
        private ScrolledWindow scrolledWindow;
        private AccelGroup accelGroup;
        private Toolbar toolbar;
        public MainWindow()
            : base("Text File Viewer")
        {
            this.DefaultSize = new Gdk.Size(600, 500);
            this.DeleteEvent += new DeleteEventHandler(MainWindow_DeleteEvent);
            this.Build();
        }

        private void MainWindow_DeleteEvent(object o, DeleteEventArgs args)
        {
            Application.Quit();
            args.RetVal = true;
        }

        private void Build()
        {
            this.Title = this.title;
            this.vbox = new VBox(false, 0);
            this.CreateMenubar();
            this.vbox.PackStart(this.menubar, false, true, 0);
            this.toolbar = new Toolbar();
            this.CreateToolbar();
            this.vbox.PackStart(this.toolbar, false, true, 0);
            this.textView = new TextView();
            this.textView.Editable = false;
            this.textView.WrapMode = WrapMode.Word;
            this.scrolledWindow = new ScrolledWindow();
            this.scrolledWindow.SetPolicy(PolicyType.Automatic, PolicyType.Automatic);
            this.scrolledWindow.Add(this.textView);
            this.vbox.PackStart(this.scrolledWindow, true, true, 0);
            this.statusbar = new Statusbar();
            this.vbox.PackStart(this.statusbar, false, true, 0);
            this.Add(this.vbox);
            this.ShowAll();
        }
        private void CreateToolbar()
        {
            ToolButton OpenToolBarBtn = new ToolButton("gtk-open");
            OpenToolBarBtn.Clicked += this.openMenu_Activated;
            SeparatorToolItem Sep1 = new SeparatorToolItem();
            ToolButton CopyToolBarBtn = new ToolButton("gtk-copy");
            CopyToolBarBtn.Clicked += this.copyMenu_Activated;
            SeparatorToolItem Sep2 = new SeparatorToolItem();
            ToolButton AboutToolBarBtn = new ToolButton("gtk-about");
            AboutToolBarBtn.Clicked += this.aboutMenu_Activated;

            this.toolbar.Add(OpenToolBarBtn);
            this.toolbar.Add(Sep1);
            this.toolbar.Add(CopyToolBarBtn);
            this.toolbar.Add(Sep2);
            this.toolbar.Add(AboutToolBarBtn);
        }

        private void CreateMenubar()
        {
            this.accelGroup = new AccelGroup();
            this.menubar = new MenuBar();
            MenuItem fileMenu = new MenuItem("_File");
            MenuItem editMenu = new MenuItem("_Edit");
            MenuItem helpMenu = new MenuItem("_Help");
            helpMenu.RightJustified = true;

            Menu fileSubMenu = new Menu();
            TearoffMenuItem fileMenuTearOff = new TearoffMenuItem();
            ImageMenuItem openMenu = new ImageMenuItem("gtk-open", accelGroup);
            openMenu.Activated += new System.EventHandler(openMenu_Activated);
            SeparatorMenuItem fileMenuSep = new SeparatorMenuItem();
            ImageMenuItem exitMenu = new ImageMenuItem("gtk-quit", accelGroup);
            exitMenu.Activated += new System.EventHandler(exitMenu_Activated);
            fileSubMenu.Add(fileMenuTearOff);
            fileSubMenu.Add(openMenu);
            fileSubMenu.Add(fileMenuSep);
            fileSubMenu.Add(exitMenu);
            fileMenu.Submenu = fileSubMenu;

            Menu editSubMenu = new Menu();
            ImageMenuItem copyMenu = new ImageMenuItem("gtk-copy", accelGroup);
            copyMenu.Activated += new System.EventHandler(copyMenu_Activated);
            TearoffMenuItem editMenuTearOff = new TearoffMenuItem();
            editSubMenu.Add(editMenuTearOff);
            editSubMenu.Add(copyMenu);
            editMenu.Submenu = editSubMenu;

            Menu helpSubMenu = new Menu();
            ImageMenuItem aboutMenu = new ImageMenuItem("gtk-about", accelGroup);
            TearoffMenuItem helpMenuTearOff = new TearoffMenuItem();
            helpSubMenu.Add(helpMenuTearOff);
            helpSubMenu.Add(aboutMenu);
            aboutMenu.Activated += new System.EventHandler(aboutMenu_Activated);
            helpMenu.Submenu = helpSubMenu;

            this.menubar.Add(fileMenu);
            this.menubar.Add(editMenu);
            this.menubar.Add(helpMenu);
        }

        void aboutMenu_Activated(object sender, System.EventArgs e)
        {
            using (Dialog dialog = new MessageDialog(this,
                                  DialogFlags.Modal | DialogFlags.DestroyWithParent,
                                  MessageType.Info,
                                  ButtonsType.Ok,
                                  "Text File Viewer - A simple text file viewer using gtk#\nDeveloped by Anuraj\nPowered by dotnetthoughts.net\n\nUnder GNU GPL v2."))
            {
                dialog.Title = "About";
                dialog.Run();
                dialog.Hide();
            }
        }

        private void copyMenu_Activated(object sender, System.EventArgs e)
        {
            Clipboard clipboad = this.textView.GetClipboard(Gdk.Selection.Clipboard);
            this.textView.Buffer.CopyClipboard(clipboad);
        }

        void exitMenu_Activated(object sender, System.EventArgs e)
        {
            Application.Quit();
        }
        FileChooserDialog dlg;
        private void openMenu_Activated(object sender, System.EventArgs e)
        {
            dlg =
                new FileChooserDialog("Select Text File", this, FileChooserAction.Open, "");
            dlg.AddButton("Open File", ResponseType.Ok);
            dlg.AddButton("Cancel", ResponseType.Cancel);

            FileFilter filter = new FileFilter();
            filter.AddPattern("*.txt");
            filter.AddPattern("*.*");
            dlg.Filter = filter;

            dlg.TypeHint = Gdk.WindowTypeHint.Dialog;
            dlg.SelectMultiple = false;
            dlg.WindowPosition = WindowPosition.Center;
            dlg.Parent = this;
            dlg.Modal = true;
            dlg.KeepAbove = true;
            dlg.DestroyWithParent = true;
            dlg.State = StateType.Normal;

            dlg.Response += new ResponseHandler(dlg_Response);
            dlg.DeleteEvent += new DeleteEventHandler(dlg_DeleteEvent);

            dlg.Run();
            dlg.Destroy();

        }

        private void dlg_DeleteEvent(object o, DeleteEventArgs args)
        {
            dlg.Destroy();
        }

        private void dlg_Response(object o, ResponseArgs args)
        {
            if (args.ResponseId == ResponseType.Ok)
            {
                this.Title = string.Format("{0} - {1}", this.title, System.IO.Path.GetFileName(dlg.Filename));
                using (StreamReader reader = new StreamReader(dlg.Filename, true))
                {
                    this.textView.Buffer.Text = reader.ReadToEnd();
                }
            }
            dlg.Destroy();
        }
    }
}

And run the application. Here is the screenshot, Text File Viewer running on my machine.

Text File Viewer using GTK#

Text File Viewer using GTK#

How to check remote file exists using C#

October 14th, 2009 Anuraj P No comments

Sometime you require to display remote images in the Web Pages, like Ads, Banner etc, it may be from different domain or a different application. This code will help you to check the existence of a Remote file using C#.

using System.Net;

///
/// Checks the file exists or not.
///
/// The URL of the remote file.
/// True : If the file exits, False if file not exists
private bool RemoteFileExists(string url)
{
    try
    {
        //Creating the HttpWebRequest
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        //Setting the Request method HEAD, you can also use GET too.
        request.Method = "HEAD";
        //Getting the Web Response.
        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
        //Returns TURE if the Status code == 200
        return (response.StatusCode == HttpStatusCode.OK);
    }
    catch
    {
        //Any exception will returns false.
        return false;
    }
}

You can also use WebClient class for the same purpose. Like this.

using System.Net;

///
/// Checks the file exists or not.
///
/// The URL of the remote file.
/// True : If the file exits, False if file not exists
private bool RemoteFileExists(string url)
{
    bool result = false;
    using (WebClient client = new WebClient())
    {
        try
        {
            Stream stream = client.OpenRead(url);
            if (stream != null)
            {
                result = true;
            }
            else
            {
                result = false;
            }
        }
        catch
        {
            //Any exception will returns false.
            result = false;
        }
    }
    return result;
}

Internally WebClient is using the HttpWebRequest and HttpWebResponse classes, so it is good to use the first method.