Web API

Passing Cookies to ASP.NET WebAPI via HttpClient

I was coding an app which uses ASP.NET Identity, and all requests require authorization. My Identity ASP.NET uses an application cookie, so I was looking for a way to pass this cookie to the Web API request. Currently, the request would return a 302 to the login page even though I’m logged in.

In the case of using HttpClient, the cookies aren’t sent in by default, and you need to manually add them the “CookieContainer”:

var cookieContainer = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler
{
    UseCookies = true,
    UseDefaultCredentials = true,
    CookieContainer = cookieContainer
};
foreach (string cookiename in Request.Cookies)
{
    var cookie = Request.Cookies[cookiename];
    cookieContainer.Add(new Cookie(cookie.Name, cookie.Value, cookie.Path, "domain here"));
}

using (var client = new HttpClient(handler))
{
    ....

That’s it! HTH.

Web API

ASP.NET Web API: Catching Deserialization Errors on Action Level

A user on forums.asp.net asked a question regarding an issue where he was throwing an exception from a custom Json Converter, but the Response was still sending back a successful 200 response. The question was how to catch that error on the action level so a meaningful  response can be sent back to the client.

http://forums.asp.net/t/2057724.aspx?Enum+deserialization+errors+ignored

The answer is ModelState. On the action level, you can do something like the following to access any errors while deserializing:

            if (ModelState.IsValid)
            {
                // valid, no errors
            }
            else
            {
                // Invalid / errors
                foreach (var state in ModelState)
                {
                    foreach (var error in state.Value.Errors)
                    {
                        var errorMessage = error.Exception.Message;
                    }
                }
            }

There are posts out there discussing how to use ModelState for validation (for example required fields), however I haven’t found any showing the use of it for deserialization errors as well. Hopefully this will be helpful to others.

Deployment, Visual Studio

Solving the Object Reference Error After Your VS 2013 Publish

After publishing a web application using the VS publish feature, you may receive the infamous “Object reference not set to an instance of an object.” error. And the annoying part is there’s no exact line number that the error is pointing to.

From past experiences, I was able to resolve in one (or more) of the following:

  1. Delete the project DLL, and replace with new DLL (either by publishing or plain FTP)
  2. If you updated a specific page, delete that page, and publish again.
  3. Refresh the application pool (#1 usually takes care of that).

Hope this helps!

SQL Server

Never use SELECT * in SQL Server Views

So, as I discovered, SQL Server kind of “caches” View columns, which can be a problem if you use SELECT *.

Let’s demonstrate:

Create the tables and the view:

CREATE TABLE Categories(CategoryID INT, CategoryName VARCHAR(50))
INSERT INTO Categories
SELECT 1, 'Category1'
UNION SELECT 2, 'Category2'

CREATE TABLE Products (ProductID INT, Description VARCHAR(50), CategoryID INT)
INSERT INTO Products
SELECT 1, 'Product1', 1
UNION SELECT 2, 'Product2', 1
UNION SELECT 3, 'Product3', 2

GO
CREATE VIEW TestView
AS
SELECT c.*, p.Description FROM Categories c JOIN Products p ON c.CategoryID = p.CategoryID
GO

Expected output of SELECT * FROM TestView:

 

 

Now let’s add a column to the Categories table:

ALTER TABLE Categories ADD NewColumn VARCHAR(50) NULL

Output of SELECT * FROM TestView:
Output2

 

 

And… our Description column is showing the data of our NewColumn! As you see, things can get real messy. The best thing would be not to use SELECT * at all, but if it’s too late and you’re seeing the issue described, you can use 2 options to refresh the View metadata and fix the problem:

  1. Use sp_refreshview
  2. ALTER or DROP and RECREATE the View

 

As a side point, it seems SQL Server Management Studio automatically converts SELECT * to individual column names when executing or saving the View in the designer / UI – probably for this reason.

SQL Server, Windows Azure

Connecting to External Sql Server from Windows Azure Website

After publishing an application from Visual Studio to a Windows Azure website (which, for the record, was incredibly easy) my website loaded fine, but after trying to login using an external SQL Server it threw me an “Access denied.” error. I resolved that by adding the IP address of the website to the external SQL Server.

The error that came up next was strange. It basically told me that my Stored Procedure which exists does not exist. My connection strings were fine in my application in Visual Studio so I couldn’t imagine what was going on. At last, I decided to check the actual web.config file which was uploaded.

Now, I had 1 Entity Framework connection string in there, with 2 standard SQL Server connection strings.

The EF one looked fine, but the standard ones had the following appended to it:

MultipleActiveResultSets=True;Application Name=EntityFramework

I’m not sure where that came from – I’m assuming it happened in the process of being published – but replacing the altered connection strings with the original, correct ones did the job. I uploaded the newly changed web.config file manually via FTP to ensure it won’t get altered again behind my back.

Hope this helps someone else.

Ecommerce

PayPal and Shopping Cart Modification

While building PayPal into an e-commerce project I was working on, I came across a problem scenario as follows:

  1. Customer adds an item to cart.
  2. Customer is redirected to PayPal.
  3. Customer opens cart page in new window, updates cart (i.e. adds new products, ups quantity). (Can happen after #4 too.)
  4. Customer signs in to PayPal, and clicks continue and authorizes the payment, redirected back to your site.

In the above scenario, the customer is able to modify his cart to his likings and then process the order for the original amount when he first clicked the PayPal button. For example, add a $5 product, click the PayPal button, add a $500 product and continue processing the order. Obviously this is a fraud issue; a customer should not be able to manipulate his/her cart after directed to PayPal and able to complete the checkout process this way.

I googled around for solutions to this, and I managed to bring up a few posts addressing, not the exact, but something like the above issue.

  1. https://drupal.org/comment/4652836#comment-4652836 – this post is actually from a Drupal forum, but hints to a solution which is to clear the cart when the user is initially directed to PayPal, with a possible cart restoration *if the user clicks cancel via PayPal*. The drawback with this is if user closes the PayPal page not via PayPal then his/her cart is lost.
  2. Idea inspired from an SO post – compare the current cart amount with the original amount sent to PayPal on the PayPal return URL. If the amounts match, continue to process the order successfully. If the amounts don’t match, then do the following: a. redirect the user to a page explaining what happened. Something like “It seems your cart was modified while your order was being processed by PayPal, and therefore we weren’t able to complete the PayPal checkout process for you. Please return to your cart, make any necessary changes and then try checking out again.”  b. send an email to website admin.

I think approach #2 is the preferred way to go about it. It addresses the issue in a neat and user-friendly way.

 

Amazon, C#

Amazon Reports API C# Integration

In a previous post I’ve shown how to to submit a feed using the Amazon Feeds API. In this post I’m going to show how to download a report from Amazon using the Reports API. Download the API from the Amazon Developer Home page.

Before we actually download the report, Amazon requires us to submit a request. The time we need to wait after the request until we can download the report varies based on the report type and possibly other factors.

Below are 2 examples of report types:

  • _GET_MERCHANT_LISTINGS_DATA_ – download all inventory.
  • _GET_FLAT_FILE_ORDERS_DATA_ – download orders from specified date.

For readability, I created an Report Type enum, with these report type values, which will be used as part of the argument of the below method. This method requests the report.

public RequestReportResult GetRequestReportResult(ReportType reportType)
{
    RequestReportRequest reportRequestRequest = new RequestReportRequest();
    reportRequestRequest.Merchant = Merchant;
    reportRequestRequest.ReportType = reportType.ToString();

    // If this is an order report, get only last week
    if (reportType == ReportType._GET_FLAT_FILE_ORDERS_DATA_)
    {
        reportRequestRequest.StartDate = DateTime.Now.AddDays(-7);
    }

    return GetClient().RequestReport(reportRequestRequest).RequestReportResult;
}

The GetClient method used here returns a MarketplaceWebServiceClient object. Refer to my previous Amazon post for the code. Also, notice that in the case of a request for an order report, we are setting the StartDate property to specify the date from which we want orders downloaded.

Now we can use this method to get a list of the requests and their statuses:

private List<ReportRequestInfo> GetReportRequests()
{
    GetReportRequestListRequest reportlistReqests = new GetReportRequestListRequest();
    reportlistReqests.Merchant = Merchant;
    GetReportRequestListResponse reportlistResponse = GetClient().GetReportRequestList(reportlistReqests);
    return reportlistResponse.GetReportRequestListResult.ReportRequestInfo;
}

Once the status of our request is _DONE_, we can go ahead and download the report. The data will be saved to a text file. From there you can do whatever you want with it, like import it into your DB.

Here’s the method to download the report. It takes in a RequestReportInfo object (which you get from the GetReportRequests method):

private FileInfo GetReportFile(ReportRequestInfo reportInfo)
{
    GetReportRequest reportRequest = new GetReportRequest();
    reportRequest.Merchant = Merchant;
    reportRequest.WithReportId(reportInfo.GeneratedReportId);

    GetReportResponse reportResponse = new GetReportResponse();

    string path = HttpContext.Current.Server.MapPath("~/Files/Report-" + reportInfo.ReportType + "-" + reportInfo.GeneratedReportId + ".txt");

    using (FileStream stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
    {
        reportRequest.Report = stream;
        reportResponse = GetClient().GetReport(reportRequest);
    }

    return new FileInfo(path);
}

That’s it! Again, there isn’t much documentation on this so I hope this post is found helpful.

Happy Coding!