Archive

Archive for October, 2009

Microsoft Community TechDays at Trivandrum

October 26th, 2009 Anuraj P No comments

logo

As posted earlier K-MUG conducted Microsoft Community TechDays in Technopark, Trivandrum on 24th October. I got a chance to attend the event and to met few K-MUG friends.

Venue Details

24th October at ParkCenter, Technopark, Trivandrum

Sessions

  1. Windows Azure & Clouds – by Ramaprasanna Chellamuthu.
  2. SQL Server – Tips and Tricks – by Vinod Kumar
  3. Coding For Fun – by Shoban Kumar
  4. Rapid Prototyping – Lessons from the trenches– by Uday M. Shankar.
  5. Windows Presentation Foundation (WPF) and interoperability – by Renuka Alex
  6. Language Integrated Query (LINQ) – by Praseed Pai
  7. Writing Secure Code – by Jairam Ramesh

Speakers

  1. Vinod Kumar works as a Technology Evangelist(Databases and BI) with Microsoft India specializing primarily on SQL Server. You can access his blog at http://blogs.sqlxml.org/vinodkumar/
  2. Uday M. Shankar is a Principal Engieer in Yahoo User Experience team. You can access his blog at http://udayms.wordpress.com.
  3. Ramaprasanna Chellamuthu works with Microsoft as a Developer Evangelist. You can access his blog at http://blogs.msdn.com/ramaprasanna/
  4. Praseed Pai is a .net consultant and a solutions architect. You can access his blog at http://praseedp.blogspot.com
  5. Renuka Alex is working as a Technical Evangelist at Infosys.
  6. Jairam Ramesh is a Security Research Consultant with Microsoft Corporation.
  7. Shoban Kumar is a Microsoft MVP working as a Senior Software Engineer. You can access his blog at http://www.codegeeks.net/

Event Details

Community TechDays Trivandrum

Community TechDays Trivandrum*

I reached the Venue just at sharp 9′O Clock (on time). There was a queue for registration. After registration, in the venue, I met few K-MUG friends, Binoy, Shoban etc.

By 9.15 Mr.Binoy (Vice President, K-MUG) welcomed all the Speakers and Attendees.

The first session was on Windows Azure by Ramaprasanna Chellamuthu, it is was nice session about What is cloud computing, Why Windows Azure, Windows Azure architecture, etc. And atlast a simple demo on How to develop an application in Windows Azure.

The next session was on SQL Server Tips and Tricks by Vinod Kumar. He started with few nice tweaks in SQL Server Management Studio, and winds up with some hidden gems like SQLDIAG, SQLIOSIM, TABLEDIFF etc.

The next session was taken by Shoban Kumar, on Coding for Fun. This session is all about writing applications for Web 2.0 applications, like Twitter, FaceBook, Bing, GMail etc.Also he give some demo on Bing(Desktop translator), Twitter(TweetMyPC application) and GMail(GMail Notifier) etc. Most of them can be downloaded from Codeplex.com.

Last session in the morning, before lunch was from Uday M Shanker, he was talking about Rapid Prototyping. In this session the main topic was MS SketchFlow, it is tool from Microsoft Blend family, used for Prototyping.

After Lunch break the first session was on LINQ from Praseed Pai. He talked about various LINQ features like LINQ as ORM, Lamda Expressions, types of Lamda expressions. Also some nice demos using LINQ in C#.

Next session was from Renuka Alex, she talked about developing user controls in WPF and using the WPF Usercontrols in Windows Form based Applications.

The Last session of the day taken by Jairam Ramesh, is to how to write secure code. In this session Jairam talked about security of Windows Apps, Web Apps etc. Also some suggestions to write code more securely.

This was the last session, after this the feedback forms collected and lucky draw Winners got some gift packets and Windows 7 DVDs.
*Thanks to Praveen.V.Nair for the session photo.

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#

Color Picker Dropdown using C#

October 15th, 2009 Anuraj P No comments

While playing around one of hobby project, I found there is a nice color picker dropdown available in WordPad, for setting the font color. I was using Windows

Color Dialog. So I thought of implementing a WordPad like color picker. And I think I almost readed my goal. I need to try this in the Toolstrip dropdown too.

//On the Form load I am loading the colors to the Dropdown.
//You can also bind the p to the Dropdown.
Type t = typeof(Color);
PropertyInfo[] p = t.GetProperties();
foreach (PropertyInfo item in p)
{
    if (item.PropertyType.FullName.Equals("System.Drawing.Color", StringComparison.CurrentCultureIgnoreCase))
    {
        this.comboBox1.Items.Add(item.Name);
    }
}

And I set the Dropdown’s DrawMode property to “OwnerDrawFixed”. And in the DrawItem event of the Dropdown I wrote the code.

if (e.Index != -1)
{
    e.DrawBackground();
    e.Graphics.FillRectangle(GetCurrentBrush(comboBox1.Items[e.Index].ToString()), e.Bounds);
    Font f = comboBox1.Font;
    e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), f, Brushes.Black, e.Bounds, StringFormat.GenericDefault);
    e.DrawFocusRectangle();
}

And the GetCurrentBrush() function returns the Brush for painting the rectangle. You can write the code in the DrawItem event too, but initialy I thought about setting the font color using the same color. But later that idea changed.

private Brush GetCurrentBrush(string colorName)
{
    return new SolidBrush(Color.FromName(colorName));
}

One issue I found in this code is, for black color, I can’t see the color name. And here is the screenshot of Color Picker Dropdown running on my machine.

Color Picker Dropdown screenshot

Color Picker Dropdown screenshot

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.