LINQ and Dynamic Query – Comparing DateTime value

By: lakswin

In one of our development, we end up with the situation that needs to check the DateTime value in Dynamic LINQ query. Trying different ways out there and googling a bit, finally got some useful references that helped us to resolve the same

Hope, you would love reading!

 

Example:

TestEntities te = new TestEntities();

string dateString = “12/01/2010″;

 

Used the following overload for “.Where” :

# 1:

IQueryable<T>.Where(Expression<Func<State, bool>> predicate)

var dateTest = te.SiteLogs

.Where(String.Format(“it.TimeStamp >= DATETIME ‘{0}’”, Convert.ToDateTime(dateString).ToString(“yyyy-MM-dd HH:mm”)))

.Select(“it.IPAddress”);

 

# 2:

IQueryable.Where(string predicate, params object[] values)

var dateTest1 = te.SiteLogs

.Where(“it.TimeStamp >= @0″,  Convert.ToDateTime(dateString))

.Select(“it.IPAddress”);

 

Observations:

In # 1,

  • We need to say the “Time” format also, that is compulsory. Otherwise it would throw an error as well.  And again, the syntax with “DATETIME” is wired 🙂
  • The resultant date format should be “yyyy-MM-dd “

 

In # 2,

Its clean and simple. I like this syntax. Here you can add any number of Params like @0, @1 & so on

 

References:

http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

http://msdn.microsoft.com/en-us/library/bb399176.aspx

 

Copy from: https://lakswin.wordpress.com/2011/10/20/linq-and-dynamic-query-%E2%80%93-comparing-datetime-value/

Image Resizing and Cropping in C#

By: JasonJano’s Blog

So the other day I put up a c# wrapper for ffmpeg. The wrapper I built is a part of my own asset storage system which I guess I will probably be putting up in chunks over the next few weeks. Today I have decided to put up my image resizing tools for your use.

Resize Now or Resize Later?

There are a couple theories to image resizing, should the image be resized at the point it gets uploaded, or at the point it gets sent out to the client?

Each method has advantages and disadvantages. Resizing at upload is good because it speeds up time to delivery as the processor has already done the resizing, additionally, the image is only resized once, vs. if the image is resized every time it is downloaded, it could be resized countless times. The problem with resizing at upload, however, is that it is now resized — you can’t un-resize it. Resizing at download then, is more processor intensive as it is resized every time someone requests a different size (one could probably get around some of this with caching, but the no matter how you slice it, it is still more processor intensive). The nice thing is that based on querystring or, however you pass the resizer data, you get a customized image size.

I have my own theory on this. If one has a ton of storage space (which most of us do have available to us now adays) it makes sense to resize in some basic sizes at upload while keeping the original as well for future resizing, if needed. Most good graphic designers break all their pages up into grids of magic 3rds anyways and would, generally, have ideas about their perfect image sizes for thumbnails, swatches, large previews, etc..

In another post I will detail how I get all of these different sizes and what not stored for use, but — for now — I will just give you the tools with which to do resizing and cropping in one spot.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
//Overload for crop that default starts top left of the image.
public static System.Drawing.Image CropImage(System.Drawing.Image Image, int Height, int Width)
{
    return CropImage(Image, Height, Width, 0,0);
}
//The crop image sub
public static System.Drawing.Image CropImage(System.Drawing.Image Image, int Height, int Width, int StartAtX, int StartAtY)
{
    Image outimage;
    MemoryStream mm = null;
    try
    {
        //check the image height against our desired image height
        if (Image.Height < Height) {
            Height = Image.Height;
        }
        
        if (Image.Width < Width) {
            Width = Image.Width;
        }
        
        //create a bitmap window for cropping
        Bitmap bmPhoto = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);
        bmPhoto.SetResolution(72, 72);
        
        //create a new graphics object from our image and set properties
        Graphics grPhoto = Graphics.FromImage(bmPhoto);
        grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
        grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
        grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
        
        //now do the crop
        grPhoto.DrawImage(Image, new Rectangle(0, 0, Width, Height), StartAtX, StartAtY, Width, Height, GraphicsUnit.Pixel);
        
        // Save out to memory and get an image from it to send back out the method.
        mm = new MemoryStream();
        bmPhoto.Save(mm, System.Drawing.Imaging.ImageFormat.Jpeg);
        Image.Dispose();
        bmPhoto.Dispose();
        grPhoto.Dispose();
        outimage = Image.FromStream(mm);
        return outimage;
    }
    catch (Exception ex)
    {
        throw new Exception("Error cropping image, the error was: " + ex.Message);
    }
}
//Hard resize attempts to resize as close as it can to the desired size and then crops the excess
public static System.Drawing.Image HardResizeImage(int Width, int Height, System.Drawing.Image Image)
{
    int width = Image.Width;
    int height = Image.Height;
    Image resized = null;
    if (Width > Height)
    {
        resized = ResizeImage(Width, Width, Image);
    }
    else
    {
        resized = ResizeImage(Height, Height, Image);
    }
    Image output = CropImage(resized, Height, Width);
    //return the original resized image
    return output;
}
//Image resizing
public static System.Drawing.Image ResizeImage(int maxWidth, int maxHeight, System.Drawing.Image Image)
{
    int width = Image.Width;
    int height = Image.Height;
    if (width > maxWidth || height > maxHeight)
    {
        //The flips are in here to prevent any embedded image thumbnails -- usually from cameras
        //from displaying as the thumbnail image later, in other words, we want a clean
        //resize, not a grainy one.
        Image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipX);
        Image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipX);
        float ratio = 0;
        if (width > height)
        {
            ratio = (float)width / (float)height;
            width = maxWidth;
            height = Convert.ToInt32(Math.Round((float)width / ratio));
        }
        else
        {
            ratio = (float)height / (float)width;
            height = maxHeight;
            width = Convert.ToInt32(Math.Round((float)height / ratio));
        }
        //return the resized image
        return Image.GetThumbnailImage(width, height, null, IntPtr.Zero);
    }
    //return the original resized image
    return Image;
}

Copy from: https://jasonjano.wordpress.com/2010/02/13/image-resizing-and-cropping-in-c/

Visual Studio 2012 / 2013 Update 1 2 3 4 Offline Installer

By: techtronic.us

Visual Studio 2012 Update 2 was released about a week ago.  This update includes lots of fixes and some features – you can see the list here.  The only problem with the update is that Microsoft does not offer an offline installer.  If you are installing this on your own PC or for one person, you may not have a need for one.  But…  if your entire team needs to install this (or you just want to have it for later for a PC rebuild, you can download all 1.8 GB and have an offline installer for you or your team to share.  Here’s how:

  1. Get the update from Microsoft here. (updated with Update 4 link)
  2. Save the file to a folder.
  3. open the folder
  4. Pro tip – Shift + right-click the background of the folder and choose ‘Open command window here’
  5. open_command_window
  6. in the command window type VS2013.4.exe /Layout
  7. (or VS2013.1.exe /Layout or VS2013.2.exe /Layout depending on your update)
  8. command_window
  9. It will then ask you where you would like to save and extract the files.
  10. vs2012_update_2_download_location
  11. This step will take some time depending on your download speed.  This is the step that adds time to the install when you choose the web installer.
  12. downloading_extracting_update_2
  13. You will now see a folder with the update installer along with all the source files.  You can now store this safe on a network share or your hard drive and update your installation of Visual Studio without downloading 2GB of files!
  14. vs2012_extracted
  15. This should work for any version of Visual Studio going forward.

Copy from: http://www.techtronic.us/blog/post/technology/visual-studio-2012-update-2-offline-installer/

Points, inches and Emus: Measuring units in Office Open XML

By: Lars Corneliussen

After I got confused with the Office Open XML (OOXML) measuring units for a couple of hours, I thought I’d share what I found on it.

I order to avoid floating point calculations and still maintain high precision the format uses some odd measurement units. Don’t think you can get away with inches, centimeters or pixels!

UPDATE: I created a conversion tool for all those units, available here.

Twentieths of a point (dxa)

The main unit in OOXML is a twentieth of a point. This is used for specifying page dimensions, margins, tabs, etc.

The international default letter size is ISO 216 A4 (210x297mm ~ 8.3×11.7in) and expressed as this:

1
2
// pageSize: with and height in 20th of a point
<w:pgSz w:w="11906" w:h="16838"/>

Calculations

20th of a Point Points

(dxa/20)

Inches

(pt*72)

Centimeters

(in*2,54)

Width 11906 595.3 8,27… 21.00086…
Height 16838 841.9 11.69… 29.70036…

As you see it doesn’t really come out even, but even enough. As you can see here, word processes files at 72dpi.

Half-points

Half-points are used to specify font sizes. A font-size of 12pt equals 24 half points:

1
2
3
4
5
// run properties
<w:rPr>
  // size value in half-points
  <w:sz w:val="24"/>
</w:rPr>

Fiftieths of a Percent

This is used for relative measurements in some places. It can for example be used for specifying tables total with, cell with and margins.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<w:tbl>
    <w:tblPr>
      <!-- table width in 50th of a percent -->
      <w:tblW w:w="2500" w:type="pct"/>
    </w:tblPr>
    <w:tblGrid/>
    <w:tr>
        <w:tc>
            <w:p>
                <w:r>
                    <w:t>Hello, World!</w:t>
                </w:r>
            </w:p>
        </w:tc>
    </w:tr>
</w:tbl>

This prints a table that takes 50% of the available with. If you want to specify the with in twentieth of points instead, you have to use specify w:type=”dxa”.

Calculation

0.5 * 5000 = 2500pct

or

(50*50)%

EMUs (English Metric Unit)

EMUs are used for coordinates in vector-based drawings and embedded pictures. The EMU is a virtual unit to bridge both centimeters and inches. One inch equates to 914400 EMUs and a centimeter is 360000. Actually I found out that the number 914400 is calculated by (the least common multiple of 100 and 254) times 72. As I understand it, this ensures that you can convert forth and back between integer 100th inches, millimeters and pixels with out any floating points. Is that correct, anybody?

Since OOXML is too verbose, the full markup would just confuse even more. Lets say we have a picture that we want to fit into a table cell.

The cell with is 4,25cm which equals to 2410 dxa.

1
<w:tcW w:w="2410" w:type="dxa"/>

The original picture is 295x413px at 72dpi and is embedded using DrawingML. The target picture size in the document has to be specified twice. Once for the drawing canvas (extent) and a second time for the embedded picture itself.

When you try to draw this in word itself you’ll have a hard time to match the actual cell size. This version is set by manually calculating the target picture size.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<w:drawing>
    <wp:anchor ...>
        ...
        <!-- drawing canvas size -->
        <wp:extent cx="1530350" cy="2142490"/>
        ...
        <a:graphic>
            <a:graphicData>
                <pic:pic>
                    ...
                    <!-- shape properties -->
                    <pic:spPr bwMode="auto">
                        <!-- 2D transform -->
                        <a:xfrm>
                            ...
                            <!-- picture size -->
                            <a:ext cx="1530350" cy="2142490"/>
                        </a:xfrm>
                        ...
                    </pic:spPr>
                </pic:pic>
            </a:graphicData>
        </a:graphic>
    </wp:anchor>
</w:drawing>

Calculations

20th of a Point Points

(dxa/20)

Inches

(pt/72)

EMU

(in*914400)

Cell Width 2410 120.5 1,67361… 1530350

Even though this is the most logical way to calculate it, it involves floating points. You can simply avoid those by calculating:

2410 * 914400 / 72 / 20 = 1530350

which can be simplified to:

2410 * 635 = 1530350

Since we want to maintain the aspect ratio of the original picture at 295:413 we have to calculate the height for the cell in dxas and for the pictures in EMUs.

The width-to-height-ratio for this picture is 1.4. So the height for the cell is 2410*1.4 = 3374 dxa and 3374*635 = 2142490 emu.

Thanks for reading! I hope this helps.

 

Copy from: http://startbigthinksmall.wordpress.com/2010/01/04/points-inches-and-emus-measuring-units-in-office-open-xml/

Export data from a DataSet into a real Excel 2007 file

Ever wanted to add an “Export to Excel” function to your ASP.Net, WinForms or WPF application ?

This free C# and VB.Net library lets you export a DataTable or DataSet of data into a “real” Excel 2007 .xlsx file, using one line of code.

CreateExcelFile.CreateExcelDocument(myDataSet, myExcelPathFilename);

…or if you’re using ASP.Net…

CreateExcelFile.CreateExcelDocument(myDataSet, myExcelFilename, Response);

You can download the full source code using the links below, so you can extend it to add Excel formatting, etc.

It uses the OpenXML libraries, rather than Microsoft’s Visual Studio Tools for Office (VSTO) libraries, so you don’t need to have Excel installed on your server.

The CreateExcelFile library

All of the code you’ll need is contained in one class, CreateExcelFile, which I’ve saved in the file CreateExcelFile.cs (or CreateExcelFile.vb for the VB.Net version).

To use this class, you simply call its CreateExcelDocument function, passing it a DataSet variable (which contains the values you want writing into Excel cells), and the path+filename of the Excel file you wish to create.

Each DataTable within your DataSet will be saved into it’s own Excel worksheet.

// Step 1: Create a DataSet, and put some sample data in it
DataSet ds = CreateSampleData();

// Step 2: Create the Excel .xlsx file
try
{
string excelFilename = “C:\\Sample.xlsx”;
CreateExcelFile.CreateExcelDocument(ds, excelFilename);
}
catch (Exception ex)
{
MessageBox.Show(“Couldn’t create Excel file.\r\nException: ” + ex.Message);
return;
}

Demo program

The attached Visual Studio 2010 C# and VB.Net WinForms demo shows how easy it is to use the CreateExcelFile library.

It consists of a simple dialog with one button on it (shown below).

When you click on the button, it’ll create a DataSet and fill it with some sample data, and prompt you for a location to save our example Excel file to. It will then call the CreateExcelDocument function to create an Excel 2007 .xlsx file containing our DataSet’s data, then open the file in Excel for you to admire.

Screenshot from the C# demo Screenshot from the C# demo

Notice how our demo application created a DataSet containing three DataTables in it, called Drivers, Vehicles & Vehicle Owners. The CreateExcelFile library then created an Excel Worksheet for each of these DataTable names, and wrote each DataTable’s data into it.

Using the “Export to Excel” library in your own application

The CreateExcelFile library has two dependences:

  • DocumentFormat.OpenXml.dll
    From the Microsoft Open XML SDK library
  • WindowsBase.dll
    From the Microsoft .Net Framework library

I have included a copy of these two files in the source code’s lib folder, but ideally, you should download the most recent version from the Microsoft website.

To use the library in your own code, simply add these two files, and the CreateExcelFile.cs file to your Visual Studio project, then add the two .dll files to the References section of your project.

Also, you need to make sure that these two files have the “Copy Local” field set to true. Without this, when you deploy your app, it won’t copy the .dlls to your bindirectory, and IIS will complain that it can’t find the OpenXML libraries.

Then just call the static CreateExcelDocument function, as shown above.

CreateExcelFile.CreateExcelDocument(ds, excelFilename);

I have deliberately left this library’s source code available for you to view and alter, as desired.

Exporting from a List<> or DataTable

With a little help from a discussion on CodeGuru, I added two extra functions, so you can now call the CreateExcelDocument function in three ways:

public static bool CreateExcelDocument<T>(List<T> list, string xlsxFilePath)
public static bool CreateExcelDocument(DataTable dt, string xlsxFilePath)
public static bool CreateExcelDocument(DataSet ds, string xlsxFilePath)

..so you should find it really easy to export your data to Excel from any of these formats.

Using the library in an ASP.Net application

November 2013: With help from my fellow developers, I have made the C# library even easier to use in an ASP.Net application. The ExportToExcel class now lets you create an Excel file without writing to a temporary file first. You just need to pass the “Response” as a parameter.

// In this example, I have a defined a List of my Employee objects.
class Employee;
List<Employee> listOfEmployees = new List<Employee>();

// The following ASP.Net code gets run when I click on my “Export to Excel” button.
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
// It doesn’t get much easier than this…
CreateExcelFile.CreateExcelDocument(listOfEmployees, “Employees.xlsx”, Response);
}

By default, this functionality is disabled in the C# file, so that non-ASP.Net developers don’t get build errors when attempting to use the library. To enable the functionality, you need to manually make two small changes:

First, uncomment the first line of code in the CreateExcelFile.cs file, so it looks like this:

#define INCLUDE_WEB_FUNCTIONS

Then add a new Reference, and select the System.Web library.

Add Reference..

And that’s it. You can now use the three new web-friendly functions for exporting to Excel.

public static bool CreateExcelDocument<T>(List<T> list, string filename, System.Web.HttpResponse Response)
public static bool CreateExcelDocument(DataTable dt, string filename, System.Web.HttpResponse Response)
public static bool CreateExcelDocument(DataSet ds, string filename, System.Web.HttpResponse Response)

Cool, hey ?

You’re welcome to use and adapt this code as you like, but – please – if you like it, leave me a comment below.

Setting the Excel column widths

By default, the CreateExcelFile class just creates a valid Excel 2007 with no formatting, colors, borders, etc.

If you wanted to change this code to set the widths of the columns in your Excel file, below are the changes you’d need to make.

First, you need to add a few lines to the CreateParts function (shown in red):

private static void CreateParts(DataSet ds, SpreadsheetDocument spreadsheet)
{
// Loop through each of the DataTables in our DataSet, and create a new Excel Worksheet for each.
uint worksheetNumber = 1;
foreach (DataTable dt in ds.Tables)
{
// For each worksheet you want to create
string workSheetID = “rId” + worksheetNumber.ToString();
string worksheetName = dt.TableName;

WorksheetPart newWorksheetPart = spreadsheet.WorkbookPart.AddNewPart<WorksheetPart>();
newWorksheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet();

// If you want to define the Column Widths for a Worksheet, you need to do this *before* appending the SheetData
// http://social.msdn.microsoft.com/Forums/en-US/oxmlsdk/thread/1d93eca8-2949-4d12-8dd9-15cc24128b10/
//
// The following example sets the column width, for all columns where we have data, to 20 pixels.

int columnWidthSize = 20;
Columns columns = new Columns();

for (int colInx = 0; colInx < dt.Columns.Count; colInx++)
{
Column column = CustomColumnWidth(colInx, columnWidthSize);
columns.Append(column);
}
newWorksheetPart.Worksheet.Append(columns);

// create sheet data
newWorksheetPart.Worksheet.AppendChild(new DocumentFormat.OpenXml.Spreadsheet.SheetData());

// save worksheet
WriteDataTableToExcelWorksheet(dt, newWorksheetPart);
newWorksheetPart.Worksheet.Save();

Then, add the following function just below the WriteDataTableToExcelWorksheet function:

private static Column CustomColumnWidth(int columnIndex, double columnWidth)
{
// This creates a Column variable for a zero-based column-index (eg 0 = Excel Column A), with a particular column width.
Column column = new Column();
column.Min = (UInt32)columnIndex + 1;
column.Max = (UInt32)columnIndex + 1;
column.Width = columnWidth;
column.CustomWidth = true;
return column;
}

If you wanted to calculate the column widths, based on the data in each column, it’s not easy.
Have a read of this article:
http://polymathprogrammer.com/2010/01/11/custom-column-widths-in-excel-open-xml/

Downloads

C# VB.Net Filename Description
ExportToExcel.zip The full Excel demo, showing how to use the CreateExcelFile library code, and the Open XML libary files.
CreateExcelFile.cs / .vb Just the C#/VB.Net source code file for the CreateExcelFile class.
ExpotToExcelExe.zip The executable (.exe) file of the Demo, if you just want to see what the application looks like.
Note: This zip file contains a copy of the .exe file created by the Visual Studio project which you can download using the link above. This .zip file is safe, but your anti-virus software might complain about it or block it, as it contains an executable file.

Copy from: http://mikesknowledgebase.azurewebsites.net/pages/CSharp/ExportToExcel.htm

Extending your ASP.NET Web API responses with useful metadata

By: 

If you ever worked with any API, which, in this day of age, you must have, you surely noticed that in most situations the API response isn’t just the result (requested data), but also a set of helpful metadata, like “total Results”, “timestamp”, “status” and so on.

In Web API, by default, you just serialize your models (or DTO) and such information are not present. Let’s build something which will solve this problem and help you decorate your response with hepful information. This would make it very easy for the client to implement paging, auto-loading scenarios, caching (if you return last modified information) and a lot more.

 

What are we going to build

First let’s go through a plan of what we are going to build.

Assume you have some sample repository. In the recent samples, I have always been using a dummy repository from this post, so let’s use it again.

Now, by default, the response will look like this (for a single item):

 

If we request for IQueryable, we obivously get an Array.

Now, what we’d like to have is something like this:

 

So much nicer isn’t it?

Designing the service

So how are we going to accomplish this? Pretty simple:
1. We will implement a DelegatingHandler which will capture all HttpResponseMessages, extract the response object and wrap into our custom generic Metadata. Then it will be flushed to the client.
2. Additionally, we’ll have a CustomQueryableAttribute, which we will use on IQueryableActions, to keep the information about the size (count) of the IQueryable. This way we will be able to provide information about what is the total size of the collection and thus support OData filtering. This way the client can request i.e. $top=3 results, but still have information about the total size of the IQueryable.

Models

As mentioned, we will use a repository from here – it’s really simple and perfect for testing. Let’s have a look at the Metadata instead.

 

 

It is a generic class, which will provide information such as:
– total results (since the data may be filtered)
– returned results (since the data may be filtered)
– results object (which is equal to the default WebAPI response)
– timestamp of the response
– status – to indicate a successful or unsuccessful response

I will leave the constructor empty for now, it will be more clear to what’s happening there, once we go through the handler and filter.

The Data annotations are there for compatibility with DataContractSerializer. Content negotation is supported, but in principle, this functionality is better suited for JSON.NET, but more on that later.

MetadataHandler

MetadataHandler will inherit from a DelegatingHandler, which means it will have access to theHttpResponseMessage before it is flushed to the client and before applying MediaFormatting.

 

 

As mentioned, we need to modify the response, and to do that we need to overrideTask<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) method and add a ContinueWith to it.

In there, we extract the object from the response and pass it to a private method for altering.

Now, here is a note. If you serialize to JSON, using JSON.NET you can do just that, it can handle that just fine. On the other hand, if you are willing to use DataContractSerializer, it will not be able to serialize object types properly. You would need known types, so you’d need either reflection or typecasting:

 

Anyway, going back to our example, the ProcessObject method:

 

In this case, we instantiate a new Metadata and set it as the content of the response. As you see, I arbitrairly set the formatter to JSON.NET. The commented out code preservers content negotiation, but if you use that you’d need to type cast the objects as mentioned before.

We also used a simple helper method to check if the response is even worth processing:

 

Let’s now revisit the constructor we omitted earlier.

 

 

The constructor takes the HttpResponseMessage and builds up useful information based on it – i.e. setting the “sucess” or “error”, and also calculating the number of returned results.

Note, if single item is requested (via regular Get(int id) type of action, not OData) it will show 1 total result, because that’s how many matches there were. Total results is greater than returned results only if you filter data with OData.

Adding support for OData and IQueryable

All of this wouldn’t be very useful if we didn’t add our key functionality, which is “total results”. To do that, we need to introduce a new attribute filter, CustomQueryableAttribute, inheriting fromQueryableAttribute.

We’d then decorate all IQueryable actions with it.

 

We override the method IQueryable ApplyResultLimit(HttpActionExecutedContext actionExecutedContext, IQueryable query), which gives us access to IQueryable prior to applying the filtering. What it means, is that we can easily save aside the total number of results of theIQueryable and then use it later in our Metadata object.

We use a bit of a hack here, since I save that in a custom header field “originalSize”. In the MessageHandler later on, we will read that value from the headers and remove it so that they don’t get sent to the client – so it only saves the purpose of transporting a variable from the ActionFilter to the MessageHandler. If you want to pass data between two ActionFilters you could useControllerContext.RouteData.Values, but for our scenario I couldn’t find a better way.

Now we need to update the MessageHandler, to make it aware of the “originalSize”:

 

So we read the header value and get rid of the redundant header key.

Registering handler, decorating methods

The final thing to do is to register the handler, so in App_Start we add:

 

For testing, I get rid of the XmlFormatter as well.

We also add our custom queryable filter to all Action’s returning IQueryable:

 

Running the application

Everything is ready, so let’s roll.

First let’s get all Urls:

Let’s test OData:

Now let’s get a single Url:

Now, just to show that this doesn’t really on any strong types, let’s add a new repository with Blogobjects.
 

Summary & source code

Hopefully someone will find the functionality described here useful. It can be obviously extended further, and optimized (perhaps someone can figure out a better way to handleDataContractSerializer).

 

Copy from: http://www.strathweb.com/2012/06/extending-your-asp-net-web-api-responses-with-useful-metadata/

Source: https://github.com/filipw/Metadata.WebApi

SelfCert: Create a Self-Signed Certificate Interactively (GUI) or Programmatically in .NET

By: 

While this isn’t new, I needed a new home for it since my old Pluralsight blog is gone now. Hopefully you’ll find it helpful!

It’s a bit of a pain to create self-signed certs using MAKECERT. So here’s a GUI-based tool that uses a combination of the .NET Framework and the CryptoAPI to create self-signed X.509 certificates. And it’s factored so that you can use the underlying library standalone – you can easily create certs programmatically now.

Here’s the GUI:

The GUI has some nifty features: you can create a PFX file directly, or you can save directly to a cert store of your choice. When you save to a cert store, an extra dialog pops up showing you where the private key file resides, so that you can adjust the ACL accordingly. I’ve got a “view private key” feature that launches explorer with the /select argument, taking you to the private key file so that you can set the ACL on it. Anyway, this extra dialog gives you some quick info you typically want, like the thumbprint. And there are buttons for browsing the cert store and viewing the certificate as well from here.

The GUI gens the RSA key pair on a background thread, so a) the app doesn’t lock up on you, and b) if you get tired of waiting for the key to gen, you can cancel easily enough :)

Here’s some code that does this programmatically by calling the Pluralsight.Crypto library that is underneath all of this. Those of you who are familiar with the CryptoAPI will recognize the key abstraction here, CryptContext.

static void GenSelfSignedCert()
{
    using (CryptContext ctx = new CryptContext())
    {
        ctx.Open();

        X509Certificate2 cert = ctx.CreateSelfSignedCertificate(
            new SelfSignedCertProperties
            {
                IsPrivateKeyExportable = true,
                KeyBitLength = 4096,
                Name = new X500DistinguishedName("cn=localhost"),
                ValidFrom = DateTime.Today.AddDays(-1),
                ValidTo = DateTime.Today.AddYears(1),
            });

        X509Certificate2UI.DisplayCertificate(cert);
    }
}

Make sure you’ve got the Microsoft .NET Framework 3.5 installed. Self-Cert relies on it.

Download the project here, which includes binaries and sources. Feel free to use Pluralsight.Crypto in your own projects if you find it useful. Enjoy!

About the Author

 is the Chief Technology Officer for Pluralsight. As CTO, Keith makes sure that Pluralsight’s content delivery platform doesn’t get in the way of your learning! He strives for less friction and more consistent quality every day.

Copy From: http://blog.pluralsight.com/selfcert-create-a-self-signed-certificate-interactively-gui-or-programmatically-in-net

OWIN OAuth 2.0 Authorization Server

By Rick AndersonHongye Sun and Praburaj Thiagarajan|March 20, 2014

This tutorial will guide you on how to implement an OAuth 2.0 Authorization Server using OWIN OAuth middleware. This is an advanced tutorial that only outlines the steps to create an OWIN OAuth 2.0 Authorization Server. This is not a step by step tutorial. Download the sample code.

Note: This outline should not be intended to be used for creating a secure production app. This tutorial is intended to provide only an outline on how to implement an OAuth 2.0 Authorization Server using OWIN OAuth middleware.

Software versions

Shown in the tutorial Also works with
Windows 8.1 Windows 8, Windows 7
Visual Studio 2013 Visual Studio 2013 Express for Desktop.

Visual Studio 2012 with the latest update should work, but the tutorial has not been tested with it, and some menu selections and dialog boxes are different.

.NET 4.5

Questions and Comments

If you have questions that are not directly related to the tutorial, you can post them athttp://katanaproject.codeplex.com/discussions. For questions and comments regarding the tutorial itself, see the comments section at the bottom of the page.

The  OAuth 2.0 framework enables a third-party app to obtain limited access to an HTTP service. Instead of using the resource owner’s credentials to access a protected resource, the client obtains an access token (which is a string denoting a specific scope, lifetime, and other access attributes). Access tokens are issued to third-party clients by an authorization server with the approval of the resource owner.

This tutorial will cover:

  • How to create an authorization server to support 4 Authorization Grants and refresh tokens.
  • Authorization code grant:
    • Implicit Grant
    • Resource Owner Password Credentials Grant
    • Client Credentials Grant
  • Creating a resource server which is protected by an access token.
  • Creating OAuth 2.0 clients.

Prerequisites

Create an Authorization Server

In this tutorial, we will roughly sketch out how to use OWIN and ASP.NET MVC to create an authorization server. We hope to soon provide a download for the completed sample, as this tutorial does not include each step. First, create an empty web app named AuthorizationServer and install the following packages:

  • Microsoft.AspNet.Mvc
  • Microsoft.Owin.Host.SystemWeb
  • Microsoft.Owin.Security.OAuth
  • Microsoft.Owin.Security.Cookies
  • Microsoft.Owin.Security.Google (Or any other social login package such as Microsoft.Owin.Security.Facebook)

Add an OWIN Startup class under the project root folder named Startup.

usingMicrosoft.Owin;usingOwin;[assembly:OwinStartup(typeof(AuthorizationServer.Startup))]namespaceAuthorizationServer{publicpartialclassStartup{publicvoidConfiguration(IAppBuilder app){ConfigureAuth(app);}}}

Create an App_Start folder. Select the App_Start folder and use Shift+Alt+A to add the downloaded version of theAuthorizationServer\App_Start\Startup.Auth.cs file.

publicvoidConfigureAuth(IAppBuilder app){// Enable the Application Sign In Cookie.
     app.UseCookieAuthentication(newCookieAuthenticationOptions{AuthenticationType="Application",AuthenticationMode=AuthenticationMode.Passive,LoginPath=newPathString(Paths.LoginPath),LogoutPath=newPathString(Paths.LogoutPath),});// Enable the External Sign In Cookie.
     app.SetDefaultSignInAsAuthenticationType("External");
     app.UseCookieAuthentication(newCookieAuthenticationOptions{AuthenticationType="External",AuthenticationMode=AuthenticationMode.Passive,CookieName=CookieAuthenticationDefaults.CookiePrefix+"External",ExpireTimeSpan=TimeSpan.FromMinutes(5),});// Enable Google authentication.
     app.UseGoogleAuthentication();// Setup Authorization Server
     app.UseOAuthAuthorizationServer(newOAuthAuthorizationServerOptions{AuthorizeEndpointPath=newPathString(Paths.AuthorizePath),TokenEndpointPath=newPathString(Paths.TokenPath),ApplicationCanDisplayErrors=true,#if DEBUGAllowInsecureHttp=true,#endif// Authorization server provider which controls the lifecycle of Authorization ServerProvider=newOAuthAuthorizationServerProvider{OnValidateClientRedirectUri=ValidateClientRedirectUri,OnValidateClientAuthentication=ValidateClientAuthentication,OnGrantResourceOwnerCredentials=GrantResourceOwnerCredentials,OnGrantClientCredentials=GrantClientCredetails},// Authorization code provider which creates and receives the authorization code.AuthorizationCodeProvider=newAuthenticationTokenProvider{OnCreate=CreateAuthenticationCode,OnReceive=ReceiveAuthenticationCode,},// Refresh token provider which creates and receives refresh token.RefreshTokenProvider=newAuthenticationTokenProvider{OnCreate=CreateRefreshToken,OnReceive=ReceiveRefreshToken,}});}

The code above enables application/external sign in cookies and Google authentication, which are used by authorization server itself to manage accounts.

The UseOAuthAuthorizationServer extension method is to setup the authorization server. The setup options are:

  • AuthorizeEndpointPath: The request path where client applications will redirect the user-agent in order to obtain the users consent to issue a token or code. It must begin with a leading slash, for example,  “/Authorize“.
  • TokenEndpointPath: The request path client applications directly communicate to obtain the access token. It must begin with a leading slash, like “/Token”. If the client is issued a client_secret, it must be provided to this endpoint.
  • ApplicationCanDisplayErrors: Set to true if the web application wants to generate a custom error page for the client validation errors on /Authorize endpoint. This is only needed for cases where the browser is not redirected back to the client application, for example, when the client_id or redirect_uri are incorrect. The /Authorize endpoint should expect to see the “oauth.Error”, “oauth.ErrorDescription”, and “oauth.ErrorUri” properties are added to the OWIN environment.
    Note: If not true, the authorization server will return a default error page with the error details.
  • AllowInsecureHttp: True to allow authorize and token requests to arrive on HTTP URI addresses, and to allow incoming redirect_uri authorize request parameters to have HTTP URI addresses.
    Security Note: This is for development only.
  • Provider: The object provided by the application to process events raised by the Authorization Server middleware. The application may implement the interface fully, or it may create an instance ofOAuthAuthorizationServerProvider and assign delegates necessary for the OAuth flows this server supports.
  • AuthorizationCodeProvider: Produces a single-use authorization code to return to the client application. For the OAuth server to be secure the application MUST provide an instance forAuthorizationCodeProvider where the token produced by the OnCreate/OnCreateAsync event is considered valid for only one call to OnReceive/OnReceiveAsync.
  • RefreshTokenProvider: Produces a refresh token which may be used to produce a new access token when needed. If not provided the authorization server will not return refresh tokens from the /Token endpoint.

Account Management

 OAuth doesn’t care where or how you manage your user account information. It’s ASP.NET Identity which is responsible for it. In this tutorial, we will simplify the account management code and just make sure that user can login using OWIN cookie middleware. Here is the simplified sample code for the AccountController:

publicclassAccountController:Controller{publicActionResultLogin(){var authentication =HttpContext.GetOwinContext().Authentication;if(Request.HttpMethod=="POST"){var isPersistent =!string.IsNullOrEmpty(Request.Form.Get("isPersistent"));if(!string.IsNullOrEmpty(Request.Form.Get("submit.Signin"))){
                authentication.SignIn(newAuthenticationProperties{IsPersistent= isPersistent },newClaimsIdentity(new[]{newClaim(ClaimsIdentity.DefaultNameClaimType,Request.Form["username"])},"Application"));}}returnView();}publicActionResultLogout(){returnView();}publicActionResultExternal(){var authentication =HttpContext.GetOwinContext().Authentication;if(Request.HttpMethod=="POST"){foreach(var key inRequest.Form.AllKeys){if(key.StartsWith("submit.External.")&&!string.IsNullOrEmpty(Request.Form.Get(key))){var authType = key.Substring("submit.External.".Length);
                    authentication.Challenge(authType);returnnewHttpUnauthorizedResult();}}}var identity = authentication.AuthenticateAsync("External").Result.Identity;if(identity !=null){
            authentication.SignOut("External");
            authentication.SignIn(newAuthenticationProperties{IsPersistent=true},newClaimsIdentity(identity.Claims,"Application", identity.NameClaimType, identity.RoleClaimType));returnRedirect(Request.QueryString["ReturnUrl"]);}returnView();}}
privateTaskValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context){if(context.ClientId==Clients.Client1.Id){
        context.Validated(Clients.Client1.RedirectUrl);}elseif(context.ClientId==Clients.Client2.Id){
        context.Validated(Clients.Client2.RedirectUrl);}returnTask.FromResult(0);}privateTaskValidateClientAuthentication(OAuthValidateClientAuthenticationContext context){string clientId;string clientSecret;if(context.TryGetBasicCredentials(out clientId,out clientSecret)||
        context.TryGetFormCredentials(out clientId,out clientSecret)){if(clientId ==Clients.Client1.Id&& clientSecret ==Clients.Client1.Secret){
            context.Validated();}elseif(clientId ==Clients.Client2.Id&& clientSecret ==Clients.Client2.Secret){
            context.Validated();}}returnTask.FromResult(0);}

ValidateClientRedirectUri is used to validate the client with its registered redirect URL.ValidateClientAuthentication checks the basic scheme header and form body to get the client’s credentials.

The login page is shown below:

Review the IETF’s OAuth 2 Authorization Code Grant section now.  Provider (in the table below) isOAuthAuthorizationServerOptions.Provider, which is of type OAuthAuthorizationServerProvider, which contains all OAuth server events.

Flow steps from Authorization Code Grant section Sample download performs these steps with:
(A) The client initiates the flow by directing the resource owner’s user-agent to the authorization endpoint. The client includes its client identifier, requested scope, local state, and a redirection URI to which the authorization server will send the user-agent back once access is granted (or denied). Provider.MatchEndpoint
Provider.ValidateClientRedirectUri
Provider.ValidateAuthorizeRequest
Provider.AuthorizeEndpoint
(B) The authorization server authenticates the resource owner (via the user-agent) and establishes whether the resource owner grants or denies the client’s access request. <If user grants access>
Provider.MatchEndpoint
Provider.ValidateClientRedirectUri
Provider.ValidateAuthorizeRequest
Provider.AuthorizeEndpoint
AuthorizationCodeProvider.CreateAsync
(C) Assuming the resource owner grants access, the authorization server redirects the user-agent back to the client using the redirection URI provided earlier (in the request or during client registration). …
  (D) The client requests an access token from the authorization server’s token endpoint by including the authorization code received in the previous step. When making the request, the client authenticates with the authorization server. The client includes the redirection URI used to obtain the authorization code for verification. Provider.MatchEndpoint
Provider.ValidateClientAuthentication
AuthorizationCodeProvider.ReceiveAsync
Provider.ValidateTokenRequest
Provider.GrantAuthorizationCode
Provider.TokenEndpoint
AccessTokenProvider.CreateAsync
RefreshTokenProvider.CreateAsync

A sample implementation for AuthorizationCodeProvider.CreateAsync and ReceiveAsync to control the creation and validation of authorization code is shown below.

privatereadonlyConcurrentDictionary<string,string> _authenticationCodes =newConcurrentDictionary<string,string>(StringComparer.Ordinal);privatevoidCreateAuthenticationCode(AuthenticationTokenCreateContext context){
     context.SetToken(Guid.NewGuid().ToString("n")+Guid.NewGuid().ToString("n"));
     _authenticationCodes[context.Token]= context.SerializeTicket();}privatevoidReceiveAuthenticationCode(AuthenticationTokenReceiveContext context){string value;if(_authenticationCodes.TryRemove(context.Token,out value)){
         context.DeserializeTicket(value);}}

The code above uses an in-memory concurrent dictionary to store the code and identity ticket and restore the identity after receiving the code. In a real application, it would be replaced by a persistent data store.

The authorization endpoint is for the resource owner to grant access to the client. Usually, it needs a user interface to allow the user to click a button and confirm the grant. OWIN OAuth middleware allows application code to handle the authorization endpoint. In our sample app, we use an MVC controller called OAuthController to handle it. Here is the sample implementation:

publicclassOAuthController:Controller{publicActionResultAuthorize(){if(Response.StatusCode!=200){returnView("AuthorizeError");}var authentication =HttpContext.GetOwinContext().Authentication;var ticket = authentication.AuthenticateAsync("Application").Result;var identity = ticket !=null? ticket.Identity:null;if(identity ==null){authentication.Challenge("Application");returnnewHttpUnauthorizedResult();}var scopes =(Request.QueryString.Get("scope")??"").Split(' ');if(Request.HttpMethod=="POST"){if(!string.IsNullOrEmpty(Request.Form.Get("submit.Grant"))){
                 identity =newClaimsIdentity(identity.Claims,"Bearer", identity.NameClaimType, identity.RoleClaimType);foreach(var scope in scopes){
                     identity.AddClaim(newClaim("urn:oauth:scope", scope));}
                 authentication.SignIn(identity);}if(!string.IsNullOrEmpty(Request.Form.Get("submit.Login"))){
                 authentication.SignOut("Application");
                 authentication.Challenge("Application");returnnewHttpUnauthorizedResult();}}returnView();}}

The Authorize action will first check if the user has logged in to the authorization server. If not, the authentication middleware challenges the caller to authenticate using the “Application” cookie and redirects to the login page. (See highlighted code above.) If user has logged in, it will render the Authorize view, as shown below:

If the Grant button is selected, the Authorize action will create a new “Bearer” identity and sign in with it. It will trigger the authorization server to generate a bearer token and send it back to the client with JSON payload.

Implicit Grant

Refer to the IETF’s OAuth 2 Implicit Grant section now.

The Implicit Grant flow shown in Figure 4 is the flow and mapping which the OWIN OAuth middleware follows.

Flow steps from Implicit Grant section Sample download performs these steps with:
(A) The client initiates the flow by directing the resource owner’s user-agent to the authorization endpoint. The client includes its client identifier, requested scope, local state, and a redirection URI to which the authorization server will send the user-agent back once access is granted (or denied). Provider.MatchEndpoint
Provider.ValidateClientRedirectUri
Provider.ValidateAuthorizeRequest
Provider.AuthorizeEndpoint
(B) The authorization server authenticates the resource owner (via the user-agent) and establishes whether the resource owner grants or denies the client’s access request. <If user grants access>
Provider.MatchEndpoint
Provider.ValidateClientRedirectUri
Provider.ValidateAuthorizeRequest
Provider.AuthorizeEndpoint
AuthorizationCodeProvider.CreateAsync
(C) Assuming the resource owner grants access, the authorization server redirects the user-agent back to the client using the redirection URI provided earlier (in the request or during client registration). …
  (D) The client requests an access token from the authorization server’s token endpoint by including the authorization code received in the previous step. When making the request, the client authenticates with the authorization server. The client includes the redirection URI used to obtain the authorization code for verification.

Since we already implemented the authorization endpoint (OAuthController.Authorize action) for authorization code grant, it automatically enables implicit flow as well.

Note: Provider.ValidateClientRedirectUri is used to validate the client ID with its redirection URL, which protects the implicit grant flow from sending the access token to malicious clients (Man-in-the-middle attack).

Resource Owner Password Credentials Grant

Refer to the IETF’s OAuth 2 Resource Owner Password Credentials Grant section now.

The Resource Owner Password Credentials Grant flow shown in Figure 5 is the flow and mapping which the OWIN OAuth middleware follows.

Flow steps from Resource Owner Password Credentials Grant section Sample download performs these steps with:
(A) The resource owner provides the client with its username and password.
(B) The client requests an access token from the authorization server’s token endpoint by including the credentials received from the resource owner. When making the request, the client authenticates with the authorization server. Provider.MatchEndpoint
Provider.ValidateClientAuthentication Provider.ValidateTokenRequest
Provider.GrantResourceOwnerCredentials Provider.TokenEndpoint AccessToken
Provider.CreateAsync
RefreshTokenProvider.CreateAsync
(C) The authorization server authenticates the client and validates the resource owner credentials, and if valid, issues an access token.

Here is the sample implementation for Provider.GrantResourceOwnerCredentials:

privateTaskGrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context){var identity =newClaimsIdentity(newGenericIdentity(
        context.UserName,OAuthDefaults.AuthenticationType), 
        context.Scope.Select(x =>newClaim("urn:oauth:scope", x)));

     context.Validated(identity);returnTask.FromResult(0);}
The code above is intended to explain this section of the tutorial and should not be used in secure or production apps. It does not check the resource owners credentials. It assumes every credential is valid and creates a new identity for it. The new identity will be used to generate the access token and refresh token. Please replace the code with your own secure account management code.

Client Credentials Grant

Refer to the IETF’s OAuth 2 Client Credentials Grant section now.

The Client Credentials Grant flow shown in Figure 6 is the flow and mapping which the OWIN OAuth middleware follows.

Flow steps from Client Credentials Grant  section Sample download performs these steps with:
(A) The client authenticates with the authorization server and requests an access token from the token endpoint. Provider.MatchEndpoint
Provider.ValidateClientAuthentication Provider.ValidateTokenRequest
Provider.GrantClientCredentials
Provider.TokenEndpoint
AccessTokenProvider.CreateAsync
RefreshTokenProvider.CreateAsync
 (B) The authorization server authenticates the client, and if valid, issues an access token.

Here is the sample implementation for Provider.GrantClientCredentials:

privateTaskGrantClientCredetails(OAuthGrantClientCredentialsContext context){var identity =newClaimsIdentity(newGenericIdentity(
        context.ClientId,OAuthDefaults.AuthenticationType), 
        context.Scope.Select(x =>newClaim("urn:oauth:scope", x)));

     context.Validated(identity);returnTask.FromResult(0);}
The code above is intended to explain this section of the tutorial and should not be used in secure or production apps.  Please replace the code with your own secure client management code.

Refresh Token

Refer to the IETF’s OAuth 2 Refresh Token section now.

The Refresh Token  flow shown in Figure 2 is the flow and mapping which the OWIN OAuth middleware follows.

Flow steps from Client Credentials Grant  section Sample download performs these steps with:
(G) The client requests a new access token by authenticating with the authorization server and presenting the refresh token. The client authentication requirements are based on the client type and on the authorization server policies. Provider.MatchEndpoint
Provider.ValidateClientAuthentication RefreshTokenProvider.ReceiveAsync
Provider.ValidateTokenRequest
Provider.GrantRefreshToken
Provider.TokenEndpoint
AccessTokenProvider.CreateAsync
RefreshTokenProvider.CreateAsync
(H) The authorization server authenticates the client and validates the refresh token, and if valid, issues a new access token (and, optionally, a new refresh token).

Here is the sample implementation for Provider.GrantRefreshToken:

publicvoidConfigureAuth(IAppBuilder app){// Code removed for clarity     // Refresh token provider which creates and receives refresh token.RefreshTokenProvider=newAuthenticationTokenProvider{OnCreate=CreateRefreshToken,OnReceive=ReceiveRefreshToken,}});}
privatevoidCreateRefreshToken(AuthenticationTokenCreateContext context){
     context.SetToken(context.SerializeTicket());}privatevoidReceiveRefreshToken(AuthenticationTokenReceiveContext context){
     context.DeserializeTicket(context.Token);}

Create a Resource Server which is protected by Access Token

 Create an empty web app project and install following packages in the project:

  • Microsoft.AspNet.WebApi.Owin
  • Microsoft.Owin.Host.SystemWeb
  • Microsoft.Owin.Security.OAuth

Create a startup class and configure authentication and Web API. See AuthorizationServer\ResourceServer\Startup.csin the sample download.

[assembly:OwinStartup(typeof(ResourceServer.Startup))]namespaceResourceServer{publicpartialclassStartup{publicvoidConfiguration(IAppBuilder app){ConfigureAuth(app);ConfigureWebApi(app);}}}

See AuthorizationServer\ResourceServer\App_Start\Startup.Auth.cs in the sample download.

usingMicrosoft.Owin.Cors;usingMicrosoft.Owin.Security.OAuth;usingOwin;namespaceResourceServer{publicpartialclassStartup{publicvoidConfigureAuth(IAppBuilder app){
            app.UseCors(CorsOptions.AllowAll);

            app.UseOAuthBearerAuthentication(newOAuthBearerAuthenticationOptions{});}}}

See AuthorizationServer\ResourceServer\App_Start\Startup.WebApi.cs in the sample download.

usingMicrosoft.Owin.Security.OAuth;usingOwin;usingSystem.Web.Http;namespaceResourceServer{publicpartialclassStartup{publicvoidConfigureWebApi(IAppBuilder app){var config =newHttpConfiguration();// Web API configuration and services// Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(newHostAuthenticationFilter(OAuthDefaults.AuthenticationType));// Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name:"DefaultApi",
                routeTemplate:"api/{controller}/{id}",
                defaults:new{ id =RouteParameter.Optional});

            app.UseWebApi(config);}}}
  • UseCors method allows CORS for all domains.
  • UseOAuthBearerAuthentication method enables OAuth bearer token authentication middleware which will receive and validate bearer token from authorization header in the request.
  • Config.SuppressDefaultHostAuthenticaiton suppresses default host authenticated principal from the app, therefore all requests will be anonymous after this call.
  • HostAuthenticationFilter enables authentication just for the specified authentication type. In this case, it’s bearer authentication type.

In order to demonstrate the authenticated identity, we create an ApiController to output current user’s claims.

namespaceResourceServer.Controllers{[Authorize]publicclassMeController:ApiController{// GET api/<controller>publicIEnumerable<object>Get(){var identity =User.IdentityasClaimsIdentity;return identity.Claims.Select(c =>new{Type= c.Type,Value= c.Value});}}}

If the authorization server and  the resource server are not on the same computer, the OAuth middleware will use the different machine keys to encrypt and decrypt bearer access token. In order to share the same private key between both projects, we add the same machinekey setting in both web.config files.

<configuration><appSettings><!-- Keys removed for clarity. --></appSettings><system.web><compilationdebug="true"targetFramework="4.5"/><httpRuntimetargetFramework="4.5"/><machineKeydecryptionKey="Enter decryption Key here"validation="SHA1"validationKey="Enter validation Key here"/></system.web><runtime><!-- Keys removed for clarity. --></runtime></configuration>

Create OAuth 2.0 Clients

We use the DotNetOpenAuth.OAuth2.Client  NuGet package to simplify the client code.

Authorization Code Grant Client

This client is an MVC application. It will trigger an authorization code grant flow to get the access token from backend. It has a single page as shown below:

  • The Authorize button will redirect browser to the authorization server to notify the resource owner to grant access to this client.
  • The Refresh button will get a new access token and refresh token using the current refresh token.
  • The Access Protected Resource API button will call the resource server to get current user’s claims data and show them on the page.

Here is the sample code of the HomeController of the client.

usingConstants;usingDotNetOpenAuth.OAuth2;usingSystem;usingSystem.Net.Http;usingSystem.Web.Mvc;namespaceAuthorizationCodeGrant.Controllers{publicclassHomeController:Controller{privateWebServerClient _webServerClient;publicActionResultIndex(){ViewBag.AccessToken=Request.Form["AccessToken"]??"";ViewBag.RefreshToken=Request.Form["RefreshToken"]??"";ViewBag.Action="";ViewBag.ApiResponse="";InitializeWebServerClient();var accessToken =Request.Form["AccessToken"];if(string.IsNullOrEmpty(accessToken)){var authorizationState = _webServerClient.ProcessUserAuthorization(Request);if(authorizationState !=null){ViewBag.AccessToken= authorizationState.AccessToken;ViewBag.RefreshToken= authorizationState.RefreshToken;ViewBag.Action=Request.Path;}}if(!string.IsNullOrEmpty(Request.Form.Get("submit.Authorize"))){var userAuthorization = _webServerClient.PrepareRequestUserAuthorization(new[]{"bio","notes"});
            userAuthorization.Send(HttpContext);Response.End();}elseif(!string.IsNullOrEmpty(Request.Form.Get("submit.Refresh"))){var state =newAuthorizationState{AccessToken=Request.Form["AccessToken"],RefreshToken=Request.Form["RefreshToken"]};if(_webServerClient.RefreshAuthorization(state)){ViewBag.AccessToken= state.AccessToken;ViewBag.RefreshToken= state.RefreshToken;}}elseif(!string.IsNullOrEmpty(Request.Form.Get("submit.CallApi"))){var resourceServerUri =newUri(Paths.ResourceServerBaseAddress);var client =newHttpClient(_webServerClient.CreateAuthorizingHandler(accessToken));var body = client.GetStringAsync(newUri(resourceServerUri,Paths.MePath)).Result;ViewBag.ApiResponse= body;}returnView();}privatevoidInitializeWebServerClient(){var authorizationServerUri =newUri(Paths.AuthorizationServerBaseAddress);var authorizationServer =newAuthorizationServerDescription{AuthorizationEndpoint=newUri(authorizationServerUri,Paths.AuthorizePath),TokenEndpoint=newUri(authorizationServerUri,Paths.TokenPath)};
         _webServerClient =newWebServerClient(authorizationServer,Clients.Client1.Id,Clients.Client1.Secret);}}}

DotNetOpenAuth requires SSL by default. Since our demo is using HTTP, you need to add following setting in the config file:

<configuration><!-- Markup removed for clarity. --><dotNetOpenAuth><messagingrelaxSslRequirements="true"/></dotNetOpenAuth></configuration>
Security Note: Never disable SSL in a production app. Your login credentials are now being sent in clear-text across the wire. The code above is just for local sample debugging and exploration.

Implicit Grant Client

This client is using JavaScript to:

  1. Open a new window and redirect to the authorize endpoint of the Authorization Server.
  2. Get the access token from URL fragments when it redirects back.

The following image shows this process:

The client should have two pages: one for home page and the other for callback.

Here is the sample JavaScript code found in the Index.cshtml file:

<scripttype="text/javascript">(function($){var authorizeUri ='@(Paths.AuthorizationServerBaseAddress + Paths.AuthorizePath)';var tokenUri ='@(Paths.AuthorizationServerBaseAddress + Paths.TokenPath)';var apiUri ='@(Paths.ResourceServerBaseAddress + Paths.MePath)';var returnUri ='@Paths.ImplicitGrantCallBackPath';

        $('#Authorize').click(function(){var nonce ='my-nonce';var uri = addQueryString(authorizeUri,{'client_id':'7890ab','redirect_uri': returnUri,'state': nonce,'scope':'bio notes','response_type':'token',});

            window.oauth ={};
            window.oauth.signin =function(data){if(data.state !== nonce){return;}

                $('#AccessToken').val(data.access_token);}

            window.open(uri,'Authorize','width=640,height=480');});

        $('#CallApi').click(function(){
            $.ajax(apiUri,{
                beforeSend:function(xhr){
                    xhr.setRequestHeader('Authorization','Bearer '+ $('#AccessToken').val());},
                dataType:'text',
                cache:false,
                success:function(data){
                    console.log(data);
                    $('#output').text(data);}});});function addQueryString(uri, parameters){var delimiter =(uri.indexOf('?')==-1)?'?':'&';for(var parameterName in parameters){var parameterValue = parameters[parameterName];
                uri += delimiter + encodeURIComponent(parameterName)+'='+ encodeURIComponent(parameterValue);
                delimiter ='&';}return uri;}})(jQuery);</script>

Here is the callback handling code in SignIn.cshtml file:

<scripttype="text/javascript">(function($){function getFragment(){if(window.location.hash.indexOf("#")===0){return parseQueryString(window.location.hash.substr(1));}else{return{};}}function parseQueryString(queryString){var data ={},
                pairs, pair, separatorIndex, escapedKey, escapedValue, key, value;if(queryString ===null){return data;}

            pairs = queryString.split("&");for(var i =0; i < pairs.length; i++){
                pair = pairs[i];
                separatorIndex = pair.indexOf("=");if(separatorIndex ===-1){
                    escapedKey = pair;
                    escapedValue =null;}else{
                    escapedKey = pair.substr(0, separatorIndex);
                    escapedValue = pair.substr(separatorIndex +1);}

                key = decodeURIComponent(escapedKey);
                value = decodeURIComponent(escapedValue);

                data[key]= value;}return data;}var fragments = getFragment();if(window.opener && window.opener.oauth && window.opener.oauth.signin){
            window.opener.oauth.signin(fragments);}
        window.close();})(jQuery);</script>
A best practice is to move the JavaScript to an external file and not embed it with the Razor markup. To keep this sample simple, they have been combined.

Resource Owner Password Credentials Grant Client

We uses a console app to demo this client. Here is the code:

classProgram{privatestaticWebServerClient _webServerClient;privatestaticstring _accessToken;staticvoidMain(string[] args){InitializeWebServerClient();Console.WriteLine("Requesting Token...");RequestToken();Console.WriteLine("Access Token: {0}", _accessToken);Console.WriteLine("Access Protected Resource");AccessProtectedResource();}privatestaticvoidInitializeWebServerClient(){var authorizationServerUri =newUri(Paths.AuthorizationServerBaseAddress);var authorizationServer =newAuthorizationServerDescription{AuthorizationEndpoint=newUri(authorizationServerUri,Paths.AuthorizePath),TokenEndpoint=newUri(authorizationServerUri,Paths.TokenPath)};
        _webServerClient =newWebServerClient(authorizationServer,Clients.Client1.Id,Clients.Client1.Secret);}privatestaticvoidRequestToken(){var state = _webServerClient.GetClientAccessToken(new[]{"bio","notes"});
        _accessToken = state.AccessToken;}privatestaticvoidAccessProtectedResource(){var resourceServerUri =newUri(Paths.ResourceServerBaseAddress);var client =newHttpClient(_webServerClient.CreateAuthorizingHandler(_accessToken));var body = client.GetStringAsync(newUri(resourceServerUri,Paths.MePath)).Result;Console.WriteLine(body);}}

Client Credentials Grant Client

Similar to the Resource Owner Password Credentials Grant, here is console app code:

classProgram{privatestaticWebServerClient _webServerClient;privatestaticstring _accessToken;staticvoidMain(string[] args){InitializeWebServerClient();Console.WriteLine("Requesting Token...");RequestToken();Console.WriteLine("Access Token: {0}", _accessToken);Console.WriteLine("Access Protected Resource");AccessProtectedResource();}privatestaticvoidInitializeWebServerClient(){var authorizationServerUri =newUri(Paths.AuthorizationServerBaseAddress);var authorizationServer =newAuthorizationServerDescription{AuthorizationEndpoint=newUri(authorizationServerUri,Paths.AuthorizePath),TokenEndpoint=newUri(authorizationServerUri,Paths.TokenPath)};
        _webServerClient =newWebServerClient(authorizationServer,Clients.Client1.Id,Clients.Client1.Secret);}privatestaticvoidRequestToken(){var state = _webServerClient.ExchangeUserCredentialForToken("test","test",new[]{"bio","notes"});
        _accessToken = state.AccessToken;}privatestaticvoidAccessProtectedResource(){var resourceServerUri =newUri(Paths.ResourceServerBaseAddress);var client =newHttpClient(_webServerClient.CreateAuthorizingHandler(_accessToken));var body = client.GetStringAsync(newUri(resourceServerUri,Paths.MePath)).Result;Console.WriteLine(body);}}

How to: Create Item Templates

The steps in the first procedure of this topic show you how to create an item template by using the Export Template wizard.

If you plan to use the item in a Windows Store app project, you’ll have to perform a few extra steps. The second procedure in this topic helps you accomplish that task.

Note Note
You cannot export templates for C++ projects.

To add a custom project item template to the Add New Item dialog box

  1. Create or open a project in Visual Studio.
  2. Add an item to the project and modify it if you want to.
  3. Modify the code file to indicate where parameter replacement should take place. For more information, see How to: Substitute Parameters in a Template.
  4. On the File menu, click Export Template.
  5. Click Item Template, select the project that contains the item, and click Next.
  6. Select the item for which you want to create a template, and click Next.
  7. Select the assembly references to include in the template, and click Next.
  8. Type the icon file name, preview image, template name, and template description, and click Finish.

    The files for the template are added to a .zip file and copied to the ..\Users\username\Documents\Visual Studio Version\Templates\ItemTemplates\ folder.

To enable the item template to be used in a Windows Store project

  1. Follow the steps in the procedure above to export an item template.
  2. Extract the .vstemplate file from the .zip file that was copied to the ..\Users\username\Documents\Visual Studio Version\Templates\ItemTemplates\ folder.
  3. Open the .vstemplate file in Notepad.
  4. In the .vstemplate file, add the following XML within the opening and closing <TemplateData> tag: <TemplateGroupID>WinRT-Managed</TemplateGroupID>.

    The following example shows the entire contents of a .vstemplate file after the line of XML <TemplateGroupID>WinRT-Managed</TemplateGroupID> has been added to it.

    <VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Item">
      <TemplateData>
        <DefaultName>MyItemStoreTemplate.xaml</DefaultName>
        <Name>MyItemStoreTemplate</Name>
        <Description>This is an example itemtemplate</Description>
        <ProjectType>CSharp</ProjectType>
        <SortOrder>10</SortOrder>
        <Icon>__TemplateIcon.ico</Icon>
        <TemplateGroupID>WinRT-Managed</TemplateGroupID>
      </TemplateData>
      <TemplateContent>
        <References />
        <ProjectItem SubType="Designer" TargetFileName="$fileinputname$.xaml" ReplaceParameters="true">MyItemTemplate.xaml</ProjectItem>
        <ProjectItem SubType="Code" TargetFileName="$fileinputname$.xaml.cs" ReplaceParameters="true">MyItemTemplate.xaml.cs</ProjectItem>
      </TemplateContent>
    </VSTemplate>
    
  5. In Notepad, save the .vstemplate file and close it.
  6. Copy and paste the .vstemplate file back to the .zip file located in the ..\Users\username\Documents\Visual Studio Version\Templates\ItemTemplates\ folder.

    If the Copy File dialog box appears, choose the Copy and Replace option.

You can now add an item based on this template to a Windows Store project by using the Add New Item dialog box.

Copy from: http://msdn.microsoft.com/en-us/library/tsyyf0yh.aspx