Archive

Posts Tagged ‘IIS 7’

How to Store and Retrieve files from SQL Server Database

October 7th, 2009 Anuraj P No comments

The forum I joined recently got lot of queries like How to Save Images in the Database, How to save files in SQL Server, How read files from Database etc. So I thought of writing a post regarding this. Even though I am part of a Web project, I am doing some Windows applications for the client. So I thought it will nice to brush-up the ASP.Net skills.

Here is the code. I am using SQL Server 2008, but I am not using FileStream for the current project, I already wrote a post to how to
manage files with FileStream feature. In this post I am using nvarchar(MAX) datatype for storing the file content.

Table Design

CREATE TABLE [dbo].[tblFiles](
	[FileId] [uniqueidentifier] NOT NULL,
	[Filename] [nvarchar](255) NOT NULL,
	[FileContent] [varbinary](max) NULL
)

And the I set FileId default to newId() and FileContent default to NULL

ALTER TABLE [dbo].[tblFiles] ADD  CONSTRAINT [DF_tblFiles_FileId]  DEFAULT (newid()) FOR [FileId]
GO
ALTER TABLE [dbo].[tblFiles] ADD  CONSTRAINT [DF_tblFiles_FileContent]  DEFAULT (NULL) FOR [FileContent]
GO

I wrote the code in C#. I am having a Asp FileUpload control and a button to upload the file, and a Repeater control with two controls, a label for displaying the filename and hyper link control for downloading the file.

<body>
<form runat="server">
<asp:FileUpload runat="server" ID="fileUploadImage" />
<asp:Button runat="server" ID="cmdUpload" Text="Upload File" OnClick="cmdUpload_Click" />
<asp:Repeater runat="server" ID="rptrFiles">
    <HeaderTemplate>
        <table>
    </HeaderTemplate>
    <ItemTemplate>
        <tr>
            <td>
                <asp:Label runat="server" ID="lblFilename" Text='<%# Eval("FileName")%>' />
            </td>
            <td>
              <asp:HyperLink runat="server" Target="_blank" ID="lbtDownload" Text="Download" NavigateUrl='<%# "Download.aspx?File="  + Eval("FileId").ToString() %>' />
            </td>
        </tr>
    </ItemTemplate>
    <FooterTemplate>
        </table>
    </FooterTemplate>
</asp:Repeater>
</form>
</body>

Uploading the File to the Database
Code behind

protected void cmdUpload_Click(object sender, EventArgs e)
{
    string fileName = Path.GetFileName(this.fileUploadImage.FileName);
    byte[] fileContent = this.fileUploadImage.FileBytes;
    using (SqlConnection connection = new SqlConnection("Server=.\\SQLEXPRESS;User Id=sa;Password=sapassword;Database=sampledb"))
    {
        connection.Open();
        using (SqlCommand command = new SqlCommand("INSERT INTO tblFiles(Filename, FileContent) VALUES(@Filename, @FileContent)", connection))
        {
            SqlParameter fileNameParameter = new SqlParameter("@Filename", System.Data.SqlDbType.NVarChar, 255);
            fileNameParameter.Value = fileName;
            SqlParameter fileContentParameter = new SqlParameter("@FileContent", System.Data.SqlDbType.VarBinary);
            fileContentParameter.Value = fileContent;
            command.Parameters.AddRange(new SqlParameter[] { fileNameParameter, fileContentParameter });
            command.ExecuteNonQuery();
        }
    }
}

And here is code to bind the repeater from the Database

DataTable dtFiles = new DataTable("Files");
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT FileId, FileName FROM tblFiles", "Server=.\\SQLEXPRESS;User Id=sa;Password=sapassword;Database=sampledb"))
{
    adapter.Fill(dtFiles);
}
this.rptrFiles.DataSource = dtFiles;
this.rptrFiles.DataBind();

Download / Read the file from Database
And to download / read the file from Database, I am passing the File unique id to another page(download.aspx).I this page I am checking for the File querysting and based on that reading filecontent from Sql and writing it to Asp.net output stream. You can get more information about how to download files from IIS in this post.

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.QueryString["File"] != null)
    {
        string fileId = Request.QueryString["File"];
        using (SqlConnection connection = new SqlConnection("Server=.\\SQLEXPRESS;User Id=sa;Password=sapassword;Database=Sample"))
        {
            connection.Open();
            using (SqlCommand command = new SqlCommand("SELECT Filename, FileContent FROM tblFiles WHERE FileId = @FileId", connection))
            {
                command.Parameters.AddWithValue("@FileId", fileId);
                SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
                if (reader.HasRows)
                {
                    reader.Read();
                    byte[] content = reader["FileContent"] as byte[];
                    string filename = reader["FileName"].ToString();
                    Response.Clear();
                    Response.ClearContent();
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
                    Response.AddHeader("Content-Length", content.Length.ToString());
                    Response.OutputStream.Write(content, 0, content.Length);
                    Response.End();
                }
            }
        }
    }
}

Please write to me if I missed something. Happy Programming .

A Simple Chat script using ASP.Net C#

September 11th, 2009 Anuraj P 2 comments

Few days back one of my colleague was looking for a simple chat script in ASP.Net, but he can’t found one. Almost all of the chat scripts were in ASP and he want to do it for an internal site. So I thought about implementing one. And here is the simple script using ASP.Net’s Page method feature. For this I am using Windows Authentication, because it is for a intranet site, where users will be coming from one domain only.

Code behind – Global.asax

private List<string> onlineUsers;
void Session_Start(object sender, EventArgs e)
{
	if (this.onlineUsers == null)
	{
            this.onlineUsers = new List</string><string>();
        }

        if (!this.onlineUsers.Contains(HttpContext.Current.User.Identity.Name))
        {
            this.onlineUsers.Add(HttpContext.Current.User.Identity.Name);
        }
        HttpContext.Current.Session["Users"] = this.onlineUsers;
}

void Session_End(object sender, EventArgs e)
{
        if (this.onlineUsers != null)
        {
            this.onlineUsers.Remove(HttpContext.Current.User.Identity.Name);
        }
	HttpContext.Current.Session["Users"] = this.onlineUsers;
}

Web.Config

<authentication mode="Windows"/>
<authorization>
	<deny users="?"/>
</authorization>

Default.aspx.cs

private static List</string><string> chatCollection;

[WebMethod(true)]
public static List</string><string> Add(string comment)
{
	string user = HttpContext.Current.User.Identity.Name;
        if (chatCollection == null)
        {
		chatCollection = new List</string><string>();
        }
        comment = comment.Replace("< ", "[").Replace(">", "]");
        comment = GetSmileys(comment);
        chatCollection.Add(string.Format("<tr><td>{0} :<font color=\"blue\">{1}</font></td></tr>", user, comment));
        return chatCollection;
}

private static string GetSmileys(string comment)
{
        if (comment.Contains("[:-)]"))
        {
        	comment = comment.Replace("[:-)]", "<img src=\"icons\\smile.gif\"/>");
        }
        else if (comment.Contains("[;-)]"))
        {
        	comment = comment.Replace("[;-)]", "<img src=\"icons\\wink.gif\"/>");
        }
        else if (comment.Contains("[:-(]"))
        {
        	comment = comment.Replace("[:-(]", "<img src=\"icons\\frown.gif\"/>");
        }
        else if (comment.Contains("[:-D]"))
        {
        	comment = comment.Replace("[:-D]", "<img src=\"icons\\biggrin.gif\"/>");
        }
        else if (comment.Contains("[:-|]"))
        {
        	comment = comment.Replace("[:-|]", "<img src=\"icons\\blankstare.gif\"/>");
        }
        else if (comment.Contains("[B-)]"))
        {
        	comment = comment.Replace("[B-)]", "<img src=\"icons\\cool.gif\"/>");
        }
        else if (comment.Contains("[}-)]"))
        {
        	comment = comment.Replace("[}-)]", "<img src=\"icons\\devilish.gif\"/>");
        }
        else if (comment.Contains("[:-P]"))
        {
        	comment = comment.Replace("[:-P]", "<img src=\"icons\\p.gif\"/>");
        }
	return comment;
}

[WebMethod(true)]
public static List</string><string> GetChat()
{
	if (chatCollection == null)
        {
        	chatCollection = new List</string><string>();
        }
        return chatCollection;
}

[WebMethod(true)]
public static List</string><string> GetUsers()
{
	if (HttpContext.Current.Session["Users"] == null)
        {
        	HttpContext.Current.Session["Users"] = new List</string><string>();
        }
        return HttpContext.Current.Session["Users"] as List</string><string>;
}

And finally the HTML

Default.aspx


< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>:: TEAM CHAT ::</title>

    <script type="text/javascript">
        function sendChat() {
            var chatText = $get("txtChatInput").value;
            if (chatText != "") {
                PageMethods.Add(chatText, sendChat_Callback);
            }
            else {
                $get("txtChatInput").focus();
            }
            return false;
        }
        function sendChat_Callback(response) {
            displayChatText(response);
            $get("txtChatInput").value = "";
            $get("txtChatInput").focus();
        }
        function GetChat() {
            PageMethods.GetChat(GetChat_Callback);
        }
        function GetChat_Callback(response) {
            displayChatText(response);
        }
        function displayChatText(response) {
            var result;
            result = "<table>";
            for (var i = response.length - 1; i >= 0; i--) {
                result = result + response[i];
            }
            result = result + "</table>";
            $get("chatOutputDiv").innerHTML = result;
        }
        function getUsers() {
            PageMethods.GetUsers(GetUsers_Callback);
        }
        function GetUsers_Callback(response) {
            $get("lstUsers").options.length = 0;
            for (var i = response.length - 1; i >= 0; i--) {
                addUsers(response[i]);
            }
        }
        function addUsers(text) {
            var optn = document.createElement("OPTION");
            optn.text = text;
            optn.value = text;
            $get("lstUsers").options.add(optn);
        }
        function LoadUI() {
            getUsers();
            GetChat();
            $get("txtChatInput").focus();
        }
        function showAbout() {
            var msg = "Copyright (c) 2009 Anuraj. All rights reserved.\nLicenced under GNU GPL v2.";
            msg += "\n\nVersion 0.2 : Supports Smileys\n";
            msg += "Smileys should be in square brackets, like below,\ncase-sensitive(Sorry I will fix it later)\n";
            msg += "Supported :- [:-)], [;-)], [:-(], [:-D], [:-|], [B-)], [}-)],[:-P]\n";
            msg += "\n\nHappy Chatting [:)]\n";
            alert(msg);
        }
        setInterval("LoadUI();", 5000);
    </script>

    <style type="text/css">
        body
        {
            font-family: Calibri;
            font-size: 11pt;
        }
        input
        {
            font-family: Calibri;
            font-size: 11pt;
            color: Blue;
        }
        .txt
        {
            border: solid 1px #000;
            font-family: Calibri;
            font-size: 11pt;
            color: Black;
        }
        option
        {
            font-family: Calibri;
            font-size: 11pt;
            color: Blue;
        }
        h1
        {
            color: Blue;
            font-size: xx-large;
            text-decoration: underline;
            text-align: center;
        }
    </style>
</head>
<body onload="javascript:LoadUI();">
    <form id="form1" runat="server" onsubmit="javascript:return sendChat();">
    <div>
        <asp :ScriptManager runat="server" ID="scriptMgr" EnablePageMethods="true" ScriptMode="Release"
            EnableViewState="false" />
        <table cellpadding="0" cellspacing="0" border="0">
            <tr>
                <td colspan="2" style="text-align: center">
                    <h1>
                        :: TEAM CHAT ::
                    </h1>
                    <span>A simple chat script using ASP.Net and C#</span>
                    &nbsp;<a href="javascript:void('About');" title="About TeamChat" onclick="javascript:return showAbout

();">?</a>&nbsp;
                </td>
            </tr>
            <tr>
                <td>

                    <input class="txt" type="text" maxlength="1500" style="width: 340px;" id="txtChatInput" />
                </td>
                <td valign="middle">
                    &nbsp;<input type="button" id="cmdSubmit" value="Send" onclick="javascript:return sendChat();" />
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    &nbsp;
                </td>
            </tr>
            <tr>
                <td colspan="2" valign="top">
                    <div id="chatOutput" style="height: 300px; width: 400px; border: solid 1px #000;
                        overflow: scroll;">
                        <div id="chatOutputDiv" style="height: 280px; width: 380px;">
                        </div>
                    </div>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    &nbsp;
                </td>
            </tr>
            <tr>
                <td colspan="2" valign="top">
                    <label>
                        Online Users</label><br />
                    <select class="txt" size="4" id="lstUsers" style="width: 400px; border: thin solid #000000;
                        font-family: Calibri; font-size: 11pt; color: #FFFFFF;">
                        <option>No users available </option>
                    </select>
                </td>
            </tr>
            <tr>
                <td colspan="2" style="text-align: center; font-size: 11px;">
                    Copyright &copy; 2009 <a href="mailto:anuraj.p@mymailserver.com">Anuraj</a>. All rights
                    reserved.<br />
                    Licenced under GNU GPL v2.
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

Here is the Image “Team Chat” running on my machine

Team chat - asp.net script screenshot

Team chat - asp.net script screenshot

Code seems like pretty self explantory. As wordpress don’t support zip attachments, I will upload, and give the source later.

Happy Chating ;)

I took the Emoticons from deviantart.com

Implementing Windows authentication in ASP.NET on IIS 7

July 30th, 2009 Anuraj P No comments

For implementing windows authentication in IIS 7 (On Windows Vista),
you need to check whether the Windows authentication installed or not. You can do this either using Programs and Features > Turn Windows features On or Off. And select the Checkbox windows authentication from Security.

Install Windows Authentication

Install Windows Authentication

After installing the Windows Authentication in your system, update your IIS in web application settings. Select Authentication, and enable the Windows Authentication. And disable the Anonymous Authentication.

Enable Windows Authentication

Enable Windows Authentication

Now in the Web.config file, set the Authentication mode to Windows.

<authentication mode="Windows" />

Also set the authorization rules, like which all users / roles need access etc.

<authorization>
<allow users="DOMAIN\USER, DOMAIN\USER2" />
<deny users="*"/>
</authorization>

Now modify the Default.aspx page so that it can display the current username.

<body>
    <form id="form1" runat="server">
    <div>
        < %= User.Identity.Name %>
    </div>
    </form>
</body>

Now run the application, it will display the Windows Authentication dialog, if your username not in the list. If you cancel the login dialog it will display a Access Denied page. If you give the correct username and password, it will display the Username.

You can get more information from How to implement Windows authentication and authorization in ASP.NET