Saturday, November 15, 2014

Microsoft Visual Studio 2015 for every developer in every platform

Microsoft release the ultimate developer tool next version for preview. Now  you can download it from Microsoft Visual Studio downloads . It is designed for support n every developer platform.

 And Microsoft enables the access to developer platform for developers as open source project It is one of favorite thing to my self. hopefully it will rapidly improve the new feature additions to the visual studio.

in 12 Nov 2014 Microsoft announced their .NET 2015 version as well with Visual Studio 2015. All the core stacks of those platforms are now open source. Here is some summery form the MSDN release notes
  • Over the coming months, we will be open sourcing the full server-side .NET Core stack, from ASP.NET 5 down to the Core Runtime and Framework, and the open source .NET will be expanded to run on Linux and Mac OS X in addition to Windows.
     
  • A preview of the next generation of our tools is available today with Visual Studio 2015 Preview and .NET 2015 Preview.  Together, these bring industry-leading cross-platform mobile development tools, deep support for cloud development, and great productivity improvements across the breadth of the developer experience.
  • Visual Studio Online is expanding its DevOps portfolio with the new Visual Studio Online Release Management service and Visual Studio Cloud Deployment Projects.

 With Visual studio 2015 developers can increase their focus on targeting the mobile device platform spanning iOS, Android and Windows, the need for cross-platform mobile development solutions has never been greater.

On top of great tools for building Universal Windows Applications, Visual Studio 2015 offers the most complete cross-platform mobile application development environment, with great solutions for C#, C++ and HTML/JavaScript development targeting iOS, Android, Windows and more.

Additionally It enables new rich emulators for android development that mostly smiler as windows Store app Emulators. It is very rich with Geo sensing , gestures etc. Now you don't need to vote on usual android bullshit emulator any more.

And Visual studio supports Apache Cordova and it enables to developers authoring, debugging, analyzing, packaging, and deploying HTML/ Javascript applications with Cordova in visual studio


Download ,  Enjoy and remember Contribute  To Visual Studio






Wednesday, November 12, 2014

NodeJs web service With MongoDb

NodeJs is one of the powerful Lagrange that can do lot of things in programming world. When size of data become larger most of databases not can handle them efficiently. Therefor it leads to the change of database structure. Relational (SQL) database is not the best solution in most cases. NoSQL (Not Only SQL) databases are the best solution in those situations. One of the best NoSQL databse is MongoDb.

You can follow above hyperlinks to download and configure Nodejs and MongoDb within your local machine. if you having trouble  just comment below..ill update another post about configurations.

With this post I am going to demonstrate how to create REST service with NodeJs and MongoDB

You can use SublimeText as text editor for node js

1 . First create Document in MongoDb Name it and UserDetails

2. Add following Data to that document
/* 0 */
{
    "_id" : ObjectId("54608e50feeb4595a4f09651"),
    "userName" : "Harith",
    "Age" : 25,
    "Expired" : true
}
 
/* 1 */
{
    "_id" : ObjectId("54608ea4feeb4595a4f09652"),
    "userName" : "Jaliya",
    "password" : "123456",
    "Age" : 30
}
 
/* 2 */
{
    "_id" : ObjectId("5461d46dfeeb4595a4f09655"),
    "name" : "Joe Bookreader",
    "address" : {
        "street" : "123 Fake Street",
        "city" : "Faketon",
        "state" : "MA",
        "zip" : "12345"
    }
}
 
/* 3 */
{
    "_id" : ObjectId("54608f20feeb4595a4f09653"),
    "UserId" : "1",
    "address" : {
        "street" : "123 Fake Street",
        "city" : "Faketon",
        "state" : "MA",
        "zip" : "12345"
    }
}


Lets start to create NodeJs REST

First create Javascript file named it as Rest.js

To use MongoDb you need to install flowing npm package by this command
 npm install mongojs

Then add package.json file to the root of the folder and copy this to it

{
  "name""Rest-server",
  "version""0.0.1",
  "private"true,
  "dependencies": {
    "express""3.3.4"
  }
}

Go to CMD and type npm install




Then start to coding real service in Rest,js

1. Import following libraries to the js file
var express = require('express');
var mongojs = require('mongojs');


2. Then create Array to store all data that comes from Mongo Database
var data = [];

3. Lets code REST Like this
// custom package
var app = express();
 
// Array definition to store data
var data = [];
 
// Http Normal get
app.get('/'function (req, res) {
    var db = require('mongojs').connect('mongodb://localhost:27017/DocumentOrDb');
    console.log("Server is in listen1");
    db.collection("UserDetails").find(function (err, docs) {
        data = [];
        docs.forEach(function (item) {
            data.push(item);
        })
    });
 
    console.log("Server end");
    res.send(data);
});

then run the service with cmd node Rest.js


Here is the full code


/*
  Rest Api with MongoDb Database 
  Author : prabathsl
  Copyright © prabathsl 2014
*/
 
// Libraries
var express = require('express');
var mongojs = require('mongojs');
 
// custom package
var app = express();
 
// Array definition to store data
var data = [];
 
// Http Normal get
app.get('/'function (req, res) {
    var db = require('mongojs').connect('mongodb://localhost:27017/DocumentOrDb');
    console.log("Server is in listen1");
    db.collection("SampleBigdata").find(function (err, docs) {
        data = [];
        docs.forEach(function (item) {
            data.push(item);
        })
    });
 
    console.log("Server end");
    res.send(data);
});


 Enjoy :) 



Thursday, November 6, 2014

Authentication with third party Auth providers in new era of Mobile Apps

When you are developing app, to increase security and manipulate users without taking user details is use authentication providers help such like Live, Google, Facebook, twitter , linked in, flickers etc.

With the newer versions of mobile BCL is not supported the olde way of authenticating with third party SDK's. All the BCL are updated with 8.1 and Universal apps.

With this post I'm gonna explain how to implement those authentication (ex: facebook)

1. you need to have facebook app. (http:\\developer.facebook.com)

To implement the Authentication you need to create separate class and interface that can handle Continuation events. Once authentication done it will redirect to the app using these Continuation objects.

Here is ContinuationManager Class that I used

using System.Text;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
 
#if WINDOWS_PHONE_APP
    /// <summary>
    /// ContinuationManager is used to detect if the most recent activation was due
    /// to a continuation such as the FileOpenPicker or WebAuthenticationBroker
    /// </summary>
    public class ContinuationManager
    {
        IContinuationActivatedEventArgs args = null;
        bool handled = false;
        Guid id = Guid.Empty;
 
        /// <summary>
        /// Sets the ContinuationArgs for this instance. Using default Frame of current Window
        /// Should be called by the main activation handling code in App.xaml.cs
        /// </summary>
        /// <param name="args">The activation args</param>
        internal void Continue(IContinuationActivatedEventArgs args)
        {
            Continue(args, Window.Current.Content as Frame);
        }
 
        /// <summary>
        /// Sets the ContinuationArgs for this instance. Should be called by the main activation
        /// handling code in App.xaml.cs
        /// </summary>
        /// <param name="args">The activation args</param>
        /// <param name="rootFrame">The frame control that contains the current page</param>
        internal void Continue(IContinuationActivatedEventArgs args, Frame rootFrame)
        {
            if (args == null)
                throw new ArgumentNullException("args");
 
            if (this.args != null && !handled)
                throw new InvalidOperationException("Can't set args more than once");
 
            this.args = args;
            this.handled = false;
            this.id = Guid.NewGuid();
 
            if (rootFrame == null)
                return;
 
            switch (args.Kind)
            {
               
 
                case ActivationKind.WebAuthenticationBrokerContinuation:
                    var wabPage = rootFrame.Content as IWebAuthenticationContinuable;
                    if (wabPage != null)
                    {
                        wabPage.ContinueWebAuthentication(args as WebAuthenticationBrokerContinuationEventArgs);
                    }
                    break;
            }
        }
 
        /// <summary>
        /// Marks the contination data as 'stale', meaning that it is probably no longer of
        /// any use. Called when the app is suspended (to ensure future activations don't appear
        /// to be for the same continuation) and whenever the continuation data is retrieved 
        /// (so that it isn't retrieved on subsequent navigations)
        /// </summary>
        internal void MarkAsStale()
        {
            this.handled = true;
        }
 
        /// <summary>
        /// Retrieves the continuation args, if they have not already been retrieved, and 
        /// prevents further retrieval via this property (to avoid accidentla double-usage)
        /// </summary>
        public IContinuationActivatedEventArgs ContinuationArgs
        {
            get
            {
                if (handled)
                    return null;
                MarkAsStale();
                return args;
            }
        }
 
        /// <summary>
        /// Unique identifier for this particular continuation. Most useful for components that 
        /// retrieve the continuation data via <see cref="GetContinuationArgs"/> and need
        /// to perform their own replay check
        /// </summary>
        public Guid Id { get { return id; } }
 
        /// <summary>
        /// Retrieves the continuation args, optionally retrieving them even if they have already
        /// been retrieved
        /// </summary>
        /// <param name="includeStaleArgs">Set to true to return args even if they have previously been returned</param>
        /// <returns>The continuation args, or null if there aren't any</returns>
        public IContinuationActivatedEventArgs GetContinuationArgs(bool includeStaleArgs)
        {
            if (!includeStaleArgs && handled)
                return null;
            MarkAsStale();
            return args;
        }
    }
 
    /// <summary>
    /// Implement this interface if your page invokes the web authentication
    /// broker
    /// </summary>
    interface IWebAuthenticationContinuable
    {
        /// <summary>
        /// This method is invoked when the web authentication broker returns
        /// with the authentication result
        /// </summary>
        /// <param name="args">Activated event args object that contains returned authentication token</param>
        void ContinueWebAuthentication(WebAuthenticationBrokerContinuationEventArgs args);
    }

To handle the continuation after authentication you nee to modify your app.xaml.cs as well. Because Once you redirect to auth providers screen you are exit (deactivate) your app. then once auth provider redirect back your app gets activate .

Create object of ContinuationManager  in App.xml.cs

public static ContinuationManager continuationManager { getprivate set; }

Then OnActivated event of the app add the continuation handle

protected async override void OnActivated(IActivatedEventArgs e)
{
   continuationManager = new ContinuationManager();
 
   //Check if this is a continuation 
   var continuationEventArgs = e as IContinuationActivatedEventArgs;
   if (continuationEventArgs != null)
   {
	continuationManager.Continue(continuationEventArgs);
   }
 
  Window.Current.Activate(); 
}



Then you are free to go with any kind of authentication that provide from auth provider 

    internal async Task FacebookLoginMethod()
        {
            String FacebookURL = "https://www.facebook.com/dialog/oauth?client_id=" + Uri.EscapeDataString("Your app Id") + "&redirect_uri=" + Uri.EscapeDataString("https://m.facebook.com/dialog/return/ms") + "&scope=read_stream&display=popup&response_type=token";
 
            System.Uri StartUri = new Uri(FacebookURL);
//To use windows phone or windows app with Fb authentication user this end uri and redirect uri. Both are working 
             System.Uri EndUri = new Uri("https://m.facebook.com/dialog/return/ms");
 
#if WINDOWS_PHONE_APP
            try
            {
                WebAuthenticationBroker.AuthenticateAndContinue(StartUri, EndUri, null, WebAuthenticationOptions.None);
            }
            catch
            {
 
            }
#endif
        }


and use this ContinueWeb authentication method inside the page that you call authentication. otherwise it will not working. Inherit the IWebAuthnticationContinuable interface to the page and add this method

public async void ContinueWebAuthentication(WebAuthenticationBrokerContinuationEventArgs args)
       {
           WebAuthenticationResult result = args.WebAuthenticationResult;
           if (result.ResponseStatus == WebAuthenticationStatus.Success)
           {
               token = await FilterToken(result.ResponseData.ToString());
 
           }
           else
           {
               MessageDialog Msg = new MessageDialog("Login failed");
               Msg.ShowAsync();
           }
 
       }


This WebAuthentication result wil contains the Authprovider's access token. Filterout it and do what ever graph is available with authentication provider. 


Enjoy ..








HttpClient Caching

Is any one of you have an experience on when send http request through http client the response become the same (no change) even your source of the response (server) is updated.

It is the way that default http protocol behaves

By default HttpClient use a cache to store responses that come up with response headers without Cache-Control header. ( Ref: HTTP Header fields)

In a scenario you need to change the cache behavior with HttpClient you can have two options

1. Edit the service (server) to response with relevant cache headers
2. Modify your request headers

Edit the service (server) to response with relevant cache headers

In this model it give two benefits to you
  • A content you will not use again is not stored in the client machine.
  • Other requests can benefit from the cache (when using the same instance of HttpClient).
In your web service go to web.config file and in-side the system.serviceModel add following tag with relevant headers you need


     <client>
      <endpoint address="http://localhost/..." >
        <headers>
          <Cache-Control>no-cache</Cache-Control>
        </headers>
      </endpoint>
    </client>


Modify your request headers

if you don't have the access to the server you can go with this option. Just ad additional header with HttpClient and send the request then response automatically include these headers

HttpClient Client = new HttpClient();
Client.DefaultRequestHeaders.Add("Cache-Control""no-cache");


Now your HttpClient is ready to handle http request with no cache .


here is Cache contol values that provide from W3 with Http headers.

    cache-directive = cache-request-directive
         | cache-response-directive
    cache-request-directive =
           "no-cache"                          
         | "no-store"                          
         | "max-age" "=" delta-seconds         
         | "max-stale" [ "=" delta-seconds ]   
         | "min-fresh" "=" delta-seconds       
         | "no-transform"                      
         | "only-if-cached"                    
         | cache-extension                     
     cache-response-directive =
           "public"                               
         | "private" [ "=" <"> 1#field-name <"> ] 
         | "no-cache" [ "=" <"> 1#field-name <"> ]
         | "no-store"                             
         | "no-transform"                         
         | "must-revalidate"                      
         | "proxy-revalidate"                     
         | "max-age" "=" delta-seconds            
         | "s-maxage" "=" delta-seconds           
         | cache-extension 
 
 
 
 Enjoy the code ..