Pages

Sunday, 28 December 2014

Oauth and Oauth2 authentication in .NET



Registering on websites is hard. So is trying to remember yet another username and password combination. Social logins makes it easy for people to register on your site and quickly sign in using the social network or email identities they already have.

To implement social Login in asp.net website follow these steps

Step 1:

Install OAuth2 package via NuGet
Install-Package OAuth2

Step 2:


Configure library in web.config
<configuration>
  <configSections>
    <section name="oauth2" type="OAuth2.Configuration.OAuth2ConfigurationSection, OAuth2, Version=0.1.*, Culture=neutral"/>
  </configSections>

  <oauth2>
    <services>
      <add clientType="GoogleClient"
           enabled="false"
           clientId="000000000000.apps.googleusercontent.com"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAA"
           scope="https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email"
           redirectUri="http://mymachine.net:53023/Auth" />
      <add clientType="FacebookClient"
           enabled="false"
           clientId="000000000000000"
           clientSecret="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
           scope="email"
           redirectUri="http://mymachine.net:53023/Auth" />
      <add clientType="VkClient"
           enabled="false"
           clientId="AAAAAAAAAAAA"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
           scope="offline"
           redirectUri="~/Auth" />
      <add clientType="TwitterClient"
          enabled="false"
           clientId="AAAAAAAAAAAAAAAAAAAAAA"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
           redirectUri="http://mymachine.net:53023/Auth" />
      <add clientType="LinkedInClient"
          enabled="false"
           clientId="aaaaaaaaaaaa"
           clientSecret="AAAAAAAAAAAAAAAA"
           redirectUri="http://mymachine.net:53023/Auth" />
      <add clientType="OdnoklassnikiClient"
           enabled="false"
           clientId="AAAAAAA"
           clientSecret="AAAAAAAAAAAA"
           clientPublic="AAAAAAAAAAAAAAAAA"
           redirectUri="~/auth" />
      <add clientType="YandexClient"
           enabled="false"
           clientId="AAAAAAAAAAAAAAAAA"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAAAA"
           redirectUri="~/auth" />
      <add clientType="MailRuClient"
           enabled="false"
           clientId="AAAAAAAAAAAAAAAAAAA"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
           redirectUri="~/auth" />
      <add clientType="FoursquareClient"
           enabled="false"
           clientId="AAAAAAAAAAAAAAAAAAAAAAAAAAA"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
           redirectUri="~/auth" />
      <add clientType="WindowsLiveClient"
           enabled="false"
           clientId="AAAAAAAAAAAAAAA"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
           scope="wl.basic wl.emails"
           redirectUri="~/auth" />
      <add clientType="InstagramClient"
           clientId="AAAAAAAAAAAAAAAAAAA"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
           scope="basic"
           redirectUri="~/auth" />
      <add clientType="DigitalOceanClient"
           clientId="AAAAAAAAAAAAAAAAAAA"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
           scope="read write"
           redirectUri="~/auth" />
    </services>
  </oauth2>

Step 3:

Add a private variable in your Accounts controller
AuthorizationRoot authorizationRoot = new AuthorizationRoot();

Step 4:

Add Social Login Action in your Accounts Controller. 
public ActionResult SocialLogin(string ProviderName)
{
    //user will hit the following action on button click 
}

Step 5:

Add Get client private Method in your controller
private IClient GetClient(string ProviderName) 
{ 
   return authorizationRoot.Clients.First(c => c.Name == ProviderName); 
} 

Step 6:

Add following code in your Social login Action 
public ActionResult SocialLogin(string ProviderName)
{
 Session["ProviderName"] = providerName;      return new RedirectResult(GetClient().GetLoginLinkUri());
}

Step 7:

Add oauth Action method to the controller
public ActionResult Auth() 

 { 

 if (Session["ProviderName"] == "google") 

 { 

 GoogleClient google = GetClient(Session["ProviderName"] ) as GoogleClient; 

 //User basic info 

 UserInfo userInfo = google.GetUserInfo(Request.QueryString); 

 myUser.Email = userInfo.Email; 

 myUser.AvatarUri = userInfo.AvatarUri; 

 myUser.FirstName = userInfo.FirstName; 

 myUser.LastName = userInfo.LastName; 

 //Store this if you want to make api calls 

 Session["googleAccessToken"] = google.AccessToken; 

} 
if (Session["ProviderName"] == "twitter") 
 { 
 TwitterClientgoogle = GetClient(Session["ProviderName"] ) as TwitterClient; 

 //User basic info 

 UserInfo userInfo = google.GetUserInfo(Request.QueryString); 

 myUser.Email = userInfo.Email; 

 myUser.AvatarUri = userInfo.AvatarUri; 

 myUser.FirstName = userInfo.FirstName; 

 myUser.LastName = userInfo.LastName; 

 //Store token if you want to make api calls 

 Session["twitterAccessToken"] = google.AccessToken; 

} 
//and so on for other social logins
} 

Step 8:

Making Api calls Define scope in config to get user permission for the resources
<add clientType="GoogleClient"
           enabled="false"
           clientId="000000000000.apps.googleusercontent.com"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAA"
           scope="https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email"
           redirectUri="http://mymachine.net:53023/Auth" />
and add following code to the any action where you want the user data
RequestFactory _factory = new RequestFactory(); 

 var client = _factory.CreateClient(new Endpoint { BaseUri = "https://www.google.com", Resource = "/m8/feeds/contacts/default/full" }); 

 var request = _factory.CreateRequest(new Endpoint { BaseUri = "https://www.google.com", Resource = "/m8/feeds/contacts/default/full" }); 

 request.AddParameter("alt", "json"); 

 request.AddHeader("Authorization", "Bearer " + Session["googleAccessToken"]); 

request.RequestFormat = RestSharp.DataFormat.Json; 

 RestSharp.RestResponse a = RestClientExtensions.ExecuteAndVerify(client, request) as RestSharp.RestResponse; 

jsonData = a.Content; 
and do whatever you want to do with it !!!.

:)

Tuesday, 21 October 2014

Come And See The Core Of Computer

Jab bhe ham kisi JOURNEY ki suruat karte hai, tab ye hamesha acha idea hota hai ki ham jis raste se hoker ja rahe hai uska ek MANTEL MAP hmare pass ho. Ye baat  INTELLECTUAL JOURNEY ke lie bhe TRUE hai, such as learning to write COMPUTER PROGRAMS. Hamare case me ham logo ko ye janna bahut jaruri hai ki computers kaam kaise karte hai. App logo ko ye janna jaruri hai ki computer program akhir hai kya? Kis tareke se kuch ENGLISH WORDS(code) calculates a Complex Math problem and other things.
Jab aap mere is post ko aage Read karenge, don’t worry if you can’t understand everything in detail. (asliyat main, ye namumkin hai that You understand every Detail  brief exposition of this blog post). Bas itna padhne par dimag lagao ki apko ek big IDEA ho COMPUTER WORKING ke bare main.
So Let,s Start…
1) Fetch And Execute Cycle IN Computer
Computer bahut he complex system hai jo bana hai bahut sare components se. but at the HEART — or the brain, jo bhe aap kahna chahe— of the computer is CPU. Aaj kal ke morden computers main CPU is a single chip Like intels i3 i5 i7 you all are familiar with but there are more, like one in your 100-MS calculator, or one in your Android Phone or one in Smart TV and the list goes on. But the main job of a CPU is to execute programs.
Jab bhe CPU starts Executing a program, it do the first work to COPY THE PROGRAM FROM HARD DISK TO RAM(Primary Memory) and why it do so ? I think you all Know the answer. After all it is a point What we all Prepare for our UPTU external exam and my frnds You all are absolutely right Ram is faster than HardDisk so it is ideal to use RAM. But i know some of you might thinking so why not to build a whole computer of 1 TB Ram. Why we even use harddisk ? There are two reason to use harddisk.
  1. Ram is very costly so it is not economical.
  2. It is Volatile, every time turn off the computer it erases all the data in it. So if we want that our cute pics, movies and songs not get erased every time we have to use a hard disk.
Programs ke sath - sath RAM also store the inputs , intermediate outputs and final result of the program. Main memory consists of a sequence of locations. These locations are numbered, and the sequence number of a location is called its address. Ye addresses bahut he important hai inke through hm RAM main rakhi Millions of Informations main se kisi bhe information tak pahunch sakte hain. And most amazing part(Actually, this is why I love RAM) of the RAM is  that its Speed is independent of Information’s memory Location means, chahe info ka address 0 ho ya 100K it can be fetched in a constant time. Is’nt it is amazing and if you want to know how it happens i will suggest u to read your CO and DLD books carefully it has all the answers.
When the CPU needs to access the program instruction or data in a particular location it sends the address of that information as a signal to the memory, memory responds by sending back the data contained in the specified location.
Machine Language ke level par CPU ke Operation Bahut simple hain(Waise in detail it is very Complicated). The CPU executes a program that is stored as a sequence of machine language instructions in main memory. It does this by repeatedly fetching an instruction from memory and executing that instruction. This process goes in this why —
1. Fetch an Instruction -> 2. Execute It
3. Fetch another Instruction -> 4. Execute it  And this Process goes on Forever.
and this process is called FATCH AND EXECUTE CYCLE. And this is all that the CPU ever does.
Details of fatch-and-execute cycle ko janna koi itna jaruri nahi hai, lakin kuch bahut basic cheje hai jo apko janni he chahie. EVERY cpu contains  a few internal registers, you can think of it as a VERY small RAM which also have Addresses and it is even faster than ram, almost equal to the speed of cpu itself. Some of these registers are used for internal purpose like LC(Location Counter Register). LC is very important because it is used to keep track of where it is in the program it is executing. Actually it holds the next Memory location (address) of instruction to be fetched from RAM. During the fatch it is update for next instruction location.
Ek computer machine language programs ko execute krta hai wo bina samghe ki what it actually means and what it do, iska sidha sa reason ye hai ki isko banaya he aise gaya hai. This is not an easy concept. Agar hm computers main aur deep jae to pta chalta hai ki asliyat main computer bna hai millions of TINY SWITCHES se jisko hm transistor kahte hai, every transister have to state on and off(or 0,1), ye transistor bade anokhe hote hain kyunki inko ek dusre se is tarike se joda ja sakta hai ki output of one switch can turn on and off another switch. As a computer computes, these switches turn each other on or off in a pattern which is determined by your program and how actually they wired up.
Now In my entire post i keep repeating the Word Machine Language. But What actually a machine language is ?
Can you tell what this means 1000 1111 ? Some would say it is a sequence of 0’s and 1’s.(Binary) some would convert it Decimal No and some one in Hexa No. But, I will suggest every one to recall the definition of Information. It is nothing, it is simply raw data which has no meaning. Now if i put the same question in this way, Can you tell what this means 1000 1111 BCD ? Now every body reading this post have a common answer 08 15. Similarly Every CPU has an instruction set in binary and whenever cpu encounter these binary number in specific pattern it perform an operation for which it is coded in chip.
Like following code perform addition in 8085 processor  
10001111 00000111 00000011 (1st bunch of sequence is opcode ADD and 2nd 3rd is 7 and 3) 
May be i was wrong because it is 5:00 in the morning and i am little tired and it is possible that i incorrectly computed the opcode of add to binary But the general idea is a machine language instruction is just a sequence of zeros and ones. Each particular sequence encodes some particular instruction. The data that the computer manipulates is also encoded as binary numbers. A computer can work directly with binary numbers because switches can readily represent such numbers. When a machine language instruction is loaded into the CPU, all that happens is that certain switches are turned on or off in the pattern that encodes that particular instruction. The CPU is built to respond to this pattern by executing the instruction it encodes

Monday, 13 October 2014

Programming Pattern #Singleton


Sometime in programming we need to have only one instance of object for example in logger class.
Such type of situation in programming is mostly handled by Singleton Classes.

Singleton is a software design pattern which ensures only one object of a type is created. This is useful when we want to create an object, which manages or coordinates some tasks in the system. A WindowManager, a FileSystem, Mouse Pointer would be good examples for places where Singleton design pattern can be applied.

The singleton pattern is one of the simplest design patterns it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance. In this case the same instance can be used from everywhere, being impossible to invoke directly the constructor each time.

How To follow Singleton programming Pattern

  • Make sure class can't create more than one variable
  • Provide a global access to that instance 

 Implementation 

  • Singleton class have a private constructor which restricts programmers to create instance of the  class.
  • Singleton class also have a static method and a private variable of the Singleton class type, this private variable used to hold the single instance of the class.
  • Static method is used to expose the private variable.
    class MySingletonClass
     {
	private static MySingletonClass instance;
	private MySingletonClass()
	{
		...
	}

	public static synchronized Singleton getInstance()
	{
		if (instance == null)
			instance = new MySingletonClass();

		return instance;
	}
	...
	public void doSomething()
	{
		...	
	}

        public void doSomethingElse()
	{
		...	
	}
    }

Uses Of Singleton Pattern

  • Logger Class
  • Configuration Class
  • Centralized Coordination of task 

 Profit 

  • Single instance save memory which is very important for low memory devices
  • Simple accessibility of shared Resource 

Note :- 

To keep things simple, above implementation not Support Multithreaded programs. If you are curious and know about multithreaded programming than i am sure you also know that "Locking the Methods" is the way.

Saturday, 8 February 2014

JavaFx : Tutorial Series - part 3

Creating UI using FXML and Scene Builder

You can use FXML to create any user interface, FXML is particularly useful for user interfaces that have large, complex scene graphs, forms, data entry, or complex animation. FXML is also well-suited for defining static layouts such as forms, controls, and tables. In addition, you can use FXML to construct dynamic layouts by including scripts.

We use the scene builder tool to create FXML. Scene Builder is a GUI tool which generates FXML.

Open Sample.fxml

1.) In your project double click on Sample.fxml
2.) The file is automatically opened in Scene Builder.

3.) Drag and drop the elements from library to workspace to create GUI.


4.) FXML is not a compiled language so you can preview it by pressing ctrl+p.

Next :- JavaFx : Tutorial Series - part 3 ( Controls )


JavaFx : Tutorial Series - part 2

Structure of JavaFX application 

     Every JavaFX application's main Class extends the Application Class and Override the start(Stage stage) Method. Start Method is entry point of Application. Stage is the the top most container which contains UI components, whether it is deployed on desktop,within a browser, or other Devices.

    Stage class has set of properties and methods.

 1.) A Scene - It contains the graphical nodes in the user interface.
 2.) A title - appears in the title bar of the window(when deployed on the desktop).
 3.)Width, Hight, X, Y, Opacity, fullScreen etc.

Using Stage Class

Add following method calls in your application ....





 public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("Sample.fxml")); //load the ui from fxml file
        
        Scene scene = new Scene(root); //A scene container
        
        stage.setScene(scene); //add the scene to stage
        stage.setTitle("My First JavaFX App"); //set the title of stage
        stage.setWidth(500); //width of stage
        stage.setHeight(500); //height of stage
        stage.setOpacity(.8); //Transparency of stage 0 for fully transparent 1 for no transparency.
        stage.show();
    }



Next:- JavaFx : Tutorial Series - part 3

Wednesday, 5 February 2014

JavaFx : Tutorial Series - part 1

JavaFx is API of java which is designed to develop Rich Internet Application. It is used to create very dynamic and attractive java applications. JavaFx uses CSS for styling GUI of java application. If one want to separate presentation of ui and back-end logic it can be done via a scripting language called FXML.

Actually it is very similar to web Programing in the sense that it uses CSS for styling like web Programming, FXML for presentation like HTML and JAVA for back-end logic like JAVASCRIPT do in web Programming.

Tools 

To develop JavaFX application following tools are needed..
  1. Latest JDK 7
  2. JRE 7
  3. IDE NetBeans 7.2 or above or Eclips
  4. JavaFx Scene Builder

First Java Application 

1 . Open NetBeans and click on New Project.
2. Select JavaFX --> JavaFX FXML Application & click Next.


3. Enter name of Project And click Finish.
4. Run your project to see sample application Hello world example.
JavaFX Sample

Monday, 27 January 2014

Very Basic chat Application using TCP/IP

In my last post i showed how TCP programming is done using java. In this post i will show you how to build a very basic command line chat application.



Very Basic Chat App:-

  1. Establish Connection between sender and receiver (Client & Server).
  2. sender(Client) sends the message Receiver(Server) display it continuously . 
  3. when client send the message "quit" both server and client quits.

Server Logic:-

  1. Create a ServerSocket object.
  2. Wait for a client to connect.
  3. If connection is established receive message .(Do this in a While loop so it can receive msg after msg)
  4. If message is "quit" break the loop.
  5. close the connection and terminate.

Server Code:-

I have commented all the importent points in code.




import java.net.*;
import java.io.*;

public class ChatServer
{  private Socket          socket   = null;
   private ServerSocket    server   = null;
   private DataInputStream streamIn =  null;

   public ChatServer(int port)
   {  try
      {  //server code to read msg from connection and write it to the cmd 
         System.out.println("Binding to port " + port + ", please wait  ...");
         server = new ServerSocket(port);  //acquiring port
         System.out.println("Server started: " + server);
         System.out.println("Waiting for a client ..."); 
         socket = server.accept(); //waiting for connection 
         System.out.println("Client accepted: " + socket);
         open();
         boolean done = false;
         while (!done) //reading again and again until quit message is not recived
         {  try
            {  String line = streamIn.readUTF();
               System.out.println(line);
               done = line.equals(".bye");
            }
            catch(IOException ioe)
            {  done = true;
            }
         }
         close();
      }
      catch(IOException ioe)
      {  System.out.println(ioe); 
      }
   }
   public void open() throws IOException  //get the input stream to read msg from connection
   {  streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
   }
   public void close() throws IOException  //close the connection
   {  if (socket != null)    socket.close();
      if (streamIn != null)  streamIn.close();
   }
   public static void main(String args[]) //Main Method
   {  
      ChatServer server = null;
      if (args.length != 1)
         System.out.println("Usage: java ChatServer port");
      else
         server = new ChatServer(Integer.parseInt(args[0]));
   }
}

Client Logic:-

  1. create a Socket.
  2. establish the connection
  3. read message from cmd and send it to connection
  4. on "quit" msg exit

Client Code:-

I have commented all the importent points in code.



import java.net.*;
import java.io.*;

public class ChatClient
{  private Socket socket              = null;
   private DataInputStream  console   = null;
   private DataOutputStream streamOut = null;

   public ChatClient(String serverName, int serverPort)
   {  System.out.println("Establishing connection. Please wait ...");
      try
      {  socket = new Socket(serverName, serverPort);
         System.out.println("Connected: " + socket);
         start();
      }
      catch(UnknownHostException uhe)
      {  System.out.println("Host unknown: " + uhe.getMessage());
      }
      catch(IOException ioe)
      {  System.out.println("Unexpected exception: " + ioe.getMessage());
      }
      String line = "";
      while (!line.equals(".quit"))  //quit logic
      {  try
         {  line = console.readLine();
            streamOut.writeUTF(line);
            streamOut.flush();
         }
         catch(IOException ioe)
         {  System.out.println("Sending error: " + ioe.getMessage());
         }
      }
   }
   public void start() throws IOException //Start
   {  console   = new DataInputStream(System.in);
      streamOut = new DataOutputStream(socket.getOutputStream());
   }
   public void stop() //stop
   {  try
      {  if (console   != null)  console.close();
         if (streamOut != null)  streamOut.close();
         if (socket    != null)  socket.close();
      }
      catch(IOException ioe)
      {  System.out.println("Error closing ...");
      }
   }
   public static void main(String args[])// Main method
   {  ChatClient client = null;
      if (args.length != 2)
         System.out.println("Usage: java ChatClient host port");
      else
         client = new ChatClient(args[0], Integer.parseInt(args[1]));
   }
}


How to Run the Code :-

  1. Open two cmd
  2. compile both file
  3. first run ChatServer using the cmnd--->  java ChatServer 5001 (where 5001 is port no)
  4. than run ChatClient using the cmnd---->java ChatClient 127.0.0.1 5001 (127.0.0.1 is your own machine address and 5001 is the port on which Server is running)

My next post is on making this chat app to handle multiple client and may be add some gui to give it a touch.
If you liked or learned something  from post than follow me on google+ and share the post .

ThankYou.