Monday, 11 February 2013

Google Plus Authentication in asp.net and c#

How to get google api access:


1. Open https://code.google.com/apis/console/?pli=1
2. Login by your gmail account.
3. Click on API Access option from left side.

 4. Click Create an OAuth 2.0 client ID.. button.
 5. It will open a dialog box.
6. Set Product Name (example: test), Product Logo (optional), Home Page URL (example: http://localhost/website/Default.aspx).
7. Click Next by filling all above information. It will open Next window.

8. Click Create client ID. It will give Branding Information.
9. Redirect URIs is blank in above image. Click on Edit Settings.. from right side vertical menu.
10. It will open a new window to fill Authorized Redirect URIs . It may be same url as Home page url, example: http:localhost/website/default.aspx. Leave Authorized JavaScript Origins as blank.

By above steps, you will get Client ID and Redirect URIs that will be used in further steps.


ASP.Net application:

In below code, first set your Client ID and Redirect URI.

I have given example to show logged in Username and profile image, you can use it in any other way also.
In function getUserInfo(), you can get result as username, email and etc..
jQuery Link: jQuery.js
If you get any issue to find above jQuery file, please mail me at vdtrip@gmail.com .

<HTML><Head>


 <script src="jquery.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
var OAUTHURL    =   'https://accounts.google.com/o/oauth2/auth?';
        var VALIDURL    =   'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=';
        var SCOPE       =   'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email';
        var CLIENTID    =   '13226233322131.apps.googleusercontent.com';
        var REDIRECT = 'http://localhost/WebSite/default.aspx';
        var LOGOUT      =   'http://accounts.google.com/Logout';
        var TYPE        =   'token';
        var _url        =   OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE;
        var acToken;
        var tokenType;
        var expiresIn;
        var user;
        var loggedIn    =   false;

   
        function login() {
            var win         =   window.open(_url, "windowname1", 'width=800, height=600');

            var pollTimer   =   window.setInterval(function() {
                try {
                    console.log(win.document.URL);
                    if (win.document.URL.indexOf(REDIRECT) != -1) {
                        window.clearInterval(pollTimer);
                        var url =   win.document.URL;
                        acToken =   gup(url, 'access_token');
                        tokenType = gup(url, 'token_type');
                        expiresIn = gup(url, 'expires_in');
                        win.close();

                        validateToken(acToken);
                    }
                } catch(e) {
                }
            }, 500);
        }

        function validateToken(token) {
            $.ajax({
                url: VALIDURL + token,
                data: null,
                success: function(responseText){ 
                    getUserInfo();
                    loggedIn = true;
                    $('#loginText').hide();
                    $('#logoutText').show();
                }, 
                dataType: "jsonp" 
            });
        }

        function getUserInfo() {
            $.ajax({
                url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken,
                data: null,
                success: function(resp) {
                    user    =   resp;
                    console.log(user);
                    $('#uName').text('Welcome ' + user.name);
                    $('#imgHolder').attr('src', user.picture);
                },
                dataType: "jsonp"
            });
        }

        //credits: http://www.netlobo.com/url_query_string_javascript.html
        function gup(url, name) {
            name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
            var regexS = "[\\#&]"+name+"=([^&#]*)";
            var regex = new RegExp( regexS );
            var results = regex.exec( url );
            if( results == null )
                return "";
            else
                return results[1];
        }

        function startLogoutPolling() {
            $('#loginText').show();
            $('#logoutText').hide();
            loggedIn = false;
            $('#uName').text('Welcome ');
            $('#imgHolder').attr('src', 'none.jpg');
        }
  

</script>
</Head>
<body>
 <a href='#' onClick='login();' id="loginText"'> Google Plus </a>
  <a href="#" style="display:none" id="logoutText" target='myIFrame' onclick="myIFrame.location='https://www.google.com/accounts/Logout'; startLogoutPolling();return false;"> Click here to logout </a>
    <iframe name='myIFrame' id="myIFrame" style='display:none'></iframe>
    <div id='uName'></div>
    <img src='' id='imgHolder'/>

</body>
</HTML>






Change phone number format using extension method in C# and asp.net

Extension Method is a very popular topic in C# that is used to increase the functionality of any Type variable that is mostly used in whole application or in terms of single use also. Best example we can see for Phone Number Format, user can enter 10 digit number in text box and we need to save it in different format for example US Phone Number Format (xxx)-(xxxx)-xxx.

First create a static class with a static method. Here I have posted a code example for Extension Method Of String Type. This example converts a normal Phone number in US format. You can write here your own code for any functionality. The main point is this keyword in Method USPhoneNumberFormat(this string value), it will fetch value from current string object.

Class:
public static class ExtensionMethods
    {
        public static string USPhoneNumberFormat(this string value)
        {
            if (value.Length == 10)
            {
                StringBuilder phoneNumber = new StringBuilder();                    

               for (int i = 0; i < 10; i++)
                {
                    if (i == 0)
                    {                       
                        phoneNumber.Append("(");
                        phoneNumber.Append(value[i]);
                    }
                    else if (i == 3 )
                    {
                        phoneNumber.Append(")-(");
                        phoneNumber.Append(value[i]);
                    }
                    else if (i == 7 )
                    {
                        phoneNumber.Append(")-");
                        phoneNumber.Append(value[i]);
                    }
                    else
                    {
                        phoneNumber.Append(value[i]);
                    }
                }
                return phoneNumber.ToString();
               }
            return value;
        }
    }

aspx.cs page:

 string value = "1234560789";
 value=value.USPhoneNumberFormat();




Saturday, 9 February 2013

Image uploading through REST API in wcf

Image can be uploaded in byte form in database through image streaming. Here I have pasted a wcf code that will save image in byte form in database. Image should be posted in stream form on service.

WCF:

Interface(contract):

   [ServiceContract]
    public interface IAPIService
    {
        [OperationContract]              
        [WebInvoke(ResponseFormat = WebMessageFormat.Json,
 UriTemplate = "PostImage", Method = "POST")]
        string PostImage(Stream sm);
        
    } 

Service file (svc):

 public class APIService : IAPIService
    { 

      public string PostImage(Stream sm)
         {
           System.Drawing.Bitmap imag = new System.Drawing.Bitmap(sm);
           byte[] imagedata = ImageToByte(imag);
            //Write code here to Save byte code to database..
          return "success";
        }

       public static byte[] ImageToByte(System.Drawing.Image img)
        {
           
            ImageConverter converter = new ImageConverter();
            return (byte[])converter.ConvertTo(img, typeof(byte[]));
        }
   }

Client Side Code:


public void PostData()
    {
        try
        {
             byte[] fileToSend = null;
        string name = "";
        
        if (FileUpload1.HasFile)
        {
            name = FileUpload1.FileName;
            Stream stream = FileUpload1.FileContent;
            stream.Seek(0, SeekOrigin.Begin);
            fileToSend = new byte[stream.Length];
            int count = 0;
            while (count < stream.Length)
            {
                fileToSend[count++] = Convert.ToByte(stream.ReadByte());
            }
            
        }

        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create 
                       ("www.abc.com/APIService.svc/PostImage");
      
        req.Method = "POST";
        req.ContentType = "application/octet-stream";
        req.ContentLength = fileToSend.Length;
        Stream reqStream = req.GetRequestStream();
        reqStream.Write(fileToSend, 0, fileToSend.Length);
        reqStream.Close();

        HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

        StreamReader reader = new StreamReader(resp.GetResponseStream());

        string result = reader.ReadToEnd();
        }
        catch (Exception ex)
        {
            
            throw ex;
        }
    }

Check email duplicacy with custom validator in asp.net

When we work on sign up page, mostly we need to check whether entered email id is duplicate in database. Either it can be achieved by server side or client side javascript/jQuery. We can use asp.net CustomValidator easily for this purpose. Below I have given controls and javascript function that is used for Validation.

JavaScript:

<script language="javascript" type="text/javascript">
    function CheckName(sender, args) {
        var txt = document.getElementById('<%=txtName.ClientID %>').value;
var count=  getDataFromDatabaseThroughWebServiceOrJavaScript(txt);
         if (count >0) {
     //if Email is already available
        args.IsValid = false;
    }
    else {
        args.IsValid = true;
    }  
   
    }
</script>

ASPX Page:

<asp:TextBox runat="server" ID="txtName" ValidationGroup="checkEmail"></asp:TextBox>

<asp:CustomValidator ID="cstVal" runat="server" ValidationGroup="checkEmail"
        ValidateEmptyText="true" Display="Dynamic" ControlToValidate="txtName" 
        ErrorMessage="Email is available already!" ClientValidationFunction="CheckName" EnableClientScript="true" ></asp:CustomValidator>

<asp:Button ID="btnSubmit" runat="server" ValidationGroup="checkEmail" />

 In CustomValidation control,  ClientValidationFunction property should to be set to Java Script function name, like in this example CheckName is ClientValidationFunction. And  EnableClientScript should be set to True.