Category Archives: ASP.NET

Coding in .NET to target the web by using ASP.NET, either VB.NET or C#.

How to consume an OAuth based REST service

Recently I decided to dive deep into REST services because of how prominent they are becoming in the industry.  Nearly most of my coding time is spent figuring out how to take one piece of software or code and connect it with another piece of software or code to produce the expected result.  RESTful web services are a great way to take a generic design such as Json or XML and come up with a standard library to talk to any system.  If you aren’t familiar with REST services, they are a simple form of HTTP communication that takes basic HTTP commands: GET, PUSH, PUT and DELETE and translates them into CRUD operations.

What does this all mean?  It means that you can call a website through a standard website client and treat it just as if you were hitting a data source.  Pretty neat huh?  A large chunk of the REST services out on the market now deal in Json with support for XML.  Json is a nice language that allows for dynamic object design without having any formal definition.  If you want to add a field, you add it.  It is very extensible and light weight allowing for quick and scalable data operations.

So how does OAuth play into all of this?  OAuth is a system that allows you to connect your application to another application in a secure fashion.  To start out, you give your application an ID.  This is sent to a service in the form of a request for access, and the user who is using your application grants what access they want to give.  Once granted your application gets back an authorization key which it uses to make future calls.  The beauty of this system is it puts the security and functionality of the application in the hands of the user and the end service.  All you need to worry about is what your authorization key is and how what services you should be calling at a given time.

My goto library for this type of call currently is called RestSharp.  This library is a REST service library built out for everything we are doing here.   Here is an example of how to create a client and make a call:

Dim auth = New RestClient(SiteURL)
Dim rqst As New RestRequest("wc-api/v2/orders", Method.GET)
Dim rtn As RestResponse

rqst.RequestFormat = DataFormat.Json
auth.Authenticator = New HttpBasicAuthenticator(ConsumerKey, ConsumerSecret)
rtn = auth.Execute(rqst)

With this call, you are reaching out to a popular WordPress plugin called WooCommerce to get a list of orders and returning back the HTTP response.  This response will be in a Json string that you can parse using the popular Newtonsoft library.  The request has all of the standard CRUD operations as well as numerous authentication libraries on top of OAuth.  For more details information about REST services or OAuth, check out the standards page here on W3C.

.NET Applications on Linux

Well, what a touchy subject this might be to some people.  I have always seen the battle go back and forth between Windows, Macintosh and Linux.  Windows being a middle-tier price range which excellent performance, Macintosh being the high end simply from marketing and Linux being the low end cost point which the most potential.  The problem I have always seen is that Microsoft holds the middle share which is always the most used share.   I have been a Microsoft developer for my entire career and I love it to death, but the power behind a Linux machine is starting to become hard to ignore.  Recently I ran into a project that was faced with spending 100 hours developing a communication platform for a piece of software or somehow getting .NET hooked into a Linux server.

Of course we went both routes as with any project whichever option is the best is the choice, but something has to work.  I came across this plugin for Apache and Linux called Mono.  Mono is a plugin/server application that lets you run ASP.NET applications on your Linux server native.  You do not have to get pushed to another server or lose your performance, you simply install the package and configure it in Apache and you are up and running.  To start, here is the mono website for you to check out and hopefully spread out through all of your Linux servers: http://www.mono-project.com/Main_Page

Hopefully you all install it and configure it so when I come through I can install my applications on your server and be just fine and dandy, if you don’t I will no doubt make you do it :)  There is a set of install instructions for each server type including Mac servers as well as CentOS, Ubuntu, Debian, etc.  Mostly it seems to just be a package installation through w-get or whatever your package flavor is.  After configuration you can use this site to configure virtual directories: http://go-mono.com/config-mod-mono/Default.aspx

The nice thing about this configuration generator is that you can create a separate config file for each virtual directory and include them in your base httpd config file under each virtual host settings section.  It is almost exactly like creating virtual applications in IIS and the performance is for the most part the same.  From what I have seen this far, .NET 4.0 is supported as well as AJAX, and I am hoping to see some more stuff go into the project to make it a viable option for hosting .NET applications.  Cheers!

Prevent SQL Injection Attack With .NET

There has been a large stir recently with how to prevent SQL injection attacks with .NET.  Huge rumors are flying about viruses because of the nuclear incident that happened in Iran.  Just to be clear, regardless of how secure any site is there is a likelihood that you can be hacked.  The best we can do is prevent as much as possible so that it takes someone who is really good to do it.  At that point you are dealing with a security expert and likely they will just want you to pay them for the information.  Back on to the subject, to solve our security problem we must first ask ourselves, what is a SQL injection?  SQL injections are a trick that hackers use to execute malicious SQL scripts on your server.

Our main goal is not to take away functionality, but to prevent SQL injection attacks

Let’s say you have a login form, and you ask for a username and password.  You have a text box bound to both fields and when they hit a Login button your form code selects from the user table where user name is equal to the User text box.  The SQL might look something like this:

SELECT UserId, UserName,Password FROM Users
WHERE UserName = '" + txtUserName.Text + "'

prevent sql injection attacks
This is where a hacker can come in and where we need to prevent SQL injection attacks.  The user name a hacker would fill out would be something like this:

'; DROP DATABASE myWebApp --

When your code executes it will send a drop database command to your server destroying all of your data.  This is likely not the intent of the hacker as they would much rather send a command to validate their password or fetch data but the goal here is to prevent SQL injection.  Here are the three big steps to prevent SQL injection attacks:

Three methods to prevent SQL injection attacks with .NET

Validate your data

The first step in a SQL injection attack is to know what the developer is expecting to happen with a field and exploit it.  In reverse, the first step to prevent SQL injection attacks is to know what a hacker intends to do with a field and prevent it.  This will involve checking that your text received is the right length, scrubbing for invalid characters and make a decent attempt at stripping out dangerous SQL commands or throwing back errors if you find anything.

Use SQL Stored Procedures

Stored procedures are the next great .NET tool, because a parameter passed through a stored procedure command is sent as literal text as opposed to executed with a command.  While converting your commands to a stored procedure does not prevent SQL injection attacks it does give you an additional security layer in case the injection makes it through and is targeting specific commands.

Use Parameters with Dynamic SQL

Another way to prevent SQL injection attacks is to embed your input from forms as parameters as opposed to injecting them directly into the statement.  This can be done simply by using an @ sign as a parameter in your statement and appending a parameter to your command object.  This looks something like this:

SqlDataAdapter saoSqlAdapter = new SqlDataAdapter(
         "SELECT UserName, UserId, Password FROM Users WHERE UserName = @userName",
         connection);
  myCommand.SelectCommand.Parameters.Add("@userName", SqlDbType.VarChar, 50);
  myCommand.SelectCommand.Parameters["@userName"].Value = txtUserName.Text;
  myDataAdapter.Fill(userDataset);

Other methods to prevent SQL injection attacks

After working these three methods you should be able to prevent SQL injection attacks from mostly all attackers, if you need more information on how to prevent SQL injection attacks check out how to prevent sql injection attacks on MSN.

HOW TO: Use Facebook Registration In .NET

As we all know Facebook is too big of a monster to not consider when developing our web applications.  Time and time again I have received the request to add a Facebook registration process to a store or blog that allows users to “Connect With Facebook” and remember their settings.  Luckily, Facebook has begun alpha support of a C# library which lets us have some fun with JSON.  Facebook uses a signed response method which encrypts information passed back and forth using your application secret and ID.  Here is some sample code for a page that would call to the Facebook API for registration/logging in.

HTML

<iframe src="https://www.facebook.com/plugins/registration.php?
client_id=xxxx&
redirect_uri=http://localhost/fbtest/completed.aspx&
fields=name,first_name,last_name,birthday,gender,location"
scrolling="auto"
frameborder="no"
style="border:none"
allowTransparency="true"
width="100%"
height="330">
</iframe>

When using this approach Facebook will pass you back to the page you specify in the redirect_url with a Form field setup called signed_request.  The nice thing about this is you create a page that accepts this call back and handles the Form field appropriate to login or register a user.  The C# library that Facebook has started working on exposes some methods which allow you to interpret this response and get some data. Here is an example on how to retrieve the response and fetch some fields from it:

VB.NET

Imports Newtonsoft.Json.Linq
'...
Partial Class FacebookRegistrationPageHandler
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        Dim fbaFacebookApp As New Facebook.FacebookApp
        Dim fsrSignedRequest As Facebook.FacebookSignedRequest
        Dim jobJSONObject As JObject

        fbaFacebookApp.AppId = "xxxx"
        fbaFacebookApp.AppSecret = "xxxx"
        fsrSignedRequest = fbaFacebookApp.SignedRequest

        jobJSONObject = JObject.Parse(fsrSignedRequest.Dictionary("registration"))
        Dim strReturnedName = CType(jobJSONObject("name"), Newtonsoft.Json.Linq.JValue).Value

    End Sub
End Class

C#

using Newtonsoft.Json.Linq;
// ...
Partial;
class FacebookRegistrationPageHandler : System.Web.UI.Page {

    protected void Page_Load(object sender, EventArgs e) {
        Facebook.FacebookApp fbaFacebookApp = new Facebook.FacebookApp();
        Facebook.FacebookSignedRequest fsrSignedRequest;
        JObject jobJSONObject;
        fbaFacebookApp.AppId = "xxxx";
        fbaFacebookApp.AppSecret = "xxxx";
        fsrSignedRequest = fbaFacebookApp.SignedRequest;
        jobJSONObject = JObject.Parse(fsrSignedRequest.Dictionary("registration"));
        object strReturnedName = ((Newtonsoft.Json.Linq.JValue)(jobJSONObject["name"])).Value;
    }
}

ASP.NET Session vs. Persistence

Today my boss asked me to cut down the performance on a web application that I thought was pretty horrible myself. The first thing I looked at is how to take out trips to the database.

I had a few persistent objects out here based on the session ID which I was collecting from the database every time a page was hit. This seemed terribly inefficient so I started poking on DevExpress’ search engine trying to find out how to take these out.

After a bit of hair pulling, I found the authentication system travels with a session, so session level properties can be stored in it.

I decided to try inheriting their authentication active directory system and use it to store a web session object.

This is the result:

Public Class SessionSecuritySystem
    Inherits ISS.Security.Web.AnonymousSecuritySystem

    Private _mUserSession As CMSUserSession
    Public Property UserSession() As CMSUserSession
        Get
            Return _mUserSession
        End Get
        Set(ByVal Value As CMSUserSession)
            _mUserSession = Value
        End Set
    End Property

    Private Sub SessionSecuritySystem_PlatformDataChanged() Handles Me.PlatformDataChanged
        Dim obsSpace As ObjectSpace
        If CMSModule.XafApplicationInstance IsNot Nothing Then
            obsSpace = CMSModule.XafApplicationInstance.CreateObjectSpace
            Me.UserSession = Activator.CreateInstance(CMSModule.SharedUserSessionType, obsSpace)
        Else
            Me.UserSession = Activator.CreateInstance(CMSModule.SharedUserSessionType)
        End If
    End Sub
End Class

This class gives me the option to store anything for the web session without making a trip to the database.

My web application was a store style website, so needless to say it cut the 100 trips to the database per page call down to 25.

Next I’m going to work on how to improve object performance with the Session.

DevExpress has noted a few times that the session object has a cache which returns back objects and if they have been modified int he database for reload.

I think the next logical path would be to store these commonly used objects and retrieve them only when they are changed. It would be nice if DevExpress worked with database triggers to get notification of object changes.