Wednesday, March 16, 2011

Chat Application In Asp.net c#

Use this Global Class Application For Developing Chat Engine

using System;

using System.Threading ;

using System.Web;

using System.Collections;

using System.Collections.Specialized;

using System.Text;

namespace ASPNETChat

{

    /// <summary>

    /// The business logic of the chat application

    /// </summary>

    public class ChatEngine

    {

        private static Hashtable Rooms = new Hashtable(40);

        public ChatEngine()

        {

        }


        /// <summary>

        /// Deletes the empty chat rooms

        /// </summary>

        /// <param name="state"></param>

        public static void CleanChatRooms(object state)

        {

            Monitor.Enter(Rooms);

            foreach(object key in Rooms.Keys)

            {

                ChatRoom room=(ChatRoom)Rooms[key.ToString()];

                room.ExpireUsers(100);

                if (room.IsEmpty())

                {

                    room.Dispose();

                    Rooms.Remove(key.ToString());

                }

            }

            Monitor.Exit(Rooms);

        }

        /// <summary>

        /// Returns the chat room for this two users or create a new one if nothing exists

        /// </summary>

        /// <param name="user1ID"></param>

        /// <param name="user2ID"></param>

        /// <returns></returns>

        public static ChatRoom GetRoom(string user1ID,string user2ID)

        {

            return GetRoom(user1ID,"",user2ID,"");

        }

        /// <summary>

        /// Returns or creats a chat room for these two users or create a new one if nothing exists

        /// </summary>

        /// <param name="user1ID"></param>

        /// <param name="user1Name"></param>

        /// <param name="user2ID"></param>

        /// <param name="user2Name"></param>

        /// <returns></returns>

        private static ChatRoom GetRoom(string user1ID,string user1Name,string user2ID,string user2Name)

        {

            ChatRoom room=null;

            string rid1=CreateRoomID(user1ID,user2ID);

            string rid2=CreateRoomID(user2ID,user1ID);

            Monitor.Enter(Rooms);


            if (Rooms.Contains(rid1))

                room=(ChatRoom)Rooms[rid1];

            else

            {

                if (Rooms.Contains(rid2))

                    room=(ChatRoom)Rooms[rid2];

                else

                {

                    //if (user1Name=="" && user2Name=="")

                    // return null;

                    //else

                    room=new ChatRoom(user1ID,user1Name,user2ID,user2Name);

                    Rooms.Add(rid1,room);

                }


            }

            Monitor.Exit(Rooms);

            return room;

        }


        #region Room ID,User IDs Manipulation

        /// <summary>

        /// Creates the room id using the ids of the two users

        /// </summary>

        /// <param name="user1"></param>

        /// <param name="user2"></param>

        /// <returns></returns>

        public static string CreateRoomID(string user1,string user2)

        {


            user1=user1.ToUpper();

            user2=user2.ToUpper();

            return user1+";"+user2;

        }

        #endregion

        #region Delete Room

        /// <summary>

        /// Deletes the specified room

        /// </summary>

        /// <param name="roomID"></param>

        public static void DeleteRoom(string roomID)

        {

            Monitor.Enter(Rooms);

            ChatRoom room=(ChatRoom)Rooms[roomID];

            room.Dispose();

            Rooms.Remove(roomID);

            Monitor.Exit(Rooms);

        }

        public static void DeleteRoom(string user1id,string user2id)

        {

            DeleteRoom(CreateRoomID(user1id,user2id));

        }

        #endregion

    }




    public class ChatRoom : IDisposable

    {

        //public Hashtable activeUsers = null;

        public ArrayList messages = null;

        public string RoomID;

        private ChatUser FirstUser;

        private ChatUser SecondUser;

        public void Dispose()

        {


            this.messages.Clear();

            this.RoomID="";

            this.FirstUser.Dispose();

            this.SecondUser.Dispose();

        }

        /// <summary>

        /// Returns the user with the specified id

        /// </summary>

        /// <param name="userID"></param>

        /// <returns></returns>

        public ChatUser GetUser(string userID)

        {

            userID=userID.ToUpper();

            if (FirstUser.UserID.ToUpper()==userID)

                return FirstUser;

            else

                return SecondUser;

        }


        #region constructors

        public ChatRoom(string user1ID,string user1Name,string user2ID,string user2Name)

        {

            this.messages = new ArrayList();

            this.RoomID=ChatEngine.CreateRoomID(user1ID,user2ID);

            this.FirstUser=new ChatUser(user1ID,user1Name);

            this.SecondUser=new ChatUser(user2ID,user2Name);

        }

        #endregion


        /// <summary>

        /// Determines if the users of the room are active or not

        /// </summary>

        /// <returns></returns>

        public bool IsEmpty()

        {

            lock(this)

            {

                if (this.FirstUser.IsActive==false&& this.SecondUser.IsActive==false)

                    return true;

                else

                    return false;

            }

        }



        #region Operations Join,Send,Leave

        //

        /// <summary>

        /// Marks the user as inactive

        /// </summary>

        /// <param name="userID"></param>

        /// <returns></returns>

        public string LeaveRoom(string userID)

        {

            //deactivate user

            ChatUser user=this.GetUser(userID);

            user.IsActive=false;

            user.LastSeen=DateTime.Now;


            //Add leaving message

            Message msg = new Message(user.UserName ,"",MsgType.Left);

            this.AddMsg(msg);

            //Get all the messages to the user

            int lastMsgID;

            ArrayList previousMsgs= this.GetMessagesSince( user.LastMessageReceived,out lastMsgID);

            user.LastMessageReceived=lastMsgID;

            //return the messages to the user

            string str=GenerateMessagesString(previousMsgs);

            if (IsEmpty())

                ChatEngine.DeleteRoom(this.RoomID);

            return "";

        }

        /// <summary>

        /// Activates the user and adds a join message to the room

        /// </summary>

        /// <param name="userID"></param>

        /// <param name="userName"></param>

        /// <returns>All the messages sent in the room</returns>

        public string JoinRoom(string userID,string userName)

        {

            //activate user

            ChatUser user=this.GetUser(userID);

            user.IsActive=true;

            user.UserName=userName;

            user.LastSeen=DateTime.Now;

            //Add join message

            Message msg=new Message(user.UserName ,"",MsgType.Join);

            this.AddMsg(msg);


            //Get all the messages to the user

            int lastMsgID;

            ArrayList previousMessages=this.GetMessagesSince(-1,out lastMsgID);

            user.LastMessageReceived=lastMsgID;


            //return the messages to the user

            string str=GenerateMessagesString(previousMessages);

            return str;

        }

        /// <summary>

        /// Adds a message in the room

        /// </summary>

        /// <param name="strMsg"></param>

        /// <param name="senderID"></param>

        /// <param name="toUserID"></param>

        /// <returns>All the messages sent from the other user from the last time the user sent a message</returns>

        public string SendMessage(string strMsg,string senderID,string toUserID)

        {

            ChatUser user=this.GetUser(senderID);

            Message msg=new Message(user.UserName ,strMsg,MsgType.Msg);

            user.LastSeen=DateTime.Now;

            this.ExpireUsers(100);

            this.AddMsg(msg);

            int lastMsgID;

            ArrayList previousMsgs= this.GetMessagesSince( user.LastMessageReceived,out lastMsgID);

            if (lastMsgID!=-1)

                user.LastMessageReceived=lastMsgID;

            string res=this.GenerateMessagesString(previousMsgs);

            return res;

        }

        #endregion

        /// <summary>

        /// Removes the users that hasn't sent any message during the last window secondes

        /// </summary>

        /// <param name="window">time in secondes</param>

        public void ExpireUsers(int window)

        {

            lock(this)

            {

                if (this.FirstUser.LastSeen != System.DateTime.MinValue )

                {

                    TimeSpan span = DateTime.Now - this.FirstUser.LastSeen;

                    if (span.TotalSeconds > window && this.FirstUser.IsActive!=false)

                    {

                        this.LeaveRoom(this.FirstUser.UserID);

                    }

                }

                if (this.SecondUser.LastSeen != System.DateTime.MinValue )

                {


                    TimeSpan span = DateTime.Now - this.SecondUser.LastSeen;

                    if (span.TotalSeconds > window && this.SecondUser.IsActive!=false)

                    {

                        this.LeaveRoom(this.SecondUser.UserID);

                    }

                }

            }

        }

        /// <summary>

        /// Adds a message to the room

        /// <param name="msg"></param>

        /// <returns> the id of the new message</returns>

        public int AddMsg(Message msg)

        {

            int count;

            lock(messages)

            {

                count = messages.Count;

                messages.Add(msg);

            }

            return count;

        }

        /// <summary>

        /// Iterates over the messages array calling ToString() for each message

        /// </summary>

        /// <param name="msgs"></param>

        /// <returns></returns>

        private string GenerateMessagesString(ArrayList msgs)

        {

            string res="";

            for (int i=0;i<msgs.Count;i++)

            {

                res+=((Message)msgs[i]).ToString()+"\n";

            }

            return res;

        }

        /// <summary>

        /// Returns an array that contains all messages sent after the message with id=msgid

        /// </summary>

        /// <param name="msgid">The id of the message after which all the message will be retuned </param>

        /// <param name="lastMsgID">the id of the last message returned</param>

        /// <returns></returns>

        public ArrayList GetMessagesSince(int msgid,out int lastMsgID)

        {

            lock(messages)

            {

                if ((messages.Count) <= (msgid+1))

                    lastMsgID=-1;

                else

                    lastMsgID=messages.Count-1;

                return messages.GetRange(msgid+1 , messages.Count - (msgid+1));

            }

        }


        /// <summary>

        /// Returns all the messages sent since the last message the user received

        /// </summary>

        /// <param name="userID"></param>

        /// <returns></returns>

        public string UpdateUser(string userID)

        {

            ChatUser user=this.GetUser(userID);

            user.LastSeen=DateTime.Now;

            this.ExpireUsers(100);

            int lastMsgID;

            ArrayList previousMsgs= this.GetMessagesSince( user.LastMessageReceived,out lastMsgID);

            if (lastMsgID!=-1)

                user.LastMessageReceived=lastMsgID;

            string res=this.GenerateMessagesString(previousMsgs);

            return res;

        }

    }

    #region the ChatUser Class

    public class ChatUser : IDisposable

    {

        public string UserID;

        public string UserName;

        public bool IsActive;

        public DateTime LastSeen;

        public int LastMessageReceived;

        public ChatUser(string id,string userName)

        {

            this.UserID=id;

            this.IsActive=false;

            this.LastSeen=DateTime.MinValue ;

            this.UserName=userName;

            this.LastMessageReceived=0;

        }

        public void Dispose()

        {

            this.UserID="";

            this.IsActive=false;

            this.LastSeen=DateTime.MinValue ;

            this.UserName="";

            this.LastMessageReceived=0;

        }

    }

    #endregion

    #region the Message Class

    public class Message

    {

        public string user;

        public string msg;

        public MsgType type;


        public Message(string _user, string _msg, MsgType _type)

        {

            user = _user;

            msg = _msg;

            type = _type;

        }

        public override string ToString()

        {

            switch(this.type)

            {

                case MsgType.Msg:

                    return this.user+" says: "+this.msg;

                case MsgType.Join :

                    return this.user + " has joined the room";

                case MsgType.Left :

                    return this.user + " has left the room";

            }

            return "";

        }


        public Message(string _user, MsgType _type) : this(_user, "", _type) { }

        public Message(MsgType _type) : this("", "", _type) { }

    }

    public enum MsgType { Msg, Start, Join, Left, Action }

    #endregion

}

 

Tuesday, March 15, 2011

Light Weight PopUp

<div>
<input id="Button1" type="button" value="Click To Popup" onclick="ShowDiv('DivOrderSearch','DivLayer')" />
</div>
  <div id="DivLayer" class="DialogueBackground">
</div>
<div id="DivOrderSearch" style="width: 400px; height: 300px; background-color: #D9E0E6;"
  class="Dialogue">
  <div class="DialogueTitle">
Popup Sample
</div>
  <div class="DialogueImg" onclick="HideDiv('DivOrderSearch');" title="Close">
</div>
<div style="padding: 10px;">
Hello World
</div>
</div>

Add javascripts

function HideDiv(PopUpDiv) {
var DivPopUp = document.getElementById(PopUpDiv);
var DivLayer = document.getElementById('DivLayer');
DivPopUp.style.display = "none";
DivLayer.style.width = "0%";
}
function ShowDiv(PopUpDiv, LayerDiv) {
var DivPopUp = document.getElementById(PopUpDiv);
var DivLayer = document.getElementById(LayerDiv);
DivPopUp.style.display = "block";
DivLayer.style.width = "100%";
DivPopUp.style.top = document.documentElement.clientHeight / 2 - DivPopUp.style.height.replace('px', '') / 2 + 'px';
DivPopUp.style.left = document.body.offsetWidth / 2 - DivPopUp.style.width.replace('px', '') / 2 + 'px';
return false;
}

Few Css Classes

.DialogueBackground
{
background-color: Gray;
filter: alpha(opacity=50);
opacity: 0.50;
position: fixed;
left: 0;
top: 0;
width: 0%;
height: 100%;
}

.Dialogue
{
background-color: White;
display: none;
z-index: 2;
border: 1px solid Black;
position: fixed;
text-align: center;
}
.DialogueImg
{
height: 30px;
position: absolute;
width: 27px;
float: right;
background-image: url(../images/closebox.png);
cursor: pointer;
right: -15px;
top: -15px;
background-repeat: no-repeat;
border: 0;
}
.DialogueTitle
{
font-size: small;
font-weight: bolder;
padding: auto;
height: 25px;
color: #ffffff;
position: relative;
background: url(../images/app_tab2.jpg) repeat-x;
top: 0px;
}
use this two images for Close button and TitleBackground
All the Best

http://wiki.asp.net/page.aspx/1441/light-weight-popup/

Export to PDF file in ASP.Net – Gridview to PDF, ASPX Page Content to PDF

Creating data driven application is one of the most commonly done task in our day today application development. In these applications, reporting and generating reports in various formats is one of the repeated requirements we will get. Read the article Export to Excel in ASP.Net 2.0 – Gridview to Excel, DataTable to Excel which discusses some handful of techniques to export the data to excel file. Apart from excel reports, generating PDF report is one of the most common reporting requirement we will get in data driven application. Exporting data to PDF format is not a straight forward task like we do for excel file generation. To do this, we have to employ some 3rd party component or develop a component ourselves by understanding the PDF file standards. 

http://www.codedigest.com/Articles/ASPNET/344_Export_to_PDF_file_in_ASPNet-Gridview_to_PDF_ASPX_Page_Content_to_PDF.aspx

C# Tutorial - Image Editing: Saving, Cropping, and Resizing

http://www.switchonthecode.com/tutorials/csharp-tutorial-image-editing-saving-cropping-and-resizingIn C# it can be tiresome to do certain image editing functions using GDI+. This post has some fun editing methods which can come in handy at times. I have also included a nice little C# program to show all the functionality of the methods below.

Saving a Jpeg

The first thing to do here is set up the method signature with the input parameters. These are the save file path (string), the Image to save (System.Drawing.Bitmap), and a quality setting (long).
private void saveJpeg(string path, Bitamp img, long quality)
The next few things to do are setting up encoder information for saving the file. This includes setting an EncoderParameter for the quality of the Jpeg. The next thing is to get the codec information from your computer for jpegs. I do this by having a function to loop through the available ones on the computer and making sure jpeg is there. The line under that makes sure that the jpeg codec was found on the computer. If not it just returns out of the method.
The last thing to do is save the bitmap using the codec and the encoder infomation.
private void saveJpeg(string path, Bitmap img, long quality)
{
   // Encoder parameter for image quality
   EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, quality);

   // Jpeg image codec
   ImageCodecInfo jpegCodec = this.getEncoderInfo("image/jpeg");

   if(jpegCodec == null)
      return;

   EncoderParameters encoderParams = new EncoderParameters(1);
   encoderParams.Param[0] = qualityParam;

   img.Save(path, jpegCodec, encoderParams);
}

private ImageCodecInfo getEncoderInfo(string mimeType)
{
   // Get image codecs for all image formats
   ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

   // Find the correct image codec
   for (int i = 0; i < codecs.Length; i++)
      if (codecs[i].MimeType == mimeType)
         return codecs[i];
   return null;
}
 

Partial Classes in ASP.net

http://www.dotnet-guide.com/partialclasses.htmlPartial class is a new functionality that is included in Visual Studio .Net 2005 and is supported in ASP.Net 2.0. This new functionality helps you to split a single class into multiple partial classes. These partial classes can be in different individual files. 

In the earlier versions of Visual Studio .Net 2005, while you create an ASP.Net application, you might have seen that a single class has to be in a single file. You will be beginning a class and ending that class in the same file. It was not possible to split a single class across multiple files. This new feature, partial class, allows you to allot different developers to develop the code for different functionalities that are available in a single class. These functionalities can be developed in partial classes and then compiled to form the required assembly.

http://www.dotnet-guide.com/partialclasses.html 

C# Snippet Tutorial - How to Draw Text on an Image

In this snippet tutorial we're going to be adding on to our series of C# image editing tutorials. This tutorial is going to provide the code required to do basic text drawing including anti-aliasing and text alignment.
For more information on C# image editing, check out our previous two tutorials: C# Tutorial - Image Editing: Saving, Cropping, and Resizing and C# Tutorial - Image Editing: Rotate.
Ok, let's get started. The first thing we need to do is get a Bitmap object from an image file.
Bitmap myBitmap = new Bitmap("C:\\myImage.jpg");
Now that we have a Bitmap object we can get a Graphics object from it. The Graphics object will be doing all of our text drawing.


Monday, March 14, 2011

Nested Datalist in asp.net c# , Item Boutnd In Nested Datalist




.Aspx Page
 <asp:DataList ID="parentDataList" CellPadding="10" CellSpacing="10" RepeatDirection="horizontal"
                            runat="server" DataKeyField="id">
                            <ItemTemplate>
                                <strong>
                                    <asp:Label CssClass="main-cotent" ID="idLabel" runat="server" Text='<%# Eval("category") %>' /></strong>
                                <asp:DataList ID="nestedDataList" runat="server" RepeatDirection="vertical">
                                    <ItemTemplate>
                                        <ul class="ul-div li" style="margin: 0px; padding: 5px px 5px 5px">
                                            <li><a href='product.aspx?cate=<%#Eval("category")%>&subcate=<%#Eval("subcategory")%>'>
                                                <asp:Label ID="Label" runat="server" Text='<%# Eval("subcategory") %>'></asp:Label></a></li></ul>
                                    </ItemTemplate>
                                </asp:DataList>
                            </ItemTemplate>
                        </asp:DataList>

.aspx.cs Page


public void BindParentDataList()
    {
        // string variable to store the connection string
        // retrieved from the connectionStrings section of web.config


        // sql command object initialized with select command text
        SqlCommand mySqlCommand = new SqlCommand("select * from tbl_category", connection);

        // check the connection state and open it accordingly.
        if (connection.State == ConnectionState.Closed)
            connection.Open();

        // Sql datareader object to read the stream of rows from SQL Server Database
        SqlDataReader myDataReader = mySqlCommand.ExecuteReader();

        // Pass the Sql DataReader object to the DataSource property
        // of DataList control to render the list of items.
        parentDataList.DataSource = myDataReader;
        parentDataList.DataBind();

        // close the Sql DataReader object
        myDataReader.Close();

        // check the connection state and close it accordingly.
        if (connection.State == ConnectionState.Open)
            connection.Close();

        // foreach loop over each item of DataList control
        foreach (DataListItem Item in parentDataList.Items)
        {

            BindNestedDataList();
        }

    }

public void BindNestedDataList()
    {

        int i;
        for (i = 0; i < parentDataList.Items.Count; i++)
        {
            // get CategoryID value for the current datalist item
            // DataKeys collection object returns the associated value
            // at specified Item Index of DataList
            Label lit = (Label)parentDataList.Items[i].FindControl("idLabel");

            // string variable to store the connection string
            // retrieved from the connectionStrings section of web.config
            //string connectionString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;

            //// sql connection object
            //SqlConnection mySqlConnection = new SqlConnection(connectionString);

            // sql command object initialized with select command text
            SqlCommand mySqlCommand = new SqlCommand("select * from tbl_subcategoryname where category='" + lit.Text + "'", connection);



            // check the connection state and open it accordingly.
            if (connection.State == ConnectionState.Closed)
                connection.Open();

            // Sql datareader object to read the stream of rows from SQL Server Database
            SqlDataReader myDataReader = mySqlCommand.ExecuteReader();

            // findControl function to get the nested datalist control
            DataList nestedDataList = (DataList)parentDataList.Items[i].FindControl("nestedDataList");

            nestedDataList.DataSource = myDataReader;
            nestedDataList.DataBind();

            // close the Sql DataReader object
            myDataReader.Close();

            // check the connection state and close it accordingly.
            if (connection.State == ConnectionState.Open)
                connection.Close();
        }