All About ASP.NET and ASP.NET Core 2 Hosting BLOG

Tutorial and Articles about ASP.NET and the latest ASP.NET Core

Cheap ASP.NET Hosting Tips :: How to Integrate Paypal in ASP.NET Site

clock July 11, 2014 09:17 by author Ben

This article discusses integration of PayPal Payment in ASP.NET web application. Nowadays PayPal is the most popular payment gateway worldwide because it is totally free to integrate and PayPal does not charge anything for opening an account, you will pay PayPal when you get paid. And the amount is also lower than other payment gateways.

PayPal supports several types of payments:

  • Payments for goods in the PayPal cart. PayPal is responsible for all operations supporting the cart in this case. Unfortunately, this option does not provide the maximum flexibility that is required to implement some projects, so the article does not consider this option.
  • Recurring billing or subscription. PayPal provides a subscription capability; that means that a definite sum will be periodically transferred from the user's account to the seller's account. The user can unsubscribe anytime. The seller can specify the subscription's period and cost. He also can organize a trial period to let the user assess the quality of services he provides. The trial period can be either paid or free.
  • "One click" shopping. Goods are not put into the cart in this case. This method also is used to pay for goods in a cart that was filled without PayPal. That's why this option provides maximum flexibility and full control of the cart.


Let’s start step by step work to integrate PayPal payment :

1.  Create PayPal account on PayPal Sandbox: Basically, PayPal provides an environment to developer that how they can integrate PayPal payment in their website. So just open URL: https://developer.paypal.com/ and click on SignUp option.

2. Create buyer (Personal Account) and one seller account (Business Account) PayPal account.

3. Having a valid PayPal API Token Key

4. Having PayPal business account email id

5. Create New Page on ASP.NET project and copy this script :

On ASPX PAGE:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"

    CodeFile="Default.aspx.cs" Inherits="_Default" %>

 

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">

</asp:Content>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

    <div>

        <table width="700" align="center" cellpadding="0" cellspacing="0">

            <tr>

                <td height="60">

                    <b>Paypal Integration in ASP.NET</b>

                </td>

            </tr>

            <tr>

                <td height="40" align="center">

                    <asp:GridView ID="gvPayPal" runat="server" AutoGenerateColumns="False" OnRowCommand="gvPayPal_RowCommand"

                        BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px"

                        CellPadding="3" CellSpacing="2">

                        <RowStyle ForeColor="#8C4510" BackColor="#FFF7E7" />

                        <Columns>

                            <asp:TemplateField HeaderText="Product Name">

                                <ItemTemplate>

                                    <asp:Label ID="lblName" runat="server" Text='<%#Eval("prodName") %>'></asp:Label>

                                </ItemTemplate>

                            </asp:TemplateField>

                            <asp:TemplateField HeaderText="Product Description">

                                <ItemTemplate>

                                    <asp:Label ID="lblDescription" runat="server" Text='<%#Eval("prodDesc") %>'></asp:Label>

                                </ItemTemplate>

                            </asp:TemplateField>

                            <asp:TemplateField HeaderText="Product price">

                                <ItemTemplate>

                                    <asp:Label ID="lblProductPrice" runat="server" Text='<%#Eval("prodPrice") %>'></asp:Label>

                                </ItemTemplate>

                            </asp:TemplateField>

                            <asp:TemplateField HeaderText="Buy Now">

                                <ItemTemplate>

                                    <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/images/buy.png"

                                       Width="64" Height="64" CommandName="buy" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />

                                </ItemTemplate>

                            </asp:TemplateField>

                        </Columns>

                        <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />

                        <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />

                        <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />

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

                        <SortedAscendingCellStyle BackColor="#FFF1D4" />

                        <SortedAscendingHeaderStyle BackColor="#B95C30" />

                        <SortedDescendingCellStyle BackColor="#F1E5CE" />

                        <SortedDescendingHeaderStyle BackColor="#93451F" />

                    </asp:GridView>

                </td>

            </tr>

        </table>

        <!-- PayPal Logo -->

        <table border="0" cellpadding="10" cellspacing="0" align="center">

            <tr>

                <td align="center">

                </td>

            </tr>

            <tr>

                <td align="center">

                    <a style="cursor:pointer;" title="Paypal payment gateway center" onclick="javascript:window.open('https://www.paypal.com/cgi-bin/webscr?cmd=xpt/Marketing/popup/OLCWhatIsPayPal-outside','olcwhatispaypal','toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=400, height=350');">

                        <img src="https://www.paypal.com/en_US/i/bnr/horizontal_solution_PPeCheck.gif" border="0"

                            alt="Solution Graphics"></a>

                </td>

            </tr>

        </table>

        <!-- PayPal Logo -->

    </div>

</asp:Content>

On CS PAGE :

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Configuration;

using System.Data.SqlClient;

using System.Data;

 

public partial class _Default : System.Web.UI.Page

{

    SqlConnection Con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());

    SqlCommand cmd = new SqlCommand();

    SqlDataAdapter da = new SqlDataAdapter();

    DataTable dt = new DataTable();

    DataRow dr;

 

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!Page.IsPostBack)

        {

            //Add some column to datatable display some products information           

            dt.Columns.Add("prodName");

            dt.Columns.Add("prodDesc");

            dt.Columns.Add("prodPrice");

 

            //Add rows with datatable and bind in the grid view

            dr = dt.NewRow();

            dr["prodName"] = "MindStick Cleaner";

            dr["prodDesc"] = "Cleans all system dummy data";

            dr["prodPrice"] = "$100.00";

            dt.Rows.Add(dr);

 

            dr = dt.NewRow();

            dr["prodName"] = "MindStick DataConverter";

            dr["prodDesc"] = "Helps to import export data in different format";

            dr["prodPrice"] = "$120.00";

            dt.Rows.Add(dr);

 

            dr = dt.NewRow();

            dr["prodName"] = "MindStick SurveyManager";

            dr["prodDesc"] = "Helps creating survey page with specified format dll";

            dr["prodPrice"] = "$140.00";

            dt.Rows.Add(dr);

 

            dr = dt.NewRow();

            dr["prodName"] = "MindStick TeraByte Importer";

            dr["prodDesc"] = "Data transfer utility";

            dr["prodPrice"] = "$30.00";

            dt.Rows.Add(dr);

 

            gvPayPal.DataSource = dt;

            gvPayPal.DataBind();

        }

    }

 

    protected void gvPayPal_RowCommand(object sender, GridViewCommandEventArgs e)

    {

        if (e.CommandName == "buy")

        {

            ImageButton ib = (ImageButton)e.CommandSource;

            int index = Convert.ToInt32(ib.CommandArgument);

            GridViewRow row = gvPayPal.Rows[index];

 

            //Get each Column label value from grid view and store it in label

            Label pName = (Label)row.FindControl("lblName");

            Label pDescription = (Label)row.FindControl("lblDescription");

            Label pPrice = (Label)row.FindControl("lblProductPrice");

 

            //Here store that person name who are going to make transaction

            Session["user"] = "Arun Singh";

 

            // make query string to store logged in user information in sql server table         

            string query = "";

            query = "insert into purchase(pname,pdesc,price,uname) values('" + pName.Text + "','" + pDescription.Text + "','" + pPrice.Text.Replace("$", "") + "','" + Session["user"].ToString() + "')";

            Con.Open();

            cmd = new SqlCommand(query, Con);

            cmd.ExecuteNonQuery();

            Con.Close();

 

            //Pay pal process Refer for what are the variable are need to send http://www.paypalobjects.com/IntegrationCenter/ic_std-variable-ref-buy-now.html

 

            string redirectUrl = "";

 

            //Mention URL to redirect content to paypal site

            redirectUrl += "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_xclick&business=" + ConfigurationManager.AppSettings["paypalemail"].ToString();

 

            //First name I assign static based on login details assign this value

            redirectUrl += "&first_name=Arun_Seller";

           

            //Product Name

            redirectUrl += "&item_name=" + pName.Text;

 

            //Product Amount

            redirectUrl += "&amount=" + pPrice.Text;

 

            //Business contact paypal EmailID

            redirectUrl += "&[email protected]";

 

            //Shipping charges if any, or available or using shopping cart system

            redirectUrl += "&shipping=5";

 

            //Handling charges if any, or available or using shopping cart system

            redirectUrl += "&handling=5";

 

            //Tax charges if any, or available or using shopping cart system

            redirectUrl += "&tax=5";

 

            //Quantiy of product, Here statically added quantity 1

            redirectUrl += "&quantity=1";

 

            //If transactioin has been successfully performed, redirect SuccessURL page- this page will be designed by developer

            redirectUrl += "&return=" + ConfigurationManager.AppSettings["SuccessURL"].ToString();

 

            //If transactioin has been failed, redirect FailedURL page- this page will be designed by developer

            redirectUrl += "&cancel_return=" + ConfigurationManager.AppSettings["FailedURL"].ToString();

 

            Response.Redirect(redirectUrl);

        }

    }

}

 

On DESIGN PAGE :

USE [MyDatabase]

GO

 

/****** Object:  Table [dbo].[purchase]    Script Date: 01/27/2013 09:26:07 ******/

SET ANSI_NULLS ON

GO

 

SET QUOTED_IDENTIFIER ON

GO

 

SET ANSI_PADDING ON

GO

 

CREATE TABLE [dbo].[purchase](

      [Id] [int] IDENTITY(1,1) NOT NULL,

      [PName] [nvarchar](100) NULL,

      [PDesc] [nvarchar](100) NULL,

      [Price] [money] NULL,

      [Uname] [varchar](50) NULL,

 CONSTRAINT [PK_purchase] PRIMARY KEY CLUSTERED

(

      [Id] ASC

)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

) ON [PRIMARY]

 

GO

 

SET ANSI_PADDING OFF

GO

On web.config file:

<?xml version="1.0"?>

<!--

  For more information on how to configure your ASP.NET application, please visit

  http://go.microsoft.com/fwlink/?LinkId=169433

  -->

<configuration>

  <connectionStrings>

    <add name="ApplicationServices" connectionString="data source=Arun-PC;Integrated Security=true; Initial Catalog= MyDatabase; User Id= Arun-PC; Password= mindstick;" providerName="System.Data.SqlClient"/>

  </connectionStrings>

  <system.web>

    <compilation debug="true" targetFramework="4.0"/>

    <authentication mode="Forms">

      <forms loginUrl="~/Account/Login.aspx" timeout="2880"/>

    </authentication>

    <membership>

      <providers>

        <clear/>

        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/"/>

      </providers>

    </membership>

    <profile>

      <providers>

        <clear/>

        <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>

      </providers>

    </profile>

    <roleManager enabled="false">

      <providers>

        <clear/>

        <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/"/>

        <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/"/>

      </providers>

    </roleManager>

  </system.web>

  <appSettings>

    <add key="token" value="(insert your paypal API Signature) "/>

    <add key="paypalemail" value="(insert with paypal login email id)"/>

    <!--Here i used sandbox site url only if you hosted in live change sandbox to live paypal URL-->

    <add key="PayPalSubmitUrl" value="https://www.sandbox.paypal.com/cgi-bin/webscr"/>

    <add key="FailedURL" value="http://localhost:49666/PayPalIntegration/Failed.aspx"/> <!--Failed Page URL-->

    <add key="SuccessURL" value="http://localhost:49666/Default.aspx"/> <!--Success Page URL-->

  </appSettings>

  <system.webServer>

    <modules runAllManagedModulesForAllRequests="true"/>

  </system.webServer>

</configuration>

6. Run the project to see the result.

 

Look no further! You have found the answer. ASPHostPortal.com is your ASP.NET 4.5 hosting home! We understand that as .NET developer, you need to find good .NET hosting that provide reliable and cheap .NET hosting. ASPHostPortal.com supports the latest .NET framework, .NET 4.5, as well as past frameworks like .NET 4, .NET 3.5, and .NET 2.0. All of our .NET hosting comes with FREE Trial Hosting. If the service does not meet your expectations, simply cancel before the end of the free trial period. No Risk!! Why wait longer?



ASP.NET 4.5.2 Hosting in United Arab Emirates with ASPHostPortal :: How toTransfer Data from One Page to another Page in ASP.NET 4.5.2

clock June 10, 2014 11:47 by author Kenny

ASP.NET is a web programming platform developed by Microsoft. It is the successor to Active Server Pages. The term "classic ASP" is often used to distinguish previous versions of Active Server Pages with the .NET (pronounced "dot net") versions. How many ways do you know to send the data between ASP.NET Pages? In this post I’m going to list 8 different ways.

Now, let me explain how to learn multiple ways to transfer data from one ASP.NET page to another. Some of these include using the cache, http posts, querystring variables, ASP.NET session state, etc. Each button in the demo has the required code in it's Click event handler, and brings you to a separate target page that gets and displays the data that was sent. Let’s check here are the methods:

1. Use the querystring:
The QueryString collection is used to retrieve the variable values in the HTTP query string.  Using this technique I will add my data with URL and on the next page will grab it.

 protected void QueryStringButton_Click(object sender, EventArgs e)
          {
              Response.Redirect("QueryStringPage.aspx?Data=" + Server.UrlEncode(DataToSendTextBox.Text));
         }


2. Use HTTP POST:
The Hypertext Transfer Protocol (HTTP) is a communication protocol that is designed to enable request-response between clients and servers.  Using this technique I will call a post back url and the on next page using Request.From I will grab it.

 <asp:Button ID="HttpPostButton" runat="server" Text="Use HttpPost" 
              PostBackUrl="~/HttpPostPage.aspx" onclick="HttpPostButton_Click"/>
 
 protected void HttpPostButton_Click(object sender, EventArgs e)
         {
      // The PostBackUrl property of the Button takes care of where to send it!
         }


3. Use Session State:
Sessions can be used to store even complex data for the user just like cookies. Actually, sessions will use cookies to store the data, unless you explicitly tell it not to. Sessions can be used easily in ASP.NET with the Session object. Using this technique I will store the data in session variable on the client machine and on the next page will grab it. Using Application Variable instead of Session Variable is recommended by experts.

    protected void SessionStateButton_Click(object sender, EventArgs e)
          {
              Session["Data"] = DataToSendTextBox.Text;
              Response.Redirect("SessionStatePage.aspx");
         }


4.  Use public properties:
Properties are not just to provide access to the fields; rather, they are supposed to provide controlled access to the fields of our class. Using this technique I will send the using a public method and on the next page will grab it using PreviousPage.MethodName.

    public string DataToSend
         {
             get
             {
                  return DataToSendTextBox.Text;
              }
         }
 
         protected void PublicPropertiesButton_Click(object sender, EventArgs e)
          {
              Server.Transfer("PublicPropertiesPage.aspx");
         }


5. Use PreviousPage Control Info:
Using this technique I will just redirect the user on next page and on the next page will use PreviousPage.FindControl to grab the data.

 protected void ControlInfoButton_Click(object sender, EventArgs e)
          {
              Server.Transfer("ControlInfoPage.aspx");
         }
 
   // target page:
 protected void Page_Load(object sender, EventArgs e)
         {
             var textbox = PreviousPage.FindControl("DataToSendTextbox") as TextBox;
              if (textbox != null)
             {
                 DataReceivedLabel.Text = textbox.Text;
             }
         }


6. Use HttpContext Items Collection:

   protected void HttpContextButton_Click(object sender, EventArgs e)
          {
              HttpContext.Current.Items["data"] = DataToSendTextBox.Text;
              Server.Transfer("HttpContextItemsPage.aspx");
         }
 
 // target page:
 protected void Page_Load(object sender, EventArgs e)
          {
              this.DataReceivedLabel.Text =(String) HttpContext.Current.Items["data"];
         }


7. Use Cookies:
Cookies are small pieces of text that are passed between browser and web server with every request. As a consequence, their values are available to any page within the site. Cookies are commonly used to store user preferences which help the site remember which features to turn on or off, for example. They might be used to record the fact that the current user has authenticated and is allowed to access restricted areas of the site. It is the browser's job to store persistent cookies as text files on the client machine. The storage duration is determined by the type of cookie and the expiry date that it is given. Cookies with no expiry date are not stored on the client machine and are cleared at the end of the user's session.

 protected void CookiesButton_Click(object sender, EventArgs e)
         {
             HttpCookie cook =  new HttpCookie("data");
             cook.Expires = DateTime.Now.AddDays(1);
             cook.Value = DataToSendTextBox.Text;
              Response.Cookies.Add(cook);
              Response.Redirect("HttpCookiePage.aspx");
         }
 
 // target page:
 protected void Page_Load(object sender, EventArgs e)
         {
             DataReceivedLabel.Text = Request.Cookies["data"].Value;
         }


8. Use Cache:
The Cache is primarily intended to be used to improve performance of web pages, in that you can add any arbitrary object to it and retrieve it at will. Cache items are stored in memory on the server, and can be considered as special global variables. In fact, pre-ASP.NET, Application state used to be treated as a kind of cache. The difference between Application variables and Cache is that Cache offers a management API. In Web Pages, cache is managed via a WebCache helper. When you want to add something to the Cache, you use the WebCache.Set method. This method takes four parameters: the name you want to give the cache item, the item itself, the number of minutes that the item should remain in the Cache (default: 20) and whether those minutes should restart everytime the item is referenced or not (default: true). This is called Sliding Expiration.

 protected void CacheButton_Click(object sender, EventArgs e)
          {
              Cache["data"] = DataToSendTextBox.Text;
              Server.Transfer("CachePage.aspx");
         }
    // target page:
     protected void Page_Load(object sender, EventArgs e)
          {
              this.DataReceivedLabel.Text = (string) Cache["data"];
         }


ASP.NET 4.5.2 Hosting in Saudi Arabia with ASPHostPortal.com :: What’s New in ASP.NET 4.5.2? – QueueBackgroundWorkItem

clock June 9, 2014 11:56 by author Kenny

ASP.NET is built on the .NET framework, which provides an application program interface (API) for software programmers. The .NET development tools can be used to create applications for both the Windows operating system and the Web. You've probably heard the word ASP.net fairly often these days, especially on developer sites and news. This article will explain what the fuss is all about. ASP.NET is not just the next version of ASP; it is the next era of web development. ASP.NET allows you to use a full featured programming language such as C# (pronounced C-Sharp) or VB.NET to build web applications easily.

New version of ASP.NET, .Net 4.5.2 was released on May 5th. Starting with the recently released version 4.5.2 of the .NET Framework, ASP.NET now supports the HostingEnvironment.QueueBackgroundWorkItem which lets you queue background threads from within an ASP.Net web application.

Well, the new HostingEnvironment.QueueBackgroundWorkItem method that lets you schedule small background work items. ASP.NET tracks these items and prevents IIS from abruptly terminating the worker process until all background work items have completed. These will enable ASP.NET applications to reliably schedule Async work items.

Remember that the QueueBackgroundWorkItem can only be called inside an ASP.NET managed app domain. It won't work if the runtime host is either Internet Explorer or some Windows shell. This is useful for long running tasks that don’t need to complete before returning a response to the user.

 using System;
 using System.Diagnostics;
 using System.Threading;
 using System.Threading.Tasks;
 using System.Web.Hosting;
 using System.Web.Mvc; 
 
 namespace QueueBackgroundWorkItem.Controllers
 {
     public class HomeController : Controller
     {
         // notice that the action did need to be declared async
         public ActionResult Index()
         {
             Func<CancellationToken, Task> workItem = DelayWrite;
             HostingEnvironment.QueueBackgroundWorkItem(workItem);
              // the view is returned before the work item is complete
            return View();
         } 
         // Background work items should use async/await to avoid tying up IIS threads
         // the runtime will provide the cancellation token
         private async Task DelayWrite(CancellationToken cancellationToken)
         {
             // perform a long running operation, e.g. network service call, computation, file IO
             await Task.Delay(5000);
             Trace.WriteLine("Executed from a background work item");         
         }  
     }
 }


ASP.NET 4.5.2 Hosting with ASPHostPortal.com :: New Features of ASP.NET 4.5.2 - Event Tracing Changes

clock June 5, 2014 06:36 by author Kenny

ASP.NET 4.5.2 is the latest ASP.NET version; it is a highly compatible, in-place update to the .NET Framework 4, 4.5 and 4.5.1. The new ASP.NET 4.5.2 some new features that very useful for ASP.NET developer. What's new in this release of .NET 4.5.2 Framework?

  • New APIs for ASP.NET apps;
  • Resizing in Windows Forms controls;
  • New workflow features;
  • Profiling improvements;
  • Debugging improvements;
  • Event tracing changes.

Well, now I will be talking about one of them. It is about “Event tracing”. As you know that Event Tracing for Windows or ETW is an efficient kernel-level tracing facility that lets you log kernel or application-defined events to a log file. It makes you can consume the events in real time or from a log file and use them to debug an application or to determine where performance issues are occurring in the application.

And not only that, ETW has more function again. ETW lets you enable or disable event tracing dynamically, allowing you to perform detailed tracing in a production environment without requiring computer or application restarts. Use ETW when you want to instrument your application, log user or kernel events to a log file, and consume events from a log file or in real time.

In the new ASP.NET 4.5.2 Event Tracing has great change. The new .NET Framework 4.5.2 enables out-of-process, Event Tracing for Windows based activity tracing for a larger surface area. Not only that, this enables Advanced Power Management (APM) vendors to provide lightweight tools that accurately track the costs of individual requests and activities that cross threads. These events are raised only when ETW controllers enable them; therefore, the changes don’t affect previously written ETW code or code that runs with ETW disabled.

Are you interest with other new features in ASP.NET 4.5.2? So just stay tune in this blog. We will always give you up to date news about ASP.NET.



ASP.NET 4.5.1 Hosting:: How to Integrate Your ASP.NET Apps in Facebook

clock May 12, 2014 11:27 by author Ben

In this article I’m going to explain how to integrate ASP.NET applications in facebook.
Facebook has provided functionality that extends the Facebook Platform to any website that wants to integrate Facebook APIs for user authentication, sharing website content with friends, and publishing feed stories to generate traffic.
Here I’ll show you how to integrate ASP.NET Apps in Facebook.  Please follow the steps given below.

Setting up Facebook App

  • To create facebook app click on Developer section
  • Click on Set up New App button.
  • Agree Facebook terms and click on Create App
  • Put Security Check keywords.
  • Click on Submit.
  • Fill basic information about app



  • Click on Facebook Integration tab.
  • Put Name of Canvas page.
  • Before putting URL of webpage of your website, I want to show how your page can get callback from facebook app. So first we create webpage in our website:
  • Create asp.net website in Visual studio.
  • Add reference of Facebook.dll from “C:\Program Files\Coding4Fun\Facebook\Binaries”. This dll will be placed after installing Facebook Developer kit on your machine.
  • Create instance of FacebookService object. you can copy facebook app api key and secret key from application page on facebook in source code.



put above values in FACEBOOK_API_KEY and FACEBOOK_SECRET constants respectively.
you can get user_id of facebook who requested this application by calling
string userId = Session["Facebook_userId"] as String;

you can also get many information about user like name, sex, location,friends etc.
User usr=_fbService.GetUserInfo();



Source Code:

using System;
using Facebook;
public partial class Facebook_ConnectFacebook : System.Web.UI.Page
{
    Facebook.Components.FacebookService _fbService = new Facebook.Components.FacebookService();
    private const string FACEBOOK_API_KEY = "191856207506775";
    private const string FACEBOOK_SECRET = "820c0b05b14a09365e072c8d37a8c49f";

    protected void Page_Load(object sender, EventArgs e)
    {
        _fbService.ApplicationKey = FACEBOOK_API_KEY; _fbService.Secret = FACEBOOK_SECRET;
        _fbService.IsDesktopApplication = false;
        string sessionKey = Session["Facebook_session_key"] as String;
        string userId = Session["Facebook_userId"] as String;
       
    // When the user uses the Facebook login page, the redirect back here
    // will will have the auth_token in the query params
       
    string authToken = Request.QueryString["auth_token"];
       
    // We have already established a session on behalf of this user
        if (!String.IsNullOrEmpty(sessionKey))
        {
            _fbService.SessionKey = sessionKey; _fbService.UserId = userId;
        }
        // This will be executed when Facebook login redirects to our page        
        else if (!String.IsNullOrEmpty(authToken))
        {
            _fbService.CreateSession(authToken);
            Session["Facebook_session_key"] = _fbService.SessionKey;
            Session["Facebook_userId"] = _fbService.UserId;
            Session["Facebook_session_expires"] = _fbService.SessionExpires;
        }
        // Need to login        
        else
        {
            Response.Redirect(@"http://www.Facebook.com/login.php?api_key=" + _fbService.ApplicationKey + @"&v=1.0\");
        }

        User usr = _fbService.GetUserInfo();
        string t = string.Format("User Name:{0}, Sex:{1}, Location: {2}", usr.Name, usr.Sex, usr.CurrentLocation.City);
        Response.Write(t);
    }
}


Best and Recommended ASP.NET 4.5.1 Hosting Solution

The next version of the .NET Framework is .NET 4.5.1. It has been published as Preview version as announced yesterday during the BUILD conference. The new update builds on top of .NET 4.5 and includes new features such as async-aware debugging, ADO.NET idle connection resiliency, and ASP.NET app suspension. ASPHostPortal.com, a leading innovator in Windows Server hosting, announces a Free Trial ASP.NET 4.5.1 hosting on Windows Server 2012 R2 for the developer community.




ASP.NET 4.5 Hosting :: Publishing Your ASP.NET 4.5 Site with Visual Studio 2012

clock May 6, 2014 08:33 by author Ben

Microsoft Visual Studio 2012 is loaded with new capabilities for Windows 8, the web, SharePoint, mobile, and cloud development—as well as the application management lifecycle tools you need to break down team barriers and reduce cycle times to deliver value continuously.

Visual Studio 2012 is New versions of Visual Studio usually coincide with updates to the .NET Framework and one of our biggest releases yet. It comes purpose-built to help you thrive in an environment in which ideas are at a premium and speed is of the essence.

This Article can tell you how to publish your asp.net 4.5 site in vistul studio 2012.
Steps to Publish Web Application in Visual Studio 2012:
Step 1: Right click on the web project in the solution explorer window and then select the option Publish.

Step 2: Publish Web Application Window will open .Here under the option Select or Import a publish profile Select the option New in the drop down.

Step 3: In New Profile Window give any name to Profile and then click on Ok.

Step 4: Next in Connection Select the Publish method File System.

Step 5: Again in Connection for Target location select the folder on your computer where you want to publish the web application and then click on Next Button.
Step 6: In Settings Select the Configuration Release in the drop down and then click on Next Button.

Step 7: Finally in the Preview Click on Publish to Publish the web Project to  folder selected in the Step 5 above.



Best and Affordable Visual Studio 2012 Hosting with ASPHostPortal.com

We have supported site developed with
Visual Studio 2012 Hosting. Host your site on our Windows Server 2012 today. Visual Studio 2012 is New versions of Visual Studio usually coincide with updates to the .NET Framework and one of our biggest releases yet. It comes purpose-built to help you thrive in an environment in which ideas are at a premium and speed is of the essence.

For fast, secure and reliable Visual Studio 2012 Hosting, look no further than ASPHostPortal.com for all your web hosting related needs. Microsoft Visual Studio 2012 provides many new capabilities to support development on the latest platforms with modern lifecycle tools to make it easier for teams to deliver value continuously.

Visual Studio Updates help ensure you always have the best solution for building modern applications and for managing the modern application lifecycle. New to Windows Extensions, Modules, and Libraries? Ready to try out? Sign up for a FREE Trial Hosting account from ASPHostPortal.com with absolutely no cost and get going in minutes. Our Windows Server is also compatible with Visual Studio 2005, Visual Studio 2008, and Visual Studio 2010.



ASP.NET Hosting Singapore (ASIA) - ASPHostPortal.com :: How to use Bootstrap is ASP.NET?

clock April 30, 2014 05:58 by author Ben

Designers need a solid foundation that gives us almost everything a typical website would require but is flexible enough for customization. Thanks to hundreds of hours spent by some developers and companies, we now have dozens of CSS Frameworks to choose from. Among all the available CSS frameworks out there, Bootstrap is my favorite and also one of the most widely used.

Bootstrap is the new technology that is integrated with the ASP.NET web project templates. It is builtin with the projects that provides responsive design and theming capabilities. Bootstrap is a sleek and powerful front-end framework for faster web development. The project templates based on bootstrap technology provides attractive themes for the web development. Bootstrap is front-end framework for easy and faster web development. This post explains how to use Bootstrap in  ASP.NET applications and outlines some of the features of this framework. Create a new ASP.NET project in Visual Studio 2013 and execute it then you will see the look and feel of the page as below.



If you want to get the above look without using Bootstrap then you have to write lot of custom CSS. Now all ASP.NET default templates like MVC, Web forms, Single Page applications and Web API are using Bootstrap framework. Bootstrap version 3 is integrated in Visual Studio 2013. The above screen scales well on different devices. If you look at the CSS code to achieve is very few lines as shown below



In order to get the Bootstrap into your project, go to Manage NuGet packages window and type Bootstrap in search box then you will find the package


Once you install the package then it brings the following files into your project, All the CSS and JavaScript files related Bootstrap framework are bundled for you to get you better performance.



Another integration feature for Bootstrap is Bootswatch, which helps you to theme your site. To apply theme to your site go to Bootswatch site and choose the theme which you like and download and copy the CSS and overwrite the  Bootstrap.css in your project. After applying one of the sample free theme then the site looks as below, In matter of seconds you can quickly change the theme of your site.

Another key feature of Bootstrap is dealing with the images, it makes the image experience as responsive without writing any code! just use the class name img-responsive.


It adds the responsive behaviour to the image and it make sure to render nicely in your site.

Reasons to trust your ASP.NET website to us

  • Server and performance - We're proud to host all of our sites in Amsterdams, USA and Singapore. We use special server technology on our web servers to offer the fastest loading time for your websites. Stable, Secure and Reliable ASP.NET hosting service.
  • 24/7-based Support - We never fall asleep and we run a service that is operating 24/7 a year. Even everyone is on holiday during Easter or Christmas/New Year, we are always behind our desk serving our customers.
  • Excellent Uptime Rate - Our key strength in delivering the service to you is to maintain our server uptime rate. We never ever happy to see your site goes down and we truly understand that it will hurt your onlines business. If your service is down, it will certainly become our pain and we will certainly look for the right pill to kill the pain ASAP.
  • High Performance and Reliable Server - We never ever overload our server with tons of clients. We always load balance our server to make sure we can deliver an excellent service, coupling with the high performance and reliable server.
  • Experts in ASP.NET Hosting - Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostPortal.com.
  • Daily Backup Service - We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it.

About ASPHostPortal.com:

ASPHostPortal.com is a hosting company that best support in Windows and ASP.NET-based hosting. Services include shared hosting, reseller hosting, and sharepoint hosting, with specialty in ASP.NET, SQL Server, and architecting highly scalable solutions. As a leading small to mid-sized business web hosting provider, ASPHostPortal.com strive to offer the most technologically advanced hosting solutions available to all customers across the world. Security, reliability, and performance are at the core of hosting operations to ensure each site and/or application hosted is highly secured and performs at optimum level.



ASP.NET Cloud Hosting with ASPHostPortal.com:: How to Encrypt and Decrypt Password Using ASP.NET

clock April 11, 2014 12:40 by author Ben

Encryption is the process of translating plain text data into something that appears to be random and meaningless. Decryption is the process of translating random and meaningless data to plain text. Why we need to use this Encryption and decryption processes. By using this process we can hide original data and display some junk data based on this we can provide some security for our data. Here I will explain how to encrypt data and how to save that data into database after that I will show how to decrypt that encrypted data in database and how we can display that decrypted data on form. I have a form with four fileds username, password, firstname, lastname here I am encrypting password data and saving that data into database after that I am getting from database and decrypting the encrypted password data and displaying that data using gridview.

 


Please write this syntax code :


After that add System.Text namespace in code behind because in this namespace contains classes representing ASCII and Unicode character encodings. After that add following code in code behind and design one table in database with four fields and give name as "SampleUserdetails".

private const string strconneciton = "Data Source=MYCBJ017550027;Initial Catalog=MySamplesDB;Integrated Security=True";
SqlConnection con = new SqlConnection(strconneciton);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindencryptedData();
BindDecryptedData();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string strpassword = Encryptdata(txtPassword.Text);
con.Open();
SqlCommand cmd = new SqlCommand("insert into SampleUserdetails(UserName,Password,FirstName,LastName) values('" + txtname.Text + "','" + strpassword + "','" + txtfname.Text + "','" + txtlname.Text + "')", con);
cmd.ExecuteNonQuery();
con.Close();
BindencryptedData();
BindDecryptedData();
}
protected void BindencryptedData()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from SampleUserdetails", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvUsers.DataSource = ds;
gvUsers.DataBind();
con.Close();
}
protected void BindDecryptedData()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from SampleUserdetails", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvdecryption.DataSource = ds;
gvdecryption.DataBind();
con.Close();
}
private string Encryptdata(string password)
{
string strmsg = string.Empty;
byte[] encode = new byte[password.Length];
encode = Encoding.UTF8.GetBytes(password);
strmsg = Convert.ToBase64String(encode);
return strmsg;
}
private string Decryptdata(string encryptpwd)
{
string decryptpwd = string.Empty;
UTF8Encoding encodepwd = new UTF8Encoding();
Decoder Decode = encodepwd.GetDecoder();
byte[] todecode_byte = Convert.FromBase64String(encryptpwd);
int charCount = Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
char[] decoded_char = new char[charCount];
Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
decryptpwd = new String(decoded_char);
return decryptpwd;
}
protected void gvdecryption_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string decryptpassword = e.Row.Cells[2].Text;
e.Row.Cells[2].Text = Decryptdata(decryptpassword);
}
}

And the result 

 


Happy Programming !!!

Need ASP.NET cloud hosting? Please visit our site at http://www.asphostportal.com. Just with only $4.00/month to get ASP.NET cloud hosting. If you have any further questions, please feel free to email us at [email protected].

Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.

You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year.

 



ASP.NET 4.5.1 Windows Cloud Hosting - With ASPHostPortal.com :: How to Transferring User Accounts from ASP.NET to MojoPortal

clock April 10, 2014 08:24 by author Kenny

MojoPortal is a free and open source content management system that allows you to maintain your Web site with no HTML coding knowledge. When you need to build a web application you usually have some business functionality in mind but there is always a certain amount of web plumbing that needs to be implemented for things like navigation, authentication of users, security and roles and other things that are needed to support most kinds of business application logic. Sometimes we need to transfer user accounts from existing ASP.NET membership based sites into MojoPortal. So, in this article i will explain about how to transferring user accounts from ASP.NET to MojoPortal.

For the first step, you must set MojoPortal to use plain text passwords.
And then, create a folder on your PC to contain the scripts > in this folder create the following .bat files:

CreateMojoUserTablesXMLFormats.bat

set login=-U [Username] -P [Password] -S [SQL Server Instance]
set database=[Databasename].[Schema].
set switches= -c -x
set formatDir=[Full path to formats directory with trailing slash]
bcp %database%mp_Users format nul %login% %switches% -f
%formatDir%mojoUsers.xml
bcp %database%mp_UserProperties format nul %login% %switches% -f
%formatDir%mojoUserProperties.xml
bcp %database%mp_userRoles format nul %login% %switches% -f
%formatDir%mp_userRoles.xml


ExportASPNETUserData.bat

set login=-U [Username] -P [Password] -S [SQL Server Instance]
set dataDir=[Full path to data directory with trailing slash]
set database=[Databasename].[Schema].
set switches= -k –c
bcp "SELECT 0 AS UserID, 1 AS SiteID, aspnet_Users.Username AS Name,
aspnet_Users.UserName AS LoginName, COALESCE
(aspnet_Membership.Email,aspnet_Users.UserName + '@dummyemail.co.uk' ) AS
Email, aspnet_Membership.LoweredEmail AS LoweredEmail, NULL AS
PasswordQuestion, NULL AS PasswordAnswer, NULL AS Gender,
aspnet_Membership.IsApproved AS ProfileApproved, NULL AS RegisterConfirmGUID,
aspnet_Membership.IsApproved AS ApprovedForForums, 0 AS Trusted, CASE
aspnet_Roles.RoleName WHEN 'xg' THEN 0 ELSE 1 END AS DisplayInMemberList, NULL
AS WebsiteURL, NULL AS Country, NULL AS [State], NULL AS Occupation, NULL AS
Interests, NULL AS MSN, NULL AS Yahoo, NULL AS AIM, NULL AS ICQ, 0 AS
TotalPosts, NULL AS AvatarURL, 0 AS TimeOffsetHours, NULL AS [Signature],
aspnet_Membership.CreateDate AS DateCreated, aspnet_Membership.UserId AS
userGUID, NULL AS Skin, 0 AS IsDeleted, aspnet_Users.LastActivityDate AS
LastActivityDate, aspnet_Membership.LastLoginDate AS LastLoginDate, NULL AS
LastPasswordChangedDate, NULL AS LastLockoutDate, 0 AS
FailedPasswordAttemptCount, NULL AS FailedPwdAttemptWindowStart, 0 AS
FailedPwdAttemptCount, NULL AS FailedPwdAnswerWindowStart,
aspnet_Membership.IsLockedOut AS IsLockedOut, NULL AS MobilePin, NULL AS
PasswordSalt, NULL AS Comment, NULL AS OpenIDURI, NULL AS WindowsLiveID,
'77C33D82-D6F0-49ED-95A7-84C11919AD94' AS SiteGUID, NULL AS TotalRevenue,
userInfo.ForeName AS FirstName, userInfo.Surname AS LastName,
aspnet_Users.Username as Pwd, 1 AS MustChangePassword, NULL AS NewEmail, NULL
AS EditorPreference, '00000000-0000-0000-0000-000000000000' AS EmailChangeGuid,
NULL AS TimeZoneID, '00000000-0000-0000-0000-000000000000' AS PasswordResetGuid
FROM %database%aspnet_Membership INNER JOIN %database %aspnet_Users ON
aspnet_Membership.UserId=aspnet_Users.UserId INNER JOIN %database%userInfo on
aspnet_Membership.UserId=userInfo.userId INNER JOIN
%database%aspnet_UsersInRoles ON
aspnet_Membership.UserId=aspnet_UsersInRoles.UserId INNER JOIN
%database%aspnet_Roles ON aspnet_UsersInRoles.RoleId =
aspnet_Roles.RoleId" queryout %dataDir%lharUsers.txt %switches% %login% -o
output/usersOutput.txt
bcp "select RoleName,UserId from %database%aspnet_Roles INNER JOIN
%database%aspnet_UsersInRoles on
aspnet_Roles.RoleId=aspnet_UsersInRoles.RoleId" queryout
%dataDir%lharUsersRoles.txt %switches% %login% -o output/userRolesOutput.txt
bcp "SELECT newid() AS PropertyID, UserId AS userGUID, [String to use
as MojoPortal PropertyName] AS PropertyName, Title AS PropertyValueString,
NULL AS PropertyValueBinary, GETDATE() AS LastUpdatedDate, 0 AS IsLazyLoaded
FROM %database%UserInfo
UNION ALL
SELECT newid() AS PropertyID, UserId AS userGUID, [String to use as
MojoPortal PropertyName] AS PropertyName, Title AS PropertyValueString,
NULL AS PropertyValueBinary, GETDATE() AS LastUpdatedDate, 0 AS IsLazyLoaded
FROM %database%UserInfo" queryout %dataDir%lharUserProfiles.txt %switches%
%login% -o output/userPropertiesOutput.txt


ImportMojoPortalUserData.bat

set login=-U [Username] -P [Password] -S [SQL Server Instance]
set database=[Databasename].[Schema].
set dataDir=[Full path to data directory with trailing slash]

set switches= -k -R

set formatDir=[Full path to outputs directory with trailing slash]

bcp %database%mp_users IN %dataDir%lharUsers.txt %login% %switches% -f %formatDir%mojoUsers.xml -o output/importUsers.txt

bcp %database%mp_userProperties IN %dataDir%lharUserProfiles.txt %login% %switches% -f %formatDir%mojoUserProperties.xml -o output/importUserProperties.txt

bcp %database%mp_userRoles IN %dataDir%lharUsersRoles.txt %login% %switches% -f %formatDir%mp_userRoles.xml -o output/importUserRoles.txt


Next step is, create the following subdirectories in this folder: data, formats, output.
After create the CreateMojoUserTablesXMLFormats.bat file and the ExportASPNETUserData.bat file, run these program.
Don’t forget to check the output directory for any errors and check the data files have been created and contain the data you expect.
After that, run the ImportMojoPortalUserData.bat. Check the output directory for any errors and check the database tables have the data.
Switch MojoPortal back to using encrypted passwords and the last test a few logins.



ASP.NET Hosting Full Trust Mode

clock April 8, 2014 09:03 by author Diego

What’s ASP.NET shared hosting trust level?

You need to check many aspects before choosing a .Net hosting provider, those aspects should include .Net MVC framework, SQL Server, disk space, monthly bandwidth, hosting prices, but there’s one thing you may ignore really – “IIS Security Trust Level”.


If you’re not familiar with what’s asp.net shared hosting trust level, here I’d like to bring you a short introduction. The trust level is real important that could affect with your site secure and performance, and a full trust level means higher risk for hackers sneak into server to make destroy. Most of small .Net hosts only can give medium trust level on their servers. If your applications need to be run a full trust mode, then you’ve to look for a web host which can give full permission to you.


<system.web>
<securityPolicy>
<trustLevel name="High" policyFile="web_hightrust.config"/>
<trustLevel name="Medium" policyFile="web_mediumtrust.config"/>
<trustLevel name="Low" policyFile="web_lowtrust.config"/>
<trustLevel name="Minimal" policyFile="web_minimaltrust.config"/>
</securityPolicy>
</system.web>

You can see there are 4 trust levels for web hosts to pre-set by default – Minimal trust, Low trust, Medium trust and High / Full trust. High trust means higher risk for hackers to sneak into server, most of Windows hosting companies doesn’t allow their customers to run full trust level by default.
- Full Trust allows the users to do everything of application pool on one Windows web server. Some of applications cannot work properly under a medium trust web server, full trust means more flexible and you’re also able to change to medium trust once your application don’t need full trust.
- High Trust, websites are limited to call unmanaged code, e.g. Win32 APIs, COM interop.
- Medium Trust level websites are limited to access the file system and not so flexible as full trust level web server.
- Low Trust & Minimal Trust level are 2 options to restrict the users heavily, it won’t allow users to connect to server actively. At present, there’s no Windows hosts offering such asp.net shared hosting plan yet.


With more and more people and companies developing websites by Microsoft .NET technology, ASP.NET shared web hosting comes to be the major solution provided by many web hosting companies. Most of people choose an ASP.NET web host considering about .NET framework version, ASP.NET MVC support, SQL Server database, disk space or bandwidth but they usually ignore the most important feature “IIS security level”. That determines whether the ASP.NET websites can run successfully on the shared web host. In result to, if you developing an ASP.NET website that works well in the local development environment and attempt to run it in the ASP.NET shared web host, you may get the following exception.


System.Security.SecurityException: That assembly does not allow partially trusted callers.


This is caused by the security level of the ASP.NET shared web host that your application is forced to run with the limited permission, by locking down the access to server file system, preventing the background threads, or interacting with COM interfaces, etc.
Full Trust and Medium Trust are two widely used levels in ASP.NET shared web hosting. The full trust provides best flexibility but it has potential security issues to the shared server, especially when the web hosting provider doesn't have rich experience on setting up Windows permission and IIS. Compared to Full Trust, you have to review the website carefully before you go with a web host only supports Medium Trust Level. You can refer to the following checkpoints for the review.
-The website shall not call unmanaged APIs.

-The website shall not access to file system, system registry, event logs and anything else related to the system.
-The website shall not generate code for execution dynamically using Code DOM.

-The website shall not use XslTransform to transform something from XML using XSLT.

-The website has to be signed with a Strong Name.

Check with the web page from Microsoft about which namespaces and classes are not supported in Medium Trust environment.
And here is quick way to confirm the compatibility of websites to Medium Trust Level, in the local environment.

1. Add partially trusted callers attribute into AssemblyInfo.cs file of the website project, as following code snippet,
[assembly: AllowPartiallyTrustedCallers]

2.Add the following line into the web.config,
<trust level="Medium" />

Medium Trust or Full Trust level? UP to Your choice:
If your website can be working fine under medium trust level, I suggest you don’t need a full trust asp.net hosting, most of popular .Net applications should be working fine under a medium trust level server, only when your application has to be run under a full trust level enviroment, then you can find an ASP.NET full trust hosting company.



Cheap ASP.NET 4.5 Hosting

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link

 photo ahp banner aspnet-01_zps87l92lcl.png

 

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Tag cloud

Sign in