Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Friday, 14 December 2018

Custom Controller Factory in ASP.NET MVC

When ASP.NET MVC receives a request, it needs to manage how to handle it with a specific controller and the action methods in it. The component that is responsible to map an incoming request to a specific controller and decide which controller to use is controller factory. There is a default controller factory in ASP.NET MVC that maps incoming requests to a controller with a Controller postfix.

        Request  --> Routing System ---> Controller Factory ---> Invoke Controller
The built-in controller factory is the registered controller factory by default and is implemented in DefaultControllerFactory class. Also it’s possible to extend its behavior with minor changes by deriving from this base class.
But in some circumstances you may need to have a fully customized behavior for your controller factories. One common example is when you use Dependency Injection frameworks where you need to use a customized factory. Fortunately, most of the DI frameworks provide such a customized controller factory out of the box, but if you were faced with a case to implement such a factory, you can implement the IControllerFactory interface and register your own custom controller factory.
IControllerFactory is an interface with two methods:
  • CreateController: Getting the RequestContext instance and the string value of controller name, returns the controller to be used.
  • ReleaseController: Gets a controller instance and releases this controller.
Implementation of a controller factory is comparatively easy, and can be done with less amount of work to be done.
In this post I implement a basic controller factory that loads controllers based on the user’s language, so a specific controller can be loaded for a specific language. In this sample application, I define the type name of controllers in web configuration file based on a pattern that corresponds to a specific culture, and implement a controller factory that loads the appropriate controllers group based on the client’s preferences.
First I define my type patterns in my configuration file as application settings. Here I have two cultures: if the user uses Farsi, then the Farsi controllers will be loaded, otherwise the default English language will be used.
<appSettings>
  <add key="EnglishControllerTypePattern" value="IControllerFactorySample.Controllers.En.{0}"/>
  <add key="FarsiControllerTypePattern" value="IControllerFactorySample.Controllers.Fa.{0}"/>
</appSettings>

Now I write my controller factory by implementing the IControllerFactory interface and its two methods.
using System;
using System.Configuration;
using System.Web.Mvc;
using System.Web.Routing;
 
namespace IControllerFactorySample.ControllerFactories
{
    public class CustomControllerFactory : IControllerFactory
    {
        #region IControllerFactory Members
 
        public IController CreateController(RequestContext requestContext, string controllerName)
        {
            if (string.IsNullOrEmpty(controllerName))
                throw new ArgumentNullException("controllerName");
 
            string language = requestContext.HttpContext.Request.Headers["Accept-Language"];
 
            string controllerType = string.Empty;
 
            if (language == "fa-IR")
                controllerType = string.Format
                    (ConfigurationManager.AppSettings["FarsiControllerTypePattern"], controllerName);
            else
                controllerType = string.Format
                    (ConfigurationManager.AppSettings["EnglishControllerTypePattern"], controllerName);
 
            IController controller = Activator.CreateInstance(Type.GetType(controllerType)) as IController;
 
            return controller;
        }
 
        public void ReleaseController(IController controller)
        {
            if (controller is IDisposable)
                (controller as IDisposable).Dispose();
            else
                controller = null;
        }
 
        #endregion
    }
}

In the CreateController function, I detect the client’s language using the HTTP headers of the request, and load the appropriate type name based on the user’s culture. Then I use reflection APIs to load the type and create an instance of the controller to be returned. Note that this implementation doesn’t mandate the Controller postfix for controller names, so rather than defining my Home controller as HomeController class, I just can use Home name. I have defined my controllers in Fa and En sub-folders inside Controllers folder, so my controller factory can load them based on the type name patterns. Besides, in the ReleaseController method, I dispose the controller as expected.
The third and last step is to add this controller factory as the default factory to ASP.NET MVC. This can be done in Global.asax and its Application_Start method where I use ControllerBuilder.SetControllerFactory to add my factory type as the default controller factory to ASP.NET MVC.
using System.Web.Mvc;
using System.Web.Routing;
using IControllerFactorySample.ControllerFactories;
 
namespace IControllerFactorySample
{
    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
            routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
            );
 
        }
 
        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
 
            ControllerBuilder.Current.SetControllerFactory(typeof(CustomControllerFactory));
        }
    }
}
As you see, building a controller factory is very straightforward and you can get it done in a few simple steps. If I run the application and set my preferred language to Farsi, then Farsi controllers will be used to serve the requests, otherwise English controllers will be loaded.



Continue Reading →

Thursday, 13 December 2018

ASP.NET MVC extensibility points

13 ASP.NET MVC extensibility points you must know

One of the main design principles ASP.NET MVC has been designed with is extensibility. Everything (or most of) in the processing pipeline is replaceable so, if you don’t like the conventions (or lack of them) that ASP.NET MVC uses, you can create your own services to support your conventions and inject them into the main pipeline.

In this post I’m going to show 13 extensibility points that every ASP.NET MVC developer should know, starting from the beginning of the pipeline and going forward till the rendering of the view.

1. RouteConstraint
Usually you could put some constrains on url parameters using regular expressions, but if your constrains depend on something that is not only about the single parameter, you can implement the IRouteConstrains’s method and put your validation logic in it.

One example of this is the validation of a date: imagine an url that has year, month and date on different url tokens, and you want to be able to validate that the three parts make a valid date.
Link 1Link 2

2. RouteHandler
Not really specific to ASP.NET MVC, the RouteHandler is the component that decide what to do after the route has been selected. Obviously if you change the RouteHandler you end up handling the request without ASP.NET MVC, but this can be useful if you want to handle a route directly with some specific HttpHanlders or even with a classic WebForm.
ReadMore: IRoutehandler asp.net mvc

3. ControllerFactory
The controller factory is the component that, based on the route, chooses which controller to instantiate and instantiate it. The default factory looks for anything that implements IController and whose name ends with Controller, and than create an instance of it through reflection, using the parameter-less constructor.

But if you want to use Dependency Injection you cannot use it, and you have to use a IoC aware controller factory: there are already controller factory for most of the IoC containers. You can find them in MvcContrib or having a look at the Ninject Controller Factory.

4. ActionInvoker
ActionInvoker is responsible for invoking the action based on it’s name. The default action invoker looks for the action based on the method name, the action name and possibly other selector attributes. Then it invokes the action method together with any filter defined  and finally it executes the action result.

If you read carefully you probably understood that most of the execution pipeline is inside the logic of the default ControllerActionInvoker class. So if you want to change any of these conventions, from the action method’s selection logic, to the way http parameters are mapped to action parameters, to the way filters are chosen and executed, you have to extend that class and override the method you want to change.

A good example of this, is the NinjectActionInvoker I developed to allow injection of dependencies inside filters.

5. ActionMethodSelectorAttribute
Actions, with the default action invoker, are selected based on their name, but you can finer tune the selection of actions implementing your own Method Selector. The framework already comes with the AcceptVerbs attribute that allows you to specify to which HTTP Verb an action has to respond to.

A possible scenario for a custom selector attribute is if you want to choose one action or another based on languages supported by the browser or based on the type of browser, for example whether it is a mobile browser or a desktop browser.

6. AuthorizationFilter
These kind of filters are executed before the action is executed, and their role is to make sure the request is “valid”.

There are already a few Authorization filters inside the framework, the most “famous” of which is the Authorize attribute that checks whether the current user is allowed to execute the action. Another is the the ValidateAntiForgeryToken that prevents CSRF attacks. If you want to implement your own authorization schema, the interface you have to implement is IAuthorizationFilter. An example could be the hour of the day.

7. ActionFilter
Action Filters are executed before and after an action is executed. One of the core filters is the OutputCache filter, but you can find many other usages for this filter. This is the most likely extension point you are going to use, as, IMHO, it’s critical to a good componentization of views: the controller only has to do its main stuff, and all the other data needed by the view must be retrieved from inside action filters.

8. ModelBinder
The default model binder maps HTTP parameters to action method parameters using their names: a http parameter named user.address.city will be mapped to the City property of the Address object that itself is a property of the method parameter named user. The DefaultModelBinder works also with arrays, and other list types.

But it can be pushed even further: for example you might use it to convert the id of the person directly to the Person object looking up on the database. This approach is explained better in the following post Timothy Khouri (aka SingingEels): Model Binders in ASP.NET MVC. The code is based on the preview 5, but the concept remains the same.

9. ControllerBase
All controllers inherit from the base class Controller. A good way to encapsulate logic or conventions inside your actions is to create you own layer supertype and have all your controllers to inherit from it.

10. ResultFilter
Like the ActionFiters, the ResultFilters are execute before and after the ActionResult is executed. Again, the OutputCache filter is an example of a ResultFilter. The usual example that is done to explain this filter is logging. If you want to log that a page has been returned to the user, you can write a custom RenderFilter that logs after the ActionResult has been executed.

11. ActionResult
ASP.NET MVC comes with many different kind of results to render views, to render JSON, plain text, files and to redirect to other actions. But if you need some different kind of result you can write your own ActionResult and implement the ExecuteResult method. For example, if you want to send a PDF file as result you could write your own ActionResult that use a PDF library to generate the PDF. Another possible scenario is the RSS feed: read more about how to write a RssResult in this post.

Look at implementing a custom action result when the only peculiarity is how the result is returned to the user.

12. ViewEngine
Probably you are not going to write your own view engine, but there are a few that you might consider using instead of the default WebForm view engine. The most interesting one, IMHO, is Spark.

But if you really want to write your own view engine, have a look at this post by Brad Wilson: Partial Rendering & View Engines in ASP.NET MVC

13. HtmlHelper
Views must be very dumb and thin, and they should only have html markup and calls to HtmlHelpers. There should be no code inside the views, so helpers come very handy for extracting the code from the view and putting it into something that is testable. As Rob Conery says: “If there's an IF, make a Helper”.

What is an HtmlHelper? Basically it’s just an extension method of the HtmlHelper class, but that’s the only requirement.

You can read more about how HtmlHelpers are a great way to encapsulate code for view on Rob’s post: Avoiding Tag Soup.



Continue Reading →

Monday, 19 November 2018

Custom Routes for MVC Application

When you request any page into MVC Application, it will go through the Routing Architecture. Your Routing system will decide your URL pattern. The default routing algorithm is like {controller}/ {action}/ {id} patterns. But it can be possible to change that pattern using Custom Routes.

Default Route
You can configure Route into the Global.aspx's Application Start Event. When you are creating an MVC application, it will already define Default route. Default route can be configured using the following code:

     routes.MapRoute(
      name: "Default",
      url: "{controller}/{action}/{id}",
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });


Custom Routes
It is possible to develop an MVC application without creating a Custom Route. But sometimes, there is a situation to change the pattern of URL in which it makes sense to create Custom Routes.

Examples of Valid Route Patterns in ASP.NET MVC

Route PatternURL Example
mysite/{username}/{action}~/mysite/jatten/login
public/blog/{controller}-{action}/{postId}~/public/blog/posts-show/123
{country}-{lang}/{controller}/{action}/{id}~/us-en/products/show/123
products/buy/{productId}-{productName}~/products/but/2145-widgets

Suppose I have a BlogController like below.

public class BlogController : Controller
    {
        public string Archive(DateTime? entryDate)
        {
            return "You wants Blog Entry on Date:=" + entryDate.ToString();
        }

        public string All()
        {
            return "All function";
        }

        public string getData(string name, int empId)
        {
            return "name: " + name + " id= " + empId;
        }
     }

1- Imagine that you want to route a request look like: /Archive/12-25-2010.

          routes.MapRoute(
                            "myBlogRoute1",
                            "{Archive}/{entrydate}",

                            new { Controller = "Blog", action = "Archive", });

2- Imagine that you want to route a request look like: /MyBlogs/All/12 or /MyBlogs/All/

            // MyBlogs/All/12  
            // MyBlogs/All/
            routes.MapRoute(
                   name: "myBlogRoute2",
                   url: "MyBlogs/{action}/{id}",
                   defaults: new
                   {
                       controller = "Blog",
                       action = "All",
                       id = UrlParameter.Optional
                   }

                 );

3- Imagine that you want to route a request look like: /MyBlogs/Suraj/Post/101

            // MyBlogs/suraj/Post/101
            routes.MapRoute(
                name: "myBlogRoute3",
                url: "MyBlogs/{name}/Post/{postId}",
                defaults: new
                {
                    controller = "Blog",
                    action = "getData",
                }

            );

https://www.tutorialsteacher.com/
Continue Reading →

Monday, 22 October 2018

MVC and WebApi


  1. Asp.Net MVC is used to create web applications that returns both views and data but Asp.Net Web API is used to create full blown HTTP services with easy and simple way that returns only data not view.
  2. Web API helps to build REST-ful services over the .NET Framework and it also support content-negotiation(it's about deciding the best response format data that could be acceptable by the client. it could be JSON,XML,ATOM or other formatted data), self hosting which are not in MVC.
  3. Web API also takes care of returning data in particular format like JSON,XML or any other based upon the Accept header in the request and you don't worry about that. MVC only return data in JSON format using JsonResult.
  4. In Web API the request are mapped to the actions based on HTTP verbs but in MVC it is mapped to actions name.
  5. Asp.Net Web API is new framework and part of the core ASP.NET framework. The model binding, filters, routing and others MVC features exist in Web API are different from MVC and exists in the new System.Web.Http assembly. In MVC, these featues exist with in System.Web.Mvc. Hence Web API can also be used with Asp.Net and as a stand alone service layer.


Continue Reading →

Tuesday, 10 April 2018

MVC 5 Features

What’s New in ASP.NET MVC 5

Attribute Routing
This is where attribute based routing comes in. Using attribute based routing we can define the route in the same place where action method is defined.
   
[Route("Products/Electronics/{id}")]
     public ActionResult GetElectronicItems(string id)
     {
         ViewBag.Id = id;
          return View();
     }

To enable attribute based routing we need to add the following in the RouteConfig file.

      public static void RegisterRoutes(RouteCollection routes)
       {
           routes.MapMvcAttributeRoutes();
       }

Optional Parameter
We can also specify if there is any optional parameter in the URL pattern defined by the Route attribute with the “?” character.

      [Route("Products/Electronics/{id?}")]
      public ActionResult GetElectronicItems(int? id) {
          ViewBag.Id = id; return View();

      }

Route constraints
We can also specify parameter constraints placing the constraint name after the parameter name separated by colon. For example we can specify that the parameter type should be integer by using the following

[Route("Products/Electronics/{id:int}")]

Route Prefix
If we have multiple action methods in a controller all using the same prefix we can use RoutePrefix attribute on the controller instead of putting that prefix on every action method.

Like we can attach the following attribute on the controller
[RoutePrefix("Products")]

So now our Route attribute on our action method does not need to specify the common prefix
[Route("Electronics/{id}")]

Filter's in MVC
Filters in MVC provide us with an elegant way to implement cross cutting concerns.Cross cutting concerns is the functionality that is used across our application in different layers.Common example of such functionality includes caching ,exception handling and logging.

We can create global or controller filters in MVC 4.Global filters are filters that are applied to all the action methods in the application while controller filters apply to all the action methods in the controller.

We can create a global filter by creating a class and registering it as a global filter

public class TestGlobalFilterAttribute : ActionFilterAttribute
   {
       public override void OnActionExecuting(ActionExecutingContext context)
       {
           base.OnActionExecuting(context);
           context.RequestContext.HttpContext.Response.Write("Global filter's in MVC are cool...");
       }
   }

//Register our global filter
GlobalFilters.Filters.Add(new TestGlobalFilterAttribute()); 

Filter Overrides in MVC 5
Now if want to override our global action filter in one of our action method's then we just need to apply the OverrideActionFilters attribute.Below we have applied the attribute to the default About method in the HomeController.

[OverrideActionFilters]
public ActionResult About(){
ViewBag.Message = "Your application description page.";
return View();
}

Scaffolding
Scaffolding means generating code automatically from the model.Suppose we have some model for which we want to generate the skeleton code for the basic Create Read Update and Delete operations then instead writing the common code we can use Scaffolding feature of MVC 5.

Bootstrap
Twitter Bootstrap is added as the default user interface framework for an MVC application. Bootstrap is a free collection of HTML and CSS based design templates created at Twitter for designing forms, navigation, buttons, tables etc.

ASP.NET Identity

One ASP.NET

Continue Reading →

Wednesday, 29 November 2017

Enterprise Library DAAB - C# .Net

Enterprise Library Data Access Application Block In C# .NET
What is a Data Access Application Block (DAAB)?  A Data Access Application Block encapsulates the performance and resource management best practices for accessing Microsoft SQL Server databases. It can easily be used as a building block in your own .NET-based application. If you use it then you will reduce the amount of custom code you need to create, test, and maintain. It comes with a single assembly with a class that has many useful methods. It reduces the amount of custom code.
A Data Access Application Block provides the following benefits:
  • It uses the functionality provided by ADO.NET 2.0 and with it, you can use ADO.NET functionality along with the application block's functionality.
  • It reduces the need to write boilerplate code to perform standard tasks.
  • It helps maintain consistent data access practices, both within an application and across the enterprise.
  • It reduces difficulties in changing the database type.
  • It relieves developers from learning different programming models for different types of databases.
  • It reduces the amount of code that developers must write when they port applications to different types of databases. Read more in http://msdn.microsoft.com/en-us/library/cc309168.aspx.
Install Enterprise Library
Please follow this link to download the Enterprise Library:
Create a new MVC web application.
Make the below changes in your web.config file.
Add a DAL Folder in your project. Add a Baseclass and add the below code in the baseclass.
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace MVC_ADO.DAL
{
    public class BaseClass
    { 
        public virtual Database GetDatabase()
        {
            Database db;
            db = DatabaseFactory.CreateDatabase("MasterDB");
            return db;
        }      
    }
}
Add a EmployeeModel class and add the below code

using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace MVC_ADO.DAL
{
    public class EmployeeModel : BaseClass
    {
        Database db = null;
        public override Database GetDatabase()
        {
            return base.GetDatabase();
        }

        public DataSet GetEmployee()
        {
            try
            {
                db = GetDatabase();
                DataSet ds = new DataSet();
                DbCommand dbCommand = db.GetStoredProcCommand("PROC_GET_EMPLIST");
                // db.AddInParameter(dbCommand, "@IP_UserID", DbType.Int32, UserID);
                //db.AddOutParameter(dbCommand, "@OP_strException", DbType.String, 200);

                ds = db.ExecuteDataSet(dbCommand);
                return ds;
            }
            catch
            {
                throw;
                // ds = null;
                //strException = ex.Message.ToString();
            }
        }
    }
}
Note: Create the PROC_GET_EMPLIST Stored Procedure in SQL Server.

Now Call the GetEmployee Function from your Controller.


using System.Web.Mvc;
using MVC_ADO.DAL;

namespace MVC_ADO.Controllers
{
    public class HomeController : Controller
    {
        EmployeeModel model = new EmployeeModel();
        public ActionResult Index()
        {
            var list = model.GetEmployee();
            return View();
        }
    }
}
You will get the list of all employees from Employee table.
Continue Reading →

Tuesday, 27 September 2016

Login with facebook

Here in This Article I am going to explain you how to implement Login with facebook in your website. first of all you need to create a new App in facebook developers. https://developers.facebook.com/apps/

1- Click On Add a New App button. a pop window will be open.
2- Select WWW (Website) Link.

3- Provide App Name and click on "Create New Facebook AppID" Button.

4- In the Opened pop window, Provide Display Name, Contact EmailId and Category.
     For Category Choose "Apps for Pages" option
Then Click on Create App ID button.



5-  Continue with Security Check window. Now, your app hes been created. you need to do some setting now.
6- Open the facebook apps home Page. https://developers.facebook.com/apps/
     You will see your App "socialLogin" in the list.


7- Click on your app. it'll redirect you on the new Page.


Now you have App ID and App Secret Key.

8- In the Settings menu on the left side, You can set other information's like Site Url, App logo and others.

9- Now, Go to Roles -> Test Users Option.
     Click On Add button to add a Test User.


A popup will be open. Just Click on Create Test Users button. 
A Test User will be created. see the below Image.


10- Now, Come to App Review Section.


Select the radio button to Yes. Now your App is Live to use.

11- Now, Come to Dashboard Basic Settings option. see the below.


Click On Quick Start button. it'll redirect you to the new page.
On the new Page Under Site Url Section you will see Next button. Click on the Next button. 
 A new section will be open. just Click On Login Option in that section. it'll open a new window again.

you don't need to follow the above red colored steps.


12- Copy the entire Html Code from Full Code Example Section. Create a new Html file named index.html in your any directory. Paste the Code in newly created file.

Note: for detailed knowledge please go through the Url https://developers.facebook.com/docs/facebook-login/web/

13- Open the html file and Add the AppId generated from your App.


14- You Can Change graph Api version based on your requirements. I've used 2.7.


15- Now Save your Html File. 

Now it's time to run the html. but before this you need to host your html on IIS server.

So, goto inetmgr and add a new Website. Provide Html file path and port that you have provided in facebook app and Host name as "localhost". Click on Ok button.



now browse the website from IIS.

Click On Log In button. facebook login window will be open. provide your user name and password., and click on Login button. 


Click on Continue button.

You will see your Username from facebook. now you're logged in with facebook.

Download html file here

Take more help from below video





Continue Reading →

Monday, 26 September 2016

Login With Google

Here in This Article I am going to explain you how to implement Login with Google in your website. first of all you need to create a new project in Google developers console. https://console.developers.google.com/



Select your existing project. if you haven't created then first of all Create a new Project.

Provide Project Name. I have provided "LoginWithGoogle". click on Create button.
Now Click on Credentials Link on Left Side Menu.
Click On OAuth consent screen Link and Fill the information. finally click on Save button.


It will Redirect you to the Credentials Page. 


Click on Create credentials Button. it'll open a menu. Click on OAuth client ID.



Click on Web application Radio button.



Fill the Information and Click on Create Button. It'll generate Client ID and Client Secret Key.


Finally Click On Save Button. 
Now You have Client ID and Secret Key for your Login with Google functionality.

Now come to your Visual Studio Project.
Create a new MVC Project.

In the Model Folder Create a new Model class.

  public class GoogleDataModel  
   {  
     public string Email_address { get; set; }  
     public string Google_ID { get; set; }  
     public string firstName { get; set; }  
     public string LastName { get; set; }  
     public string fullName { get; set; }  
     public string Client_ID { get; set; }  
     public string Return_url { get; set; }  
     public string userProfilePic { get; set; }  
     public string Gender { get; set; }  
   }  

In the Home Controller add the Client Key and Secret Key.

  public class HomeController : Controller  
   {  
     string clientId = "767676544437878-m5h7tpngqjkch6sr9visngstdu09agic.apps.googleusercontent.com";  
     string clientSecret = "qL78qLvihhfgf9VWT189898fG9";  
     public ActionResult Index()  
     {  
       ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";  
       return View();  
     }  
     public ActionResult GetGoogleAccount()  
     {  
       return View();  
     }  
  ------
  ---------

In the Index View Add the Login Button and Some Javascript Code.

  <input type="button" id="Button1" value="Login With Google" onclick="OpenGoogleLoginPopup();" />  
  
 <script type="text/javascript" language="javascript">  
     var clientId = "767676544437878-m5h7tpngqjkch6sr9visngstdu09agic.apps.googleusercontent.com";  

     function OpenGoogleLoginPopup() {  
       var url = "https://accounts.google.com/o/oauth2/auth?";  
       url += "scope=https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email&";  
       url += "state=%2Fprofile&"  
       url += "redirect_uri=http://localhost:53285/Home/GetGoogleAccount&"  
       url += "response_type=token&"  
       url += "client_id="+clientId;  
       window.location = url;  
     }  
   </script>   

Now, In the GetGoogleAccount View Add the Below Code.

 @{  
   ViewBag.Title = "GetGoogleAccount";  
 }  
 <script type="text/javascript">  
   try {  
     debugger;  
     // First of all, parse the querystring  
     var params = {}, queryString = location.hash.substring(1),regex = /([^&=]+)=([^&]*)/g, m;  
     while (m = regex.exec(queryString)) {  
       params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);  
     }  
     var ss = queryString.split("&")  
     if (ss != undefined) {  
       window.location = "About?" + ss[1];  
       history.pushState("", "", "About");  
     }  
     else  
       window.location = "About";  
   } catch (exp) {  
   }  
 </script>  

Now, In the About Action add the below Code.

  public ActionResult About()  
     {  
       GoogleDataModel model = new GoogleDataModel();  
       if (Request.QueryString["access_token"] != null)  
       {  
         string test = Request.QueryString["access_token"];  
       }  
       if (Request.QueryString["access_token"] != null)  
       {  
         String URI = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + Request.QueryString["access_token"].ToString();  
         WebClient webClient = new WebClient();  
         Stream stream = webClient.OpenRead(URI);  
         string b;  
         /*I have not used any JSON parser because I do not want to use any extra dll/3rd party dll*/  
         using (StreamReader br = new StreamReader(stream))  
         {  
           b = br.ReadToEnd();  
         }  
         b = b.Replace("id", "").Replace("email", "");  
         b = b.Replace("given_name", "");  
         b = b.Replace("family_name", "").Replace("link", "").Replace("picture", "");  
         b = b.Replace("gender", "").Replace("locale", "").Replace(":", "");  
         b = b.Replace("\"", "").Replace("name", "").Replace("{", "").Replace("}", "");  
         /*  
         "id": "109124950535374******"  
          "email": "usernamil@gmail.com"  
          "verified_email": true  
          "name": "firstname lastname"  
          "given_name": "firstname"  
          "family_name": "lastname"  
          "link": "https://plus.google.com/10912495053537********"  
          "picture": "https://lh3.googleusercontent.com/......./photo.jpg"  
          "gender": "male"  
          "locale": "en" }   
         */  
         Array ar = b.Split(",".ToCharArray());  
         for (int p = 0; p < ar.Length; p++)  
         {  
           ar.SetValue(ar.GetValue(p).ToString().Trim(), p);  
         }  
         model.Email_address = ar.GetValue(1).ToString();  
         model.Google_ID = ar.GetValue(0).ToString();  
         model.firstName = ar.GetValue(4).ToString();  
         model.LastName = ar.GetValue(5).ToString();  
         model.fullName = model.firstName + " " + model.LastName;  
         model.Gender = ar.GetValue(8).ToString();  
         model.userProfilePic = ar.GetValue(7).ToString();  
         model.userProfilePic = model.userProfilePic.Replace("https", "https:");  
       }  
       return View(model);  
     }  

Add the Code in About.cshtml

 @model LoginWithFbDemo.Models.GoogleDataModel  
 @{  
   ViewBag.Title = "About";  
 }  
   <div id="ClientDetails">  
   <br ><br >  
     @Html.TextBoxFor(x=> x.fullName)  
   @Html.TextBoxFor(x=> x.Email_address)  
   <img id="imgProfile" src="@Model.userProfilePic" style="width:auto"/><br >  
   </div>  

Now you're done. Run the Application.


 Click On Login With Google Button.


Provide the Email Id and Password. Click on Sign In Button.

It'll ask the Permission. Click on Allow button.


It will redirect you to the About Page. You will see your Name, Email Id and Profile Pic.

Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (55) CD (1) CI (2) CloudComputing (2) Coding (10) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (20) Entity Framework (5) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) jwtToken (4) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives