Showing posts with label Asp.Net. Show all posts
Showing posts with label Asp.Net. Show all posts

Sunday, 11 January 2015

Cookieless sessions in ASP.Net

In this article we are going to see the cookieless mode in Asp.net, normally each application is received in client browser by having a send and receive mode of Request and Response. For a every request from user, server maintain a session to identify whether same user is requesting the page or different user requesting the page in application. To identity the user maintain the session id for each user.

Normally the Session Id is stored in the Cookiess as in the name of ASP.NET_SessionId with a value of some random number. For the first request it will generate the number for the sessionid for the user, from the second request from the user it will maintain the same sessionId between the client and server. So to maintain the Session it is mandatory to enable the cookies in client side.

Sometimes there is a chance that the cookie's can be disabled in client Browser, Like block the application to set the data on client side , this means it is blocking the application to set the any data in client side. so now we cant able to store any cookies in client machine, so we cant able to handle the storing of session in the client machine.

We can understand this in a simple example.

Let we create a some Aspx pages from the Login screen, when the user entered the username and password save the credentials in the sessions, so we can access it any time in the application, so now each user have an session id based on that only, individual user information are segregated.

            Session["username"] = username.Text;
            Session["password"] = pwd.Text;

Later in some part of the code if we use to access the values from the session we can able to get it using the simple steps.

Session["username"].ToString();
Session["password"].ToString();

so now there is a scenario that the cookies in the client side is disabled, what will happen we cant able to get the values from Session instead we get a null value.

Below image shows the storing sessionid in cookie in the name of ASP.NET_SessionId



from the above we can see the variable name ASP.NET_SessionId

Now we going to see the state when the cookies disabled, we can do a simple  configuration steps make the session to maintain for user by specifying the web.config Cookieless="true" in sessionstate.

http://server/(session ID here)/sample.aspx

In Cookieless state session id is maintained in the Url of the application like below
session id : S(v4fzi2eitec02vnzmblvkwyu) in the url

http://localhost:17186/S(v4fzi2eitec02vnzmblvkwyu)/sample.aspx

 <sessionState cookieless="true" mode="InProc" customProvider="DefaultSessionProvider">

For every request the session id is maintained in the url with the unique value for the same user.

normally cookieless property have a six values

AutoDetect
UseDeviceProfile
UseCookies
UseUri
true
false

cookieless="AutoDetect" :
************************
 It will automatically detect the status of the cookies, whether cookies enabled in this browser or not. based on this it will decide to maintain the session value in url or in cookies.

For this it will use another cookie name and use some url concat with the application url to check whether cookies are enabled or not.

In the above u can see the cookie name AspxAutoDetectCookiesSupport in the browser, On the first load it will try to place the cookie in the browser in the name of AspxAutoDetectCookiesSupport and concat a query string in the url, to mention that this autodetect the cookies and tested by concat the following line. ?AspxAutoDetectCookieSupport=1 .with the url of application like this

http://localhost:176/(X(1)S(v4fzi2eitec02vnzmblvkwyu))/sample.aspx?AspxAutoDetectCookieSupport=1

The above url is the result url after check and redirect because , when it check for the cookie placed in the name AspxAutoDetectCookiesSupport  ,it doesnt find that so it place the session value in url

 and redirect to the same page again with result

Cookies not enabled resulted url :
http://localhost:17186/(X(1)S(v4fzi2eitec02vnzmblvkwyu))/sample.aspx?AspxAutoDetectCookieSupport=1

After a redirect to another page http://localhost:17186/(X(1)S(v4fzi2eitec02vnzmblvkwyu))/home.aspx

Cookies enabled resulted url :
http://localhost:17186/sample.aspx?AspxAutoDetectCookieSupport=1

After a redirect to another page
http://localhost:17186/home.aspx

cookieless="True":
********************
In this option we are forcing the application to use the cookieless mode and maintain the session in the Url.

cookiesless="false"
********************
In this options we are forcing the application to use the cookie based session mode.

remaining are the same one of the above we have mentioned.when we are using cookieless url based session, then we have to keep in mind that we have to maintain the session id to be passed in the url, otherwise for a new url it will generate a different session.

In Response.Redirect use the relative path to redirect with in the application, so now the session id automatically concat with the url like same below

Response.Redirect("~/home.aspx");

If you use the absolute path in the Response.Redirect then it will create a new one Response.Redirect("http;//localhost/home.aspx");

To avoid this use the uses the ApplyAppPathModifier method on the Response:

Response.ApplyAppPathModifier("/home.aspx");

Normally in this method stealing a session id possible, it gives a ways to session hijacking.

From the above information you can learn some of the information about session and cookieless sessions.



Saturday, 25 October 2014

Create a Push notification service using the SignalR with sample Rectangle Drag application from various users

              In this article we are going to see how to create a Push notification service , First of all what is an Push notification means, in generally speaks in some social networking sites you have seen that updates of others persons notifies you in real time data, how it is notifies an client ? when the server reaches any changes from the clients then it is pushes the changes from the server to all users, ie is known as Push notification, or server to client push mechanism.

    First in this sample we are going to create a application which an rectangle that can be drag and moved to any part of the browser using jquery UI plugin. After creating the Application launch the App in two different browers or more than that to test the Push notification, Now where is the Push notification present here ?

    Whenever an Rect is drag and move in any browser , then the position of the Rect in that browser while moving is indicates to all clients who are al1 using that link other than same browser , so now the position of that Rect is sends to all browser as notifications, in client part when we receive the updates we are moving the Rect of the browser to that position along with some text indication.

     First we using the IE to drag , then we can see the push notification result in Chrome browser that Rect moves along with some text info indication, Then in the second term now try to move in Chrome browser now we can see that Rect in IE starts move along with some text information indication.


First create a Empty MVC project , Then install a SignalR from the Manage-Nuget-Packages , Now you can see that two Js are download in  scripts folder.

1. Jquery.min.js 
2. Jquery.SignalR.min.js

In this sample we are using the Jquery UI along with this.

1.  jquery-1.6.4.min.js
2.  jquery.signalR-2.1.2.min.js
3.  jquery-ui.min-1.11.1.js

Dowload this Js files from Jquery exclude the Signalr, we can get the SignalR from the NugetPackages

Create a class called Startup to indicates that this a startup class 


using Microsoft.Owin;
using Owin;
using MyWebApplication;

[assembly: OwinStartup(typeof(MyWebApplication.Startup))]
namespace MyWebApplication
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}



Then Starts write the Server and client code for the notifications

1. Create a Cs file to create a Hub.
2. Create a Html file to create a client code.

Now add the following lines in the Html first before start the sample

     <script src="Scripts/jquery-1.6.4.min.js"></script>
    <script src="Scripts/jquery-ui.min-1.11.1.js"></script>

    <script src="Scripts/jquery.signalR-2.1.2.min.js"></script>

Then start write the code in Hub cs, Create a class which must be inherit from the Hub class, then implement some function which can be called from the client.Then create an method which can be called from server to push data , but how the server knews the method, to avoid this problem all method indication in server or client must be dynamic, ie is method are binded and called at runtime.

In client side add a script tag which is created at runtime and added.
      <script src="signalr/hubs"></script>

some times you can see that this script is not found or showing 404 error number , this can resolve by following steps 

This issue is generally due to a missing or invalid script reference to the auto-generated Hub JavaScript proxy at '~/signalr/hubs'.

Please make sure that the Hub route is registered before any other routes in your application.

In ASP.NET MVC 4 you can do the following:

      <script src="~/signalr/hubs"></script
some times ~/ doesnt need in my app also doesnt needed.

If you're writing an ASP.NET MVC 3 application, make sure that you are using Url.Content for your script references:

        <script src="@Url.Content("~/signalr/hubs")"></script>

If you're writing a regular ASP.NET application use ResolveClientUrl for your script references or register them via the ScriptManager using a app root relative path (starting with a '~/'):

<script src='<%: ResolveClientUrl("~/signalr/hubs") %>'></script>

Now  
In client create a method updateContainer to push the data from the server to client, then create a method in server MoveContainer to indicates the changes from the client to server.create a hub name SmartMoveHub and gives it a custom name by using attribute HubName.

When we run the application we can see that js signalr/hubs that has created at runtime , which consits of many information regarding the server communication from the client.

Normally Signalr uses the websockets,server sentevents for communication [HTML5], if it is not avaliable for the client then it tries for forever frames,Ajax Long polling for comet long held connection.

HTML5
***************
Websockets,
Server Sent Events

LongHeld connection
*********************
Forever Frames
Ajax LongPolling


HTML Code:
***************


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>

    <style type="text/css">
        #divcontainer{
            width:100px;
            height:100px;
            background-color:orangered;
            cursor:move;
        }
    </style>

</head>
<body>
    <div  id="datapush">
       
    </div>
    <div id="divcontainer">

    </div>

    <script src="Scripts/jquery-1.6.4.min.js"></script>
    <script src="Scripts/jquery-ui.min-1.11.1.js"></script>
    <script src="Scripts/jquery.signalR-2.1.2.min.js"></script>
   
    <script src="signalr/hubs"></script>
    <script type="text/javascript">
        $(document).ready(function () {

            var smartmovehub = $.connection.smartMove;

            smartmovehub.client.updateContainer = function (x, y) {
                $('#datapush').html('Rect is moved to Top :' + x + ', Left :' + y + ' By Push Notification From other users');
                $('#divcontainer').css('top', x).css('left', y);
            };

            $.connection.hub.start().done(function () {

                $('#divcontainer').draggable({
                    drag: function (evt,ui) {
                        smartmovehub.server.moveContainer(ui.position.top,ui.position.left);
                    }
                });
               
            });

        });
    </script>



</body>

</html>

Hub Code:
**************

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;

namespace SampleSignalR
{
    [HubName("smartMove")]
    public class SmartMoveHub:Hub
    {
        public void MoveContainer(int x, int y)
        {
            Clients.Others.updateContainer(x, y);
        }
    }

}


Startup code:
**************


using Microsoft.Owin;
using Owin;
using MyWebApplication;

[assembly: OwinStartup(typeof(MyWebApplication.Startup))]
namespace MyWebApplication
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}



Open the Url in Different Browser like IE and Chrome,Now
Drag the Rectangle In IE Browser, you can see that Rect in Chrome gets change the Postion by indication the position in Chrome



Now Drag the Rectangle in Chrome , now you can see the same changes in the IE



This kind of Push notification services using the Chatting applications , notification etc. From this post  you can able to read an  information about Signalr and it Usage in Real time applications.










Saturday, 17 May 2014

Difference between the ASP.Net MVC and ASP.Net WebForm

     In this article we are going to see the difference between the asp.net MVC and asp.net Webform, Most of the time many have clarifications on basic things but when try to really find the difference it is hard for them to tell all the things. Asp.net MVC is a template which follows the MVC format. Ok, Let we see the difference.

ASP.Net MVC:
*************

  1. This follows the MVC pattern model (model, view, controller)
  2. View are loosely coupled, view and logic are kept separately
  3. Have partial views to make a commonly reused code separately.
  4. No state management techniques
  5. Route based url, url are mapped in to controllers and there actions instead of file.
  6. Not based on Physical file redirecting.
  7. Have Layout to have consistent look and feel.


ASP.Net Web form:
****************

  1. This follows the Event based model 
  2. aspx page is tightly coupled with the code behind aspx.cs
  3. Have the User control for have commonly reused code.
  4. Have state management like session and View state
  5. Filename must be mention in the Url for mapping the physical file for request.
  6. Based on physical file redirecting.
  7. Have master pages to have consistent look and feel

From this article you can learn the difference between the ASP.NET MVC and Webform.



Friday, 16 May 2014

Convert Ms Document in to Pdf in ASP.Net C#

In this article we are going to see how to convert the MsDoc in to PDF, for this we have to install one addin for the MsOffice Then we have to use the MsWord class to access the word object 

Click here to install or Download the Add-In for the Microsoft office to convert the Doc to PDF

After Install the Add-in start writing the code in Aspx page to upload the Document to the server and then convert it to do this we have to use the file upload control.Drag and Drop the File upload control and A Button control, then the design will look like following image

Sample Word document content:

.

Add the reference to the Microsoft.Office.Interop.Word

Then Paste the following code in the button click of the upload control.

using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class Sample : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }


        protected void Button1_Click(object sender, EventArgs e)
        {
            FileUpload1.SaveAs(Server.MapPath("~/Doc/" + FileUpload1.FileName));

            string sourcefile = Server.MapPath("Doc\\") + FileUpload1.FileName;
            string outputfile = Server.MapPath("Doc\\") + FileUpload1.FileName.Replace(".doc", ".pdf").Replace(".pdfx", ".pdf");
           
            if(outputfile!=null || outputfile!="")
            {
                Application wordApplication = new Application();
                Document wordDocument = null;
                object paramSourceDocPath = sourcefile;

                object paramMissing = System.Reflection.Missing.Value;
                string paramExportFilePath = outputfile;
               
               
                WdExportFormat paramExportFormat = WdExportFormat.wdExportFormatPDF;
                bool paramOpenAfterExport = false;
                WdExportOptimizeFor paramExportOptimizeFor = WdExportOptimizeFor.wdExportOptimizeForPrint;
                WdExportRange paramExportRange = WdExportRange.wdExportAllDocument;
                int paramStartPage = 0;
                int paramEndPage = 0;
                WdExportItem paramExportItem = WdExportItem.wdExportDocumentContent;
                bool paramIncludeDocProps = true;
                bool paramKeepIRM = true;
                WdExportCreateBookmarks paramCreateBookmarks = WdExportCreateBookmarks.wdExportCreateWordBookmarks;
                bool paramDocStructureTags = true;
                bool paramBitmapMissingFonts = true;
                bool paramUseISO19005_1 = false;
                try
                {
                    wordDocument = wordApplication.Documents.Open(ref paramSourceDocPath, ref paramMissing, ref paramMissing, ref paramMissing,
                        ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing,
                        ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing);

                    if (wordDocument != null)
                        wordDocument.ExportAsFixedFormat(paramExportFilePath, paramExportFormat, paramOpenAfterExport, paramExportOptimizeFor,
                            paramExportRange, paramStartPage, paramEndPage, paramExportItem, paramIncludeDocProps, paramKeepIRM,
                            paramCreateBookmarks, paramDocStructureTags, paramBitmapMissingFonts, paramUseISO19005_1, ref paramMissing);
                }
                catch (Exception ex)
                {
                }
                finally
                {
                    if (wordDocument != null)
                    {
                        wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
                        wordDocument = null;

                    } if (wordApplication != null)
                    {
                        wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing); wordApplication = null;
                    }

                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
            }
        }


   
    }

}

we have to close and quit the word document, wordapplication otherwise it will remain in the memory.

Now Run the application and choose one doc file and click upload, at the first time it will raise exception because you have to create a doc folder in the server application path, then now try again the doc is uploaded to the under the folder doc and converted pdf is saved in the same directory under the same name.

Output Pdf




From this article you can learn how to convert the document to Pdf using Microsoft Add-in.