Wednesday, March 5, 2014

upload files


Handler :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace Payroll.Handler
{
    ///
    /// Summary description for DownloadAppraisalSheet
    ///

    public class DownloadAppraisalSheet : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            String fileName = String.Empty;
            String FolderPathQuery = String.Empty;
            fileName = HttpUtility.UrlDecode(context.Request.Params["fileName"]);
            FolderPathQuery = HttpUtility.UrlDecode(context.Request.Params["FolderPath"]);
            String FolderPath = context.Server.MapPath(FolderPathQuery + "\\" + fileName);
            FileInfo file = new FileInfo(FolderPath);
            if (file.Exists)
            {
                string ext = Path.GetExtension(FolderPath);
                string type = String.Empty;
                type = MimeType(ext);
                HttpContext.Current.Response.ContentType = type;
                HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename = {0}", System.IO.Path.GetFileName(FolderPath)));
                HttpContext.Current.Response.TransmitFile(FolderPath);
                HttpContext.Current.Response.Flush();
            }
            else {
           
           
            }
        }
        public static string MimeType(string Extension)
        {
            string mime = "application/octetstream";
            if (string.IsNullOrEmpty(Extension))
                return mime;

            string ext = Extension.ToLower();
            Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
            if (rk != null && rk.GetValue("Content Type") != null)
                mime = rk.GetValue("Content Type").ToString();
            return mime;
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

File to Save Folder : Handler

using System;
using System.IO;
using System.Web;
using System.Web.SessionState;

namespace Payroll.Handler
{
    ///
    /// Summary description for ImagePhoto
    ///

    public class ImagePhoto : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                HttpContext.Current.Response.ContentType = "text/HTML";

                string FName = "";
                string replaceundersore = "";
                string FileName = "";
                HttpFileCollection hfc = HttpContext.Current.Request.Files;

                string imagename = HttpContext.Current.Request.QueryString["filename"];
                var folderArray = imagename.Split('/');

              
                var array = imagename.Split('_');
                string path = HttpContext.Current.Server.MapPath("~/EmployeePhoto/");
                if (!Directory.Exists(path))
                {
                    System.IO.Directory.CreateDirectory(path);
                }
                for (int index = 0; index < hfc.Count; index++)
                {
                    HttpPostedFile hpf = hfc[index];
                    // change here for IE 8, as file name returns the full file path.

                    if (hpf.ContentLength >= 0)
                    {
                        if (hpf.FileName.Contains(" "))
                        {
                            replaceundersore = hpf.FileName.Replace(" ", "-");
                        }
                        else
                        {
                            replaceundersore = hpf.FileName;
                        }

                        if (replaceundersore.Contains("_"))
                        {
                            FName = replaceundersore.Replace("_", "-");
                        }
                        else
                        {
                            FName = replaceundersore.Replace("_", "-");
                        }

                        int a = hpf.ContentLength;

                        //   string RandomNo = HttpContext.Current.Session["RandomNo"].ToString();
                        // FileName = RandomNo + FName;

                        FileName = FName;
                        string finalname = "";
                        // below code is for IE 8 as it fetch the full address of file.
                        int indexof = FileName.LastIndexOf("\\");
                        if (indexof != -1)
                        {
                            FileName = FileName.Substring(indexof + 1);
                        }

                        if (array[0] != null)
                        {
                            var fn = array[0].Substring(array[0].LastIndexOf('/') + 1);
                            finalname = fn + "_" + FileName;
                        }
                        else
                        {
                            finalname = FileName;
                        }
                    
                        hpf.SaveAs(path + "/" + finalname);
                     
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}




Jquery File


 
Sample To Call
   var obj={ FolderLetter: '/AppraisalFormLetter',
    FolderSheet: '/AppraisalFormSheet',

   DownloadAppraisal: function (FolderPath,FileName) {
        $.ajaxFileUpload({
            type: "POST",
            url: "../Handler/DownloadAppraisalSheet.ashx?filename=" + FileName + "&FolderPath=" + FolderPath,
            secureuri: false,
            fileElementClass: 'dynamicFileAppraisalFormSheet2', // File uploader Class name
            async: false,
            success: function () {

            },
            error: function (data, status, e) {
                commonNotification.ErrorMessage('Error in uploading the file.');
                return false;
            }
        });


    },

/// Import : Appraisal Form Sheet
    AppraisalFormSheetImportfile: function () {

        $.ajaxFileUpload({
            type: "POST",
            url: "../Handler/AppraisalSheetHandler.ashx?filename=" + oAppraisal.AppraisalFormSheet,
            secureuri: false,
            fileElementClass: 'dynamicFileAppraisalFormSheet',
            async: false,
            success: function () {
                oAppraisal.AppraisalFlag = 1;
            },
            error: function (data, status, e) {
                commonNotification.ErrorMessage('Error in uploading the file.');
                return false;
            }
        });
        return false;
    }
}


$(document).ready(function(){


  $('.downloadsSheet').live('click', function () {
    
        oAppraisal.AppraisalFormSheet = $(this).parent().parent().parent().find('.AppraisalSheet').text();
        oAppraisal.DownloadAppraisal(oAppraisal.FolderSheet, oAppraisal.AppraisalFormSheet);

        // window.open(oAppraisal.FolderSheet + '/' + oAppraisal.AppraisalFormSheet, 'Download');
    });
    $('.downloadsLetter').live('click', function () {
        oAppraisal.AppraisalFormLetter = $(this).parent().parent().parent().find('.AppraisalLetter').text();
        oAppraisal.DownloadAppraisal(oAppraisal.FolderLetter, oAppraisal.AppraisalFormLetter);

    });



});








 //---------------------Begin Import Upload Appraisal Form Sheet ---------------------------------------------------------

            var upAFSheet = $('#upAFSheet').val(); // File upload controler
            var fileAFSheetInput = $("#upAFSheet")[0];

            try {
                var fileSheetSize = 0;
                //for IE
                if ($.browser.msie) { //before making an object of ActiveXObject,
                    //please make sure ActiveX is enabled in your IE browser
                    var objFSO = new ActiveXObject("Scripting.FileSystemObject");
                    var fileSheetPath = $("#upAFSheet")[0].value;
                    var objSheetFile = objFSO.getFile(fileSheetPath);
                    fileSheetSize = objSheetFile.size;
                    //size in kb fileSize = fileSize / 1048576; //size in mb 
                }
                else {
                    fileSheetSize = fileAFSheetInput.files[0].size;
                }
            }
            catch (err1) {
                alert('Tools -> Internet Options -> choose the Security tab Click the Custom Level button Enable the following settings: Run ActiveX controls and plug-ins Initialize and script ActiveX controls not marked as safe.');
                $('#btnCity').removeAttr('disabled');
                return false;
            }


            if (fileSheetSize > '25600000') {
                commonNotification.ErrorMessage("File exceeds 25MB.");
                return false;
            }



            //changed as not working with chrome.
            upAFSheet = upAFSheet.replace("C:\\fakepath\\", "");

            // below code is for IE 8 as it fetch the full address of file.
            var indexof = upAFSheet.lastIndexOf('\\');
            var fileName = '';
            if (indexof != -1) {
                upAFSheet = upAFSheet.substring(indexof + 1, upAFSheet.length)
            }

            var nameAFSheet1 = upAFSheet.replace(/ /g, "-");
            var nameAppraisalSheet = nameAFSheet1.replace(/_/g, "-");
            var Time = new Date();
            Time = Time.getHours() + Time.getMinutes() + Time.getSeconds() + "_";

            oAppraisal.AppraisalFormSheet = Time + nameAppraisalSheet;

            oAppraisal.AppraisalFormSheetImportfile();

            //---------------------End Import Upload Appraisal Form Sheet ---------------------------------------------------------


  

Monday, March 3, 2014

cookies

$("#btnLogin").click(function () {
        var hasError1 = true;
        if ($("#txtEmail").validationEngine('validateField', '#txtEmail')) {
            hasError1 = false;
        }
        if ($("#txtPassword").validationEngine('validateField', '#txtPassword')) {
            hasError1 = false;
        }
        if (hasError1 == true || hasError1 == "true") {
            if ($('#chkRememberEmail').attr('checked')) {
                $.cookie("cookieEmail", $('#txtEmail').val(), { expires: 30 });
                $.cookie("cookiepassword", $('#txtPassword').val(), { expires: 30 });
            }
            else {
                $.cookie('cookieEmail', null);
                $.cookie('cookiepassword', null);
            }
            user.Login();
            if (user.IsAuthenticate == 'true') {
                GetUserCompaniesMasterPage(user.SitePath);
                user.GetLoginUserFirstMenuPageID();
                Menu.PageID = user.PageId;
                Menu.SitePath = user.SitePath;
                Menu.GetPage();
            }
        }
        return false;
    });


----------------------------------------------------------------------------------------------

$("#spnLoginRemember").click(function () {
        var checkBoxes = $("#chkRememberEmail");
        checkBoxes.attr("checked", !checkBoxes.attr("checked"));
    });

----------------------------------------------------------------------------------------------------
Page load

 if ($.cookie("cookieEmail") != "" && $.cookie("cookiepassword") != "") {
        if ($.cookie("cookieEmail") != null && $.cookie("cookiepassword") != null) {
            $('#txtEmail').val($.cookie("cookieEmail"));
            $('#txtPassword').val($.cookie("cookiepassword"));
            $('#chkRememberEmail').attr('checked', 'checked');
        }
    }

----------------------------------------------------

$('#chkRememberEmail').click(function () {
        if ($('#chkbxremember').attr('checked')) {
            $('#chkbxremember').removeAttr('checked');
        }
        else {
            $('#chkbxremember').attr('checked', 'checked');
        }
    });

--------------------------------------------------------------------------------------------------------------------

Jquery.cookie1.js

/*jshint eqnull:true */
/*!
 * jQuery Cookie Plugin v1.1
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2011, Klaus Hartl
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.opensource.org/licenses/GPL-2.0
 */
(function($, document) {

    var pluses = /\+/g;
    function raw(s) {
        return s;
    }
    function decoded(s) {
        return decodeURIComponent(s.replace(pluses, ' '));
    }

    $.cookie = function(key, value, options) {

        // key and at least value given, set cookie...
        if (arguments.length > 1 && (!/Object/.test(Object.prototype.toString.call(value)) || value == null)) {
            options = $.extend({}, $.cookie.defaults, options);

            if (value == null) {
                options.expires = -1;
            }

            if (typeof options.expires === 'number') {
                var days = options.expires, t = options.expires = new Date();
                t.setDate(t.getDate() + days);
            }

            value = String(value);

            return (document.cookie = [
                encodeURIComponent(key), '=', options.raw ? value : encodeURIComponent(value),
                options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
                options.path    ? '; path=' + options.path : '',
                options.domain  ? '; domain=' + options.domain : '',
                options.secure  ? '; secure' : ''
            ].join(''));
        }

        // key and possibly options given, get cookie...
        options = value || $.cookie.defaults || {};
        var decode = options.raw ? raw : decoded;
        var cookies = document.cookie.split('; ');
        for (var i = 0, parts; (parts = cookies[i] && cookies[i].split('=')); i++) {
            if (decode(parts.shift()) === key) {
                return decode(parts.join('='));
            }
        }
        return null;
    };

    $.cookie.defaults = {};

})(jQuery, document);


-------------------------------------------------------------------------------------------------------------

handler.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace Payroll.Handler
{
    ///
    /// Summary description for FileUploader
    ///

    public class FileUploader : IHttpHandler
    {


        //Rajveer Final Change
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                HttpContext.Current.Response.ContentType = "text/HTML";

                string FName = "";
                string replaceundersore = "";
                string FileName = "";
                HttpFileCollection hfc = HttpContext.Current.Request.Files;

                string imagename = HttpContext.Current.Request.QueryString["filename"];
                var folderArray = imagename.Split('/');

                //if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/Documentfiles/") + folderArray[0]))
                //{
                //    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/Documentfiles/") + folderArray[0]);
                //}
                //if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/Documentfiles") + folderArray[0] + '/' + folderArray[1]))
                //{
                //    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/Documentfiles/") + folderArray[0] + '/' + folderArray[1]);
                //}

                //if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/Documentfiles") + folderArray[0] + '/' + folderArray[1] + '/' + folderArray[2]))
                //{
                //    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/Documentfiles/") + folderArray[0] + '/' + folderArray[1] + '/' + folderArray[2]);
                //}



                var array = imagename.Split('_');
                string path = HttpContext.Current.Server.MapPath("~/Resume/");
                if (!Directory.Exists(path))
                {
                    System.IO.Directory.CreateDirectory(path);
                }
                for (int index = 0; index < hfc.Count; index++)
                {
                    HttpPostedFile hpf = hfc[index];
                    // change here for IE 8, as file name returns the full file path.

                    if (hpf.ContentLength > 0)
                    {
                        if (hpf.FileName.Contains(" "))
                        {
                            replaceundersore = hpf.FileName.Replace(" ", "-");
                        }
                        else
                        {
                            replaceundersore = hpf.FileName;
                        }

                        if (replaceundersore.Contains("_"))
                        {
                            FName = replaceundersore.Replace("_", "-");
                        }
                        else
                        {
                            FName = replaceundersore.Replace("_", "-");
                        }

                        int a = hpf.ContentLength;

                        //   string RandomNo = HttpContext.Current.Session["RandomNo"].ToString();
                        // FileName = RandomNo + FName;


                        FileName = FName;
                        string finalname = "";
                        // below code is for IE 8 as it fetch the full address of file.
                        int indexof = FileName.LastIndexOf("\\");
                        if (indexof != -1)
                        {
                            FileName = FileName.Substring(indexof + 1);
                        }

                        if (array[0] != null)
                        {
                            var fn = array[0].Substring(array[0].LastIndexOf('/') + 1);
                            finalname = fn + "_" + FileName;
                        }
                        else
                        {
                            finalname = FileName;
                        }

                        // below code is for IE 8 as it fetch the full address of file.
                        //var indexof = name2.lastIndexOf('\\');
                        //var fileName = '';
                        //if (indexof != -1) {
                        //    name2 = name2.substring(indexof + 1, name2.length)
                        //}


                        hpf.SaveAs(path + "/" + finalname);

                        // byte[] test = ReadImageFile(FileName);
                    }


                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}



--------------------------------

   

fill in blanks

ALL Reading Blanks: Special All approaches aim to increase blood flow to areas of tension and to release painful knots opt1 muscle kn...