European Windows 2012 Hosting BLOG

BLOG about Windows 2012 Hosting and SQL 2012 Hosting - Dedicated to European Windows Hosting Customer

Visual Studio UK Hosting - HostForLIFE.eu :: Tutorial New API For Refreshing Data in LightSwitch in Visual Studio 2013

clock December 17, 2013 07:47 by author Administrator

New API For Refreshing Data in LightSwitch in Visual Studio 2013

You can get Visual Studio 2013 here: http://www.microsoft.com/visualstudio/eng/2013-downloads.

The Sample Project

When we open it up, it will be converted to the new Visual Studio 2013 format. However, to get it to run we have right-click on the first project

The API
The new refresh() API consists of  two methods that each return a Promise object.

  • Refresh()
    Asynchronously loads the first page of items into this collection and returns a promise that will be fulfilled when the first page is loaded. Existing results will be refreshed on the first page and subsequent pages unless load() is called again.
  • Refresh(navigationPropertyNames)
    Updates the entity with values from the data source if the entity
    is not changed.
    <param name="navigationPropertyNames" type="Array" optional="true">
    . An array of names of navigation properties to be included. An empty array means no properties will be included. If not specified, all reference properties are included.

Sample usage

  • Refresh the Order entity and its Customer, Employee, Shipper

        screen.Order.details.refresh();

  • Refresh only the Order entity

        screen.Order.details.refresh([]);

  • Refresh the Order entity and its Customer

        screen.Order.details.refresh(["Customer"]);

The Problem

Let’s say we have a field on the Order entity that is updated in the save pipeline when an associated OrderDetail record is updated.

In the OrderDetail record, the updating event looks like this:

We can update an OrderDetail record

Save the changes. But the time is unchanged on the screen (even though it has been updated in the database).

The Solution

We can instantly have the entity updated if we use the new refresh() method.

To do so requires us to implement our own code to open the edit screen (so we have an opportunity to implement the refresh code).
We select the Item Tap action for the Orders list.

Select Write my own method.

We then edit the code for the method we created.
We use the following code:

myapp.Main.Order_ItemTap_execute = function (screen) {
    myapp.showAddEditOrder(null, {
        beforeShown: function (addEditOrderScreen) {
            // Set the Order on the AddEditOrder screen
            // to the selected Order on the Main screen
            addEditOrderScreen.Order = screen.Orders.selectedItem;}
        },
        afterClosed: function (addEditScreen, navigationAction) {
            // If the user commits the change,
            // update the selected order on the Main screen
            if (navigationAction === msls.NavigateBackAction.commit) {
 // *****************************************
// The .refresh() method refreshes the Order
screen.Orders.selectedItem.details.refresh();
            }
        }
    });
};

When we update the record we will see the date instantly updated without the need to refresh the entire screen.



European Italy Umbraco Hosting :: Adding New Tab Under uCommerce Admin Sections in Umbraco 6.0.0

clock December 12, 2013 06:50 by author Administrator

What is uCommerce?

uCommerce is an e-commerce offering fully integrated with Umbraco for building online stores. With uCommerce and Umbraco you create unique and powerful e-commerce webshops fully customized to your client's requirements.

uCommerce is completely integrated with the Umbraco membership system. Configure whether you want customers created during checkout for login to review ordering history and more.

  • Use the Umbraco membership to stay in touch with with past customers.
  • Create profiles for your customers automatically when they buy
  • Segment customers using groups
  • View customer profiles in back office
  • Store additional information about your customer on their profile such as sign ups for newsletters
  • Search for customer profiles
  • Maintain e-mail templates with rich text editing capabilities
  • Control who can maintain your store

So, how to adding new tab under uCommerce Admin sections in Umbraco 6.0.0? Steps for adding new tab in uCommerce section :

1. Add new user control for custom tab view


To add new tab first create new user control in your website, go to website in visual studio add new user control where you want as per your defined directory structure. It is good to place new user control under /usercontrols folder in Umbraco website.

So the virtual path for newly created user control will be “../../../usercontrols/TestTab.ascx”.
Inherit newly created user control from Ucommerce.Presentation.Web.Controls.ViewEnabledControl<T>
The generic parameter T must be type of view which you want to load your user control to appear on. Most commonly used views and their types are discussed below.

So if you are inheriting your user control from any of these views you can register for following events.
event EventHandler<EntityCommandEventArgs<T>> Saving;
event EventHandler<EntityCommandEventArgs<T>> Saved;

event EventHandler<EntityCommandEventArgs<T>> Deleting;
event EventHandler<EntityCommandEventArgs<T>> Deleted;

2. Insert New Row For Tab in Database

In uCommerce uCommerce_AdminTab refers to uCommerce_AdminPage for parent page container of your tab(usercontrol). So you have to add your usercontrol entry into uCommerce_AdminTab table and should give the AdminPageId from uCommerceAdminPage table to select on which view or page you going to add your new tab. See the visuals



As per the information in the above table you can insert an entry into uCommerce_AdminTab table for new tab. Build your solution and your new tab is ready under the view you have selected.

Hide/Show custom tab for particular section


As explained earlier your new tab will be visible for view you have selected, Consider an example where you want to do some functionality Completed Orders (uCommerce >> Orders >> Completed Orders) and if you have followed above steps your new tab will be visible for all remaining sections like New Orders, Requires Attention etc.
To hide or show your tab for particular section only, implement ISection interface in your user control and set the Show property as per your requirement.
For ex:


So this will show your custom user control for Completed Orders only.



European HostForLIFE.eu Proudly Launches Entity Framework 6 with FREE Trial Hosting

clock December 11, 2013 06:31 by author Administrator

HostForLIFE.eu offers a variety of cheap and affordable European Windows ASP.NET Shared Hosting Plans to fit any need. No matter whether you’re starting a Blog with WordPress, installing a CMS solution with Drupal, opening a Forum with PHPBB, starting an Online Store with nopCommerce, or any number ventures beyond those mentioned above, our Windows ASP.NET Web Hosting plans are exactly what you’ve been looking for. HostForLIFE.eu is Microsoft No #1 Recommended ASP.NET Host Provider.
Entity Framework 6 (EF6) is an object-relational mapper that enables .NET developers to work with relational data using domain-specific objects. It eliminates the need for most of the data-access code that developers usually need to write.

Entity Framework is now available and there are top features to consider in this minor release:

Features that come for free. These are capabilities that are part of the core. You don’t even have to know they’re there to benefit from them, much less learn any new coding.

Level-setting features. A major enhancement is that Code First now supports mapping to Stored Procedures, something that has been supported by models created in the designer.

Another change is more interesting. With EF6, the EF APIs have been extracted from the .NET Framework; they’re now completely encapsulated in the NuGet package.

EF Designer in this category. It has been moved out of Visual Studio as of the 2013 edition, and instead provided as an extension to Visual Studio.

Ninja features. Support for asynchronous queries and saves, the return of custom Code First conventions, more extensibility using the new DbConfiguration type, support for mocking in unit tests, configurable retries on spotty connections, and even more.

For complete information about this new product, please visit our site at http://www.hostforlife.eu



Visual Studio Hosting - HostForLIFE.eu - Spain :: Integrating PayPal With Visual Studio LightSwitch

clock December 10, 2013 05:35 by author Administrator

This example application shows how you can integrate a complex API such as PayPal Adaptive Payments with Visual Studio LightSwitch.

The Sample Application

You can test out the sample application at:

https://paypalstore.lightswitchhelpwebsite.com/HTMLClient/

(use your user name and password of your LightSwitchHelpWebsite.com account)

Note: All transactions are real and your PayPal account will be debited $2.00. However, please  do not complete a transaction and then reverse the charges, that will cause me quite a hassle.

A user can browse the available pictures and purchase a copy by clicking the Buy a Copy button.

  • They are taken to a page where they can click the Buy Now button.

  • They are taken to the PayPal site where they can pay.

  • They can use a credit card (if the merchant account has that option), check, or their PayPal account.

  • After making payment they see a confirmation.

 

  • They are taken back to the application, to the My Purchases page.

Clicking on a purchase record will take them to a page where they can download the picture, if the payment has cleared.

 

  • If the payment has not cleared, it will say so and display any error messages. Once payment has cleared this page will allow them to download the picture.

  • Any user can upload their own pictures, indicate that they are a Merchant, and enter their PayPal account.

An administrator can see and diagnose all transactions. The administrator is defined when the application is published using the Visual Studio LightSwitch publishing wizard.

The administrator PayPal account is also configured in the web.config file (this is covered in the next section).

The PayPal API

Also note, the PayPal IPN notifications, will only work if the application has been published using the using the Visual Studio LightSwitch publishing wizard and is at a location that can be reached by the PayPal servers.

 


The code in the sample LightSwitch application uses the PayPal Adaptive Payments Classic API: https://developer.paypal.com/webapps/developer/docs/classic/adaptive-payments/gs_AdaptivePayments/. You can get a complete overview of PayPal Adaptive Payments at this link: https://developer.paypal.com/webapps/developer/docs/classic/adaptive-payments/integration-guide/APIntro/.

Specifically it uses the Pay API call to make a parallel payment: https://developer.paypal.com/webapps/developer/docs/classic/api/adaptive-payments/Pay_API_Operation/.

It also uses the PayPal IPN Classic API to determine when a payment has been completed: https://developer.paypal.com/webapps/developer/docs/classic/products/instant-payment-notification/.

Running The Sample Application

  • You will also need to go to: https://apps.paypal.com to create a PayPal Classic Application (this is because at the time of this writing the Adaptive Payments API is not available using the newer REST Services API).

  • Create a new application. This will create a Sandbox ID that you will need to also put in the web.config of the sample app.

  • When you create your application, use the settings in the image above.

You will need to create PayPal Sandbox test accounts: https://developer.paypal.com/webapps/developer/docs/classic/lifecycle/ug_sandbox/#accounts

The merchant test account will need to be entered in the web.config of the LightSwitch application.

  • The sample transactions will need three accounts and no two can be the same so you will need to create two additional test accounts (besides the test merchant account that will be created for you) to use to test the application.

Open the sample LightSwitch application (available on the downloads page), switch to file view, and open the Web.config, and enter the values in the spaces marked ***.

The application should now work.

If it doesn’t work for you:

Also note: the PayPal IPN notifications will only work if the application has been published using the using the Visual Studio LightSwitch publishing wizard and is at a location that can be reached by the PayPal servers.

When the sample application was created, I used the PayPal Nuget package to install the needed binaries: https://www.nuget.org/packages/PayPalCoreSDK.

Exploring The Sample Application

The PayPal version adds additional tables and screens.

Note that important code is implemented to properly secure the PayPal tables:

     // PayPalPurchaseTransactions
        #region PayPalPurchaseTransactions
        partial void PayPalPurchaseTransactions_Filter(ref Expression<Func<PayPalPurchaseTransaction, bool>> filter)
        {
            // Only an Admin can see the entire table
            if (!(this.Application.User.HasPermission(Permissions.SecurityAdministration)))
            {
                // Users can see any Transction where they are the buyer or the seller
                filter = e => e.PurchaserUserName == this.Application.User.Identity.Name
                    || e.SellerUserName == this.Application.User.Identity.Name;
            }
        }
        partial void PayPalPurchaseTransactions_Inserting(PayPalPurchaseTransaction entity)
        {
            // Set time and IP Address
            var context = System.Web.HttpContext.Current;
            entity.PurchaseTime = DateTime.Now;
            entity.PurchaseIPAddress = context.Request.UserHostAddress;
            // Payment Status is always set to Pending
            entity.payment_status = "Pending";
        }
        partial void PayPalPurchaseTransactions_Updating(PayPalPurchaseTransaction entity)
        {
            // An update can only be made by the orginal user
            if (!(entity.PurchaserUserName == this.Application.User.Identity.Name
                || entity.SellerUserName == this.Application.User.Identity.Name
                || this.Application.User.HasPermission(Permissions.SecurityAdministration)))
            {
               throw new Exception(string.Format("Only buyer, seller or administrator can update!"));
            }
            // Payment Status is always set to Pending
            // IPN handler updated this value directly outside of oData
            entity.payment_status = "Pending";
        }
        partial void PayPalPurchaseTransactions_CanDelete(ref bool result)
        {
            // Only an Admin can access the table (.ashx file has an override)
            result = this.Application.User.HasPermission(Permissions.SecurityAdministration);
        }
        #endregion
        // PayPalIpnTransactions
        #region PayPalIpnTransactions
        partial void PayPalIpnTransactions_CanDelete(ref bool result)
        {
            // Only an Admin can access the table (.ashx file has an override)
            result = this.Application.User.HasPermission(Permissions.SecurityAdministration);
        }
        partial void PayPalIpnTransactions_CanInsert(ref bool result)
        {
            // Only an Admin can access the table (.ashx file has an override)
           result = this.Application.User.HasPermission(Permissions.SecurityAdministration);
        }
        partial void PayPalIpnTransactions_CanUpdate(ref bool result)
        {
            // Only an Admin can access the table (.ashx file has an override)
            result = this.Application.User.HasPermission(Permissions.SecurityAdministration);
        }
        partial void PayPalIpnTransactions_CanRead(ref bool result)
        {
            // Only an Admin can access the table (.ashx file has an override)
            result = this.Application.User.HasPermission(Permissions.SecurityAdministration);
        }
        #endregion
        // PayPalTransactions
        #region PayPalTransactions
        partial void PayPalTransactions_CanDelete(ref bool result)
        {
            // Only an Admin can access the table (.ashx file has an override)
            result = this.Application.User.HasPermission(Permissions.SecurityAdministration);
        }
        partial void PayPalTransactions_CanInsert(ref bool result)
        {
            // Only an Admin can access the table (.ashx file has an override)
            result = this.Application.User.HasPermission(Permissions.SecurityAdministration);
        }
        partial void PayPalTransactions_CanRead(ref bool result)
        {
            // Only an Admin can access the table (.ashx file has an override)
            result = this.Application.User.HasPermission(Permissions.SecurityAdministration);
        }
        partial void PayPalTransactions_CanUpdate(ref bool result)
        {
            // Only an Admin can access the table (.ashx file has an override)
            result = this.Application.User.HasPermission(Permissions.SecurityAdministration);
        }
        #endregion 

The Screen

  • The Main screen is the screen customers use to search for and purchase copies of pictures.
  • The following code shows the Buy a Copy button if the person who uploaded the picture is a Merchant:

myapp.Main.isMerchant_render = function (element, contentItem) {
    // Show button if isMerchant
    if (contentItem.value == true) {
        // Get the UserPicture
        var objUserPicture = contentItem.parent;
       element.innerHTML =
         "<button type='button'>Buy a Copy</button>";
    };
};

  • When the Buy a Picture button is clicked the following code runs that calls the Adaptive Payments handler that contacts PayPal to generate a PayKey:

myapp.Main.UserPictures_ItemTap_execute = function (screen)

{    // Get the selected Picture
    var objUserPicture = screen.UserPictures.selectedItem;
    // Get selected selectedPictureId
    selectedPictureId = screen.UserPictures.selectedItem.Id;  
   // Show the UserPicture
    myapp.showPurchaseItem(objUserPicture, {
        beforeShown: function (PurchaseItemScreen) {
            msls.promiseOperation(CallAdaptivePaymentsHandler)
                .then(function PromiseSuccess(AdaptivePaymentsHandlerResult) {
                    // Parse the JSON returned
                    var objPayPalResponse = jQuery.parseJSON(AdaptivePaymentsHandlerResult);
                    // Set the PayPal response
                    PurchaseItemScreen.PayPalRedirectUrl = objPayPalResponse.PayPalRedirectUrl
                        + "_ap-payment&paykey="
                        + objPayPalResponse.PayPalPaykey;
                    PurchaseItemScreen.PayPalPaykey = objPayPalResponse.PayPalPaykey;
                    PurchaseItemScreen.PayPalPaymentExecStatus =
objPayPalResponse.PayPalPaymentExecStatus;
                    PurchaseItemScreen.PayPalError = objPayPalResponse.PayPalError;
                    PurchaseItemScreen.PayPalErrorMessage = objPayPalResponse.PayPalErrorMessage;
               });
        }
    });
};

 

  • The following code is the Adaptive Payments handler that contacts PayPal and returns a PayKey:

using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Collections.Generic;
using System.Collections.Specialized;
using PayPal;
using PayPal.Exception;
using PayPal.Util;
using PayPal.AdaptivePayments;
using System.Configuration;
using PayPal.AdaptivePayments.Model;
using System.Linq;
using Microsoft.LightSwitch.Server;
namespace LightSwitchApplication
{
    [Serializable]
    public class PayPalResponse
    {
        public string PayPalRedirectUrl { get; set; }
        public string PayPalPaykey { get; set; }
        public string PayPalPaymentExecStatus { get; set; }
        public bool PayPalError { get; set; }
        public string PayPalErrorMessage { get; set; }
    }
    public class adaptivepaymentshandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            Pay(context);
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        /// <summary>
        /// Handle Pay API calls
        /// </summary>
        /// <param name="context"></param>
        private void Pay(HttpContext context)
        {
            // Get the PictureID
            int UserPicturesId = Convert.ToInt32(context.Request.Params["UserPicturesId"]);
            // Global values
            int PayPalPurchaseTransactionId = -1;
            string PayPalRedirectUrl = ConfigurationManager.AppSettings["PAYPAL_REDIRECT_URL"];
            string SellerPayPalEmail = "";
            string SellerUserName = "";
            // Instantiate PayPalResponse class
            PayPalResponse objPayPalResponse = new PayPalResponse();
            objPayPalResponse.PayPalPaykey = " ";
            objPayPalResponse.PayPalPaymentExecStatus = " ";
            objPayPalResponse.PayPalRedirectUrl = PayPalRedirectUrl;
            objPayPalResponse.PayPalErrorMessage = " ";
            objPayPalResponse.PayPalError = false;
            using (var serverContext =
                ServerApplicationContext.CreateContext()
                )
            {
                // Insert a record in the Transaction table
                var objPayPalTransaction =
                    serverContext.DataWorkspace.ApplicationData.PayPalPurchaseTransactions.AddNew();
                // Get the Picture
                var objPicture = (from Pictures in serverContext.DataWorkspace.ApplicationData
                                      .Pictures.GetQuery().Execute()
                                  where Pictures.Id == UserPicturesId
                                  select Pictures).FirstOrDefault();
                if (objPicture == null)
                {
                    // No Picture found
                    objPayPalResponse.PayPalError = true;
                    objPayPalResponse.PayPalErrorMessage =
                        string.Format("UserPicturesId {0} not found.", UserPicturesId);
                }
                else
                {
                    // Get the Merchant
                    var objUserProfiles = (from UserProfiles in serverContext.DataWorkspace.ApplicationData
                                               .UserProfiles.GetQuery().Execute()
                                           where UserProfiles.UserName == objPicture.UserName
                                           select UserProfiles).FirstOrDefault();
                    if (objUserProfiles == null)
                    {
                        // No Seller Found
                        objPayPalResponse.PayPalError = true;
                        objPayPalResponse.PayPalErrorMessage =
                            string.Format("UserName {0} does not have a UserProfile record.", objPicture.UserName);
                    }
                    else
                    {
                        // Set SellerUserName
                        SellerUserName = objUserProfiles.UserName;
                        if (objUserProfiles.PayPalEmail.Length < 5)
                        {
                            // Seller does not have a PayPal Email set
                            objPayPalResponse.PayPalError = true;
                            objPayPalResponse.PayPalErrorMessage =
                                string.Format("UserName {0} does not have a PayPal Email set.", objPicture.UserName);
                        }
                        else
                        {
                            // Get values needed to construct PayPal request
                            SellerPayPalEmail = objUserProfiles.PayPalEmail;
                            objPayPalTransaction.payment_status = "Pending";
                            objPayPalTransaction.PayPalError = false;
                            objPayPalTransaction.PayPalRedirectUrl = PayPalRedirectUrl;
                            objPayPalTransaction.PurchaserUserName = Application.Current.User.Name;
                            objPayPalTransaction.SellerPayPalEmail = SellerPayPalEmail;
                            objPayPalTransaction.SellerUserName = objUserProfiles.UserName;
                            // Associate the Picture to the PayPalTransaction
                            objPayPalTransaction.Picture = objPicture;
                            // Save the record so we get a Id to use in the PayPal request
                            serverContext.DataWorkspace.ApplicationData.SaveChanges();
                            // set PayPalPurchaseTransactionId
                            PayPalPurchaseTransactionId = objPayPalTransaction.Id;
                        }
                    }
                }
                // Proceed if no errors
                if (!objPayPalResponse.PayPalError)
                {
                    string currentPath =
                        System.Web.HttpContext.Current.Request.Url.OriginalString
                        .Replace(@"/PayPal/adaptivepaymentshandler.ashx", "");
                    ReceiverList receiverList = new ReceiverList();
                    receiverList.receiver = new List<Receiver>();
                    string strActionType = "PAY";
                    string currencyCode = "USD";
                    string cancelUrl = string.Format(@"{0}/HTMLClient/?mode=cancel", currentPath);
                    string returnUrl = String.Format(@"{0}/HTMLClient/?mode=return", currentPath);
                    string IpnURL = String.Format(@"{0}/PayPal/IPNListener.aspx", currentPath);
                    Receiver Receiver1 = new Receiver(Decimal.Parse("1.0"));
                    Receiver1.email = SellerPayPalEmail;
                    Receiver1.primary = false;
                    Receiver1.paymentType = "SERVICE";
                    receiverList.receiver.Add(Receiver1);
                    Receiver Receiver2 = new Receiver(Decimal.Parse("1.0"));
                    Receiver2.email = ConfigurationManager.AppSettings["PAYPAL_MERCHANT_EMAIL"];
                    Receiver2.primary = false;
                    Receiver2.paymentType = "SERVICE";
                    receiverList.receiver.Add(Receiver2);
                    PayRequest req = new PayRequest(new RequestEnvelope("en_US"),
                        strActionType,
                        cancelUrl,
                        currencyCode,
                        receiverList,
                        returnUrl);
                    // IPN Url (only enable with a published internet accessable application)
                    req.ipnNotificationUrl = IpnURL; 
                   // set optional parameters
                    //(Optional) Whether to reverse parallel payments if an error occurs with a payment.
                    //Allowable values are:
                    //true – Each parallel payment is reversed if an error occurs
                    //false – Only incomplete payments are reversed (default)
                    req.reverseAllParallelPaymentsOnError = true;
                    //(Optional) A unique ID that you specify to track the payment.
                    //Note: You are responsible for ensuring that the ID is unique.
                    //Maximum length: 127 characters
                    req.trackingId = PayPalPurchaseTransactionId.ToString();
                    // (Optional) The payer of PayPal fees. Allowable values are:
                    //    SENDER – Sender pays all fees (for personal, implicit simple/parallel payments;
                    //    do not use for chained or unilateral payments)
                    //    PRIMARYRECEIVER – Primary receiver pays all fees (chained payments only)
                    //    EACHRECEIVER – Each receiver pays their own fee (default, personal and unilateral payments)
                    //    SECONDARYONLY – Secondary receivers pay all fees
                    //    (use only for chained payments with one secondary receiver)
                    // req.feesPayer = "EACHRECEIVER";
                    // Calll PayPal to get PayKey          
                    AdaptivePaymentsService service = new AdaptivePaymentsService();
                    PayResponse resp = null;
                    try
                    {
                        resp = service.Pay(req);
                    }
                    catch (System.Exception e)
                    {
                        objPayPalResponse.PayPalError = true;
                        objPayPalResponse.PayPalErrorMessage = e.Message;
                        // Write to the database ********
                        objPayPalTransaction.PayPalError = true;
                        objPayPalTransaction.PayPalErrorMessage = e.Message;
                        serverContext.DataWorkspace.ApplicationData.SaveChanges();
                        OutputResponse(context, objPayPalResponse);
                    // Check for errors
                    if ((resp.responseEnvelope.ack == AckCode.FAILURE) ||
                        (resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
                    {
                        string strError = "";
                        objPayPalResponse.PayPalError = true;
                        foreach (var error in resp.error)
                        {
                            strError = strError + " " + error.message;
                        }
                        objPayPalResponse.PayPalErrorMessage = strError;
                        // Write to the database ********
                        objPayPalTransaction.PayPalError = true;
                        objPayPalTransaction.PayPalErrorMessage = strError;
                        serverContext.DataWorkspace.ApplicationData.SaveChanges();
                    }
                    else
                    {
                        objPayPalResponse.PayPalPaykey = resp.payKey;
                        objPayPalResponse.PayPalPaymentExecStatus = resp.paymentExecStatus;
                        // Write to the database ********
                        objPayPalTransaction.PayPalPaykey = resp.payKey;
                        objPayPalTransaction.PayPalPaymentExecStatus = resp.paymentExecStatus;
                        serverContext.DataWorkspace.ApplicationData.SaveChanges();
                    }
                }
            }
            // Return Response
            OutputResponse(context, objPayPalResponse);
        }
        private static void OutputResponse(HttpContext context, PayPalResponse objPayPalResponse)
        {
            // Create JavaScriptSerializer
            System.Web.Script.Serialization.JavaScriptSerializer jsonSerializer =
                new System.Web.Script.Serialization.JavaScriptSerializer();
            // Output as JSON
            context.Response.Write(jsonSerializer.Serialize(objPayPalResponse));
            return;
        }
    }
}

 

  • When the user clicks the Buy Now button they are taken to PayPal with the PayKey that has all the details of the transaction.
  • When the payment has been processed the following code listens for the IPN notification (that was set in the Adaptive Payments handler):

Try
    {
        byte[] parameters = Request.BinaryRead(HttpContext.Current.Request.ContentLength);
        if (parameters.Length > 0)
        {
            IPNMessage ipn = new IPNMessage(parameters);
            bool isIpnValidated = ipn.Validate();
            string transactionType = ipn.TransactionType;
            NameValueCollection map = ipn.IpnMap;
            if (isIpnValidated)
            {
                string connString =
                System.Web.Configuration.WebConfigurationManager
                .ConnectionStrings["_IntrinsicData"].ConnectionString;
                // Connect to the database
                PayPalTransactionsDataContext db = new LinqToSQL.PayPalTransactionsDataContext(connString);
                // Log the PayPal data received
                var objPayPalIpnTransaction = new LinqToSQL.PayPalIpnTransaction();
                string PayPalPayKey = ipn.IpnValue("pay_key"); ;
                string PayPalStatus = ipn.IpnValue("status");
                objPayPalIpnTransaction.transaction_type = ipn.IpnValue("transaction_type");
                objPayPalIpnTransaction.status = ipn.IpnValue("status");
                objPayPalIpnTransaction.sender_email = ipn.IpnValue("sender_email");
                objPayPalIpnTransaction.action_type = ipn.IpnValue("action_type");
                objPayPalIpnTransaction.payment_request_date = ipn.IpnValue("payment_request_date");
                objPayPalIpnTransaction.reverse_all_parallel_payments_on_error
                   ipn.IpnValue("reverse_all_parallel_payments_on_error");
                objPayPalIpnTransaction.return_url = ipn.IpnValue("return_url");
                objPayPalIpnTransaction.cancel_url = ipn.IpnValue("cancel_url");
                objPayPalIpnTransaction.ipn_notification_url = ipn.IpnValue("ipn_notification_url");
                objPayPalIpnTransaction.pay_key = ipn.IpnValue("pay_key");
                objPayPalIpnTransaction.memo = ipn.IpnValue("memo");
                objPayPalIpnTransaction.fees_payer = ipn.IpnValue("fees_payer");
                objPayPalIpnTransaction.trackingId = ipn.IpnValue("trackingId");
                objPayPalIpnTransaction.preapproval_key = ipn.IpnValue("preapproval_key");
                objPayPalIpnTransaction.reason_code = ipn.IpnValue("reason_code");
                objPayPalIpnTransaction.currencyCode = ipn.IpnValue("currencyCode");
                objPayPalIpnTransaction.approved = ipn.IpnValue("approved");
                objPayPalIpnTransaction.charset = ipn.IpnValue("charset");
                objPayPalIpnTransaction.transaction_0_id = ipn.IpnValue("transaction[0].id");
                objPayPalIpnTransaction.transaction_0_status = ipn.IpnValue("transaction[0].status");
                objPayPalIpnTransaction.transaction_0_id_for_sender
ipn.IpnValue("transaction[0].id_for_sender");
                objPayPalIpnTransaction.transaction_0_status_for_sender_txn =
                  ipn.IpnValue("transaction[0].status_for_sender_txn");
                objPayPalIpnTransaction.transaction_0_refund_id = ipn.IpnValue("transaction[0].refund_id")
                objPayPalIpnTransaction.transaction_0_refund_amount =
                    ipn.IpnValue("transaction[0].refund_amount");
                objPayPalIpnTransaction.transaction_0_refund_account_charged
                    ipn.IpnValue("transaction[0].refund_account_charged");
                objPayPalIpnTransaction.transaction_0_receiver = ipn.IpnValue("transaction[0].receiver");
                objPayPalIpnTransaction.transaction_0_invoiceId = ipn.IpnValue("transaction[0].invoiceId");
                objPayPalIpnTransaction.transaction_0_amount = ipn.IpnValue("transaction[0].amount");
                objPayPalIpnTransaction.transaction_0_is_primary_receiver
ipn.IpnValue("transaction[0].is_primary_receiver");
                objPayPalIpnTransaction.transaction_1_id = ipn.IpnValue("transaction[1].id");
                objPayPalIpnTransaction.transaction_1_status = ipn.IpnValue("transaction[1].status");
                objPayPalIpnTransaction.transaction_1_id_for_sender ipn.IpnValue("transaction[1].id_for_sender");
                objPayPalIpnTransaction.transaction_1_status_for_sender_txn = ipn.IpnValue("transaction[1].status_for_sender_txn");
                objPayPalIpnTransaction.transaction_1_refund_id = ipn.IpnValue("transaction[1].refund_id");
                objPayPalIpnTransaction.transaction_1_refund_amount = ipn.IpnValue("transaction[1].refund_amount");
                objPayPalIpnTransaction.transaction_1_refund_account_charged = ipn.IpnValue("transaction[1].refund_account_charged");
                objPayPalIpnTransaction.transaction_1_receiver = ipn.IpnValue("transaction[1].receiver");
                objPayPalIpnTransaction.transaction_1_invoiceId = ipn.IpnValue("transaction[1].invoiceId");
                objPayPalIpnTransaction.transaction_1_amount = ipn.IpnValue("transaction[1].amount");
                objPayPalIpnTransaction.transaction_1_is_primary_receiver = ipn.IpnValue("transaction[1].is_primary_receiver");
                // Save the record
                db.PayPalIpnTransactions.InsertOnSubmit(objPayPalIpnTransaction);
                db.SubmitChanges();
                // Only do the following if the status is COMPLETED
                if (PayPalStatus == "COMPLETED")
                {
                    // Start a Transaction log record
                    var objPayPalTransaction = new LinqToSQL.PayPalTransaction();
                    // Search for related PayPalPurchaseTransaction
                    var result = (from PayPalPurchaseTransactions in db.PayPalPurchaseTransactions
                                    where PayPalPurchaseTransactions.PayPalPaykey == PayPalPayKey
                                    select PayPalPurchaseTransactions).FirstOrDefault();
                    if (result != null)
                    {
                        // Update PayPalPurchaseTransaction
                        result.payment_status = "COMPLETED";
                        // Make a log entry                               
                        objPayPalTransaction.LogDateTime = DateTime.No
                        objPayPalTransaction.pay_key = PayPalPayKey;
                        objPayPalTransaction.LogData = String.Format(
                            "IPN Received for pay_key: {0} - Updated payment to COMPLETED", PayPalPayKey);
                    }
                    else
                    {
                        // Make a log entry                               
                        objPayPalTransaction.LogDateTime = DateTime.Now;
                        objPayPalTransaction.pay_key = PayPalPayKey;
                        objPayPalTransaction.LogData = String.Format(
                            "IPN Received for pay_key: {0} - Associated payment not found!", PayPalPayKey);
                    }
                    // Save the record
                    db.PayPalTransactions.InsertOnSubmit(objPayPalTransaction);
                    db.SubmitChanges();
                }
            }
        }
    }
    catch (System.Exception ex)
    {
        string connString =
            System.Web.Configuration.WebConfigurationManager
            .ConnectionStrings["_IntrinsicData"].ConnectionString;
        // Connect to the database
        PayPalTransactionsDataContext db = new LinqToSQL.PayPalTransactionsDataContext(connString);
        // Start a Transaction log record
        var objPayPalTransaction = new LinqToSQL.PayPalTransaction();
        // Make a log entry                               
        objPayPalTransaction.LogDateTime = DateTime.Now;
        objPayPalTransaction.pay_key = "";
        objPayPalTransaction.LogData = String.Format(
            "Error in {0} : {1}", this.GetType().Name, ex.Message);
        // Save the record
        db.PayPalTransactions.InsertOnSubmit(objPayPalTransaction);
        db.SubmitChanges();
        return;
    }

 

Linq to Sql is used because the call from PayPal is unauthenticated and the LightSwitch application is running under forms authentication. Entity Framework or ADO .Net could have also been used.

(you must have Visual Studio 2012 (or higher) installed to run the code)



European ASP.NET 4.5 Hosting - HostForLIFE.eu :: New Features Visual Studio LightSwitch 2013

clock November 27, 2013 06:46 by author Scott

We believe that some of you’re looking for this new features on LightSwitch 2013. We also support the latest Visual Studio LightSwitch 2013. You can take a look our hosting plan. In today post I will show what’s new on Visual Studio LightSwitch 2013.

Targeting .NET 4.5

A LightSwitch solution is composed of a server-side project based on ASP.NET and client projects based on either Silverlight (desktop), the new HTML client, or both. Until Visual Studio 2012 Update 3 (the latest update available when this article was written), the server project targeted .NET Framework 4.0. In Visual Studio 2013, the server project targets .NET Framework 4.5, enabling developers to take advantage of all the benefits of the latest version of ASP.NET and the .NET platform.

New Structure and Solution Explorer Enhancements

There are many important changes in how LightSwitch projects are created and structured in Visual Studio 2013. The first important change is that every screen and every table is now represented by a file with the .lsml extension. These files are based on the XML markup language, and they make it easier to give projects a better organization.

Please take a look this image below:

Every .lsml file has a code-behind file. For instance, a screen in the Silverlight client can have a Visual Basic or C# code-behind file, whereas in the HTML client .lsml files have JavaScript code-behind files. On the server side, table definition files with the .lsml extension always have VB or C# code-behind files, depending on which programming language you chose when creating the project.

The new project structure also affects Solution Explorer in other areas. Visual Studio 2013 no longer offers Logical view and File view; you simply have the usual classic view of any kind of project you can open in Visual Studio. This change makes the LightSwitch development environment even simpler and provides a more logical approach. You can compare the new view to an extended File view. You also can take advantage of all the best tools offered by Solution Explorer since Visual Studio 2012 (a blog post on MSDN explains the details), such as search, scoping, and duplicate views.

Improved Team Development

Another important improvement thanks to the new project structure affects team development. If you've had a chance to work with Team Foundation Server and source control over a LightSwitch application, you know how painful merging changes can be. In previous versions of LightSwitch, not all elements in the solution were managed by the source control engine. Now that everything is basically a file, every element is added to source control, allowing Team Foundation Server to manage the application changes correctly, thereby enabling team members to be more productive and efficient.

Easier Navigation

Switching between designers and visual elements is a frequent task. To make this common task easier, LightSwitch now offers the following options:

  • Navigation buttons are available on the left end of the standard toolbar. With these buttons, you can easily go back and forward to elements you worked with previously.
  • The Related Items drop-down list, available at the upper-right corner of any designer allows for easy navigation to screens, entities, and queries that have a relationship with the item you're currently viewing.

Enhanced Views with Multiple Designers

One of the biggest limitations in previous editions of the IDE in LightSwitch was the inability to open multiple designers concurrently. This feature was requested frequently, as you often need to copy-and-paste items from one screen or table to another.

HTML Client: JavaScript IntelliSense and DOM Explorer Improvements

At a higher level, Visual Studio 2013 has added several improvements to the JavaScript code editor and the DOM Explorer window. Because such improvements are part of Visual Studio, the LightSwitch development experience can take advantage of them as well. The code editor for JavaScript has been dramatically improved; for instance, all the occurrences of an identifier are now highlighted, and a navigation bar at the upper-right corner makes it easier to browse methods and declarations, as shown in image below.

Another great new improvement in the coding experience is the new auto brace complete. With this feature, Visual Studio 2013 automatically adds closing quotes, parentheses, brackets, and braces for you as you type code.

The DOM Explorer window allows for inspecting the Document Object Model (DOM) of an HTML page while it's being shown—a particularly handy feature at debugging time. In Visual Studio 2013, DOM Explorer highlights in yellow the parts of the HTML page that are being rendered; such highlights are very useful for understand the rendering progress. DOM Explorer also now supports direct editing, meaning that you can add new HTML attributes to the code while inspecting the page. The right side of the window provides additional tools for inspecting styles and layout properties, including events

The JavaScript interactive console now supports IntelliSense, which makes testing code a faster and sharper task.

Intrinsic Database Management with Linked Database Projects

When you create tables in a LightSwitch application, a SQL Server database (the intrinsic database) is created for you. Then you can publish the database along with the application via the deployment wizard or with SQL scripts. Visual Studio 2013 brings an interesting new opportunity: You can link the intrinsic database to a SQL Server database project. This feature opens an incredible number of scenarios, such as writing custom scripts or adding stored procedures into the intrinsic database.

Looking forward to try this new feature? Please check http://www.hostforlife.eu. We have offered the latest Visual Studio 2013 hosting on our hosting environment.



Europe Crystal Report Hosting :: Crystal Report Show Blank Report, How to Resolve It?

clock November 12, 2013 11:00 by author Scott

I know some of you will receive strange error on Crystal Report. It is working fine on your local computer but when you hosted it, and upload it to server, it doesn’t show anything, means blank site. Hmm…. How to solve this problem? Maybe this tutorial can get help you out.

This is the story:

I had wired up a Crystal Report through a Web Form (actually embedded within an ASP.NET MVC Web Application) and loaded through the CrystalReportViewer across an ADO.NET DataSet.

All was merry on my development machine, the report loaded fine with no problems.

However, when deploying to our live server which was setup with the Crystal Reports Re-distributable Package for .NET Deployment, it was a different story.

The report was blank. Due to Crystal’s “brilliant” (cough) error reporting, I had no clue why the report failed to load other than just not seeing it.  So I decided to check the Windows Event Log for any trails (as I’ve been caught out on this before) and low and behold there was our nasty exception:

Exception type: ConfigurationErrorsException
Exception message: It is an error to use a section registered as allowDefinition=’MachineToApplication’ beyond application level.  This error can be caused by a virtual directory not being configured as an application in IIS. (c:\inetpub\wwwroot\aspnet_client\system_web\2_0_50727\crystalreportviewers12\web.config line 6)

Well for me, creating the application as a .NET application in IIS, was not my issue, this had already been done.  The error after a bit of fiddling, I actually found out, was due to that Crystal Reports-issued Web.config mentioned in the exception (c:\inetpub\wwwroot\aspnet_client\system_web\2_0_50727\crystalreportviewers12\Web.config).  It was conflicting with my application.

After spending some time with this file, I couldn’t get the error message to budge.  So I took easy street, a good ‘ole rename.  I humbly decided I did not need this file after looking through the properties, there were no mission-critical properties relevant to my app in there, so click, rename, voila, report online.

Hope this was your problem.



European Umbraco Hosting - Germany :: Creating Umbraco Site with HostForLIFE.eu

clock November 8, 2013 07:52 by author Scott

In this tutorial, I will show you how to deploy Umbraco website on our shared hosting environment. Easy and faster.

First, you need to create blank SQL database.

1. Open Visual Web Developer Express 2010/VS 2010 Pro
2. Open Database Explorer (View -> Database Explorer) (in Visual Studio 2010 you will open “Server Explorer”).
3. The Database Explorer should show up on the right side of the IDE.
4. Right click Data Connections and select Add Connection.
5. Enter the server name in the first text box (type the name of your local SQL Server).
6. Type the name of the database in the database name field and click “OK.”
7. In Database Explorer you will see your local database.  Right click on it and choose Publish to Provider.

Then:

To generate the script that will create the backup of your database follow the steps listed below.

1. Click “Next” on the welcome screen of Publishing Wizard.
2. Ensure that your database is selected, check Script all objects in the selected database and click “Next.”
3. Choose the Script to file option and type the name of the script you will be generating. Click “Next.”
4. Leave the default Publishing Options and click “Next.”
5. Click “Finish.”

The final steps are:

1. Open your database in SQL Server Management Studio 2008.
2. Click File/Open/File and navigate to the SQL script you just created from your SQL Server.
3. Input your database login and password from Control Panel
4. Once the script is opened, navigate to the very top of the page and type:

  • USE [database name] (without the brackets)
  • GO

5. Click the “Execute” button.

It creates all tables exactly the same as you have in your local DB.

Happy coding!



European SQL Hosting - Amsterdam :: Difference Between Stored Procedure and Function in SQL Server

clock October 28, 2013 08:44 by author Scott

Today post I will show you the difference between Stored Procedure and Function in SQL Server. Stored Procedures are pre-compile objects which are compiled for first time and its compiled format is saved which executes (compiled code) whenever it is called. But Function is compiled and executed every time when it is called.

Basic Difference

  • Function must return a value but in Stored Procedure it is optional( Procedure can return zero or n values).
  • Functions can have only input parameters for it whereas Procedures can have input/output parameters .
  • Function takes one input parameter it is mandatory but Stored Procedure may take o to n input parameters..
  • Functions can be called from Procedure whereas Procedures cannot be called from Function.

Advance Difference

  1. Procedure allows SELECT as well as DML(INSERT/UPDATE/DELETE) statement in it whereas Function allows only SELECT statement in it.
  2. Procedures can not be utilized in a SELECT statement whereas Function can be embedded in a SELECT statement.
  3. Stored Procedures cannot be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section whereas Function can be.
  4. Functions that return tables can be treated as another rowset. This can be used in JOINs with other tables.
  5. Inline Function can be though of as views that take parameters and can be used in JOINs and other Rowset operations.
  6. Exception can be handled by try-catch block in a Procedure whereas try-catch block cannot be used in a Function.
  7. We can go for Transaction Management in Procedure whereas we can't go in Function.

Hope it will completely enough to explain the difference about stored procedure and Function.



European Windows 2012 Hosting - Netherlands :: How to Enable and monitor ASP.NET App Suspend on Windows Server 2012 R2

clock October 16, 2013 08:43 by author Scott

This is great feature in Windows Server 2012 and I found this interesting article from MSDN about App Suspend on Windows Server 2012. So, I decide to copy this article from msdn. Thanks to msdn.

App Suspend is a new hosting configuration in Internet Information Services (IIS) in Windows Server 2012 R2. The only requirement is that your app is running on the .NET Framework 4.5.1, which comes with Windows Server 2012 R2. No code changes are required. It’s literally as simple as the flip of a switch. Let’s take a look at that switch.

How to enable ASP.NET App Suspend

Enabling ASP.NET App suspend is pretty easy, in Internet Information Services Manager. As I wrote earlier, this setting is set on an app pool basis. Here’s what you need to do.

Open the IIS Manager

Right-click on an app pool – you’ll see the context menu

Select “Advanced Settings …”

You will see the Advanced Settings dialog. The “Idle Time-out” settings are the important ones to look at for this scenario, particularly the “Idle Time-out Action”. The default for that setting is terminate.

Change the “Idle Time-out Action” to Suspend, as you see below. Your app pool is now configured for ASP.NET App Suspend.

You will probably want to test out this feature. You could wait the entire 20 minutes, however, I suggest that you temporarily set the time-out to 1 minute, for testing purposes. Do remember to switch it back.

Monitoring site suspension

You can validate that an app was suspended in the event viewer, in the Application event log. Search for event 2310. You can see an example event, below.

Done.



Press Release - Premier European HostForLIFE.eu Proudly Announces FREE Trial Windows ASP.NET Hosting

clock October 8, 2013 12:31 by author Scott

European Windows and ASP.NET hosting specialist, HostForLIFE.eu, has officially launched FREE trial web hosting package. This free trial is offered for the next 14 days and at anytime, the customers can always cancel anytime. This FREE trial packages combine generous or unlimited web space, unlimited bandwith, unlimited email accounts, 1 MSSQL database, 1 MySQL database. There is also the ability to host multiple websites in this package. As the market for hosted solutions continues to grow, the new hosting range is designed to exceed the growing technical demands of businesses and IT professionals.

HostForLIFE.eu continues to invest heavily in developing powerful and resilient Business web hosting packages. The new range scales to accommodate a wide range of business needs including ecommerce and multiple websites. The range comprises of Classic Package, which is priced €3.00/month. The Budget Package is priced at €5.50/month. There is Economy package which is priced €8.00/month, this is the most favourite package and it is designed for Portal/Business site. And then Business Package is priced at €11.00/month. Furthermore, the Business Package delivers HostForLIFE’s most powerful shared hosting feature set to date, and is optimized for hosting multiple and business websites.

Every day thousands of people decide to set up a website for business or personal use. New business owners and the average consumer don't always have access to unlimited budgets. HostForLIFE.eu understand the importance of reliable hosting but are not always prepared to pay the exorbitant prices that reliable hosts charge.

“We believe that all customers should be given a free trial before buying into a service and with such approach, customers are confident that the product / service that they choose is not faulty or wrong.” Said John Curtis, VP Marketing and Business Development at HostForLIFE.eu. “With this free trial hosting, we want our customers to test drive our quality services. We believe that our web hosting platform and customer support are up there with the best and our commitment to give the best for our customers.”

HostForLIFE.eu is awarded Top No#1 SPOTLIGHT Recommended Hosting Partner by Microsoft (see www.microsoft.com/web/hosting/HostingProvider/Details/953). HostForLIFE.eu services is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and other European countries. Besides this award, HostForLIFE.eu has also won several awards from reputable organizations in the hosting industry and the detail can be found on HostForLIFE.eu official website.

For more information about this FREE trial package offered by HostForLIFE.eu, please visit http://www.hostforlife.eu

About HostForLIFE.eu:

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. HostForLIFE.eu deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

HostForLIFE.eu number one goal is constant uptime. HostForLIFE.eu data center uses cutting edge technology, processes, and equipment. HostForLIFE.eu has one of the best up time reputations in the industry.

HostForLIFE.eu second goal is providing excellent customer service. HostForLIFE.eu technical management structure is headed by professionals who have been in the industry since it's inception. HostForLIFE.eu has customers from around the globe, spread across every continent. HostForLIFE.eu serves the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.   



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in