Wednesday, July 4, 2012

.map function


The .map() method is particularly useful for getting or setting the value of a collection of elements.
JQuery.map() can be used when to save as array

var ArrayVal = $('input[name="textbox1[]"]').map(function () { return $(this).val() }).get().join(',');
//the ArrayVal will be comma seperated string

//on retreival part deftn
jQuery.map( arrayOrObject, callback( value, indexOrKey ) )

$.each(ArrayVal, function (key, value) {
alert("key :"+key + " val : " + value);
});


<table>
<tr><td><input type="text" id="txt1" name="textbox1[]" /></td></tr>
<tr><td><input type="text" id="txt2" name="textbox1[]" /></td></tr>
<tr><td><input type="text" id="txt3" name="textbox1[]" /></td></tr>
<tr><td><input type="text" id="txt4" name="textbox1[]" /></td></tr>
</table>

the input type can be either text, checkbox, radio, etc

Friday, June 15, 2012

Radio button change function

/*
if there exist a group of html radio button having same name attribute their click or change can be determined as follows
*/
$("input:radio[name=Test]").change(function () {
    var value = $(this).val();
 });

Inside body tag

<input type="radio" name="Test" value="1"/>
<input type="radio" name="Test" value="2"/>
<input type="radio" name="Test" value="3"/>

Tuesday, June 12, 2012

EXPANDING COLLAPSING DIV

/*
if there a situation that need to have arrange div as blocks/bricks structure then follow this
*/

STEP1:
<link href="../Script/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" />
<script src="../Script/jquery.min.js" type="text/javascript"></script>
STEP2:

<script type="text/javascript">
        $(document).ready(function () {
            $("#expanderHead").click(function () {
                $("#expanderContent").slideToggle();
                if ($("#expanderSign").text() == "+") {
                    $("#expanderSign").html("−")
                }
                else {
                    $("#expanderSign").text("+")
                }
            });
        });
</script>
STEP3:

  <div id="expanderHead" style="cursor: pointer; background-color: Gray; width: 250px;padding-left:10px" class="ui-corner-all">
            EXPANDING COLLAPSING DIV <span id="expanderSign" style="color: Black;font-size:larger"><b>+</b></span>
        </div>
        <div id="expanderContent" style="display: none;padding-left:30px">
            content<br />
            content<br />
            content<br />
            content<br />
            content<br />
        </div>

Expand Collapse (toogle) div


/*
if there a situation that need to have arrange div as blocks/bricks structure then follow this
*/

STEP1:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js" type="text/javascript"></script>
STEP2:
<div class="divHeading">
Heading 1
</div>
<div class="divContent">
contents here 1
</div>
<div class="divHeading">
Heading 2
</div>
<div class="divContent">
contents here 2
</div>

STEP3:
.divHeading {
margin: 1px;
color: #fff;
padding: 3px 10px;
cursor: pointer;
position: relative;
background-color:#c30;
}
.divContent {
padding: 5px 10px;
background-color:#fafafa;
}

STEP4:
<script type="text/javascript">
$(document).ready(function() {
  $(".divContent").hide();
  //toggle the componenet with class msg_body
  $(".divHeading").click(function()
  {
    $(this).next(".divContent").slideToggle(500);
  });
});
</script>

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');