google

Newest Post

Showing posts with label C#.NET. Show all posts
Showing posts with label C#.NET. Show all posts

Convert base64 into Image, Resize the image and again convert it into base64

| Saturday, March 5, 2016
Read more »
Convert base64 into Image, Resize the image and again convert it into base64

Use Following Code:

                       byte[] bytes = (byte[])row["Picture"];

                        Image image;

                       //Convert byte[] into image
                        using (MemoryStream ms = new MemoryStream(bytes))
                        {
                            image = Image.FromStream(ms);
                        }

                        // Resize the image
                        Bitmap b = new Bitmap(200, 200);
                        Graphics g = Graphics.FromImage((Image)b);
                        g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                        g.DrawImage(image, 0, 0, 200, 200);
                        g.Dispose();
                        image = (Image)b;

                        using (MemoryStream ms = new MemoryStream())
                        {
                            // Convert Image to byte[]
                            image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                            byte[] imageBytes = ms.ToArray();

                            // Convert byte[] to Base64 String
                            string base64String = Convert.ToBase64String(imageBytes);
                            obj.StudentPicture = base64String;
                        }

Convert base64 into Image, Resize the image and again convert it into base64

Posted by : Stranger
Date :Saturday, March 5, 2016
With 0comments

Code to export the Grid View/Data Grid data into Excel File.

| Friday, February 13, 2015
Read more »
 protected void btnExportToExcel_Click(object sender, EventArgs e)  
   {  
     try  
     {  
       DataTable dt = student.GetDetails("B.Tech").Tables[0];  
       DataGrid GridView1 = new DataGrid();  
       GridView1.DataSource = dt;  
       GridView1.DataBind();  
       Response.Clear();  
       Response.Buffer = true;  
       Response.AddHeader("content-disposition", string.Format("attachment; filename=StudentsBTech.xls"));  
       Response.Charset = "";  
       Response.ContentType = "application/vnd.ms-excel";  
       StringWriter sw = new StringWriter();  
       HtmlTextWriter htw = new HtmlTextWriter(sw);  
       GridView1.GridLines = GridLines.Both;  
       GridView1.AllowPaging = false;  
       GridView1.RenderControl(htw);  
       Response.Output.Write(sw.ToString());  
       GridView1.DataBind();  
       Response.Flush();  
     }  
     catch (Exception ex)  
     {  
     }  
     finally { Response.End(); }  
   }  
   public override void VerifyRenderingInServerForm(Control control)  
   { }  

Code to export the Grid View/Data Grid data into Excel File.

Posted by : Stranger
Date :Friday, February 13, 2015
With 0comments

Could not add reference to "System.Net.Http.Formatting" namespace in WPF web api client project

| Friday, December 12, 2014
Read more »
For adding the reference in your web api client

1. Right click on "References" in the solution.
2. Following window will open.


3. Select location "Extension" as shown above and check "System.Net.Http.Formatting" namespace
4. and DONE!!!

Integrating PushSharp In the WCF Restful Web Service to display Push Notifications in Apple, Android and Windows devices

| Monday, September 29, 2014
Read more »
Hello Folks, Today I will demonstrate the method of integrating the PushSharp library in WCF Restful Web Service to send the Push Notifications to Apple, Android and Windows devices.


This library and its documentation is available on the GitHub at following link

Redth/PushSharp


Create a new WCF web service in the Visual Studio(Here I am using Visual Studio 2012). After creating the Web Service, Go to Tools-> NuGet Package Manager -> Manage NuGet Packages for Solution as shown in following image.




In the Package Manager, Search "PushSharp" 


After installing PushSharp NuGet Package, following dlls will be added in the bin folder of the solution. 




Next are the lines of the code which are used to send the notifications from the web service. Please consider following is the minimalist code required to send notifications to devices. For additional functionality, please go through the samples given in the GitHub library of PushSharp.

For Sending Push Notifications to the Android device.

 public void SendAdnoirdPush(string APIKey, string DeviceID, string Message)  
   {  
     var push = new PushBroker();  
     push.RegisterGcmService(new GcmPushChannelSettings(APIKey));  
     push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(DeviceID)  
             .WithJson("{\"alert\":\"" + Message + "\",\"badge\":7,\"sound\":\"sound.caf\"}"));  
   }  

APIKey of the App can be obtained from the Google Developer Console.
DeviceId of the device using the App.
Message to be displayed in the Notification.


For Sending Push Notifications to the iOS device.

 public void SendiOSPush(string DeviceID, string Message, string sound)  
   {  
     var push = new PushBroker();  
     var appleCert = File.ReadAllBytes(new DirectoryInfo(HostingEnvironment.ApplicationPhysicalPath) + "/pushNotificatio.p12");  
     push.RegisterAppleService(new ApplePushChannelSettings(true, appleCert, "CertificatePassword"));  
     push.QueueNotification(new AppleNotification()  
                   .ForDeviceToken(DeviceID)  
                   .WithAlert(Message)  
                   .WithBadge(7)  
       .WithSound(sound));  
     //.WithSound("sound.caf")); //default  
   }  

DeviceId of the device using the App.
Message to be displayed in the Notification
sound to be played with Notification

For implementing the iOS Notifications, a signed certificate is required to be generated from the Developer Console. That certificate is copied in the system and Path is given as in the method above. 
Please be careful while mapping the path of the certificate. The certificate is different for sandbox and production
RegisterAppleService requires the certificate password. 

For Sending Push Notifications to the Windows phone.

 public void SendWindowsPhonePush(string ChannelUri, string pageName, string Header, string Message)  
   {  
     var push = new PushBroker();  
     push.RegisterWindowsPhoneService();  
     push.QueueNotification(new WindowsPhoneToastNotification()  
     .ForEndpointUri(new Uri(ChannelUri))  
     .ForOSVersion(WindowsPhoneDeviceOSVersion.Eight)  
     .WithBatchingInterval(BatchingInterval.Immediate)  
     .WithNavigatePath("/" + pageName)  
     .WithText1(Header)  
     .WithText2(Message));  
   }  

ChannelUri is the unique identifier for each device using the App
pageName to navigate to when notification is clicked
Header to be displayed in the Notification Header
Message to be displayed in the Notification Message


and voila!!!! DONE

Above methods can also be combined into one method to send notification to all types of devices., also If notifications are to be sent to multiple devices of same OS, then a "for" loop can be traversed as per the requirement for each method.

Convert DataSet or DataTable into JSON in C#

| Tuesday, June 10, 2014
Read more »
 public string ConvertToJSON(DataSet ds)  
 {  
 System.Web.Script.Serialization.JavaScriptSerializer serializer = 
new System.Web.Script.Serialization.JavaScriptSerializer();  
     List<Dictionary<string, object>> rows = 

new List<Dictionary<string, object>>();  
     Dictionary<string, object> row = null;  
     foreach (DataRow dr in ds.Tables[0].Rows)  
     {  
       row = new Dictionary<string, object>();  
       foreach (DataColumn col in ds.Tables[0].Columns)  
       {  
         row.Add(col.ColumnName.Trim(), dr[col]);  
       }  
       rows.Add(row);  
     }  
     return serializer.Serialize(rows);  
 }  

Convert DataSet or DataTable into JSON in C#

Posted by : Stranger
Date :Tuesday, June 10, 2014
With 0comments

Update the .edmx file when the database changes

| Saturday, May 17, 2014
Read more »
To update the .edmx file when the database changes

  1. In the Model Browser, right-click the .edmx file and select Update Model from Database.
  2. The Update Model Wizard starts. If there is no database connection specified, the Choose Your Database Connection dialog box appears. Otherwise, the Choose Your Database Objects dialog box appears. 
  3. If the Choose Your Database Connection dialog box appears, specify a database connection. Otherwise, go to the next step.
  4. For details about specifying a connection, see Choose Your Data Connection Dialog Box (Entity Data Model Wizard). When you have specified the connection, click Next to display the Choose Your Database Objects dialog box.
  5. Click the Add tab.
    Nodes for tables, views, and stored procedures are displayed. If any objects have been added to the database (or were not included in the previous storage model), you can expand the corresponding node to view the objects that are available to add to the conceptual model.
  6.  If an object has been deleted from the conceptual model but has not also been deleted from the storage model, the object will not be available to add to the conceptual model.
  7. Expand the Tables, Views, and Stored Procedures nodes, and check the objects you want to add to the .edmx file.
  8. Click the Refresh tab.
    Nodes for tables, views, and stored procedures that are included in the existing storage model are displayed. Any changes that have been made to these database objects will be reflected in the updated storage model. Changes to the conceptual model are made when columns are added to a table or view.
  9. Click the Delete tab.
    Nodes for tables, views, and stored procedures are displayed. If an object has been deleted from the database and was included in the previous storage model, you can expand the corresponding node. The objects in these nodes will be deleted from the updated model.
    Click Finish to update the .edmx file with the database changes.

Reference - MSDN

Update the .edmx file when the database changes

Posted by : Stranger
Date :Saturday, May 17, 2014
With 0comments

How to apply RowFilter on DataView

| Friday, May 9, 2014
Read more »
Following code can be used to apply filter on the DataView

 DataSet ds = new DataSet();  
 ds= GetData();  
 DataView dv = ds.Tables[0].DefaultView;  
 dv.RowFilter = "SrNo='" + txtSNo.Text.Trim() + "'";   


LIKE, AND , OR operators can also be used in the RowFilter of Dataview.

To access the filtered records, each DataRowView of the DataView

 foreach (DataRowView drv in dv)  
       {  
         currentName = Convert.ToString(drv["Name"]);  
       }  



How to apply RowFilter on DataView

Posted by : Stranger
Date :Friday, May 9, 2014
With 0comments

Unable to find the requested .Net Framework Data Provider. It may not be installed.

| Thursday, April 10, 2014
Read more »
Above error can be caused by if the "Provider" given in "SqlDataSource" or any other data source control is not updated.

This error can be resolved either by updating the Provider details in connection string property of web.config file or you simply remove the

 ProviderName="<%$ ConnectionStrings:DbConnectionString.ProviderName %>"  


from SqlDataSource control or any other data source control.

Convert byte[] array into base64 string in C#.NET or ASP.NET

| Wednesday, April 2, 2014
Read more »
Following is the code which can be used to convert an Image data from the SQL Server Database Image type column. SQL Server returns image column in the format of byte array i.e byte[].

  if (ds.Tables.Count > 0)  
       {  
         if (ds.Tables[0].Rows.Count > 0)  
         {  
           string MyImage = Convert.ToBase64String((byte[]) ds.Tables[0].Rows[0]["MySnap"]);  
          }  
       }  

We can retrieve the image column in DataSet or using the DataReader and then use Convert.ToBase64String() method to convert it into base64 string.

Above code can also be used for WCF service methods while sending data from database to mobile devices or some other purpose.

Convert byte[] array into base64 string in C#.NET or ASP.NET

Posted by : Stranger
Date :Wednesday, April 2, 2014
With 0comments

ScriptManager.RegisterStartupScript using JavaScriptSerializer - To display the Alert or Message Box from Code behind

| Thursday, March 13, 2014
Read more »
While registering a message using the javascript code in RegisterStartupScript, message might contain some escape characters like ' or " this will definitely break the javascript. Hence we need to encode it, for example using JavaScriptSerializer as follows.



  string message = new JavaScriptSerializer().Serialize(ex.Message.ToString());  
  string myScript = String.Format("alert('{0}');", msg);  
  ScriptManager.RegisterStartupScript(page, page.GetType(), "MyScript", myScript, true);  




How to use Built-in Content Filters of RadEditor to enable Absolute URLs

| Thursday, February 6, 2014
Read more »
RadEditor provides feature to upload images, documents, videos etc along with the content. The default path for uploading and viewing these attachments is the path relative to the website.

To make the path absolute for certain situations, add ContentFilters="MakeUrlsAbsolute" attribute to the RadEditor as follows.


  <telerik:RadEditor runat="server" ID="RadEditor1" SkinID="DefaultSetOfTools" Height="400px" ContentFilters="MakeUrlsAbsolute"  
         Width="100%" CssClass="addeditor">  
         <Content>  
         </Content>  
         <ImageManager ViewPaths="~/Upload" UploadPaths="~/Upload" DeletePaths="~/Upload"></ImageManager>  
         <DocumentManager MaxUploadFileSize='2100000' ViewPaths="~/Upload" UploadPaths="~/Upload" DeletePaths="~/Upload"></DocumentManager>  
       </telerik:RadEditor>  

It will make all src attributes in the editor content to have absolute URLs

How to use Built-in Content Filters of RadEditor to enable Absolute URLs

Posted by : Stranger
Date :Thursday, February 6, 2014
With 0comments

Comparison between ASP.NET MVC Web Application and ASP.NET website

| Tuesday, January 28, 2014
Read more »
ASP.NET Web Forms ASP.NET MVC
ASP.NET WebForms model follows a Page Life cycle. No Page Life cycle like WebForms. Request cycle is simple in ASP.NET MVC model.
As every page (.aspx) has its own controller (code behind i.e. aspx.cs/.vb file), so both are tightly coupled.Hence there is no separation of concerns. View and Controller are neatly separate. Very clean separation of concerns.
Because of this coupled behavior, automated testing is really difficult. Test driven development is quite simple using this approach.Testability is a key feature in ASP.NET MVC. 
ASP.NET web forms maintain state throughout the website.In order to achieve this stateful behavior, viewstate is used. ASP.NET MVC approach is stateless as that of the web. So there is no concept of viewstate.
Statefulness has a lots of problem for web environment in case of excessively large viewstate. Large viewstate means increase in page size. As controller and view are not dependent and also no viewstate concept in ASP.NET MVC, so output is very clean.
ASP.NET Web Forms use Page controller pattern approach for rendering layout. In this approach, every page has its own controller, i.e., code-behind file that processes the request. ASP.NET MVC uses Front Controller approach. That approach means a common controller for all pages processes the requests.
Along with statefulness, Microsoft tries to introduce server-side controls as in Windows applications. Purpose was to provide somehow an abstraction to the details of HTML. In ASP.NET Web Forms, minimal knowledge of HTML, JavaScript and CSS is required. In MVC, detailed knowledge of HTML, JavaScript and CSS is required.
The above abstraction was good but provides limited control over HTML, JavaScript and CSS which is necessary in many cases. Full control over HTML, JavaScript and CSS.
With a lots of control libraries availability and limited knowledge of other related technologies, ASP.NET WebForms is RAD(Rapid Application Development) approach. It's a step back. For developers decrease in productivity.
It’s good for small scale applications with limited team size. It’s better as well as recommended approach for large-scale applications where different teams are working together.

Comparison between ASP.NET MVC Web Application and ASP.NET website

Posted by : Stranger
Date :Tuesday, January 28, 2014
With 0comments

What is the need of Master Pages?

| Saturday, January 18, 2014
Read more »
In Web site development with ASP.NET, the master page is a feature that enables you to define common structure and interface markup elements for your Web site, including headers, footers, style definitions, or navigation bars. The master page can be shared by any of the pages in your Web site, called the Content Page, and removes need to duplicate code for shared elements within your Web site.

Before Master Pages
Every website contains a common layout for most of the pages. Earlier before master pages,layout code was written on every page, which led to code redundancy and it was difficult to maintain also.

The common layout problem can be handled in two ways 
1. Using Master Pages
2. Using User Controls

User controls have few disadvantages
1. Code of User control is compiled again and again every time page loads.
2. Any change to the public environment of the User control needs to update code on the linked pages

Another option is Master Pages.A Master page is a feature that enables you to define common structure and interface markup elements for your Web site, including headers, footers, style definitions, or navigation bars. The master page can be shared by any of the pages in your Web site, called the Content Page, and removes need to duplicate code for shared elements within your Web site.

A master page is similar to an ordinary ASP.NET page except for the top @Master directive and the presence of one or more ContentPlaceHolder server controls. A ContentPlaceHolder
control defines a region in the master page that can be customized in a derived page. ContentPlaceHolder acts as container which holds controls/items defined in the derived pages.

 <asp:ContentPlaceHolder runat="server" ID="mainContent" />  

In the derived pages, server control is used to provide actual content to ContentPlaceHolders of Master Page. The link between placeholders and content is
established through the Content place holder ID.

 <asp:Content runat="server" contentplaceholderID="mainContent">  
 </asp:Content>  

1. In a master page, there can be multiple content place holders.
2. Content page is used to fill the content in their master pages and it should only contain <asp:Content> server control. Everything (like different content) should be
defined in that only.
3. For a given Content place holder, default content can be defined in the master page itself. If it has not been overridden in Content page, the content defined in the master will be
displayed.
4. A placeholder can't be bound to more than one content region in a single content page. If you have multiple <asp:Content> server tags in a content page, each must point to a
distinct placeholder in the master.
5. A ContentPlaceHolder control can be used only in a master page. Content placeholders are not valid on regular ASP.NET pages. If such a control is found in an ordinary Web
page, a parser error occurs.
6. The MasterPage class, in turn, inherits UserControl. So, at the end of the day, a master page is treated as a special kind of ASP.NET user control.


Attributes of @Master Directive

1. Language: This attribute tells the compiler about the language being used in the code-behind. Values can represent any .NET-supported language, including Visual Basic, C#, or JScript .NET.


2. AutoEventWireup: For every page there is an automatic way to bind the events to methods in the same master file or in code behind. The default value is True.


3. CodeFile: Specifies the code-behind file with which the MasterPage is associated.


4. Title: Set the MasterPage Title.


5. MasterPageFile: Specifies the location of the MasterPage file to be used with the current MasterPage. This is used for Nested Master Pages.


6. EnableViewState: Indicates whether view state is maintained across page requests. true if view state is maintained; otherwise, false. The default is true.


7. Inherits: Specifies a code-behind class for the page to inherit. This can be any class derived from the Page class.

Language used in master page and content pages can be different.

Master page can be attached to content page in different ways
1. Page Level
2. Folder Level
3. Application Level

Since Master and Content pages are interdependent, either of the page changes, dynamic assembly needs to be re-created.

When the user requests a page, first it checks whether master page exists or not. If there is any master page, then first master page will be compiled. If the folder consists of multiple master pages, all of them will be compiled at the same time. So when the user access any page for the first, page loading may take a little bit time for compiled, from the next time onwards, it won’t take much time, as master pages are already compiled and cached. When compared to User controls, this is an advantage for master pages as User Controls need compilation every time.

Master pages can be nested. There is no limitation on nesting levels. Nested master pages will have ContentPlaceHolder as well as @MasterPageFile directive.

What is the need of Master Pages?

Posted by : Stranger
Date :Saturday, January 18, 2014
With 0comments

Web response to display data from another website

| Wednesday, March 20, 2013
Read more »
Data from another website can be displayed in our own website using simple "WebRequest" and "WebResponse".WebRequest uses URL of the another website which can be passed hard coded or dynamically.

Add a Label control on the webpage.

 <asp:Content ID="Content2" ContentPlaceHolderID="generalContent" runat="Server">  
   <asp:Label ID="lblDisplay" runat="server">   
   </asp:Label>  
 </asp:Content>  

Add following code in Page_Load or any other event like button click etc.

 WebRequest wReq = WebRequest.Create("https://www.youtube.com/watch?v=CGu8W4cFlUw");  
       WebResponse mRes = wReq.GetResponse();  
       StreamReader sr = new StreamReader(mRes.GetResponseStream());  
       string sHTML = sr.ReadToEnd();  
       sr.Close();  
       mRes.Close();  
       if (sHTML != string.Empty && sHTML != null)  
       {  
         lblDisplay.Text = sHTML;  
       }  

Add required namespaces in the cs file

 using System;  
 using System.Collections.Generic;  
 using System.IO;  
 using System.Linq;  
 using System.Net;  
 using System.Web;  
 using System.Web.UI;  
 using System.Web.UI.WebControls;  

and That's it.

Enjoy!!!

The output in the browser will be


Web response to display data from another website

Posted by : Stranger
Date :Wednesday, March 20, 2013
With 1 comments:
Tag : ,

Integrate Linked In JavaScript API with ASP.NET

| Monday, March 11, 2013
Read more »
This page on Linked - In developer website explains the method to integrate JavaScript API with ASP.NET.
There are various ways Linked-In can be integrated in an ASP.NET website. I will explain the JavaScript API integration in this article.

Following are the steps of the Linked-In JS API integration.

1. Register yourself as developer on the linked-in website.
2. Create a new application or use an existing one. API Key and Secret Key of the application will be used for this integration.
3. Most Important - Make sure to specify the domain or list of domains for which above API key will be used, in "JavaScript API Domains" as in this screenshot:

JavaScript API Domains
4.Add following script in the <head> section of the html or aspx page to access the Linked-In API framework.
 <script type="text/javascript" src="http://platform.linkedin.com/in.js">  
  api_key: your_api_key_goes_here  
 </script>  

5. Add the following HTML to the body of your document to display the Linked-In Sign In button.
 <script type="in/Login">  
 </script>  



6. On clicking the above button, it should popup an authorization window asking you to Sign In to LinkedIn and grant API permission to your application. By default this pop up will ask for "Basic Profile Permissions" only.
Sign In and grant API permission
7. Test the page by reloading the page a few times. Notice that the login button reappears every time, even though you have already logged into the app and granted permission.Configure the authorize parameter in the framework script tag:
 <script type="text/javascript" src="http://platform.linkedin.com/in.js">  
  api_key: your_api_key_goes_here   
  authorize: true  
 </script>  

So far we have done integrating the LinkedIn Sign In and API permissions. In the next part I will explain how to display the details from the LinkedIn Profile.

LinkedIn JavaScript API uses REST services as back end. Lets rewrite the code above.

1. Introduce two parameters while importing the JS API framework.
 <script type="text/javascript" src="http://platform.linkedin.com/in.js">  
     api_key: your api key  
     onLoad: onLinkedInLoad  
     authorize: true  
   </script>  

The onLoad parameter tells the framework to wait until it's finished loading and then invoke a JavaScript function of your choosing. In this example, the function's name is onLinkedInLoad.
As discussed previously, setting authorize to true automatically authenticates any viewers who have previously granted your site permission using the JavaScript API.

2.The IN Object- The IN object is your way to hook into the LinkedIn JavaScript API. It's what the framework script tag inserts into the page. All the JavaScript API functions will begin with IN..
 function onLinkedInLoad() {  
       IN.Event.on(IN, "auth", onLinkedInAuth);  
     }  

In.Events. Events listen for activities, and run code when they happen. This line says to listen for the auth event, which triggers when someone signs in, and execute the onLinkedInAuth() function afterwards. Events are covered in more detail in the JavaScript API Reference.

3. Add the following HTML to the body of your document to display the Linked-In Sign In button.
 <script type="in/Login">  
 </script>  




4. Fetching profile information
 function onLinkedInAuth() {  
       IN.API.Profile("me")  
       .result(displayProfiles);  
     }  

The first part, IN.API.Profile("me"), makes a request to the LinkedIn API servers for the profile belonging to the signed-in user. The keyword "me" is a special short-hand way of referring to the signed-in member.
After it successfully retrieves data, the JavaScript framework sends the information to a callback function you specify in the result() method. In this case, it's a reference to the displayProfiles() function which we'll define below.
The In.API.Profile() method supports three of ways to identify a member: "me", member ids (like 4KoRHzE6GO), and public profile URLs.

5. Add controls in the body of the page to display profile details.
 Hello  
   <asp:Label ID='lblName' runat="server"></asp:Label>  

6. Results from the Profile API come grouped under one parameter.The displayProfiles() function receives a parameter which is the complete JSON-formatted result of the underlying call. By default the data is always in a values array. Since this is the Profile API call, values contains profile data. In this case, there's only one profile for the signed-in member, me, so it's in values[0]. The fields and field names returned for a profile are : id, firstName, lastName, headline, and pictureUrl.

 function displayProfiles(profiles) {  
     member = profiles.values[0];  
      document.getElementById("lblName").innerHTML = member.firstName + " " + member.lastName;  
 }  

7. To fetch additional profile details, fields() method can be used. Change the "onLinkedInAuth" method to include fields() method.

 function onLinkedInAuth() {  
       IN.API.Profile("me")  
       .fields("firstName", "lastName", "industry", "location:(name)", "picture-url", "headline", "summary")  
       .result(displayProfiles);  
     }  

8. Change the "displayProfiles" method as follows and add additional control in the body of the page to display more details.

 function displayProfiles(profiles) {  
       member = profiles.values[0];  
       alert(JSON.stringify(member));  
       member.lastName + "<br/> Location is " + member.location.name + " </p>";  
       document.getElementById("lblName").innerHTML = member.firstName + " " + member.lastName;  
       document.getElementById("imgProfile").src = member.pictureUrl;  
       document.getElementById("lblSummary").innerHTML = "<pre>" + member.summary + "</pre>";  
       document.getElementById("lblIndustry").innerHTML = member.industry;  
 }  

Please note
 alert(JSON.stringify(member)); 

This will display the JSON string returned by the LinkedIn API call.

LinkedIn contains many other useful resources beyond member profiles. The JavaScript API allows you access to every part of LinkedIn exposed through REST APIs. For a complete list read out REST APIs documentation.
The commonly used resources have high-level wrapper classes to help you access them (IN.API.Profile is one such wrapper). Currently, these are:
  • IN.API.Connections
  • IN.API.MemberUpdates
  • IN.API.NetworkUpdates
  • IN.API.PeopleSearch
  • IN.API.Profile
9. Handling errors:  The JavaScript API will inspect the REST response on your behalf and if an error occurred (the API returns an HTTP non-200 status code), the framework will notify you. You can specify a special error handler for using the optional error() method:

 function onLinkedInAuth() {  
       IN.API.Profile("me")  
       .fields("firstName", "lastName", "industry", "location:(name)", "picture-url", "headline")  
       .result(displayProfiles)  
       .error(displayProfilesErrors);  
     }  

Add a div in the body to display the errors.

 <div id="profiles">  
   </div>  

Display error message in the above div as follows:

 function displayProfilesErrors(error) {  
       profilesDiv = document.getElementById("profiles");  
       profilesDiv.innerHTML = error.message;  
       console.log(error);  
     }  

LinkedIn Members publish a variety of information about themselves on their member profile. Check out the link to view list of Profile Fields.

By default the API call processes "BasicPofile" permissions vide r_basicprofile.

To access email address fields, API requires r_emailaddress member permission.
To access profile related fields which are not covered under basic profile permissions like three-current-positions, date-of-birth etc, the API request requires r_fullprofile member permission.
To access contact information fields, API requires r_contactinfo member permission.
To access connection fields, API requires r_networkmember permission.
To access group membership fields, API requires rw_groupsmember permission.
To access network update fields, API requires rw_nusmember permission.

Scope parameter is added in the framework request to access fields other than basic profile.

 <script type="text/javascript" src="http://platform.linkedin.com/in.js">  
     api_key: your api key  
     scope: r_basicprofile r_emailaddress r_fullprofile  
     onLoad: onLinkedInLoad  
     authorize: true  
   </script>  

All basic, email and full profile fields can be accessed with above permissions.

 function onLinkedInAuth() {  
       IN.API.Profile("me")  
       .fields("firstName", "lastName", "industry", "location:(name)", "picture-url", "headline", "summary", "num-connections", "public-profile-url", "distance", "positions", "email-address", "educations", "date-of-birth")  
       .result(displayProfiles)  
       .error(displayProfilesErrors);  
     }  


Leave comments if anything in above code doesn't work. I have working code with me. Drop me your email id to get same.


Reference Links

Integrate Linked In JavaScript API with ASP.NET

Posted by : Stranger
Date :Monday, March 11, 2013
With 9comments

Architecture of .Net Framework

| Saturday, March 2, 2013
Read more »
The .Net Framework is an inbuilt windows component that supports Building and running the next generation of application xml web services. The .Net Framework has been developed to cater to the following objectives and Requirements:
  • To provide a consistent object-oriented environment to develop applications;
  • To provide a code execution environment that simplifies deployment and versioning;
  • To provide a code execution that eliminates the issues faced by scripted environments with respect to performance.
  • To provide a common programming model where the choice of a programming
  • Language becomes a matter of choice.
The .Net framework is made up of two components- Common Language Runtime (CLR) and the .Net Framework Class Library (FCL).The CLR is the basic for the .Net Framework and provides various services that application can use. It also forms the environment that other application run on.

The runtime is supposed to be an agent that manages code at execution time, providing core services, such as memory management, thread management, and remoteing. It also encourages security and robustness by implementing safety and other type of code accuracy. Since code management is a basic principal of the runtime is known as unmanaged code. The .Net framework consists of web Forms, Windows Forms and console applications the pertain to the presentation layer of an application.
  • Web forms are used in web-based application whereas windows forms are used in windows based application.
  • You can create a character-based console application that can be executed from the command line.
  • .Net Framework consists of two other component the .Net Framework Base classes the CLR.

Common Language Runtime
  • The Common Language Runtime (CLR) is a core component of Microsoft's .NET initiative. It is Microsoft's implementation of the Common Language Infrastructure (CLI) standard, which defines an execution environment for program code. In the CLR, code is expressed in a form of bytecode called the Common Intermediate Language (CIL, previously known as MSIL—Microsoft Intermediate Language).
  • Developers using the CLR write code in a language such as C# or VB.NET. At compile time, a .NET compiler converts such code into CIL code. At runtime, the CLR's just-in-time compiler converts the CIL code into code native to the operating system. Alternatively, the CIL code can be compiled to native code in a separate step prior to runtime by using the Native Image Generator (NGEN). This speeds up all later runs of the software as the CIL-to-native compilation is no longer necessary.
  • Although some other implementations of the Common Language Infrastructure run on non-Windows operating systems, Microsoft's implementation runs only on Microsoft Windows operating systems.
Intermediate Language

In the .NET environment, a source code which is written in any one of the programming languages should be translated into a byte code format before its execution. This byte code format is called Common Intermediate Language(CIL) or Microsoft Intermediate Language (MSIL).
Common Intermediate Language:
  • Common Intermediate Language (CIL, pronounced either "sil" or "kil") (formerly called Microsoft Intermediate Language or MSIL) is the lowest-level human-readable programming language defined by the Common Language Infrastructure specification and used by the .NET Framework and Mono. Languages which target a CLI-compatible runtime environment compile to CIL, which is assembled into bytecode. CIL is an object-oriented assembly language, and is entirely stack-based. It is executed by a virtual machine.
  • CIL was originally known as Microsoft Intermediate Language (MSIL) during the beta releases of the .NET languages. Due to standardization of C# and the Common Language Infrastructure, the bytecode is now officially known as CIL. Because of this legacy, CIL is still frequently referred to as MSIL, especially by long-standing users of the .NET languages.
JIT Compilation
  • The high level programming languages that need to be compiled require a runtime, so that the architecture on which the language runs is provided with details on how to execute its code.
  • All the programming languages use its corresponding runtime to run the application.
  • For example, To run an application developed using Visual Basic, the computer on which the application will be run must be installed with the Visual Basic runtime. The Visual Basic runtime can run only the applications developed with Visual Basic and not the ones developed with any other programming language like Java.
  • In the .NET Framework, all the Microsoft .NET languages use a common language runtime, which solves the problem of installing separate runtime for each of the programming languages. Microsoft .NET Common Language Runtime installed on a computer can run any language that is Microsoft .NET compatible.
  • The main advantage of the .NET Framework is the interoperability between different languages. As all the Microsoft .NET languages share the same common runtime language, they all work well together. For example, you can use an object written in C# from Visual Basic.NET. The same applies for all the other Microsoft .NET languages.
  • When you compile a Microsoft.NET language, the complier generates code written in the Microsoft Intermediate Language (MSIL). MSIL is a set of instructions that can quickly be translated into native code.
  • A Microsoft.NET application can be run only after the MSIL code is translated into native machine code. In .NET Framework, the intermediate language is complied "just in time" (JIT) into native code when the application or component is run instead of compiling the application at development time. The Microsoft.NET runtime consists of two JIT compilers. They are standard JIT compiler and the EconoJIT compiler. The EconoJIT compiler compiles faster than the standard JIT compiler, but the code it produces is not as optimized as the code obtained from the standard JIT compiler.
Managed Code
The code whose execution is managed by the .Net Framework Common Language Runtime is known as Managed code. It refers to a contract of cooperation between natively executing code and the runtime.The process of compiling and executing managed code in given below.
  • Compile a programs developed in a language that targets the CLR, instead of compiling the source code into machine level code, the compiler translates it into Microsoft Intermediate language(MSIL) or Intermediate language (IL).No matter which lang has been used to develop the application , it always get translated into IL. This ensure languages interoperability.
  • In addition to translating the code into IL, the compiler also produce metadata about the program during the process of compilation. Meta data contains the description of the program
  • The IL and the metadata are linked in an assembly.
  • The compiler creates the .EXE or .DLL file.
  • Execute the .Exe or .DLL file, the code and all the other relevant information from the base class library is sent to the class loader. The class loader the code in the memory.
  • Before the code can be executed, the .Net framework needs to convert the IL into native or CPU-specific code. The Just-In-Time (JIT) compiler translator the code from IL into managed native code.
  • The CLR supplies a JIT compiler for each supported CPU architecture.
  • During JIT compilation, the code is also checked for type safety. Type safety ensures that objects are always accessed in a compatible way, you try to pass an 8-byte value to a method the accepts a 4-byte value as it parameter.
  • After translating the IL into native code, the converted code is sent to the .Net runtime manager.
  • The .Net runtime manager executes the code. While executing the code, security check the performed to ensure that the code has the appropriate permissions for accessing the available resources.

Metadata
  • Metadata is binary information describing your program that is stored either in a common language runtime portable executable (PE) file or in memory. When you compile your code into a PE file, metadata is inserted into one portion of the file, while your code is converted to Microsoft intermediate language (MSIL) and inserted into another portion of the file.
  • Every type and member defined and referenced in a module or assembly is described within metadata. When code is executed, the runtime loads metadata into memory and references it to discover information about your code's classes, members, inheritance, and so on.
Benefits of metadata:

     Metadata is the key to a simpler programming model, eliminating the need for Interface Definition Language (IDL) files, header files, or any external method of component reference. Metadata allows .NET languages to describe themselves automatically in a language-neutral manner, unseen by both the developer and the user. Additionally, metadata is extensible through the use of attributes. Metadata provides the following major benefits:



Self-describing files:

  • Common language runtime modules and assemblies are self-describing. A module's metadata contains everything needed to interact with another module.
  • Metadata automatically provides the functionality of IDL in COM, allowing you to use one file for both definition and implementation. Runtime modules and assemblies do not even require registration with the operating system.
  • As a result, the descriptions used by the runtime always reflect the actual code in your compiled file, which increases application reliability.
Language Interoperability and easier component-based design:

  • Metadata provides all the information required about compiled code for you to inherit a class from a PE file written in a different language.
  • You can create an instance of any class written in any managed language (any language that targets the common language runtime) without worrying about explicit marshaling or using custom interoperability code.
Attributes:

  • The .NET Framework allows you to declare specific kinds of metadata, called attributes, in your compiled file. Attributes can be found throughout the .NET Framework and are used to control in more detail how your program behaves at run time.
  • Additionally, you can emit your own custom metadata into .NET Framework files through user-defined custom attributes. For more information, see Extending Metadata Using Attributes.
Metadata Tools:
Several tools are used to handle metadata.
  • Reflection is a tool which is used to handle metadata.
  • Third party tools (Ex : Post sharp, Mono ceil) are used to retrieve and manipulate metadata.
  • Manifest is a text file that contains metadata about .NET assemblies.
Automatic Memory Management

Automatic memory management is one of the services that the common language runtime provides during Managed Execution. The common language runtime's garbage collector manages the allocation and release of memory for an application. For developers, this means that you do not have to write code to perform memory management tasks when you develop managed applications. Automatic memory management can eliminate common problems, such as forgetting to free an object and causing a memory leak, or attempting to access memory for an object that has already been freed. This section describes how the garbage collector allocates and releases memory.
  1. Allocating Memory
  2. Releasing Memory
  3. Generation and Performance
  4. Releasing memory for Unmanaged Resource

Architecture of .Net Framework

Posted by : Stranger
Date :Saturday, March 2, 2013
With 1 comments:
Tag : ,

Extending the Named and Optional Parameters

| Tuesday, February 26, 2013
Read more »
In Named and Optional Parameters, article illustrates about the named and optional parameters. In this article I am extending this article to differentiate between parameters ,arguments and more about optional parameters.

The parameter is a variable which is the part of the method, however argument is the variable which invoke in the place of parameter.

Arguments initialize parameters.


 public void Method(string parameter)  
 {   
   txtString.Text = parameter;  
 }  

When this method is called then argument is passed.

 Method(argument);  

Little bit more about the Optional Parameters

Optional parameters restrictions

  1. Ref or out modifiers not allowed.
  2. Paramsarray is not allowed as optional, and must be the last parameter.
  3. Optional parameters must be written after required parameters.
  4. Default value of optional parameter must be a Compile-time constant.

Extending the Named and Optional Parameters

Posted by : Stranger
Date :Tuesday, February 26, 2013
With 0comments
Tag :

Named and Optional Parameters

| Saturday, February 16, 2013
Read more »
With the introduction of C# 4.0, named and optional parameters have been included in the language. They can be used to enhance the readability of source code and simplify some calls by specifying which parameters the argument values refer to.

Named parameters enable us to specify an argument for a particular parameter by associating the argument with the parameter's name rather than with the parameter's position in the parameter list.

Optional parameters enable us to omit arguments for some parameters. 

Both techniques can be used with methods, indexers, constructors, and delegates.With named and optional parameters, the arguments are evaluated in the order in which they appear in the argument list, not the parameter list.

Named and optional parameters, when used together, enable us to supply arguments for only a few parameters from a list of optional parameters. This capability greatly facilitates calls to COM interfaces such as the Microsoft Office Automation APIs.

Named Parameters
When a method is called with named arguments/parameters, they free us from the constrain of remembering the order of parameters to be passed to the method. Parameters can be passed in any order and compiler allocates temporary local memory for those named parameter variables

e.g

 public int Volume(int height, int length, int breadth)  
     {  
       return height * length * breadth;  
     }  

The above method can be called like this:


 protected void Page_Load(object sender, EventArgs e)  
     {  
       int result = Volume(10, 10, 10);  
       int result2 = Volume(length:10,height:10,breadth:10);  
     }  

int result = Volume(10, 10, 10);
It calls the Volume method by sending arguments in order of position of arguments.

int result2 = Volume(length:10,height:10,breadth:10);
It calls the Volume method by sending arguments with named parameters.

We can mix named and unnamed arguments in a call as long as all of the unnamed arguments appear before any named ones. The unnamed arguments will be applied in the order that they appear in the method’s signature.

 Optional Parameters 
The definition of a method, constructor, indexer, or delegate can specify that its parameters are required or that they are optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters.
Each optional parameter has a default value as part of its definition. If no argument is sent for that parameter, the default value is used.

e.g

 public void ExampleOptional(int required, string optionalstring = "hello", int optionalint = 10)  
     {  
     }  

Above method can be called like this:

  protected void Page_Load(object sender, EventArgs e)  
     {  
       ExampleOptional(3, ,4); //This line will cause compiler error,because an argument is provided for the third parameter but not for the second  
       ExampleOptional(3, optionalint: 4);  
     }  

IntelliSense uses brackets to indicate optional parameters.

Named and Optional Parameters

Posted by : Stranger
Date :Saturday, February 16, 2013
With 0comments
Tag :

Google Checkout implementation on ASP.NET

| Friday, February 15, 2013
Read more »
To integrate Google Checkout on ASP.NET.

Google Checkout implementation on ASP.NET

For Visual studio 2010/2012, Nuget package for Google Checkout is also available. Download the Google Checkout Nuget from following link:

Nuget.Google.Checkout

Google Checkout implementation on ASP.NET

Posted by : Stranger
Date :Friday, February 15, 2013
With 0comments

Random number generator function in C#

| Tuesday, February 12, 2013
Read more »

Random number generator function in C#

Posted by : Stranger
Date :Tuesday, February 12, 2013
With 0comments
Tag :
Prev
▲Top▲