Wednesday, 10 February 2016

USING OAUTH2.0 TO ACCESS GOOGLE CALENDAR VIA API'S USING .NET


PREREQUISITE

  1. Knowledge of Basic .NET and object oriented programming
  2. Basic Knowledge of API'S
  3. Basic knowledge of database
  4. working knowledge of Visual studio

Download Solution from here

OAuth Overview

Google providers you huge list of API'S to access the google resources . This resources can be accesses only after passing the authentication  layer successfully.Google APIs use the OAuth 2.0 protocol for authentication and authorization. Google supports common OAuth 2.0 scenarios such as those for web server, installed, and client-side applications.


What is OAuth Protocol?

OAuth is an open-source authorization protocol - or  set of rules for authorization  that allows a third-party  application to access a user’s data without the user needing to share login credentials. It purely works on  token-based authorization mechanism.


Roles

OAuth defines four roles:

Resource Owner

An entity capable of granting access to a protected resource. When the resource owner is a person, it is referred to as an end-user.
Resource Server The server hosting the protected resources, capable of accepting and responding to protected resource requests using access tokens.


Client

An application making protected resource requests on behalf of the resource owner and with its authorization. The term "client" does not imply any particular implementation characteristics (e.g., whether the application executes on a server, a desktop, or other devices).


Authorization Server

The server issuing access tokens to the client after successfully authenticating the resource owner and obtaining authorization. The interaction between the authorization server and resource server is beyond the scope of this specification. The authorization server may be the same server as the resource server or a separate entity. A single authorization server may issue access tokens accepted by multiple resource servers.


In this article , I am going to explain and implement Google Calendar Integration with .Net Application(which again can be either windows desktop,console,phone or web application/website site) which will perform some operations like retrieving,adding,deleting and updating events in google calendar.Let we assume and start with console application and then later with web application
Let us quickly go through steps to setup Project in visual studio


SETUP VISUAL STUDIO PROJECT

1)  open Visual studio and make sure you have at least 4.0 .Net framework version selected like shown below
2)  Add the following NuGet Package
using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using Google.Apis.Services;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
you can do it in two ways.

a)USING NGET CONSOLE: just fallow below steps



 
PM> Install-Package Google.Apis.Calendar.v3
b)USING VISUAL STUDIO NGET PACKAGE UI: Fallow below steps-



Congrats , you are done with package installation and visual studio setup.Now you are ready to code but before you start coding you need to setup Google Calendar Service Setup

SET UP PROJECT IN GOOGLE CONSOLE

To begin or make our application talk to Google Calendar we have to obtain OAuth 2.0 client credentials from the Google Developers Console. Let us fallow below steps
1) Go to Google Developers Console . If you don't have account just create new google account.
2) In Google console fallow below steps
Great, we have created Google console project successfully  and got Client secret key also

LET US CODE

using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using Google.Apis.Services;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;

namespace DotNetGoogleCalendarIntegration
{
    class Program
    {
//I just include calendar scope here because i want to access 
//user calendar for event retrieval and insertion
static string[] Scopes = { CalendarService.Scope.Calendar };
static string Applicationname = "Faith Application";
static void Main(string[] args)
{
UserCredential credential;
CalendarService service;
//JSON File created in Google console and added to application folder
using (var stream = new FileStream("..\\..\\googleclient_secret.json",
 FileMode.Open, FileAccess.Read))
{  
    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
      Scopes,
      Environment.UserName,
      CancellationToken.None,
      new DatabaseStore(@"Database Server Name", "database username",
 "password", "databasename", "tablename")).Result;
 //oauth sucks need to get refresh token and save it for persistence and
     to avoid popup dialog every time for ACCEPT and DENY
    // Console.WriteLine(credential);      

}
// Create Calendar Service.
service = new CalendarService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = Applicationname ,
});

// Define parameters of request.
EventsResource.ListRequest request = service.Events.List("primary");
request.TimeMin = DateTime.Now;
request.ShowDeleted = false;
request.SingleEvents = true;
request.MaxResults = 10;
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;
Console.WriteLine("Upcoming events for Shabir:");
Console.WriteLine("====================================================");
Events events = request.Execute();
if (events.Items.Count > 0)
{
    foreach (var eventItem in events.Items)
    {
string when = eventItem.Start.DateTime.ToString();
string title = eventItem.Description.ToString();
string organizer = eventItem.Organizer.Email.ToString();
if (String.IsNullOrEmpty(when))
{
when = eventItem.Start.Date;
}
Console.WriteLine("{0}" + Environment.NewLine + "{1}" + Environment.NewLine + " 
 {2}" + Environment.NewLine + "   {3}", eventItem.Summary, when, title, organizer);
Console.WriteLine("------------------------------------------------------");
    }

}
else
{
    Console.WriteLine("No upcoming events found.");
}


//ADDING EVENT
Event newEvent = new Event();
newEvent.Summary = "Shabir Meeting";
newEvent.Description = "Today going to discuss regarding OAuth Protocol";
newEvent.Start = new EventDateTime();
newEvent.Start.DateTime = DateTime.Now.AddHours(5);
newEvent.End = new EventDateTime();
newEvent.End.DateTime = DateTime.Now.AddHours(8);
service.Events.Insert(newEvent, "primary").ExecuteAsync();
Console.Read();
}
    }
}
Note: In Case you are looking for saving in local file, i mean implementing IFileDataDtore change above function code snippet with
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
      Scopes,
      Environment.UserName,
      CancellationToken.None,
          CancellationToken.None,
          new FileDataStore(@"D:\CalendarCsharp")).Result;

DatabaseStore.cs


RECAP ALL STEPS

All applications follow a basic pattern when accessing a Google API using OAuth 2.0. At a high level, you follow four steps: 

1. Obtain OAuth 2.0 credentials from the Google Developers Console.

Visit the Google Developers Console to obtain OAuth 2.0 credentials such as a client ID and client secret that are known to both Google and your application. The set of values varies based on what type of application you are building. For example, a JavaScript application does not require a secret, but a web server application does.

2. Obtain an access token from the Google Authorization Server.

Before your application can access private data using a Google API, it must obtain an access token that grants access to that API. A single access token can grant varying degrees of access to multiple APIs. A variable parameter called scope controls the set of resources and operations that an access token permits. During the access-token request, your application sends one or more values in the scope parameter.

3. Send the access token to an API.

After an application obtains an access token, it sends the token to a Google API in an HTTP authorization header. Access tokens are valid only for the set of operations and resources described in the scope of the token request. For example, if an access token is issued for the Google+ API, it does not grant access to the Google Calendar API. You can, however, send that access token to the Google+ API multiple times for similar operations.

4. Refresh the access token, if necessary.

Access tokens live very short. If your application needs access to a Google API beyond the lifetime of a single access token, it can obtain a refresh token. A refresh token allows your application to obtain new access tokens which you can persist in DataStore  by inheriting it from IDataStore. the implementation of IDatastore is shown below


 IMPORTANT POINT: 

In case above code doesn't work, you can use below method for google aouthorization.

When i used above code with asp.net web on production,I experienced "timeout issue".  In case you are facing same issue just use below method

 IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(
                 new GoogleAuthorizationCodeFlow.Initializer
                 {
                     ClientSecrets = GetClientConfiguration().Secrets,
                     DataStore = new DbStore(@"****.21.58.192", "shabihgghgjdy3", "Shab****r@123", "FaithDb", "GoogleUser"),
                     Scopes = new[] { CalendarService.Scope.Calendar }
                 });

            var uri = Request.Url.ToString();
            var code = Request["code"];
            if (code != null)
            {
                var token = flow.ExchangeCodeForTokenAsync(txtEmailAddress.Text, code,
                    uri.Substring(0, uri.IndexOf("?")), CancellationToken.None).Result;

                // Extract the right state.
                var oauthState = AuthWebUtility.ExtracRedirectFromState(
                    flow.DataStore, txtEmailAddress.Text, Request["state"]).Result;
                Response.Redirect(oauthState);
            }
            else
            {
                var result = new AuthorizationCodeWebApp(flow, uri, uri).AuthorizeAsync(txtEmailAddress.Text,
                    CancellationToken.None).Result;
                if (result.RedirectUri != null)
                {
                    // Redirect the user to the authorization server.
                    Response.Redirect(result.RedirectUri);
                }
                else
                {
                    // The data store contains the user credential, so the user has been already authenticated.
                 }
              }

IDataStore Implementation

using Google.Apis.Json;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DotNetGoogleCalendarIntegration
{
    public class DatabaseStore : IDataStore
    {

//database parameters
readonly string tableName;
readonly string serverName;
readonly string loginName;
readonly string passWord;
readonly string databaseName; 
private Boolean _IsConnected { get; set; }
public Boolean connectionAlive { get { return _IsConnected; } }

/// <param name="database">database name</param>
public DatabaseStore(String server, string login, string password, string databasename, string tablename)
{
tableName = tablename;
serverName = server;
loginName = login;
passWord = password;
databaseName = databasename;
SqlConnection myConnection = this.connectdb();   // Opens a connection to the database.
if (_IsConnected)
{
    // check if the Table Exists;
    try
    {
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select 1 from GoogleOAuthUser where 1 = 0",myConnection);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{var hold = myReader["Column1"];}
    }
    catch
    {
// table doesn't exist we create it
SqlCommand myCommand = new SqlCommand("CREATE TABLE [dbo].GoogleOAuthUser( " +
  " username [nvarchar](100) NOT NULL," +
  " RefreshToken [nvarchar](4000) NOT NULL," +
  " Userid [nvarchar](50) NOT NULL" +
   " ) ON [PRIMARY]", myConnection);
myCommand.ExecuteNonQuery();
    }
}

myConnection.Close();
}
/// Stores the given value for the given key. It creates a new 
    ///file (named <see cref="GenerateStoredKey"/>) in 
<typeparam name="T">///type to store in the data store</typeparam>
/// <param name="key">The key</param>
/// <param name="value">The value to store in the data store</param>
public Task StoreAsync<T>(string key, T value)
{
if (string.IsNullOrEmpty(key))
{
    throw new ArgumentException("Key MUST have a value");
}
var serialized = NewtonsoftJsonSerializer.Instance.Serialize(value);
SqlConnection myConnection = this.connectdb();
if (!_IsConnected)
{
    throw new Exception("Not connected to the database");
}
// Try and find the Row in the DB.
using (SqlCommand command = new SqlCommand
    ("select Userid from GoogleOAuthUser where UserName = @username", myConnection))
{
    command.Parameters.AddWithValue("@username", key);
    string hold = null;
    SqlDataReader myReader = command.ExecuteReader();
    while (myReader.Read())
    {
hold = myReader["Userid"].ToString();
    }
    myReader.Close();
    if (hold == null)
    {
try
{
// New User we insert it into the database
string insertString = "INSERT INTO [dbo].GoogleOAuthUser  (username,RefreshToken,Userid) " +
  " VALUES (@key,@value,'1' )";
SqlCommand commandins = new SqlCommand(insertString, myConnection);
commandins.Parameters.AddWithValue("@key", key);
commandins.Parameters.AddWithValue("@value", serialized);
commandins.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new Exception("Error inserting new row: " + ex.Message);
}
    }
    else
    {
try
{
// Existing User We update it
string insertString = "update GoogleOAuthUser " +
  " set  RefreshToken= @value  " +
  " where username = @key";
SqlCommand commandins = new SqlCommand(insertString, myConnection);
commandins.Parameters.AddWithValue("@key", key);
commandins.Parameters.AddWithValue("@value", serialized);
commandins.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new Exception("Error updating user: " + ex.Message);
}
    }
}
   myConnection.Close();
return TaskEx.Delay(0);
}
/// <summary>
/// Deletes the given key. It deletes the <see cref="GenerateStoredKey"/>
 /// named file in <see cref="FolderPath"/>.
/// </summary>
/// <param name="key">The key to delete from the data store</param>
public Task DeleteAsync<T>(string key)
{
if (string.IsNullOrEmpty(key))
{
    throw new ArgumentException("Key MUST have a value");
}
SqlConnection myConnection = this.connectdb();
if (!_IsConnected)
{
    throw new Exception("Not connected to the database");
}
// Deletes the users data.
string deleteString = "delete GoogleOAuthUser from " +
  " where username = @key";
SqlCommand commandins = new SqlCommand(deleteString, myConnection);
commandins.Parameters.AddWithValue("@key", key);
commandins.ExecuteNonQuery();
myConnection.Close();
return TaskEx.Delay(0);
}
public Task<T> GetAsync<T>(string key)
{
//Key is the user string sent with AuthorizeAsync
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("Key MUST have a value");}
TaskCompletionSource<T> tcs = new TaskCompletionSource<T>();
ConnectionStringSettings mySetting = ConfigurationManager.ConnectionStrings["strSqlConnection"];
if (mySetting == null || string.IsNullOrEmpty(mySetting.ConnectionString))
    throw new Exception("Fatal error: missing connecting string in web.config file");
string connString = mySetting.ConnectionString;
   SqlConnection objConn = new SqlConnection(connString);
objConn.Open();
// Try and find the Row in the DB.
using (SqlCommand command = new SqlCommand("select RefreshToken from GoogleOAuthUser 
    where UserName = @username;", objConn))
{
    command.Parameters.AddWithValue("@username", key);
    string RefreshToken = null;
    SqlDataReader myReader = command.ExecuteReader();
    while (myReader.Read())    {
RefreshToken = myReader["RefreshToken"].ToString();
    }
    if (RefreshToken == null)
    {
// we don't have a record so we request it of the user.
tcs.SetResult(default(T));
    }
    else
    {
try
{
// we have it we use that.
tcs.SetResult(NewtonsoftJsonSerializer.Instance.Deserialize<T>(RefreshToken));
}
catch (Exception ex)
{
tcs.SetException(ex);
}
    }
}
return tcs.Task;
}
/// <summary>
/// Clears all values in the data store. 
///This method deletes all files in <see cref="FolderPath"/>.
/// </summary>
public Task ClearAsync()
{
SqlConnection myConnection = this.connectdb();
if (!_IsConnected)
{
    throw new Exception("Not connected to the database");
}
// Removes all data from the Table.
string truncateString = "truncate table [dbo].GoogleOAuthUser ";
SqlCommand commandins = new SqlCommand(truncateString, myConnection);
commandins.ExecuteNonQuery();
myConnection.Close();
return TaskEx.Delay(0);
}

/// <summary>Creates a unique stored key based on the key and the class type.</summary>
/// <param name="key">The object key</param>
/// <param name="t">The type to store or retrieve</param>
public static string GenerateStoredKey(string key, Type t)
{
return string.Format("{0}-{1}", t.FullName, key);
}
//Handel's creating the connection to the database
private SqlConnection connectdb()
{
ConnectionStringSettings mySetting = ConfigurationManager.ConnectionStrings["strSqlConnection"];
if (mySetting == null || string.IsNullOrEmpty(mySetting.ConnectionString))
    throw new Exception("Fatal error: missing connecting string in web.config file");
string connString = mySetting.ConnectionString;
SqlConnection myConnection = null;
try
{
    myConnection = new SqlConnection(connString);
    try
    {
myConnection.Open();  
if (myConnection.State == System.Data.ConnectionState.Open)
{
_IsConnected = true;
}
else
{
throw new ArgumentException("Error unable to open connection to the database.");
}
    }
    catch (Exception ex)
    {
throw new ArgumentException("Error opening Connection to the database: " + ex.Message);
    }

}
catch (Exception ex)
{
    throw new ArgumentException("Error creating Database Connection: " + ex.Message);
}

return myConnection;
}

    }
}
The authorization sequence begins when your application redirects a browser to a Google URL; the URL includes query parameters that indicate the type of access being requested. Google handles the user authentication, session selection, and user consent. The result is an authorization code, which the application can exchange for an access token and a refresh token.
The application should store the refresh token for future use and use the access token to access a Google API. Once the access token expires, the application uses the refresh token to obtain a new one.

RETRIEVING EVENTS FROM GOOGLE CALENDAR

Here's a c# code snippet that returns upcoming events from a Google calendar
 //   // Create Calendar Service.
service = new CalendarService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = ApplicationName,
});

// Define parameters of request.
EventsResource.ListRequest request = service.Events.List("primary");
request.TimeMin = DateTime.Now;
request.ShowDeleted = false;
request.SingleEvents = true;
request.MaxResults = 10;
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;
Console.WriteLine("Upcoming events for Shabir:");
Console.WriteLine("====================================================");
Events events = request.Execute();
if (events.Items.Count > 0)
{
    foreach (var eventItem in events.Items)
    {
string when = eventItem.Start.DateTime.ToString();
string title = eventItem.Description.ToString();
string organizer = eventItem.Organizer.Email.ToString();
if (String.IsNullOrEmpty(when))
{
when = eventItem.Start.Date;
}
Console.WriteLine("{0}" + Environment.NewLine + "{1}" + Environment.NewLine + "  
     {2}" + Environment.NewLine + "   {3}", eventItem.Summary, when, title, organizer);
Console.WriteLine("------------------------------------------------------");
    }

}
else
{
    Console.WriteLine("No upcoming events found.");
}

INSERTING EVENTS INTO GOOGLE CALENDAR

Here's a c# code snippet that inserts events into Google calendar
 
Event newEvent = new Event();
newEvent.Summary = "Shabir Meeting";
newEvent.Description = "Today going to discuss regarding OAuth Protocol";
newEvent.Start = new EventDateTime();
newEvent.Start.DateTime = DateTime.Now.AddHours(5);
newEvent.End = new EventDateTime();
newEvent.End.DateTime = DateTime.Now.AddHours(8);
service.Events.Insert(newEvent, "primary").ExecuteAsync();
Console.Read();
  
 

IMPORTANT POINTS

1) There are three types of client IDs, so be sure to get the correct type for your application: There are three types of client IDs, so be sure to get the correct type for your application:
  1. Web application client IDs
  2. Installed application client IDs
  3. Service Account client IDs
2)Keep your client secret private. If someone obtains your client secret, they could use it to consume your quota, incur charges against your Console project, and request access to user data.

Friday, 29 January 2016

WCF Data Services with ASP.NET Application to Expose Data as oData

Overview

Download Solution from here

WCF Data Services (formerly ADO.NET Data Services,) is a platform for what Microsoft calls Data Services. It is actually a combination of the runtime and a web service through which the services are exposed. WCF Data Services exposes data, represented as Entity Data Model (EDM) objects, via web services accessed over HTTP. The data can be addressed using a REST-like URI. The data service, when accessed via the HTTP GET method with such a URI, will return the data. The web service can be configured to return the data in either plain XML, JSON or RDF+XML. In the initial release, formats like RSS and ATOM are not supported, though they may be in the future. In addition, using other HTTP methods like PUT, POST or DELETE, the data can be updated as well. POST can be used to create new entities, PUT for updating an entity, and DELETE for deleting an entity.

Create ASP.NET application to expose data as OData

I will be walking you through creating an ASP.NET application that utilizes a WCF (Windows Communication Foundation) data service, along with the WCF Data Services Entity Framework Provider to render the data  as an OData endpoint.

In this article, I will be using Visual Studio 2015 Community version, which you can download for free by going to this link and clicking the Download button under Visual Studio Community.

You will create a sample data service that uses WCF Data Services to expose an Open Data Protocol (OData) feed that is based on the FaithDb sample database. The task involves the following basic steps:

  1. Create an ASP.NET Web application.

  2. Define the data model by using the Entity Data Model tools.

  3. Add the data service to the Web application.

  4. Enable access to the data service.

Create an ASP.NET Web application.

Once you have, open it up and create an ASP.NET Web Application using the Visual C# empty template. Name the project Faith.FaithDataService and save it somewhere on your local drive (see image below).

To define the data model

  1. In Solution Explorer, right-click the name of the ASP.NET project, and then click Add New Item.

  2. For the name of the data model, type ArticleModel.edmx.

  3. In the Entity Data Model Wizard, select Generate from Database, and then click Next

  4. Connect the data model to the database by doing one of the following steps, and then click Next:

    • If you do not have a database connection already configured, click New Connection and create a new connection.

    • If you have a database connection already configured to connect to the FaithDbdatabase, select that connection from the list of connections.


  5. On the final page of the wizard, select the check boxes for all tables in the database, and clear the check boxes for views and stored procedures.

  6. Click Finish to close the wizard.


To create the data service

  1. In Solution Explorer, right-click the name of your ASP.NET project, and then click Add New Item.

  2. In the Add New Item dialog box, select WCF Data Service.For the name of the service, type OurDataService.By default, the code-editor window opens. In Solution Explorer, the service will have the name, OurDataService, with the extension .svc.cs or .svc.vb

  3. In the code for the data service, replace the comment /* TODO: put your data source class name here */ in the definition of the class that defines the data service with the type that is the entity container of the data model, which in this case is NorthwindEntities. The class definition should look this the following:

    IMPORTANT POINT:Incase you are using entity framework 6 you need to install WCF Data service Entity Framework Provider like shown below

    Replace the base type of your DataService. For EF 5 or below, your data service should inherit from DataService<T> where T is a DbContext or ObjectContext. For EF 6 or greater, your data service should inherit from EntityFrameworkDataService<T> where T is a DbContext like shown below


To enable access to data service resources

  1. In the code for the data service, replace the placeholder code in the InitializeService function with the following:


    This enables authorized clients to have read and write access to all resources .You can set it for the specified entity sets also.

Next & Final Steps

You have successfully created a new data service that exposes an OData feed that is based on the FaithDbsample database, and you have enabled access to the feed for clients that have permissions on the ASP.NET Web application. Next, you will start the data service from Visual Studio and you will access the OData feed by submitting HTTP GET requests through a Web browser:

Run Asp.net Application and Set OurDataService.srv as startup Page or directly view ourservice.srv in browser  The output will be shown like shown below

if you will observe It is showing list of tables from database or list of entities Model is made of.



Same way you can check other entities like

 1)http://localhost:49902/OurDataService.svc/Articles/
2)http://localhost:49902/OurDataService.svc/ArticlesAuthories/

Hope this Helps


Thursday, 21 January 2016

Simple way to Develop , Build and Deploy your windows AZURE Cloud Service

AZURE Cloud Service



In this article, we are going to walk through how to create  and deploy your Windows AZURE Cloud Service.
It also provides a good introduction on how to quickly  create and set up your Windows AZURE Cloud Service for deployment.
 

Cloud Computing

The "cloud" in cloud computing can be defined as the set of hardware, networks, storage, services, and interfaces (I.T Infrastructure) that combine to deliver aspects of computing as a service. Cloud services can be software, infrastructure, and storage over the Internet (either as separate components or a complete platform) based on user demand.
It can also be defined next stage in the Internets evolution, providing the means by which everything — from computing power to computing infrastructure, applications and business processes can be delivered to you as a service wherever and whenever you need and will be charged on basis of usage like we use electricity and pay on basis of monthly usage..

Some businesses, such as Google and Amazon, already have most of their IT resources in the cloud. They have found that it can eliminate many of the complex constraints from the traditional computing environment, including space, time, power, and cost.
Now coming to Microsoft they have also setup cloud computing for their customers known as AZURE.

AZURE

Microsoft way of cloud computing :) Windows Azure is Microsoft's application platform for the public cloud. You can use this platform in many different ways. For instance, you can use Windows Azure to build a web application that runs and stores its data in Windows Azure data centers. You can use Windows Azure just to store data, with the applications that use this data running on-premises (that is, outside the public cloud). You can use Windows Azure to create virtual machines for development and test or to run SharePoint and other applications. You can use Windows Azure to build massively scalable applications with lots and lots of users. Because the platform offers a wide range of services, all of these things-and more-are possible.
 

Develop,Build and Deploy your windows AZURE Cloud Service in Steps



STEP 1. CREATE AN ACCOUNT
If you already have an account, connect by clicking on PORTAL

STEP2: CREATE A SERVICE CLOUD

  • Click on CLOUD SERVICE tab and  Click New (+ New)
Here it is possible to create a Quick Cloud Service and configure it again later or create a custom cloud service by chosing configuration.
  • So lets create a Quick Cloud Service and fill parameters such as URL, REGION OR AFFINITY GROUP , SUBSCRIPTION. Next click on link Create Cloud Service


  • Service created screen
        
Our Cloud Service is now created Quickly or Customized, lets get Azure SDK Tools so as to code our service logic.
  • Click on OurCustomersService and click on link install a Windows AZURE SDK, and our Visual Studio Version and Install it.
STEP 3: CREATE A CLOUD SERVICE PROJECT
Here we are going to create a WCF Service and deploy it on our cloud Service.
  • So, create a new Project ,chose Windows Azure Cloud Service template and WCF Service Web Role.
web role provides an environment for running web sites or applications as supported by Internet Information Services (IIS) 7.0


  • WCF web Service (OurCustomersService.svc) looks like as shown below:

  • To test this service locally first just create console application ,windows or web what ever you are comfort with .just fallow below steps
 
  1.   I will create windows console application to test this service
 



OUTPUT FROM THIS SERVICE IS:-



 Now Deployment

STEP 4 : DEPLOY A CLOUD SERVICE PROJECT
  • To deploy our Cloud Service, we have to Create a Package : chose our Service Configuration and Build Configuration and note the output directory or remove files to our custom directory.
  • Next , Go back again to our Portal, click on OurCustomersService,  and click on link New production deployment
  • Next  chose a deployment name and our Package and configuration files
  • Now reference our Cloud Service and test It

Hope this help..


Shabir

Sunday, 10 January 2016

How to retrieve a visitor's IP address,Region and other details

BRIEF INTRODUCTION:-

Every visitor i mean any user coming to your website/web application has an IP address. If  you want to keep track of user ip address along with other details. I
The issue  is when they're behind a proxy . So, here are the code snippets in ASP and .Net that first check for an IP addresses that's forwarded from behind a proxy, and if there's none then just get the IP address.


And here's the IP retriever with proxy detection in .Net (C#)

public string IpAddress()
{
    string strIpAddress;
    strIpAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    if (strIpAddress == null)
    {
       strIpAddress = Request.ServerVariables["REMOTE_ADDR"];
    }
    return strIpAddress;
}
And here's the same IP retriever with proxy detection in .Net, but in VB.Net (CODE BEHIND FILE OR FUNCTIONS)

Public Function IpAddress()
    Dim strIpAddress As String
    strIpAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
    If strIpAddress = "" Then
       strIpAddress = Request.ServerVariables("REMOTE_ADDR")
    End If
    IpAddress = strIpAddress
End Function
Now question is how you retieve all the details like counry,region,region code ,latitite and logitute
Here is the complate code for getting all details about user 
 private string GetVisitor()
{
//client connecting to a web server through an HTTP proxy or load balancer
String ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
{
ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
return ip;}
private DataTable GetLocation(string strIPAddress)
{
WebRequest rssReq = WebRequest.Create("http://freegeoip.net/xml/" + 
strIPAddress);
WebProxy px = new WebProxy("http://freegeoip.net/xml/" + strIPAddress, true);
rssReq.Proxy = px;
rssReq.Timeout = 2000;
try
{
WebResponse rep = rssReq.GetResponse();
XmlTextReader xtr = new XmlTextReader(rep.GetResponseStream());
DataSet ds = new DataSet();
ds.ReadXml(xtr);
return ds.Tables[0];
 }
catch
{return null;}
}
protected void btnGetIpaddress_Click(object sender, EventArgs e){
try{
DataTable dt = new DataTable();
dt = GetLocation(GetVisitor());
if (dt.Rows.Count > 0)
{
dvIpaddressdetail.DataSource = dt;
dvIpaddressdetail.DataBind();
}
string ipaddress= dt.Rows[0].Field<string>(0);
}
catch (Exception ex)
{
throw ex;
}
}


ASPX PAGE
 <div class="middle-form" >
<form name="form" autocomplete="off" runat="server">
<div class="row">
<h3 style="margin-left:20%;"> Lookup IP address and Domain location now with our 
free IP Locator.</h3>
</div>

<div class="row"> 
<asp:TextBox ID="txtipaddress" runat="server" Text="182.68.166.132" 
CssClass="text-holder"></asp:TextBox
</div>
<div class="row"> 
<asp:Button ID="btnGetIpaddress" runat="server" Text="Lookup IP Address With IP 
Lookup" OnClick="btnGetIpaddress_Click" CssClass="btn btn-blue"/> </div>

<div class="row" style="margin-top:15px!important;"><br />
<asp:DetailsView ID="dvIpaddressdetail" runat="server" Width="100%" 
CellPadding="4" ForeColor="#333333" GridLines="None" HeaderText="IP ADDRESS 
DETAIL" BorderColor="#EEEEEE" BorderStyle="Solid">
<AlternatingRowStyle BackColor="White" />

<CommandRowStyle BackColor="#F9F9F9" Font-Bold="True" />

<FieldHeaderStyle BackColor="#F2F2F2" Font-Bold="True" />

<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />

<HeaderStyle BackColor="#0099FF" Font-Bold="True" ForeColor="White" />

<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />

<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
</asp:DetailsView>

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
ControlToValidate="txtipaddress" ErrorMessage="*"></asp:RequiredFieldValidator>

<asp:HiddenField ID="txtlat" runat="server" ClientIDMode="Static" />

<asp:HiddenField ID="txtlon" runat="server" ClientIDMode="Static" />

</div>
</form>
</div>


See live demo of this http://shabirhakim.net/Tools/GetMyIPAddress.aspx

How to Build a Full-Stack Web App with Blazor

  Blazor Stack Overview Important Points: Blazor stack gives you options to create Web Applications without writing JavaScript (doesn't ...