Showing posts with label xml. Show all posts
Showing posts with label xml. Show all posts

Thursday, September 29, 2011

WCF vs Web service


WCF is a programming model and API. "WCF Service" implies an app that uses such programming model.
"Web Service" is an app that exposes an HTTP (REST (XML or JSON), SOAP or otherwise) interface.
You can build a Web service using WCF, but you can also build a Web service using other APIs or "stacks". Like PHP or Java, for example.
With WCF you can build web services but you can also build services that are not, "Webbish". For example you can build a service that accepts incoming binary requests over only a local pipe interface. It is still a service, but it is not a "web service" because it is not using web protocols (generally HTTP and XML).

Tuesday, July 5, 2011

Developers: just a few lines of JavaScript connects your site to Hotmail, Messenger, and SkyDrive


Today, developers almost always integrate multiple web platforms into their sites – Facebook, Twitter, Google, Hotmail, and more. With this in mind, we’ve tried to make it as easy as possible for developers to use our platform alongside others to connect their websites to Messenger, SkyDrive, and Hotmail. We’re achieving this goal by focusing on the following principles:
  1. All it takes is a few lines of JavaScript to unlock powerful integration. Utilize as few lines of script as is feasible to enable single sign-on and (with the user’s consent) to allow the app access to specific data from their Hotmail, Messenger, or SkyDrive account, all without requiring a single line of server-side code for the common scenarios.
  2. The Messenger Connect JavaScript API feels familiar to developers who use other popular web platforms. Ensure the API is familiar to web developers who are already using popular web platforms that perform similar tasks.
  3. Combining our APIs with other integrated services on a page shouldn’t cause clutter. Ensure it is straightforward and cost effective to use Messenger Connect in tandem with other web platform offerings without a negative impact on developers or end users.
These principles have informed the design of our new JavaScript library that developers can include in their websites to add single sign-on and integration with services like Hotmail, Messenger, and SkyDrive.
Let’s see some of these principles in action.

All it takes is a few lines of JavaScript to unlock powerful integration

The following self-contained code sample can be hosted on any website, and will render a Connect button as shown below, which a user can click to connect to the website and be greeted by their first name.
Connect button
In the following code sample, the client_id and redirect_uri should be replaced with the developer client ID you can obtain from our application settings site, and the URL of the HTML page, respectively.
<html><head>
<title>Greeting the User Test page</title>
    <link rel="stylesheet" type="text/css" href="style.css" />
<script src="//js.live.net/v5.0/wl.js" type="text/javascript"></script>
    <script type="text/javascript">
        var APPLICATION_CLIENT_ID = "YOUR CLIENT ID",
        REDIRECT_URL = "YOUR REDIRECT URL";
        WL.Event.subscribe("auth.login", onLogin);
        WL.init({
            client_id: APPLICATION_CLIENT_ID,
            redirect_uri: REDIRECT_URL,
            response_type: "token"
        });
        
        WL.ui({
            name: "signin",
            element: "signInButton",
            brand: "hotmail",
            type: "connect"
        });

        function greetUser(session) {
            var strGreeting = "";
            WL.api(
            {
                path: "me",
                method: "GET"
            },
            function (response) {
                if (!response.error) {
                    strGreeting = "Hi, " + response.first_name + "!"
                    document.getElementById("greeting").innerHTML = strGreeting;
                }
            });
        }
     
        function onLogin() {
            var session = WL.getSession();
            if (session) {
                greetUser(session);              
            }
        }
    </script>
</head>
<body>
    <p>Connect to display a welcome greeting.</p>
    <div id="greeting"></div>
    <div id="signInButton"></div>
</body>
</html>
There are a number of key concepts in the above example that I’ll briefly go over. The first step to using the JavaScript SDK is to include the wl.js script file on your webpage.
<script src="//js.live.net/v5.0/wl.js" type="text/javascript"></script>
If your target audience doesn’t speak English, it is fairly straightforward to load versions of the JavaScript library that contain localized strings for dozens of languages.
After including the Messenger Connect JavaScript API, there are a few setup steps to link up components of the page with the JavaScript API, as shown below:
WL.Event.subscribe("auth.login", onLogin);
WL.init({
            client_id: APPLICATION_CLIENT_ID,
            redirect_uri: REDIRECT_URL,
            response_type: "token"
        });
The WL.Event.subscribe call above indicates that the onLogin() function should be invoked after the user has been successfully signed in. The WL.init call above is used to specify the application’s client ID, and the URL that the user should be redirected to after signing in which, for this example, is the current page:
WL.ui({
name: "signin",
element: "signInButton",
brand: "hotmail",
type: "connect"
});
The call to WL.ui is used to draw the Hotmail connect button. The code above attaches it to the DIV named “signInButton”. Once the user has signed in and granted consent to allow the page to access their data, the onLogin() function is invoked:
function onLogin() {
    var session = WL.getSession();
    if (session) {
        greetUser(session);              
    }
}
This function checks to see if a valid login session has been created and if so, invokes the greetUser() functionshown below:
function greetUser(session) {
    var strGreeting = "";
    WL.api(
    {
        path: "me",
        method: "GET"
    },
    function (response) {
        if (!response.error) {
            strGreeting = "Hi, " + response.first_name + "!"
            document.getElementById("greeting").innerHTML = strGreeting;
        }
    });
}
This method employs the work horse of the JavaScript SDK: WL.api. This function is used for making REST API requests. In this specific example, the request is made to fetch the user object for the current user using the “me” query. Once the user object is obtained, the webpage displays the user’s first name.

The Messenger Connect JavaScript API feels familiar to developers who use other popular web platforms

We want to ensure that we don’t add to the learning curve for developers, so we made sure that our JavaScript API would work in familiar ways for developers who integrate with multiple popular web platforms via JavaScript. For example, you may want to include social sharing for Facebook and Twitter alongside the ability to access SkyDrive photo albums and the ability to add events to your Hotmail calendar.
Common tasks in our JavaScript API such as signing in the user, accessing data from their contact list, viewing their photos, and showing the permission dialog all look and work very similarly to comparable scenarios in other common platforms like Facebook, Twitter, etc. This makes it very easy for any developer who is familiar with programming against these APIs to pick up and start integrating SkyDrive, Hotmail, and Messenger into their websites.

Combining Hotmail, Messenger, and SkyDrive with other integrated services on a page shouldn’t cause clutter

Websites typically don’t just offer integration with one service provider. It is common for a website to want to enable sharing to multiple sites like Facebook and Twitter, or allow users to upload their photos from Flickr, Facebook, and SkyDrive.
One of the challenges with supporting services that identity multiple providers on a website is what many have dubbed “the NASCAR effect,” which is when a site has so many logos from so many different providers that it looks a little like a race car with too many corporate sponsors. This practice often ends up confusing users due to the paradox of choice.
To help with this, we make it easy for your app or site to check if a customer uses one of our services before even offering the option to connect. Again, with just a few lines of JavaScript, you can tailor your connection and offer the right features to the right users – just use the WL.getLoginStatus function as follows:
WL.getLoginStatus(function (response) {
           if (response.status && response.status!= ‘Unknown’) {
               WL.ui({
                name: "signin",
                brand: "hotmail",
                type: "connect",
                element: "signInButton"
               });
           }else{
           /* draw sign-in button for other identity providers */ 
           }
       });
The code above checks to see if the customer uses one of our services, and if the status comes back as “Unknown,” it can then call some fallback code that draws the sign-in control of another identity provider such as Facebook, Twitter, or Google.
These are just a few examples of the ways we’ve improved our JavaScript API to simplify the developer experience. Keep the feedback coming, and we look forward to seeing more of your apps and sites connected to Hotmail, Messenger, and SkyDrive.

Sunday, June 26, 2011

Bulk Insert using GridView and Sql Server XML



Download source and store procedure script from here.


private void InsertEmptyRow()
{
DataTable dt = new DataTable();
DataRow dr = null;


dt.Columns.Add(new DataColumn("CustName", typeof(string)));
dt.Columns.Add(new DataColumn("CustPosition", typeof(string)));
dt.Columns.Add(new DataColumn("CustCity", typeof(string)));
dt.Columns.Add(new DataColumn("CustState", typeof(string)));


for (int i = 0; i < 5; i++)
     {
          dr = dt.NewRow(); dr["CustName"] = string.Empty;
          dr["CustPosition"] = string.Empty;
          dr["CustCity"] = string.Empty;
          dr["CustState"] = string.Empty; dt.Rows.Add(dr);
    }
   gvCustomer.DataSource = dt; gvCustomer.DataBind();
}



 As, you see above code I am creating five empty rows initially which is empty. This method I am calling at page load event. Note :- I am creating only five empty rows, you can create as much required for your bulk insert according to your requirement And one more difference between, Bulk update and bulk insert is that as we fetch all records for bulk update, so we don’t have empty rows, but in insert we have five empty rows. One more thing, Suppose we insert three rows and two rows empty what would happen ?. For that I am checking if name field is empty or not, else don’t insert.

 StringBuilder sb = new StringBuilder(); sb.Append("");
for (int i = 0; i < gvCustomer.Rows.Count; i++) 

      { 
      TextBox txtName = gvCustomer.Rows[i].FindControl("txtName") as TextBox; 
      TextBox txtPosition = gvCustomer.Rows[i].FindControl("txtPosition") as TextBox; 
      TextBox txtCity = gvCustomer.Rows[i].FindControl("txtCity") as TextBox;
      TextBox txtState = gvCustomer.Rows[i].FindControl("txtState") as TextBox;
      if(txtName.Text.Length != 0)
           sb.Append("");
}
sb.Append("
");


As you see, I am checking txtName if length is more then zero then insert record else skip it. As other insert detail is simple.


string conStr = WebConfigurationManager.ConnectionStrings["BlogConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand("InsertCustomer", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@XMLCustomer", sb.ToString());


try
{
using (con)
{
con.Open();
cmd.ExecuteNonQuery();
}

lblError.Text = "Record(s) Inserted successfully";
lblError.ForeColor = System.Drawing.Color.Green;
}
catch (Exception ex)
{
lblError.Text = "Error Occured";
lblError.ForeColor = System.Drawing.Color.Red;
}


Store procedure also simple, just direct insert from XML structure what it consist, this is also difference between bulk update as in which we check in where condition of customer id matches or not


set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go


CREATE PROCEDURE [dbo].[InsertCustomer]
(
@XMLCustomer XML
)
AS
BEGIN


INSERT INTO CUSTOMER
(CustName,CustPosition,CustCity,CustState)
SELECT
TempCustomer.Item.value('@Name', 'VARCHAR(50)'),
TempCustomer.Item.value('@Position', 'VARCHAR(50)'),
TempCustomer.Item.value('@City', 'VARCHAR(50)'),
TempCustomer.Item.value('@State', 'VARCHAR(50)')
FROM @XMLCustomer.nodes('/root/row') AS TempCustomer(Item)


RETURN 0
END


Note :- In bulk update, we are passing customer id also, here its not required as it is auto increment.

I hope you like this article about how to insert bulk records at a time. Like to have a feedback on this article.


Original article :- http://weblogs.asp.net/manojkdotnet/archive/2010/01/26/bulk-insert-using-gridview-and-sql-server-xml.aspx