Skip to main content

Posts

Showing posts from 2011

Hierarchical MenuItem in ASP.NET

In all websites we have menus of some type or other. Here we will talk about creating a hierarchical menu using ASP.NET MenuItem. Add a MenuItem control to the page as shown below < form id ="frmMain" runat ="server">     < div >         < asp : Menu ID ="menuHotels" runat ="server"             onmenuitemclick ="menuHotels_MenuItemClick">                     </ asp : Menu >     </ div > </ form > Code in code behind page:  As this is a sample application please ignore hard coding of connectionstring and naming convention. using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; namespace Hotels {     public partial class HotelWorld : System.Web.UI. Page     {         protected void Page_Load(

How to delete and create windows service using SC

This post is going to be a really small and simple. In this I will just write down the use of SC utility to delete and create windows services. There are lot of resources on web but I am just posting it to have it for my reference :) as I perform these actions quiet often. How to create .NET windows service :- On local computer Go to Run -> Cmd use SC -  sc create <service name>  binpath= "<exe folder>\<exe name>" e.g. sc create MySampleService binpath= "D:\MySampleServiceProject\MySampleService.exe" point to note: There should not be a space between binPath and '='. Service name should be in double quotes ("). There must be a space between '=' and the services exe path. On Remote Computer Go to Run -> Cmd  use SC -  sc <remoteservername> create <service name>  binpath= "<exe folder>\<exe name>" How to delete.NET windows service :- sc delete <servicename>

Detect ASP.NET session timeout

HTTPContext object - Provides access to the entire current context (including the request object). You can use this class to share information between pages. It is created early in the asp.net pipeline. It is also used to map the request to a session. Thus, we can use this object to find out whether the session has expired or not. In my application I am using a master page for the login page and I hope that is what you all will be doing. This is the code which I have used to find redirect the user to another URL if the session has expired. protected override void OnInit(EventArgs e)     {         base.OnInit(e);         if (Context.Session != null)         {             //check whether a new session was generated             if (Session.IsNewSession)             {                 //check whether a cookies had already been associated with this request                 HttpCookie sessionCookie = Request.Cookies["ASP.NET_SessionId"];            

Partial Search in sql server

Here I am not going to talk about fulltext search as generally in small applications which not that expensive servers we do not really go for full text indexes. Thus we are going to talk about wild card search. Now a days providing search facility to end user has become quite normal. Users generally will have 'n' fields to search. They can search by providing values for all fields or they may provide values for only one field. There are two solutions to this:- The one i like - I have not put any validation in place which we should as if there is no parameter specified the procedure will fail because of bad syntax as there will be a bad where clause. Thus check if no parameter is spec CREATE PROCEDURE SearchProcedureName         -- Add the parameters for the stored procedure here         @Name VARCHAR(100),         @Id VARCHAR(10),         @error int output AS BEGIN set @error = -1 if((ISNULL(@Name, '') ='') and (ISNULL(@Id, '') ='

Displaying image is a gridview - ImageField

Can not display images in gridview. Images are not getting displayed in gridview. Quite often I have seen people getting bugged by this problem. This problem arises normally due to wrong image URL. This is because web server was not able to find the image and thus did not return a valid URL. Consider a scenario where in my D: drive I have a folder name Images now if there are few images in it and I just wrote a small program to read the file name and display image using a gridview like this:- Default.aspx - <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"     CodeBehind="Default.aspx.cs" Inherits="GridView_Image._Default" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderI

Extension Method C#

Once a type is defined and compiled into a .NET assembly, its definition is, more or less, final. In order to add new members, update members, or remove members we need to recode and recompile the code base into an updated assembly. Or we could use System.Reflection.Emit namespace to reshape a compiled type dynamically. Extension methods allow us to extend the functionality of previously compiled types. Using extension methods, we can add functionality to precompiled types while providing the illusion these methods were there all along. When we create extension methods, the existing precompiled assembly is not literally modified. Rather, the type is extended within the current project. If we package extension methods into a custom .NET *.dll, other applications would need to reference this library to make use of the extensions. To this end, extension methods are really just a way to ‘pretend’ a type has new functionality. The real type is not modified in any way. Why do we need

Implicitly typed local variables

It is not a new feature anymore, but I realized few of my friends still do not know the benefits and need of it. Thus, I feel it is worth writing. This post may not be helpful for you experts!!! Example to start of with and put few questions         public void ImplicitVars()         {             var i = 0;             var s = "Do I know";             Console.WriteLine("i is of type {0}",i.GetType().FullName);             Console.WriteLine("s is of type {0}",s.GetType().FullName);         } Output i is of type System.Int32 s is of type System.String Now add another line after second Console.WriteLine - i = "Error"; public void ImplicitVars() { var i = 0; var s = "Do I know"; Console.WriteLine("i is of type {0}",i.GetType().FullName); Console.WriteLine("s is of type {0}",s.GetType().FullName); i = "Error"; } We will get a compile time error. “Cannot implicitly convert type string to

Partition a table present in merge replication and deploy the changes on production

I have been playing with merge application of late, but for production changes and not on a sample project. Let me first share our environment with you. We have a central server and few number of clients. Server and client share same schema. We have used merge replication to replicate the changes. There were some load issues and thus few changes have to be done. I will list down the change, which I am going to talk about today. Partition a table vertically. Transfer data from the existing table into the new table. Make sure that the network usage (replication) will be as less as possible. This is a normal scenario for those who are working on distributed environment. I am sharing this post for all those who will work on such environments in future . Challenges For once it all seems so simple. We can run a data migration script which will transfer data from table A to table B on client and server and we are good. But, the problem is that then the merge replication will try

Add (Drop) a new article (table) at publisher in merge replication

Let us add the article using the GUI first. First of all create the table on publisher database. Now right click on the publisher and select properties from the menu. Click on articles. Uncheck the - "Show only checked articles in the list" checkbox, in order to see the newly added table. Select the table as shown in the figure below. Press ok The article has now been added to the publisher We now need to recreate the snapshot Right click the publication and select – “View snapshot agent status”. Click start to regenerate snapshot. Now right click on the subscription (I have both on same server you may have on different servers) and select “View synchronization status” Click on start on the agent. The schema changes will propagate to the client if you have "Replicate schema changes" property set to true in the publisher.

SQL Server JOIN basics

Yesterday I took an interview of an EXPERIENCED candidate. I was quite shocked to see the information he has on JOINs. Thus I thought about blogging about the basics of JOINs. The scenario I gave him was - CREATE TABLE #JOIN1 (     ID INT,     [TEXT] VARCHAR(100) ) CREATE TABLE #JOIN2 (     ID INT,     [TEXT] VARCHAR(100) ) INSERT INTO #JOIN1 VALUES(1,'TEXT JOIN 1 - 1') INSERT INTO #JOIN1 VALUES(2,'TEXT JOIN 1 - 2') INSERT INTO #JOIN1 VALUES(3,'TEXT JOIN 1 - 3') INSERT INTO #JOIN1 VALUES(1,'TEXT JOIN 1 - 4') INSERT INTO #JOIN1 VALUES(NULL,'TEXT JOIN 1 - 5') INSERT INTO #JOIN2 VALUES(1,'TEXT JOIN 2 - 1') INSERT INTO #JOIN2 VALUES(2,'TEXT JOIN 2 - 2') INSERT INTO #JOIN2 VALUES(4,'TEXT JOIN 2 - 3') INSERT INTO #JOIN2 VALUES(NULL,'TEXT JOIN 2 - 4') INSERT INTO #JOIN2 VALUES(5,'TEXT JOIN 2 - 5') Note: There is no primary key column. Left Outer Join MSDN defines a left outer join as - Th

Reading/importing tab delimited text file using VBA–Excel

One of my friend, who is a mechanical engineer, had to import a tab delimited text file in Excel. He gets this (these) file(s) as input for God Knows What . He asked for my help and then I realized it is worth blogging about as may be helpful for many of my civil/mech/chem…. friends. So first thing first:- How to create a tab delimited text file 1. Open notepad –> Write text in first column –> press tab –>write in second column and so on. –> save the file with .tab extension. 2. Open excel-> enter values in different column-> Open the File menu and select the Save as... command.-> In the Save as type drop-down box, select the Text (tab delimited) (*.txt) option.->Select the Save button. If you see warning messages pop up, select the OK or Yes button. Here I am going to write a macro to read all the values Sub ReadTextFile()     Dim iRow      As Long   Dim Fname     As Variant   Dim Record    As String   Dim P         As Variant   Dim iCol  

Dynamic charts with ASP.NET, Windows chart controls

We all know how important charting is now days. We all store lots of data but the end users generally are the people who do not have much time to use it after putting in hours in correlating and analyzing it. They generally ask for reports charts etc. Traditionally either we had to use GDI+ or buy a third party tool to provide these facilities. MS has started providing this facility free of cost since 2008 (though it was not part of 3.5 framework but one can download the exe and can install it). Starting from framework 4.0 charting controls are also shipping with .NET. It is quite easy to use chart controls, let us see how. Create a web application project and from the toolbox (in design mode) drag chart control. It will be present under the data section. Configure the datasource and set the chart type and X and Y column for the chart. I am using a SQLDataSource and AdventureWorks as my DB. Now we are good to go. Press F5 and you can see the chart. Let us extend the functiona