Wednesday, December 30, 2015

Detect requesting device type and redirect in ASP.NET and JQuery, Java script

In ASP.NET WebForms we have an option to check whether the requested device is Mobile or not – Request.IsMobileDevice, which is not appropriate in most of the scenarios! I mean, it’s failing to detect the device type correctly!
Now, we discuss about custom solution for ASP.NET WebForms – detect the device type and redirecting!
Suppose if you have two versions of your web application – Mobile & Desktop, and you may wish to get the device information  and redirect the user to the appropriate web app based on the requested device

    private string DeviceName()
    {
        string DeviceName = "Other"; // Desktop
        string[] MobileDevices = new string[] { "iPhone", "iPad","iPod","BlackBerry",
                                                     "Nokia", "Android", "WindowsPhone",
                                                     "Mobile"
                                                     };
        foreach (string MobileDeviceName in MobileDevices)
        {
            if ((Request.UserAgent.IndexOf(MobileDeviceName, StringComparison.OrdinalIgnoreCase)) > 0)
            {
                DeviceName = MobileDeviceName;
                break;

            }
        }//end:foreach loop

        return DeviceName;
    }


if (DeviceName() == "Android")
        {
            //Response.Redirect("Mobile/Home.aspx");
            lblMesage.Text = "Mobile Device    " + DeviceName();
        }
        else
        {
            //Response.Redirect("Desktop/Home.aspx");
            lblMesage.Text = "other device";
        }

==================================

in Javascript 

 $(document).ready(function () {           
            var ua = navigator.userAgent.toLowerCase();
            var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
            if (isAndroid) {
                 window.location= "http://www.murlid05.blogspot.com";
            }

});

Monday, August 24, 2015

Warn User if Back is Pressed

You may want to warn user if Back button is pressed. This works in most of the cases. If you have some unsaved form data, you might want to trigger a warning message to user if Back button is pressed.
Following Javascript snippet will add a warning message in case Back button is pressed:

window.onbeforeunload = function() { return "You work will be lost."; };


for detail click here

Disable Back Button in Browser using JavaScript

We can disable the back navigation by adding following code in the webpage. Now the catch here is that you have to add this code in all the pages where you want to avoid user to get back from previous page. For example user follows the navigation page1 -> page2. And you want to stop user from page2 to go back to page1. In this case all following
<SCRIPT type="text/javascript">
    window.history.forward();
    function noBack() { window.history.forward(); }
</SCRIPT>
</HEAD>
<BODY onload="noBack();"
    onpageshow="if (event.persisted) noBack();" onunload="">


The above code will trigger history.forward event for page1. Thus if user presses Back button on page2, he will be sent to page1. But the history.forward code on page1 pushes the user back to page2. Thus user will not be able to go back from page1.

Thursday, August 13, 2015

Show Last Visited Pages from Cookie using Javascript & JQuery Or Store User Latest Visit Pages in Cookie

You need to just add this js code on you page and provide the class id where you wanted to show your result only, rest of the thing my code will do

/************By Murli on 12 Aug 2015 ********************/
/*******Purpose: To show last 4 visited pages using object & array on the site***************/
/********* http://murlid05.blogspot.in/ *****************/

var template = { Title: "", Desc: "Temp Name", Url: "" };

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString() + "; path=/";
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return "";
}

function checkCookie(PageTitle, PageDescription, PageUrl) {

    var newArray = new Array(); /*Temp Array to generate cookie*/
    var tempObject = ""; /*To hold the already exists page data*/
    var arrObject;  /*To store cookie value in a object*/

    if (getCookie("RecentViewList") != '') {
        arrObject = $.parseJSON(getCookie("RecentViewList")); /* Convert string to object */
    }

    if (arrObject != null) {
        $.each(arrObject, function (index, value) {
            if (PageUrl == value.Url) {
                tempObject = { Title: PageTitle, Desc: PageDescription, Url: PageUrl };
            } else {
                newArray.push({ Title: value.Title.toString(), Desc: value.Desc.toString(), Url: value.Url.toString() });
            }
        });
    }

    if (tempObject != "") {
        newArray.push(tempObject);
    } else {
        if (newArray.length > 3) newArray.splice(0, 1); /*Remove most recent value from array*/
        tempObject = { Title: PageTitle, Desc: PageDescription, Url: PageUrl };
        newArray.push(tempObject);
    }

    var stringObj = JSON.stringify(newArray); /*Convert Array to JSON formated string*/
    setCookie("RecentViewList", stringObj, 1);

    FnShowonPage(); /*Draw on a page*/
}


function FnShowonPage() {
    var arr = getCookie("RecentViewList");
    var Description = "";
    arr = $.parseJSON(arr);
    var HtmlData = "<a class='closerightFloater' href='javascript:;'></a><ul class='browserVisitlist'>";
    $.each(arr, function (index, value) {
        Description = (value.Desc.length > 120) ? (value.Desc.substring(0, 120) + "....") : value.Desc;
        HtmlData += "<li><a class='recentLinks' title=" + value.Title + "' href='" + value.Url + "' >" + value.Title.substring(0, 25) + "</a><p>" + Description + "</p></li>";
    });
    HtmlData += "</ul>";
    $(".rightPanelbrowsebig").html(HtmlData);
}


$(document).ready(function () {
    var PageDescription = $("meta[name='description']").attr("content");
    var PageTitle = document.title.replace("é","e");
    var PageUrl = window.location.href;

    if ((typeof document.title !== "undefined") && (typeof $("meta[name='description']").attr("content") !== "undefined")) {
        PageDescription = (typeof $("meta[name='description']").attr("content") !== "undefined") ? PageDescription : "No";
        // alert(PageDescription + "  ::Under On load:   " + PageTitle + "  ::::     " + PageUrl);
        checkCookie(PageTitle.toString(), PageDescription.toString(), PageUrl.toString());
    }
    else {
        //alert("somthing wrong   :   " + PageTitle);
    }
})

Wednesday, July 8, 2015

Download excel report in MVC


public ActionResult Download(string working)
        {
           // return View();
            ViewBag.Message = "Welcome to Report Generation!";
            Temp cm = new Temp();
            List model = cm.getAll();
            GridView gv = new GridView();
            gv.DataSource = model;
            gv.DataBind();
            Session["temp"] = gv;


            if (Session["temp"] != null)
            {
                return new DownloadFileActionResult((GridView)Session["temp"], "temp.xls");
            }
            else
            {
                //Some kind of a result that will indicate that the view has 
                //not been created yet. I would use a Javascript message to do so. 
                return View(model);
            }
            //return View(model);
        }
 public class Temp
    {
        public int id { get; set; }
        public string Name { get; set; }
        public Temp() { }
        Temp(int _id,string _name)
        {
            id = _id;
            Name = _name;
        }
        public List getAll()
        {           
            List list = new List();
            list.Add(new Temp(1, "Murli"));
            list.Add(new Temp(3, "Deepak"));
            list.Add(new Temp(5, "Prakash"));
            list.Add(new Temp(7, "Mahandar"));
            return list;
        }
    }

public class DownloadFileActionResult : ActionResult
{
    public GridView ExcelGridView { get; set; }
    public string fileName { get; set; }
    public DownloadFileActionResult(GridView gv, string pFileName)
    {
        ExcelGridView = gv;
        fileName = pFileName;
    }

    public override void ExecuteResult(ControllerContext context)
    {

        //Create a response stream to create and write the Excel file
        HttpContext curContext = HttpContext.Current;
        curContext.Response.Clear();
        curContext.Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
        curContext.Response.Charset = "";
        curContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        curContext.Response.ContentType = "application/vnd.ms-excel";

        //Convert the rendering of the gridview to a string representation 
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        ExcelGridView.RenderControl(htw);

        //Open a memory stream that you can use to write back to the response
        byte[] byteArray = Encoding.ASCII.GetBytes(sw.ToString());
        MemoryStream s = new MemoryStream(byteArray);
        StreamReader sr = new StreamReader(s, Encoding.ASCII);

        //Write the stream back to the response
        curContext.Response.Write(sr.ReadToEnd());
        curContext.Response.End();
    }
}  

Use multiple submit button on MVC


Create two submit button inside the form
<form action="index"> <input type="submit" name="submitButton" value="Filter" /> <input type="submit" name="submitButton" value="Download" /> </form>
on the controller action use switch case to target the final action command
public ActionResult Index(StatisticsReport stc, string submitButton) { switch (submitButton) { case "Filter" : break; case "Download": return RedirectToAction("Download", list); } } public ActionResult Download(List list) { return View(); }