Wednesday, April 23, 2014

Java Script Tutors with Asp.net

While Using showModalDialog (window.showModalDialog) of JavaScript
you can close Current Child Window and Refresh Parent Page Using Following:

set location of current window to opener and refresh current window.

This will give Location (URL) of parent window who opened child window.
window.opener.location

function ClickbtnBindGridView()
{
window.opener.location.href = window.opener.location;
window.close();
}

and we can call using Script Manager in asp.net Code Behind :

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), Guid.NewGuid().ToString(), "ClickbtnBindGridView();", true);

Above Functions Works well For  Firefox and Chrome

for Internet Explorer we can use :

On Parent Form :
JavaScript:
<script type="text/javascript">
    function OpenChildWindow() {
        //open a new dialog window
        var sFeatures = "dialogHeight: 200px;";
        sFeatures += "dialogWidth: 400px;";
        sFeatures += "center: yes;";
        sFeatures += "edge: sunken;";
        sFeatures += "scroll: no;";
        sFeatures += "status: yes;";
        sFeatures += "resizeable: no;";
        var url = 'ChildForm.aspx?SomeValue=12345';

        entryWindow = window.showModalDialog(url, 'ChildForm', sFeatures);
        if (entryWindow == true) {
            alert("Watch for CurrTime & ChildWin labels," +
                  " its going to update as new window saved.");
            //this would trigger the update panels
            //update as the button is part of the UP
            window.document.getElementById('btnHiddenForUpdate').click();
        }
        else {
            //No change will happen to the parent page as child page did nothing
            alert("Nothing on the page will change " +
                  "as the new child window was cancelled.");
        }
    }
</script>


HTML :
<form id="form1" runat="server">
    <asp:ScriptManager ID="smParent" runat="server" />
       <div id="divUpdatePanel">           
             <asp:UpdatePanel ID="upParent" runat="server">
                <ContentTemplate>
                    <asp:Label ID="lblCurrTime" runat="server" Text="CurrTime:">
                    </asp:Label> <br />
                    <asp:Label ID="lblChildWinValue" runat="server"
                               Text="ChildWin Value:"></asp:Label><br />
                    <br /><a href="javascript:OpenChildWindow();">
                             Click to open the Child Window</a><br />
                    <input type="button" id="btnHiddenForUpdate"
                           runat="server" style="display:none"
                           onserverclick="btnHiddenForUpdate_ServerClick" />
                </ContentTemplate>
            </asp:UpdatePanel>
       </div>
       <div id="divNormalUpdatePanel">
            <asp:Panel ID="pnlFullPostback" runat="server">
                <asp:Label ID="lblPageLoadTime" runat="server"
                 Text="PageLoadTime:"></asp:Label>
            </asp:Panel>
       </div>
</form>


Child Form can be 2 ways
  Method 1
JavaScript:
  <script type="text/javascript">
        function WindowClose() {
        
            window.returnValue = true;
            window.close();
        }
        function WindowCancel() {
         
            window.returnValue = false;
            window.close();
        }
</script>


HTML:
<form id="form1" runat="server">
    <div>
      <input id="Button2" type="button" value="Update" runat="server" onclick="WindowClose();"   title="CLose Button" />
        <input type="button"  value="Close" onclick="WindowCancel();" title="CLose Button" />
    
    </div>
    </form>


Method 2
JavaScript
<script  type="text/javascript">

function UpdateClick() {
    window.returnValue = true;
    window.close();

}
</script>


HTML
 <asp:Button ID="btnUpdate" Text="Update" runat="server" CssClass="Button" OnClick="btnUpdate_Click" />
                   <asp:Button ID="btnCancel" Text="Cancel" runat="server" CssClass="Button" OnClientClick="javascript:window.close();" />

Sunday, April 13, 2014

Tutorial: How to do Cookieless ASP.NET Forms Authentication

Background

A cookie is a piece of text that a Web site can park on a user's machine to be retrieved and reused later. The information stored consists of harmless name-value pairs.
Cookies store the ID of the session and browsers transparently move their contents back and forth between the Web server and the local user's machine. When a cookie-enabled browser receives a response packet, it looks for attached cookies and stores their content to a text file in a particular folder in the local Windows directory. Next, when the browser sends a request to the site, it looks in the cookies folder for a cookie that originated from that domain. If found, the cookie is automatically attached to the outgoing packet. The cookie hits the server application where it is detected, extracted, and processed. In the end, cookies make Web sites much easier to navigate because they provide the illusion of continuity on top of a user's experience that necessarily spans over multiple requests.
 

Problem of Cookies

Cookies were alleged to contain dangerous programs capable of stealing valuable information even beyond the physical boundaries of the machine. Cookies are not programs and never run like programs; other software that gets installed on your machine, though, can use the built-in browser support for cookies to do bad things remotely. Furthermore, cookies are at risk of theft. Once stolen, a cookie that contains valuable and personal information can disclose its contents to malicious hackers and favor other types of Web attacks. In summary, by using cookies you expose yourself to risks that can be zeroed off otherwise
 
Because cookies are data written to your browser from the server. This prefigures some potential security risks and an overall situation less then ideal. (In some cases and countries, it's even illegal for an application to require cookies to work.)
 
If you take a look at your site's statistics regarding browsers used to access pages, you might be surprised to discover that a significant share of users connect with cookies disabled. This poses a point for you as a developer.
 

Solutions

The main reason for cookieless sessions in ASP.NET is that users—for whatever reasons—may have cookies disabled on their browsers. Like it or not, this is a situation you have to face if your application requires session state. Cookieless sessions embed the session ID in the URL and obtain a two-fold result. On the one hand, they provide a way for the Web site to correctly identify the user making the request. On the other hand, though, they make the session ID clearly visible to potential hackers who can easily steal it and represent themselves as you.
 
To implement cookieless sessions you don't have to modify your programming model—a simple change in the web.config file does the trick—but refactoring your application to avoid storing valuable information in the session state is strongly recommended too. At the same time, reducing the lifetime of a session to less than the default 20 minutes can help in keeping your users and your site safe.
 

How to implement cookieless authentication in ASP.net?

 
Step 1: Adjust the web.config file.
Interestingly enough, you don't have to change anything in your ASP.NET application to enable cookieless sessions, except the following configuration setting.
<sessionState cookieless="true" />
 
<authentication mode="Forms">
<forms loginUrl="Login.aspx" protection="All" timeout="30" name=".ASPXAUTH" path="/" requireSSL="false" slidingExpiration="true" defaultUrl="default.aspx"
cookieless="UseUri" enableCrossAppRedirects="true"/>
</authentication>
 
Step 2: Adjust all of the URL navigations in aspx files.
Be careful, the following code breaks the session:
<a runat="server" href="/test/page.aspx">Click</a>
 
To use absolute URLs, resort to a little trick that uses the ApplyAppPathModifier method on the HttpResponse class. The ApplyAppPathModifier method takes a string representing a URL and returns an absolute URL that embeds session information.
<a runat="server"
href=”<% =Response.ApplyAppPathModifier("page.aspx")%>” >Click</a>
 
Step 3: Adjust all of the URL navigations in aspx.cs files.
If the URL is set in the code, you need to do it in the following way:
 
this.Tab2.Url = Response.ApplyAppPathModifier("Page.aspx");
Step 4: Adjust all of the authentication method in your login page.
 
After the username and password have been verified, we need to do the following things to set the cookieless login state.
 
// Create a new ticket used for authentication
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // Ticket version
username, // Username associated with ticket
DateTime.Now, // Date/time issued
DateTime.Now.AddMinutes(10), // Date/time to expire
true, // "true" for a persistent user cookie
string.Empty, // User-data
string.Empty // Path cookie valid for
);
// Hash the ticket
string hash = FormsAuthentication.Encrypt(ticket);
//The following is the cookie way for your reference
//HttpCookie cookie = new HttpCookie(
// FormsAuthentication.FormsCookieName, // Name of auth cookie
// hash); // Hashed ticket
// Add the cookie to the list for outgoing response
//Response.Cookies.Add(cookie);
 
//The following is the cookieless way we want:
FormsAuthentication.SetAuthCookie(username, false); //this set the cookieless data. Response.Redirect(Response.ApplyAppPathModifier(Request.QueryString["ReturnUrl"]));