Google+ Peter Bromberg's .NET Blog | C#

Peter Bromberg's .NET Blog All Things Programming

Global Unhandled Exception Logging

28. November 2016 08:53 by admin in C#, EXCEPTIONS

We as developers often don't account for the fact that we may not be catching and handling all possible exceptions.This is particularly problematic in Windows Services as if something bad happens, the service may continue running but will be in a state where it isn't actually "doing anything".

Code like the following can be used to catch and handle any exception for which no handler has been wired in, and such exceptions can be logged using your preferred method:

 

namespace YourNamespace {

static class Program

{

[STAThread]

static void Main()

{

AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

}

static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)

{ HandleException(e.Exception);

}

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)

{

HandleException((Exception)e.ExceptionObject);

}

static void HandleException(Exception e)

{

//Handle your Exception here

}

}

}

How to Ensure that jQuery is only loaded once

26. July 2016 13:50 by admin in ASP.NET, C#, Jquery

Often we have pages and master pages and "bundles" that load scripts like jQuery and we can't always be sure that a particular page already has it loaded. Here is a script that will only inject jQuery into a page if it has not already been loaded:

<HTML>
<HEAD>

<!-- comment or uncomment next line to test it out --->
<script src='https://code.jquery.com/jquery-3.1.0.min.js'></script>

<script>

// Only do anything if jQuery isn't defined

if (typeof jQuery == 'undefined') {

function getScript(url, success) {

var script = document.createElement('script');

    script.src = url;

var head = document.getElementsByTagName('head')[0],done = false;

// Attach handlers for all browsers

script.onload = script.onreadystatechange = function() {

if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {

done = true;

// callback function provided as param

success();

script.onload = script.onreadystatechange = null;

head.removeChild(script);

};

};

head.appendChild(script);

};

 

getScript('https://code.jquery.com/jquery-3.1.0.min.js', function() {

if (typeof jQuery=='undefined') {

// Super failsafe

} else {

alert("We Loaded it!");

// jQuery loaded 

}

});

 

} else { 

// jQuery was already loaded

alert("jQuery is Already Loaded!");

// Run your jQuery Code

};

</script>

</HEAD>

<BODY>

</BODY>

 

</HTML>

 

Implementing a Custom IPrincipal in an ASP.NET MVC Application

25. January 2014 14:45 by admin in ASP.NET, C#, MVC

 I have an MVC application for which I have implemented a Custom ExtendedMembership - derived Membership class that is hosted via a WCF Service.

I have a custom MembershipProviderForwarder class that plugs right into my web.config as the Membership provider, but what it actually does is forward all Membership calls to my WCF Service, which uses the real custom Membershp provider, and returns back all the results to the app from over the wire.

In this manner I can have any number of MVC apps all using the same provider via my Webservice.

Since I have custom Membership fields, but only a couple, I didn't want to get into writing a lot of Profile code. Instead, I have a Custom User object that has these extra fields which can be returned from the UserProfile table in SQL Server.

The issue is that I only want to make Webservice calls when the user first logs in, and I want to store my custom fields in the Forms Ticket (it has a UserData property for just this purpose). In this manner I can use the PostAuthenticateRequest event to pull my custom data our of the forms cookie and attach my custom IPrincipal to the HttpContext.Current.User property for each subsequent request. Here is how I did that:

 

1. Create the interface

 

interface ICustomPrincipal : IPrincipal

{

    int UserId { get; set; }

    string FirstName { get; set; }

    string LastName { get; set; }

}

 

2. CustomPrincipal

 

public class CustomPrincipal : ICustomPrincipal

{

    public IIdentity Identity { get; private set; }

    public bool IsInRole(string role) { return false; }

 

    public CustomPrincipal(string email)

    {

        this.Identity = new GenericIdentity(email);

    }

 

    public int UserId { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

}

 

3. CustomPrincipalSerializeModel - for serializing custom information into userdata field in FormsAuthenticationTicket object.

 

public class CustomPrincipalSerializeModel

{

    public int UserId { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

}

 

4. LogIn method - setting up a cookie with custom information

 

if (Membership.ValidateUser(viewModel.Email, viewModel.Password))

{

    var user = userRepository.Users.Where(u => u.Email == viewModel.Email).First();

 

    CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();

    serializeModel.UserId = user.Id;

    serializeModel.FirstName = user.FirstName;

    serializeModel.LastName = user.LastName;

 

    JavaScriptSerializer serializer = new JavaScriptSerializer();

 

    string userData = serializer.Serialize(serializeModel);

 

    FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(

             1,

             viewModel.Email,

             DateTime.Now,

             DateTime.Now.AddMinutes(15),

             false,

             userData);

 

    string encTicket = FormsAuthentication.Encrypt(authTicket);

    HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);

    Response.Cookies.Add(faCookie);

 

    return RedirectToAction("Index", "Home");

}

 

5. Global.asax.cs - Reading cookie and replacing HttpContext.User object, this is done by overriding PostAuthenticateRequest

 

protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)

{

    HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];

    if (authCookie != null)

    {

        FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

        JavaScriptSerializer serializer = new JavaScriptSerializer();

        CustomPrincipalSerializeModel serializeModel = serializer.Deserialize<CustomPrincipalSerializeModel>(authTicket.UserData);

        CustomPrincipal newUser = new CustomPrincipal(authTicket.Name);

        newUser.UserId = serializeModel.UserId;

        newUser.FirstName = serializeModel.FirstName;

        newUser.LastName = serializeModel.LastName;

        HttpContext.Current.User = newUser;

    }

}

 

 

6. Access in Razor views

 

@((User as CustomPrincipal).Id)

@((User as CustomPrincipal).FirstName)

@((User as CustomPrincipal).LastName)

 

and in code:

 

    (User as CustomPrincipal).Id

    (User as CustomPrincipal).FirstName

    (User as CustomPrincipal).LastName

Convert ASCII to Hexadecimal and Hexadecimal to ASCII

6. August 2013 08:12 by admin in CONVERSION, C#, General

 

Here a couple of utility methods in C# to make ASCII to Hexadecimal conversions.

 
 public string HexToAscii( string hex)
{
string res = String.Empty ;for (int a = 0; a <hex.Length ; a = a + 2)
{
string CharToConvert = hex.Substring(a, 2);int n = Convert.ToInt32(CharToConvert, 16);char c = (char)n;
res += c.ToString();
}
return res;
} 
public string AsciiToHex(string ascii)
{
StringBuilder sb = new StringBuilder();byte[] inputBytes = Encoding.UTF8.GetBytes(ascii);foreach (byte b in inputBytes)
{
sb.Append(string.Format("{0:x2}", b));
}
return sb.ToString();
}