C# Faster way to truncate a string

Very often I found this problem and now I got a solution!

I’ve compared some methods and I was decided which one. But I verified time (if you want to know how, read this post) of them and the final solutions are:

static string TruncateLongString(string str, int maxLength)
{
    return str.Substring(0, Math.Min(str.Length, maxLength));
}

or

string TruncateString(string str, int maxLength)
{
    return new string(str.Take(maxLength).ToArray());
}

The best solution than even is the second one!

TruncateString

Calculate the execution time of a method

I found a simple code to know the execution time of a method. First of all you have to import the following namespace:

using System.Diagnostics;

Then you use Stopwatch to know the execution time.

Stopwatch sw = Stopwatch.StartNew();
DoSomeWork();
sw.Stop();

Console.WriteLine("Time taken: {0}ms", sw.Elapsed.TotalMilliseconds);

 

Happy coding!

String to Hex - Hex to String Convert

You can convert a string to hex or vice-versa with this methods. Example for real world; You want set / get some data from URL, but if your data has some special chars (like ^$ %) it'll be problem... In this case, you can use this methods and convert your data to hex.

public string ConvertStringToHex(string asciiString)
{
    string hex = "";
    foreach (char c in asciiString)
    {
        int tmp = c;
        hex += String.Format("{0:x2}",
               (uint)System.Convert.ToUInt32(tmp.ToString()));
    }
    return hex;
}

public string ConvertHexToString(string HexValue)
{
    string StrValue = "";
    while (HexValue.Length > 0)
    {
        StrValue += System.Convert.ToChar(System.Convert.ToUInt32(
                        HexValue.Substring(0, 2), 16)).ToString();
        HexValue = HexValue.Substring(2, HexValue.Length - 2);
    }
    return StrValue;
}

 

Happy coding!

Regular expression for UK postcode

I'm looking for an answer to my regular expresssion problem in c#. I'm looking for a match on a specific postcode format and have run into problems. Here you can find my solution with the regex pattern.

C#

public bool IsPostCode (string postcode)
{
    return (
        Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][0-9][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)") ||
        Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][0-9][0-9][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)") ||
        Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][A-HK-Ya-hk-y][0-9][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)") ||
        Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][A-HK-Ya-hk-y][0-9][0-9][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)") ||
        Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][0-9][A-HJKS-UWa-hjks-uw][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)") ||
        Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][A-HK-Ya-hk-y][0-9][A-Za-z][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z{2}$)") ||
        Regex.IsMatch(postcode, "(^[Gg][Ii][Rr][]*0[Aa][Aa]$)")
        );
}

Visual Basic

Public Function IsPostCode(postcode As String) As Boolean
    Return (Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][0-9][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)") OrElse
                Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][0-9][0-9][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)") OrElse
                Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][A-HK-Ya-hk-y][0-9][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)") OrElse
                Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][A-HK-Ya-hk-y][0-9][0-9][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)") OrElse
                Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][0-9][A-HJKS-UWa-hjks-uw][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)") OrElse
                Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][A-HK-Ya-hk-y][0-9][A-Za-z][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)") OrElse
                Regex.IsMatch(postcode, "(^[Gg][Ii][Rr][]*0[Aa][Aa]$)"))
End Function

Happy coding!

OWIN and Facebook: the developers of this app have not set up this app properly for Facebook Login?

Facebook-error

Did you received this error when you try to login in your Owin app with Facebook?

App Not Set Up: This app is still in development mode, and you don't have access to it. Switch to a registered test user or ask an app admin for permissions.

Solution

  1. Go to https://developers.facebook.com/
  2. Click on the My Apps menu on the top bar and select your appFacebook-DeveloperThe circle next to your app name is not fully green. When you hover mouse on it, you'll see a popup saying, "Not available to all users because your app is not live." So next, you've to make it publicly available. Facebook-Developer_Dashboard
  3. Click on Setting at left panel Facebook-Developer_Settings
  4. In Basic tab add your "Contact Email" (a valid email address - I've added the one which I'm using with developers.facebook.com) and make "Save changes".
  5. Next click "Status & Review" at left panel
  6. Look for this, Do you want to make this app and all its live features available to the general public? and Turn ON the switch next to this. Facebook_Developer_Status_Review
  7. Confirm the question “Are you sure you want to make your app public? It will become available to everyone.”
  8. That's it! - App is now publicly available. See the fully green circle next to the app name.Facebook-Developer_AppPublish

Happy coding!

C# ASP.NET MVC OWIN and Twitter authentication error

We have an MVC project using OWIN Framework to allow our users to authenticate using Twitter.
However starting today, we have been getting this exception when trying to authenticate:

System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.

Thanks to the power of open source we can see that the thumbprints for the twitter certificates have been coded in the Katana Project.

Microsoft.Owin.Security.Twitter.TwitterAuthenticationOptions

Recently some certificates must have changed and now the thumbprints no longer match.

Please add a new thumb print for the "VeriSign Class 3 Public Primary Certification Authority - G5" Certificate to your Twitter Auth Options in your Startup.Auth.cs (for MVC users).

Change from the default:

app.UseTwitterAuthentication(
    consumerKey: "XXXX",
    consumerSecret: "XXX"
);

with:

app.UseTwitterAuthentication(new TwitterAuthenticationOptions
{
    ConsumerKey = "XXXX",
    ConsumerSecret = "XXXX",
    BackchannelCertificateValidator = 
      new Microsoft.Owin.Security.CertificateSubjectKeyIdentifierValidator(
        new[] {
        // VeriSign Class 3 Secure Server CA - G2
        "A5EF0B11CEC04103A34A659048B21CE0572D7D47",
        // VeriSign Class 3 Secure Server CA - G3
        "0D445C165344C1827E1D20AB25F40163D8BE79A5", 
        // VeriSign Class 3 Public Primary Certification Authority - G5
        "7FD365A7C2DDECBBF03009F34339FA02AF333133", 
        // Symantec Class 3 Secure Server CA - G4
        "39A55D933676616E73A761DFA16A7E59CDE66FAD", 
        // Symantec Class 3 EV SSL CA - G3
        "‎add53f6680fe66e383cbac3e60922e3b4c412bed", 
        // VeriSign Class 3 Primary CA - G5
        "4eb6d578499b1ccf5f581ead56be3d9b6744a5e5", 
        // DigiCert SHA2 High Assurance Server C‎A 
        "5168FF90AF0207753CCCD9656462A212B859723B",
        // DigiCert High Assurance EV Root CA 
        "B13EC36903F8BF4701D498261A0802EF63642BC3" 
      })
});

Happy coding!

ASP.NET MVC Return image dynamically drawn in controller

If you have problem returning dynamically drawn image from controller below informations may help. The task looks easy and should be achieved with this code:

public ActionResult Image(string text)
{
    //Create new image
    Image img = new Bitmap(100, 50);
    Graphics g = Graphics.FromImage(img);
            
    //Do some drawing
    Font font = new Font("Arial", 24);
    PointF drawingPoint = new PointF(10, 10);
            
    g.DrawString(text, font, Brushes.Black, drawingPoint);

    //Return Image
    MemoryStream ms = new MemoryStream();
    img.Save(ms, ImageFormat.Png);

    return new FileStreamResult(ms, "image/png");
}

 

Unfortunately this won't work. At least not in .NET 4.0. Perceptive person will notice that after writing image to the stream it position property isn't at the beginning and FileStreamResult apparently can't deal with this.

MVCImageDynamically

After reseting stream position everything works well (bold line).

using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

...

public ActionResult Hello(string text)
{
    //Create new image
    Image img = new Bitmap(100, 50);
    Graphics g = Graphics.FromImage(img);
            
    //Do some drawing
    Font font = new Font("Arial", 24);
    PointF drawingPoint = new PointF(10, 10);
            
    g.DrawString(text, font, Brushes.Black, drawingPoint);

    //Return Image
    MemoryStream ms = new MemoryStream();
    img.Save(ms, ImageFormat.Png);

    ms.Position = 0;

    return new FileStreamResult(ms, "image/png");
}

 

Additionally the view which asynchronously (but without ajax) retrieve image from our controller:

<div id="divResult"></div>

<input type="text" id="txtText" value="Hello" />

<input type="button" name="submit" onclick="javascript:Hello();" value="Draw" />

<script type="text/javascript">

function Hello()
{
    var link = '@Url.Content("~/Controller/Hello")';

    var txt = document.getElementById('txtText').value;

    link += '?';
    link += 'text=' + txt;

    document.getElementById('divResult').innerHTML = '<img src="' + link + '" alt="' + txt+ '" />';

    return false;
}

</script>

 

or you can you an action like:

<img src="@Url.Action("Hello", new { text = "Hello guys!" })" 
       alt="Image for Hello guys!" style="width: 250px;" />

 

Happy coding!

ASP.NET MVC OWIN and Microsoft account

  1. Register an app in the Microsot Account Developer Center

    Go to the Microsoft Account Developer Center and create a new application. After you have registered the application take note of the App ID and App Secret:

    Microsoft_Account_Developer_Center_PSCFYI

    Microsoft_Account_Developer_Center_PSCFYI_2
  2. Install the Nuget Package

    Install the Nuget Package which contains the Microsoft OAuth provider.

    Install-Package Microsoft.Owin.Security.MicrosoftAccount
  3. Register Provider

    Locate the file in your project called \App_Start\Startup.Auth.cs. Ensure that you have imported the Owin namespace:

    using Owin;

    In the ConfigureAuth method add the following lines of code:

    app.UseMicrosoftAccountAuthentication(
        clientId: "Your client ID", 
        clientSecret: "Your client secret");
  4. Advanced Configuration

    To use the advanced configuration options, be sure to use the Microsoft.Owin.Security.MicrosoftAccount namespace:

    using Microsoft.Owin.Security.MicrosoftAccount;
    Request extra permissions

    If no scope is specified, the Microsoft OAuth provider will request permissions for the wl.basic scope. If you would like to request any other scopes, your will need to pass these scopes in the Scope property. For example, to request the wl.calendars permission, you can register the Microsoft provider as per the following example:

    var options = new MicrosoftAccountAuthenticationOptions
    {
        ClientId = "Your client ID",
        ClientSecret = "Your client secret",
    };
    options.Scope.Add("wl.calendars");
    app.UseMicrosoftAccountAuthentication(options);

    For the full list of available permissions, see Scopes and permissions on the MSDN.

    Specify an alternative callback path

    By default the Microsoft provider will request Microsoft to redirect to the path /signin-microsoft after the user has signed in and granted permissions on Microsoft. You can specify an alternative callback path:

    var options = new MicrosoftAccountAuthenticationOptions
    {
        ClientId = "Your client ID",
        ClientSecret = "Your client secret",
        CallbackPath = new PathString("/oauth-redirect/microsoft")
    };
    app.UseMicrosoftAccountAuthentication(options);

    You need to also make sure that the Redirect URI of your application in the Microsoft Account Developer Center matches this new callback path.

    Retrieve access token and other user information returned from Microsoft

    You can retrieve the access token and other user information returned from Microsoft in the OnAuthenticated callback function which gets invoked after the user has authenticated with Microsoft:

    var options = new MicrosoftAccountAuthenticationOptions
    {
        ClientId = "Your client ID",
        ClientSecret = "Your client secret",
        Provider = new MicrosoftAccountAuthenticationProvider
        {
            OnAuthenticated = async context =>
            {
                // Retrieve the OAuth access token to store for subsequent API calls
                string accessToken = context.AccessToken;
    
                // Retrieve the user ID
                string microsoftUserId = context.Id;
    
                // Retrieve the user's full name
                string microsoftFullName = context.Name;
    
                // You can even retrieve the full JSON-serialized user
                var serializedUser = context.User;
            }
        }
    };
    app.UseMicrosoftAccountAuthentication(options);

Happy coding!

Adding MVC 5 Identity to our Existing Project

First of all to your solution from NuGet you have to execute the following command:

  • Install-Package EntityFramework (Entity Framework)
  • Install-Package EntityFramework.SqlServerCompact (Entity Framework SQL Server Compact)
  • Install-Package Microsoft.AspNet.Identity.Core (ASP.NET Identity Core)
  • Install-Package Microsoft.AspNet.Identity.EntityFramework (ASP.NET Identity EntityFramework)
  • Install-Package Microsoft.AspNet.Identity.Owin (ASP.NET Identity Owin)
  • Install-Package Microsoft.Owin.Security.Facebook (Owin.Security.Facebook)
  • Install-Package Microsoft.Owin.Security.Google (Owin.Security.Google)
  • Install-Package Microsoft.Owin.Security.MicrosoftAccount (Owin.Security.MicrosoftAccount)
  • Install-Package Microsoft.Owin.Security.Twitter (Owin.Security.Twitter)
  • Install-Package Microsoft.AspNet.WebApi.Client (ASP.NET Web API 2 Client)
  • Install-Package Microsoft.Owin.Host.SystemWeb (Owin.Host.SystemWeb)

That should be all the NuGet references you need to install. Now let’s create the files that make up Visual Studio 2013’s MVC 5 Web Application’s Account Login and Registration System.

We will start in the App_Start folder and make our way down.

Right click on App_Start folder and Add > Class. Name it: FilterConfig.cs
place the following code in your file:

using System.Web;
using System.Web.Mvc;
  
namespace PSC
{
   public class FilterConfig
   {
      public static void RegisterGlobalFilters(GlobalFilterCollection filters)
      {
         filters.Add(new HandleErrorAttribute());
      }
   }
}

Right click on App_Start folder and Add > Class. Name it: Startup.Auth.cs
Dont forget the dot between Startup & Auth “Startup.Auth.cs”
place the following code in your file:

using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;

namespace PSC
{
    public partial class Startup
    {
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Enable the application to use a cookie to store information for the signed in user
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login")
            });
            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            // clientId: "",
            // clientSecret: "");

            //app.UseTwitterAuthentication(
            // consumerKey: "",
            // consumerSecret: "");

            //app.UseFacebookAuthentication(
            // appId: "",
            // appSecret: "");

            //app.UseGoogleAuthentication();
        }
    }
}

The rest of the code for this project I am going to simply put in a .Zip file and let you install manually, because it is too much code to put on the tutorial. Simply extract the .zip file and copy the files from the Controllers folder to the controllers folder in your project, and so on.

So I simply opened up the folder of this Zip File and drag & Dropped them into the solution. I did not have to include the files, Visual Studio made them available upon dropping them in.

Ok we should have all of those files in the project now, go through each one and open them one by one and make sure there are no errors or squiggly lines. If we did our job at providing all of the right references before dropping these files in there should be no errors.

We still need to add one more file, we can do this manually. Right Click on the root directory and add a class. Name it Startup.cs Inside that file put the following code:

using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(PSC.Shorturl.Web.Startup))]
 namespace PSC
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}

That should allow us to build and run our project.

Now our project is working with Identity, OWIN, the account pages work, but we need a link in our navigation to them.

Remember to add _LoginPartial.cshtml somewhere in the layout!

PSC_Identity_Files.zip (10.8KB)

The current type, is an interface and cannot be constructed. Are you missing a type mapping?

You might have missed to register your Interface and class (which implements that inteface) registration in your code.

e.g if the error is
"The current type, xyznamespace. Imyinterfacename, is an interface and cannot be constructed. Are you missing a type mapping?"

Then you must register the class which implements the Imyinterfacename in the UnityConfig class in the Register method. Using the following code as an example

using System;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using PSC.Shorturl.Web.Business;
using PSC.Shorturl.Web.Business.Implementations;

namespace PSC.Shorturl.Web.App_Start
{
    /// 
    /// Specifies the Unity configuration for the main container.
    /// 
    public class UnityConfig
    {
        #region Unity Container
        private static Lazy container = new Lazy(() =>
        {
            var container = new UnityContainer();
            RegisterTypes(container);
            return container;
        });

        /// 
        /// Gets the configured Unity container.
        /// 
        public static IUnityContainer GetConfiguredContainer()
        {
            return container.Value;
        }
        #endregion

        /// Registers the type mappings with the Unity container.
        /// The unity container to configure.
        /// There is no need to register concrete types such as controllers or API controllers (unless you want to 
        /// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.
        public static void RegisterTypes(IUnityContainer container)
        {
            // NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.
            // container.LoadConfiguration();

            // TODO: Register your types here
            container.RegisterType();
        }
    }
}

Advertsing

125X125_06

TagCloud

MonthList

CommentList