Wednesday, May 30, 2012

File Upload

PAGE1.aspx
 <img src="../images/upload-new.png" title="Upload New Documents" id="TestNewUpload"
style="cursor:pointer; margin-left:870px;" href="PAGE2.aspx"/>


$("#TestNewUpload").live('click', function (e) {

            var page = $(this).attr("href")
            page += "?ID=" + TestID + "&Type =" +1;
            var $dialog = $('<div></div>')
                .html('<iframe style="border: 0px; " src="' + page + '" width="100%" height="100%"></iframe>')
                .dialog({
                    autoOpen: false,
                    modal: true,
                    height: 450,
                    width: 600,
                    title: "Upload document",
                    buttons: {
                        "Close": function () {
                            $dialog.dialog('close');
                        }
                    },
                    close: function (event, ui) {
                    }
                });
            $dialog.dialog('open');
            e.preventDefault();
        }); 

PAGE1 END

PAGE2.aspx
<form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <Triggers>
                <asp:PostBackTrigger ControlID="btnUpload" />
            </Triggers>
            <ContentTemplate>
                <div id="divUpload" runat="server">
                    <table>
                        <tr><td>Title</td><td>
<asp:TextBox ID="txtTitle" runat="server" MaxLength="99"></asp:TextBox>
                            </td></tr>
                        <tr><td>Document</td>
                            <td><asp:FileUpload ID="fuTestUploads" runat="server" /></td></tr>                       
                        <tr><td></td>
                            <td>
          <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
                            </td></tr>
                    </table>
                </div>
                <div id="divMessage" runat="server" class="centered">
                    <center>
                        <span style="font-weight:bold; font-size:15px;"> Document uploaded successfully! </span>
                    </center>
                    <br />
                    <asp:LinkButton ID="lbtnUploadMore" runat="server"
                        onclick="lbtnUploadMore_Click">Upload More</asp:LinkButton>
                </div>
            </ContentTemplate>
        </asp:UpdatePanel>
        <asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
            <ProgressTemplate>
                <div class="centered">
                    <img src="../images/ajax-loader.gif" alt="" />
                    &nbsp; Please wait...
                </div>
            </ProgressTemplate>
        </asp:UpdateProgress>
    </div>
    </form>

//ASPX.CS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.AccessControl;

namespace TESTUI
{
    public partial class PAGE2: System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                divMessage.Visible = false;
                trDiscipline.Visible = false;
                int RegulationType = Convert.ToInt32(Request.QueryString["RegulationType"].ToString());
                if (RegulationType == 3)
                {
                    trDiscipline.Visible = true;
                }
            }
        }

        private void DisplayMessage(string msg)
        {
            string strText = "alert('" + msg + "')";
            string myScript = String.Format(strText);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "MyScript", myScript, true);
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (!fuTestUploads.HasFile)
            {
                return;
            }
            int TestID = Convert.ToInt32(Request.QueryString["TestID"].ToString());
            int Type = Convert.ToInt32(Request.QueryString["Type"].ToString());
           

            string Title = txtDocumentTitle.Text;
            string FileName = System.IO.Path.GetFileName(fuTestUploads.FileName);
            string Extension = System.IO.Path.GetExtension(fuTestUploads.PostedFile.FileName);
            int Size = fuTestUploads.PostedFile.ContentLength;

            ServiceReference1.OFRTWCFServiceClient Proxy = new ServiceReference1.OFRTWCFServiceClient();

            int FileID = Proxy.AddDocument(Title, Type, FileName, Extension, Size, TestID);

            if (FileID != 0)
            {
                string path = Server.MapPath( "~/files/" + FileID.ToString());
               
                //DirectorySecurity scr = new DirectorySecurity(AppDomain.CurrentDomain.BaseDirectory.ToString(), AccessControlSections.All);
                System.IO.Directory.CreateDirectory(path);
                fuRegulationsUploads.PostedFile.SaveAs(path + "/" + fuTestUploads.PostedFile.FileName);
                txtDocumentTitle.Text = string.Empty;
                divUpload.Visible = false;
                divMessage.Visible = true;
            }
        }

        protected void lbtnUploadMore_Click(object sender, EventArgs e)
        {
            divUpload.Visible = true;
            divMessage.Visible = false;
        }
    }
}
PAGE2 END

Tuesday, May 29, 2012

File Download

To download a file
1. Create a new aspx page and code as follows


//TEST.ASPX
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestFileDownload.aspx.cs" Inherits="TESTUI.TestFileDownload" %>


//TEST.ASPX.CS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Threading;

namespace TestUI
{
    public partial class TestFileDownload: System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string FileId = Request.QueryString["FileID"].ToString();
            string FileName = Request.QueryString["FileName"].ToString();
             
            string path = Server.MapPath( "~/files/" + FileId + "/" + FileName);

            fileDownload(FileName, path);

        }

        private void fileDownload(string fileName, string fileUrl)
        {
            Page.Response.Clear();
            bool success = ResponseFile(Page.Request, Page.Response, fileName, fileUrl, 1024000);
            if (!success)
                Response.Write("Downloading Error!");
            Page.Response.End();

        }
        public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
        {
            try
            {
                FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                BinaryReader br = new BinaryReader(myFile);
                try
                {
                    _Response.AddHeader("Accept-Ranges", "bytes");
                    _Response.Buffer = false;
                    long fileLength = myFile.Length;
                    long startBytes = 0;

                    int pack = 10240; //10K bytes
                    int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1;
                    if (_Request.Headers["Range"] != null)
                    {
                        _Response.StatusCode = 206;
                        string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
                        startBytes = Convert.ToInt64(range[1]);
                    }
                    _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                    if (startBytes != 0)
                    {
                        _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
                    }
                    _Response.AddHeader("Connection", "Keep-Alive");
                 
                    _Response.ContentType = "application/octet-stream";
                    _Response.ClearContent();
                    _fileName = _fileName.Replace(" ", "");
                    _Response.AddHeader("Content-Disposition", "attachment;filename=" + _fileName);

                    br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                    int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;

                    for (int i = 0; i < maxCount; i++)
                    {
                        if (_Response.IsClientConnected)
                        {
                            _Response.BinaryWrite(br.ReadBytes(pack));
                            Thread.Sleep(sleep);
                        }
                        else
                        {
                            i = maxCount;
                        }
                    }
                }
                catch
                {
                    return false;
                }
                finally
                {
                    br.Close();
                    myFile.Close();
                }
            }
            catch
            {
                return false;
            }
            return true;
        }
    }
}



2. Pass Parameters ie FileID and FileName to download

var FileID = 1;
var  FileName = "TestFileName";
 FileName = FileName.replace(/&/g, "%26");

window.open('../TestFileDownload.aspx?FileID=' + FileID + '&FileName=' + FileName, '_blank');

Open a new page as Popup

 var page = "../TestPage.aspx";
  page += '?ID=' + TestID + '&ProjID=' + Pid ;

var $dialog = $('<div></div>')
                .html('<iframe style="border: 0px; " src="' + page + '" width="100%" height="100%"></iframe>')
                .dialog({
                    autoOpen: false,
                    modal: true,
                    height: 700,
                    width: 1200,
                    title: "Upload Documents For " + Upload,
                    buttons: {
                        "Close": function () {
                            GetDetails();
                            $dialog.dialog('close');
                        }
                    },
                    close: function (event, ui) {
                        GetDetails();
                    }
                });
            $dialog.dialog('open');
            e.preventDefault();



//Call this on a button click

Delegate

$("#divTest").delegate('table select', 'change', function () {
       var tempddl1 = $(this).parent().find("select option:selected").eq(0).text();
       var tempddl2 = $(this).parent().find("select option:selected").eq(1).text();
       alert("do something");
});


<div id="divTest">
<table><tr><td>
<select>
<option>One</option>
<option>Two</option>
</select>
Some seperation
<select>
<option>One1</option>
<option>Two1</option>
</select>

</td></tr></table>

<table><tr><td>
<select>
<option>One</option>
<option>Two</option>
</select>
 Some seperation
<select>
<option>One1</option>
<option>Two1</option>
</select>
</td></tr></table>
</div>


//to do an action on the change of any SELECT inthe parent DIV
//use delegate

Friday, May 25, 2012

Clone Function

1. USE JS
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script>

2. INSIDE DOCUMENT.READY
//START 2
//NEW CLONED ELEMENT ADDED ON CLICKING
 $("#imgAdd").click(function () {
        $("#tblTest").find("tr:last").after($("#tblTest").find("tr:last").clone());
        //IF YOU WANT TO FILL NEWILY CLONED THING WITH A TEXT
         //$("#tblTest").find("tr:last").find("input:text").val("hello test");
  });
// REMOVING LAST ADDED ITEM
 $("#imgRemove").click(function () {
            if ($("#tblTest").find("tr:first").nextAll().length >= 1) {
                 $("#tblTest").find("tr:last").remove();
             }
 });
 //END 2
//IF TO REMOVE ALL CLONED ELEMENTS USE
 //$("#tblTest").find("tr:first").remove();


3. ON THE BODY TAG
  <table id="tblTest">
        <tr>
            <td>
                Your text here &nbsp;<input type="text" />            </td>
        </tr>
    </table>
    <img alt="" src="../Images/add.gif" id="imgAdd"/>
    <img alt="" src="../Images/remove.png" id="imgRemove"/>

Multiple Scroll

1. USE THE JS FILE
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script>

2. DOCUMENT.READY

 <script type="text/javascript" language="javascript">
        $(document).ready(function () {
            $("#cbxScroll").click(function () {
                if ($('#cbxScroll').attr('checked')) {                   
                    window.setInterval("checkScroll(document.getElementById('divLeft'), document.getElementById('divRight'))", 1);
                }
                else {
                    window.setTimeout('location.reload()', 10);
                }
            });
        });

        // Multiple Scroll - START
        var lastSeen = [0, 0];
        function checkScroll(div1, div2) {
            if (!div1 || !div2) return;
            var control = null;
            if (div1.scrollTop != lastSeen[0]) control = div1;
            else if (div2.scrollTop != lastSeen[1]) control = div2;
            if (control == null) return;
            else div1.scrollTop = div2.scrollTop = control.scrollTop;
            lastSeen[0] = div1.scrollTop;
            lastSeen[1] = div2.scrollTop;
        }
        // Multiple Scroll - END
    </script>

3. INSIDE BODY TAG

<div id="divScroll" style="margin-left: 1100px">
        <input id="cbxScroll" type="checkbox" />Enable Multiple Scroll
</div>

 <div style="width: 1100px;">
        <div id="divLeft" style="width: 500px; height: 100px; border: groove gray; float: left;
            overflow: scroll">
            ssss<br />
            aaaa<br />
            cccc<br />
            dddd<br />
            zzzz<br />
            eeee<br />
            qqqq<br />
            xxxx
        </div>
        <div id="divRight" style="width: 500px; height: 100px; border: groove gray; float: left;
            margin-left: 10px; overflow: scroll">
            ssss<br />
            aaaa<br />
            cccc<br />
            dddd<br />
            zzzz<br />
            eeee<br />
            qqqq<br />
            xxxx
        </div>
    </div>

Monday, May 14, 2012

ul-li style

<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
  • One
  • Two
  • Three

if to remove these bullets, add style
ul
{
list-style-type: none;
}

One
Two
Three

To arrange these in vertical
li
{
float:left;
}