Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Saturday, May 11, 2013

One or more types required to compile a dynamic expression cannot be found. Are you missing a reference?

Just had an issue trying to use a dynamic object in a .NET test project – at build time I had the compiler error:

One or more types required to compile a dynamic expression cannot be found. Are you missing a reference?

In the end all I had to do was reference “Microsoft.CSharp” from my test project.

Wednesday, May 8, 2013

AntiScrape - IIS ASP.NET Http Module

Download Code

no-scrapeAntiScrape is an IIS ASP.NET Http Module to help in the fight against website scrapers!

How does it work?

AntiScrape hooks into the IIS ASP.NET request/response pipeline.

When your website users request a page, it automatically adds secret hidden links to the page that normal users in web browsers won't see. However, website scrapers that are scanning the HTML of the page will see the link and follow it.

Once the scraper has followed the secret link, they are recorded as being a scraper, and from then on what happens is entirely up to you!

You can either:

  • Return custom content and/or HTTP status code for every other request the scraper makes (even for legitimate content), or
  • Introduce a configurable random delay for all requests that the scraper makes, slowing the scraper down, or
  • Do nothing, other than log the scraping activity.

The settings for AntiScrape are integrated into the web applications web.config.

How are the scraping requests logged?

The module comes with a reference implementation of the data persistence layer for SQL Server, but other implementations can be easily added by implementing the IDataStorage interface in an assembly that resides in the web applications bin folder (remembering to remove the assembly containing the SQL Server reference implementation). AntiScrape uses Microsoft Unity to resolve the IDataStorage interface at run-time.

Development Goals

As part of this project I wanted to ensure that the module could be integrated with an existing web solution as easily as possible. Therefore the sample web project is just a vanilla web forms project created with File, New Web Project in Visual Studio, plus the dlls and some config changes. There are some other minor tweaks to show the results of the scraping requests in a table, but that’s it!

Development Status

This software is currently in active development, and so not recommended for production environments at present.

Stuff I have yet to deal with:

  • Legitimate scrapers – such as search engine crawlers
  • Randomizing the honeypot url

Once I have something reasonable that answers these I shall put together a NuGet package that integrates the module and applies the config transforms.

Live Demo

Live demo is available on Windows Azure here: AntiScrape Demo

Source Code

Source code is available on Github here.

Technology Used

X-POW - Proof Of Work for ASP.NET MVC

Rusty_PadlockX-POW is a proof-of-work implementation for ASP.NET MVC.

View the source code here.


How It Works

The server-side implementation is as an MVC ActionFilterAttribute called RequireXpowAttribute. This does not allow the request through unless the hash problem has been solved.
The client-side implementation is a javascript library that uses Web Workers to perform the hash calculations off the main javascript thread. It raises an event when the hash has been solved, informing the page that it can continue on to the original target.

Configuration

There are two settings that can be tweaked in the web.config:
<appSettings>
  <add key="LeadingBytes" value="2"/>
  <add key="LeadingBytesValue" value="7"/>
</appSettings>
  • LeadingBytes is the number of bytes at the start of the hash to consider when checking the value
  • LeadingBytesValue is the maximum value that the leading bytes of the hash should be to be considered valid
Both of these settings are a single byte, and so are in the range of 0 to 7


Original Technical Details

These details are from the original spec I wrote, and so are slightly out-of-date and need some tidying up. I will update them as soon as I can, but are included here for the extra detail they bring!

Overview
Client requests page. Server sends back page with X-PoWRequest header containing 128bit value. First byte is number of leading zeroes that hash result must have, the other 15 bytes are random. Server also sets cookie value with same name. Client must generate own 128bit value so that when server value and client value are combined into a single 256bit value and hashed using SHA-256 the first N bytes of the hash are zero

Example
Server sends:

              NZ[       random data          ]
X-PoWRequest: 0465A709F1CE40EABEFEF4C94FA0E9A8

Where NZ is number of leading zero bytes the hash of the result must have, in this case 4 Also stores value in a list of request values for the session.

Client responds:

X-PoWRequest: 0465A709F1CE40EABEFEF4C94FA0E9A8
X-PoWResponse: ED807302BF6A403ABE0C0864E271E284

Server checks that X-PoWRequest is present, if not response invalid.
Server checks that X-PoWResponse is present, if not response invalid.
Server checks that X-PoWRequest is in the list of values in the session, if not response invalid.

Server combines values into single 256bit value:

[         server value         ][         client value         ]
0465A709F1CE40EABEFEF4C94FA0E9A8ED807302BF6A403ABE0C0864E271E284

Computes hash:

[                              hash                            ]
00000000891444D0AE14416C4D25E59EACE0404151F44C118F8B1CF868C314A8

Checks first 4 bytes are zero, if so response valid server removes request value from session list

Client
Client is a javascript library that is included in any page that will need to pass x-pow tests. Starts up once document has finished loading (body.onload, or $(document).ready())

Possibly postpone body.onload, and/or $(document).ready() until the script has solved the problem? http://api.jquery.com/jQuery.holdReady/

It will do nothing if the X-PoWRequest cookie/header is not present - raise ready event immediately.

If it is present, then it will start attempting to solve the problem. Maybe each attempt is on a timer in order to keep other scripts responsive - use webworker if available? http://code.google.com/p/ie-web-worker/

Once problem is solved X-PoWRequest and X-PoWResponse cookie/headers are added and javascript event is raised to indicate that the page is ready to communicate with the server again. This event should be used to update the dom to enable interaction with server - GET/POST/PUT/DELETE etc.

Other possible client implementations:

Create Portable Class Library (http://msdn.microsoft.com/en-us/library/gg597391.aspx) that adds support to Silverlight/WP7/.NET applications.

Create a single static method that returns Task and performs the calculations asynchronously in a background thread, something like:

public static Task<byte[]> GenerateResponse(byte[] request)
public static Task<string> GenerateResponse(string request)
public static Task GenerateResponse(HttpContext context)

Other helper methods:

public static bool RequiresResponse(HttpContext context)
public static string GetRequest(HttpContext context)
public static byte[] GetRequest(HttpContext context)
public static void SetResponse(HttpContext context, byte[] request, byte[] response)
public static void SetResponse(HttpContext context, string request, string response)

Server
Server is an ASP.NET MVC Filter Attribute which checks the request value is the one stored for the session, and then calculates the hash of the request and response values, and checks that the leading zeros are the correct number.

Also need an element that adds the X-PoWRequest header to server responses that are required to interact with controller actions that have the filter attribute applied to them. Perhaps an attribute on controller actions that return views that then need to interact with other controller actions that require xpow.

[ActivateXpow] - ActionResult returned has X-PoWRequest header present, and server value added to session xpow value cache.

[RequireXpow] - Checks that the X-PoWRequest and X-PoWResponse headers are present. Checks the request value is the one stored for the session. Calculates the hash of the request and response values. Checks that the leading zeros are the correct number.

Possible other approach:

Single attribute - [RequireXpow] - When an initial request is made to the action with this attribute, the action redirects to a built in action that delivers a defined view and also the xpow request to the browser, which performs the calculation and resubmits the request to the original action with the xpow response included automatically without the need for user intervention. This defined view just needs to be a simple "processing" animation, perhaps with some kind of feedback.

Issues with this approach would be preserving the original HTTP POST data (although this might be trivial).

Thursday, May 2, 2013

Using WebGL + SignalR To Create A Multiplayer HTML5 Space Simulation – Part 1

 

multiplayer_3d_demo_screenshot1

View Demo

Although the name suggest that this is a game, at present it is merely a demo. When you visit the site (in a browser that fulfils the requirements below) then you will be presented with a first-person view from your own personal spaceship, flying through the galaxy.

Other people also viewing the site at the same time as you will be visible to you as spaceships flying through space, their positions updated in real time. Your spaceship will also be visible to them.

Controls

Mouse

  • Moving the mouse pointer away from the centre will turn your ship in that direction
  • Left click moves your ship forward
  • Right click moves your ship backwards

Keyboard

  • W moves your ship forward
  • A moves your ship to the left
  • S moves your ship backwards
  • D moves your ship to the right
  • Q rotates your ship around the forward axis to the left
  • E rotates your ship around the forward axis the the right
  • R moves your ship upwards
  • F moves your ship down

 

HUD

Top left displays your radar, which shows where other ships are in space. Your ship is represented by the large green dot in the centre, other ships are smaller red dots around. If a red dot is on top of the green dot that means that either the other ship is right next to you, or directly in front of you.

Bottom left displays the game info messages, which will tell you about events in the galaxy, such as a new player joining the game.

Requirements

You will need a browser that supports WebGL, running on a reasonably powerful computer with decent graphics hardware.

The currently recommended browser is Google Chrome. The demo works ok on Firefox (but not as fast as Chrome), and not at all on IE 10 or less. Apparently this may be changed in IE 11 (which will possibly support WebGL).

Google Chrome has also been found to work on Android devices, such as Tablets and recent phones. However what does not work at present is the touch interface for these devices. At present this is primarily a desktop-with-mouse driven experience.

Technology

This demo uses WebGL for the graphics rendering. It also uses either WebSockets, Server-Sent Events or AJAX Long Polling for the real-time communications.

It is built with the following technologies:

  • Three.js is a WebGL javascript library
  • SignalR is Real-Time Communications library for the web
  • Windows Azure is Microsofts Cloud Hosting Solution

 

Live Demo

A live demo is available here: http://awesome3dgame.azurewebsites.net/

Source Code

Source code is available on Github here: https://github.com/SneakyBrian/Awesome3DGame

Future Posts

In future posts I will delve into the details of how this was implemented.

Thursday, November 15, 2012

Poker Odds API - ASP.NET MVC 4 Web API Knockout.js Example


Download Source Code
pokerPoker Odds API is an example API built using ASP.NET MVC Web API. Given a Texas Holdem Poker hand (and optionally the community cards) it will calculate the odds of winning.


How It Works

Poker Odds uses the excellent PokerHandEval code written by Keith Rule (based in turn on the poker-eval library). Users of the API submit information on their hand, and get back information on the possible outcomes of the game.
Cards are submitted as a sequence of two character codes separated by spaces. For example, to specify that your pocket cards are the two of diamonds and the queen of clubs, you would pass "2d qc" as the pocket parameter. If you wanted to pass 7 Hearts, Ace of Spades and 10 Hearts as the board, you would specify this as "7h as th". Note that the characer "t" indicates 10.


Live Demo

A live demo is hosted at http://pokerodds.azurewebsites.net/


Source Code

Source code is available here: https://github.com/SneakyBrian/PokerOdds


Example

Requesting the following url (in Firefox or Chrome, which specify XML by default):
http://pokerodds.azurewebsites.net/api/TexasHoldem/?pocket=2d%20qc&board=7h%20as%20th
Results in the response:
<TexasHoldemOdds xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/PokerOdds.Mvc.Web.Models.TexasHoldem">
<Board>7h as th</Board>
<CalculationTimeMS>1678</CalculationTimeMS>
<Completed>true</Completed>
<Outcomes>
<PokerOutcome>
<HandType>HighCard</HandType>
<HandTypeName>HighCard</HandTypeName>
<WinPercentage>8.459619319933843</WinPercentage>
</PokerOutcome>
<PokerOutcome>
<HandType>Pair</HandType>
<HandTypeName>Pair</HandTypeName>
<WinPercentage>20.051439464020408</WinPercentage>
</PokerOutcome>
<PokerOutcome>
<HandType>TwoPair</HandType>
<HandTypeName>TwoPair</HandTypeName>
<WinPercentage>5.14609555312608</WinPercentage>
</PokerOutcome>
<PokerOutcome>
<HandType>Trips</HandType>
<HandTypeName>Trips</HandTypeName>
<WinPercentage>0.90100823218307036</WinPercentage>
</PokerOutcome>
<PokerOutcome>
<HandType>Straight</HandType>
<HandTypeName>Straight</HandTypeName>
<WinPercentage>1.326353264373616</WinPercentage>
</PokerOutcome>
<PokerOutcome>
<HandType>Flush</HandType>
<HandTypeName>Flush</HandTypeName>
<WinPercentage>0</WinPercentage>
</PokerOutcome>
<PokerOutcome>
<HandType>FullHouse</HandType>
<HandTypeName>FullHouse</HandTypeName>
<WinPercentage>0</WinPercentage>
</PokerOutcome>
<PokerOutcome>
<HandType>FourOfAKind</HandType>
<HandTypeName>FourOfAKind</HandTypeName>
<WinPercentage>0</WinPercentage>
</PokerOutcome>
<PokerOutcome>
<HandType>StraightFlush</HandType>
<HandTypeName>StraightFlush</HandTypeName>
<WinPercentage>0</WinPercentage>
</PokerOutcome>
</Outcomes>
<OverallWinSplitPercentage>35.884515833637018</OverallWinSplitPercentage>
<Pocket>2d qc</Pocket>
</TexasHoldemOdds>



Or the same url in IE results in a JSON formatted response:







{
"Pocket" : "2d qc",
"Board" : "7h as th",
"Outcomes" : [{
"HandType" : 0,
"HandTypeName" : "HighCard",
"WinPercentage" : 8.459619319933843
}, {
"HandType" : 1,
"HandTypeName" : "Pair",
"WinPercentage" : 20.051439464020408
}, {
"HandType" : 2,
"HandTypeName" : "TwoPair",
"WinPercentage" : 5.14609555312608
}, {
"HandType" : 3,
"HandTypeName" : "Trips",
"WinPercentage" : 0.90100823218307036
}, {
"HandType" : 4,
"HandTypeName" : "Straight",
"WinPercentage" : 1.326353264373616
}, {
"HandType" : 5,
"HandTypeName" : "Flush",
"WinPercentage" : 0.0
}, {
"HandType" : 6,
"HandTypeName" : "FullHouse",
"WinPercentage" : 0.0
}, {
"HandType" : 7,
"HandTypeName" : "FourOfAKind",
"WinPercentage" : 0.0
}, {
"HandType" : 8,
"HandTypeName" : "StraightFlush",
"WinPercentage" : 0.0
}
],
"OverallWinSplitPercentage" : 35.884515833637018,
"Completed" : true,
"CalculationTimeMS" : 1816
}






Technology Used



Tuesday, October 9, 2012

ZeroMQ + MsgPack + .NET

I have created a simple testbed to demonstrate 2 .NET applications communicating with each other using ZeroMQ Publisher/Subscriber connections for the communications layer, and MsgPack as the serialization/deserialization layer.

ZeroMQ is a highly efficient and scalable network layer that acts as a reliable messaging layer on top of raw sockets. Performance is key here.

For ZeroMQ I use the x86 NuGet package available here: http://nuget.org/packages/clrzmq/2.2.5

MsgPack is a serialization library where efficient storage of the serialized data, and performance of the serialization and deserialization is the main focus.

For MsgPack I found that the current NuGet package was somewhat behind the times, so I built the dll by downloading the latest source from https://github.com/msgpack/msgpack-cli and building it in release configuration, and adding it as a reference to both the client and server applications.

With the two libraries combined, an application should be very efficient and performance should be very high. I built this testbed primarily to see how straightforward it was to use these libraries from .NET applications. As you can see, it is very straightforward indeed!

Here is the client implementation:



Here is the server implementation:



Here is the shared model:



The full solution is available here: https://github.com/SneakyBrian/ZeroMQ_MessagePack_Testbed

Friday, October 5, 2012

XML2JSON – Command line tool for converting XML to JSON

XML2JSON is a simple command line tool for converting XML files to JSON. It uses the JSON.NET library.

Usage:

XML2JSON.exe input.xml output.json


Example Input:



<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
</catalog>


Example Output:



{
"catalog": {
"book": [
{
"id": "bk101",
"author": "Gambardella, Matthew",
"title": "XML Developer's Guide",
"genre": "Computer",
"price": "44.95",
"publish_date": "2000-10-01",
"description": "An in-depth look at creating applications \r\n with XML."
},
{
"id": "bk102",
"author": "Ralls, Kim",
"title": "Midnight Rain",
"genre": "Fantasy",
"price": "5.95",
"publish_date": "2000-12-16",
"description": "A former architect battles corporate zombies, \r\n an evil sorceress, and her own childhood to become queen \r\n of the world."
}
]
}
}


Code


This is the code for the program:











The full .NET solution is available here: https://github.com/SneakyBrian/XML2JSON

Create A Dynamic Object From An XML File

Here are a couple of simple methods that load an xml file into a dynamic object that can be used in code. At present this code does not handle xml attributes, only elements.

Thursday, April 1, 2010

Nice Curves! - Catmull–Rom spline in C#

Download sample code

Suppose you have a series of points that define a region.

points

When you “join-the-dots” you end up with something that looks quite “pointy”.

lines

What if you want your region to look a little curvier than this?

Splines are a great way of calculating extra points between these key points to allow you to create much more organic and natural looking regions.

In this example I used a Catmull-Rom Spline to create curves from a limited set of points. Catmull-Rom is a good spline algorithm to use if you need the line to pass through the points that you define, but appear as curved as possible. It is quite often used for calculating camera tracks from key frames in the field of computer graphics.

The Catmull-Rom requires 4 points, and it calculates the spline points between the 2nd and 3rd points.

catmullrom_spline

The algorithm uses the 1st and 4th points as targets for the smoothing of the curve.

Here is the code to generate a single spline point from the list of key points.


/// <summary>
/// Calculates interpolated point between two points using Catmull-Rom Spline/// </summary>
/// <remarks>
/// Points calculated exist on the spline between points two and three./// </remarks>
/// <param name="p0">First Point</param>
/// <param name="p1">Second Point</param>
/// <param name="p2">Third Point</param>
/// <param name="p3">Fourth Point</param>
/// <param name="t">
/// Normalised distance between second and third point /// where the spline point will be calculated/// </param>
/// <returns>
/// Calculated Spline Point/// </returns>static public PointF PointOnCurve(PointF p0, PointF p1, PointF p2, PointF p3, float t)
{
    PointF ret = new PointF();

    float t2 = t * t;
    float t3 = t2 * t;

    ret.X = 0.5f * ((2.0f * p1.X) +
    (-p0.X + p2.X) * t +
    (2.0f * p0.X - 5.0f * p1.X + 4 * p2.X - p3.X) * t2 +
    (-p0.X + 3.0f * p1.X - 3.0f * p2.X + p3.X) * t3);

    ret.Y = 0.5f * ((2.0f * p1.Y) +
    (-p0.Y + p2.Y) * t +
    (2.0f * p0.Y - 5.0f * p1.Y + 4 * p2.Y - p3.Y) * t2 +
    (-p0.Y + 3.0f * p1.Y - 3.0f * p2.Y + p3.Y) * t3);

    return ret;
}

In order to use this function you must pass in the four points that describe the spline. The spline point itself is only generated between points 2 and 3. The parameter t is the normalised distance between points 2 and 3 for which we are calculating the spline point. This means that this is the distance on the arc between the 2nd and 3rd point on a scale of 0 to 1 - 0 being point 2 and 1 being point 3. For instance, a value of 0.5 will be half-way between points 2 and 3, 0.25 a quarter of the way, etc.

Therefore, in order to calculate the arc between points 2 and 3 to a resolution of 10 points, we will have to call this method 9 times with values of t of 0.1, 0.2, 0.3, 0.4 etc.

As is discussed in this Stack Overflow article, a better explanation of the maths behind Catmull-Rom splines is available here: http://www.mvps.org/directx/articles/catmull/

I have produced a sample application that allows the user to click within the window to create key points, and then hit the “Calculate” button to generate the spline points, which is then rendered as a continuous curve, intersecting each point.


catmullrom


Here is the example solution on Github.

Wednesday, March 31, 2010

Reading Images From SQL Server using SqlDataReader.GetBytes

Searching around on the internet I found it difficult to find some example C#/.NET code on using SqlDataReader.GetBytes to read image data from a varbinary field in a SQL Server 2008 database. Eventually I found a solution that worked for me, so I thought I would share it with the world.

My solution returns an IEnumerable<T> and uses yield allowing the handling of very large datasets, as each avatar object is returned as the SqlDataReader reads each row, rather than reading in all the rows and processing them all into image data at once.

Anyway, here is the code:

/// <summary>
///
Get Enumerable List Of Avatar Images From User Table
/// </summary>
/// <param name="connectionString">
///
Connection String For Database
/// </param>
/// <returns>
///
Enumerable List Of UserAvatar type.
/// </returns>
IEnumerable<UserAvatar> GetAvatarImages(string connectionString)
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();

using (var command = connection.CreateCommand())
{
command.CommandText = @"SELECT [ID], [Avatar] FROM [User] WHERE [Avatar] IS NOT NULL";

using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
//create a memory stream in which to write the raw data
using (var ms = new MemoryStream())
{
var buffer = new byte[1024];

//this call (with a null buffer paramater)
//will tell us the size of the data in the field
var dataSize = reader.GetBytes(1, 0, null, 0, 0);
var dataRemaining = dataSize;
while (dataRemaining > 0)
{
var bytesToRead = (int)(buffer.Length < dataRemaining ? buffer.Length : dataRemaining);
//fill the buffer
reader.GetBytes(1, dataSize - dataRemaining, buffer, 0, bytesToRead);
//write the buffer to the MemoryStream
ms.Write(buffer, 0, bytesToRead);
dataRemaining -= bytesToRead;
}

//Move the position of the MemoryStream
//Back to the beginning
ms.Seek(0, SeekOrigin.Begin);

//create a temporary placeholder image
//from the MemoryStream data
using (var tempImage = Image.FromStream(ms))
{
yield return new UserAvatar
{
ID = reader.GetInt32(0),
//Copy the temporary image data
//to a new bitmap. Disposing of
//this new bitmap becomes the
//responsibilty of the caller.
Image = new Bitmap(tempImage)
};
}
}
}
}
}
}
}