Using Data Annotations to validate models

You can validate action results too and MVC methods by passing in the model which has the data annotations as part of the parameter list

Coding Wise

The .NET Framework provides us a set of attributes that we can use to validate objects. By using the namespace System.ComponentModel.DataAnnotations we can annotate our model’s properties with validation attributes.

View original post 181 more words

Identity column jumping from 6 to 1000+ in SQL Server 2012

I was surprised to find out that overnight, a unique identifier had jumped from 6 to 1012 and upon investigation, it looks like SQL Server, when restarted, messes up the seed of the unique identifier to a new value (this is why you should never use ints for primary keys!)
Don’t expect identity values to be dense. For example, a rollback when inserting a row will cause an identity value to be “consumed” leaving a gap in the numbers.

I wrote a small SP which can be used to re-seeed the identity of a table in a all DBs on a server:

USE [master]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[ResetOrderIdentityAfterRestart]
AS
BEGIN
begin TRAN
SET NOCOUNT ON;

DECLARE @db_name varchar(280), @SQL nvarchar(500);

PRINT '-------- DB Reseet Report --------';

DECLARE db_name_cursor CURSOR FOR
select DatabaseName + '.dbo.table' from tblClients WHERE ACTIVE = 1

OPEN db_name_cursor

FETCH NEXT FROM db_name_cursor
INTO @db_name

WHILE @@FETCH_STATUS = 0
BEGIN
PRINT ' '
print '----- Resetting count: ' + @db_name

-- Declare an inner cursor based
-- on vendor_id from the outer cursor.

SET @SQL = '
declare @id int = 0
SELECT @id = MAX(ID) FROM ' + @db_name + '

DBCC CHECKIDENT (''' + @db_name + ''', reseed, @id)
'

exec sp_executeSQL @SQL

FETCH NEXT FROM db_name_cursor
INTO @db_name
END
CLOSE db_name_cursor;
DEALLOCATE db_name_cursor;

Commit

END

Then add it in to Start up by using following syntax.

EXEC sp_procoption 'ResetOrderIdentityAfterRestart', 'startup', 'on';

Using ASMX webservices with HttpWebRequest in c# 4.0

If you want to call a .NET 4.0 C# web service, without using the WSDL or “Add Service Reference” in Microsoft Visual Studio 2015, you can use the following functions written in c#:

/// <summary>
/// Execute a Soap WebService call
/// </summary>
public override void Execute()
{
HttpWebRequest request = CreateWebRequest();
XmlDocument soapEnvelopeXml = new XmlDocument();
soapEnvelopeXml.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<soap:Body>
<HelloWorld3 xmlns=""http://tempuri.org/"">
<parameter1>test</parameter1>
<parameter2>23</parameter2>
<parameter3>test</parameter3>
</HelloWorld3>
</soap:Body>
</soap:Envelope>");
using (Stream stream = request.GetRequestStream()) 
{ 
soapEnvelopeXml.Save(stream); 
}
using (WebResponse response = request.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream())) 
{ 
string soapResult = rd.ReadToEnd();
Console.WriteLine(soapResult);
} 
}
}
/// <summary>
/// Create a soap webrequest to [Url]
/// </summary>
/// <returns></returns>
public HttpWebRequest CreateWebRequest()
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(@"http://dev.nl/Rvl.Demo.TestWcfServiceApplication/SoapWebService.asmx"); 
webRequest.Headers.Add(@"SOAP:Action"); 
webRequest.ContentType = "text/xml;charset=\"utf-8\""; 
webRequest.Accept = "text/xml"; 
webRequest.Method = "POST"; 
return webRequest; 
}

Result

<?xml version=”1.0″ encoding=”utf-8″?><soap:Envelope xmlns:soap=”http://schemas.xmlsoap.org/soap/envelope/” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns:xsd=”http://www.w3.org/2001/XMLSchema”><soap:Body><HelloWorld3Response xmlns=”http://tempuri.org/”><HelloWorld3Result>test</HelloWorld3Result></HelloWorld3Response></soap:Body></soap:Envelope>

 

You can use complex types in you’re request. I use fiddler to get the contents of the soap envelope.

How to create a hashed MD5 password?

While some systems have not heard of the MD5 vulnerability, they might require you to build up a hashed password.
Here’s the code in C# and VB.net. Once you’ve grabbed the code you need, have a read on the two links below detailing MD5 Hash collisions.

using System.Security.Cryptography;
-------------------
 // step 1, calculate MD5 hash from input
    MD5 md5 = System.Security.Cryptography.MD5.Create();
    byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
    byte[] hash = md5.ComputeHash(inputBytes);
// step 2, convert byte array to hex string
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < hash.Length; i++)
    {
      sb.Append(hash[i].ToString(“X2”));
    }
    return sb.ToString();

In VB.NET

Private Function GetMd5Password(ByVal psStr AsString) As String 
Dim md5Hasher As New MD5CryptoServiceProvider()
Dim sBuilder As New StringBuilder()
Dim nX As Integer' Convert the input string to a byte array and compute the hash.
Dim byData As Byte() = md5Hasher.ComputeHash(ASCIIEncoding.Default.GetBytes(psStr))

' Create a new Stringbuilder to collect the bytes and create a string.
' Loop through each byte of the hashed data and format each one as a hexadecimal string.
For nX = 0 To byData.Length -1
    sBuilder.Append(byData(nX).ToString("x2"))
Next
' Return the hexadecimal 
string.ReturnsBuilder.ToString().ToUpper
End Function

MD5 was intended to be a cryptographic hash function, and one of the useful properties for such a function is its collision-resistance. Ideally, it should take work comparable to around 264264 tries (as the output size is 128128 bits, i.e. there are 21282128 different possible values) to find a collision (two different inputs hashing to the same output). (Actually, brute-forcing this is today almost in the range of possible, so this alone would be a reason not to use any small-output hash function like MD5.)

http://www.mscs.dal.ca/~selinger/md5collision/ Explanation of how MD5 collisions occur
http://www.links.org/?p=6 MD5 Collisions Visualised

OWIN Classes with Access-Control-Allow-Origin Header: *

XMLHttpRequest cannot load http://localhost:7802/token. No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
Origin ‘http://localhost:7812&#8217; is therefore not allowed access

This error means that there is an attempt to access a resource from a different domain by a web app, and the requested resource does not have any policies that would allow the apps from the origin domain to consume it. This error can be reproduced by loading a web app on a different domain (or port) and making an AJAX call to an API. The code would be
something similar to the following:
Client App
API App
$.ajax({
type: “POST”,
7/api/contact”,
contentType: ‘application/json’,
data: JSON.stringify(contact),
headers: {
‘Authorization’: ‘Bearer ‘ + tokenProvider.token,
},
success: function (res) {

callback();
},
error: function (req, status, error) {

callbackError();
}
});
[HttpPost]
[ResponseType(typeof(Contact))]
[Route(“~/api/contact”)]
public IHttpActionResult PostContact
        ([FromBody]Contact contact)
{
    IHttpActionResult result = null;
    if (!ModelState.IsValid)
    {
          result=BadRequest(ModelState);
    }
    else
     {
          //handle request
     }
     return result;
}

When making a CORS request, we need to understand that for every request that we send to a different domain, there may be two requests made to the server, preflight and actual requests. For each of these requests, the server must respond with the Access-Control-Allow-Origin header set with the name of the origin domain.

Preflight Request
 
A preflight or OPTIONS (HTTP verb) request is created by the
browser before the actual request (PUT,POST) is sent for a resource in
another domain. The goal is to have the browser and server validate that the other
domain has access to that particular resource. This is done by setting the Access-Control-Allow-Origin
header with the host or origin domain.
Actual Request
 
Once the preflight request has a response with the
corresponding headers, the browser sends the actual request. For this request,
the server also checks the CORS policies and adds the Access-Control-Allow-Origin
header with the host domain.
OWINS CORS
 
The way to implement CORS using OWIN and MVC Web API is by first configuring the oAuth server options with an implementation of OAuthAtuhorizationServerProvider on the Startup class.
[assembly: OwinStartup(typeof(ozkary.Startup))]
namespace ozkary
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {

ConfigureAuth(app);
        }
        private void ConfigureAuth(IAppBuilder app)
        {
            // Configure the application for OAuth based flow
            var oAuthOptions = new OAuthAuthorizationServerOptions
            {
                Provider =
new AuthorizationServerProvider(),
                                
            };
            // Enable the application to use bearer tokens to authenticate
users

app.UseOAuthAuthorizationServer(oAuthOptions);
           
        }  
    }
}
The OwinStartup directive allows OWIN to run the StartUp class and inject the AppBuilder instance in the Configuration method. This is what we need in order to configure the custom provider that can handle our token management, user validation and CORS headers. (token and user validation is not in the scope of this article). The implementation of
AuthorizationServerProvider is listed below: (listing only the areas that are relevant to support CORS)
public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
    {                      
        /// <summary>
        /// match endpoint is called before Validate
Client Authentication. we need
        /// to allow the clients based on
domain to enable requests
        /// the header
        /// </summary>
        /// <param
name=”context”></param>
        /// <returns></returns>
        public override Task MatchEndpoint(OAuthMatchEndpointContext context)
        {

SetCORSPolicy(context.OwinContext);
            if (context.Request.Method == “OPTIONS”)   
            {               

context.RequestCompleted();
                return Task.FromResult(0);
            }
            return base.MatchEndpoint(context);
        }
       
      
        /// <summary>
        /// add the allow-origin header only
if the origin domain is found on the     
        /// allowedOrigin
list
        /// </summary>
        /// <param
name=”context”></param>
        private void SetCORSPolicy(IOwinContext context)
        {
            string allowedUrls = ConfigurationManager.AppSettings[“allowedOrigins”];
            if (!String.IsNullOrWhiteSpace(allowedUrls))
            {
                var list = allowedUrls.Split(‘,’);
                if (list.Length > 0)
                {
                    string origin =
context.Request.Headers.Get(
“Origin”);
                    var found = list.Where(item =>
item == origin).Any();
                    if (found){

context.Response.Headers.Add(
“Access-Control-Allow-Origin”,

new string[] { origin });
                    }                   
                }
                
            }

context.Response.Headers.Add(
“Access-Control-Allow-Headers”
                                   new string[] {“Authorization”, “Content-Type” });

context.Response.Headers.Add(
“Access-Control-Allow-Methods”
                                   new string[] {“OPTIONS”, “POST” });
        }                
    }
The code above overrides the MatchEndpoint handler. This area of the code is called for every request including the preflight request (OPTIONS). Note that this handler is called before a call is made to Validate Client Authentication. This is where we need to manage the logic of adding the headers using OWIN.  We do this by calling
the SetCORSPolicy method.
The SetCORSPolicy method looks for a configuration setting (allowedOrigins) that contains the whitelist of domains that can consume the resources from our API. It then reads the Origin header to get the domain name (including scheme and port i.e. http://mydomain.com:80). If the origin domain is found in the configuration, the Access-Control-Allow-Origin response header is set to the origin domain value.
This is what helps us resolve the “No ‘Access-Control-Allow-Origin’ header is present on the requested resource”.
The SetCORSPolicy method is also a good place to add other response headers that may be required for accessing our API. For example, we may need to add the Access-Control-Allow-(Header and Methods) for additional access. (Not CORS related)
We can use the browser developer tools to take a look at the network request and response headers. When CORS is configured properly, the response headers should look similar to this:
What to Avoid
 
When using the OWIN middleware to handle our CORS calls, we want to stay away from adding these headers in other areas of the application as this causes a duplicate header exception. Some of the things to avoid include:
  • Do not add these headers on the web.config file
  • Do not use app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll) as this allows all origin domains to have access. We could use this option for public APIs with no restrictions.
  • Do not use the config.EnableCors from WebApiConfig (HttpConfiguration) as we are already using a middleware to handle this concern. This option can be used when OWIN is not being used and we need to allow CORS
  • When configuring the whitelist for CORS, we need to make sure to include the scheme, domain and port number  (especially when testing with Visual Studio).   http://localhost is not the same as http://localhost:5733 and  http://www.ozkary .com is not the same as http://ozkary.com. We need to match the Origin header value

 

Conclusion

 

We need to keep in mind that once we start using OWIN, we are essentially passing the CORS concern to the middleware. We do not want to start making changes in different areas of the application as that just makes thing confusing. We just need to focus on the AuthorizationServerProvider and add the necessary implementation to enable CORS in our apps.