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();
        }
    }
}

How to Convert an IP Address to IP Number in SQL

The process of converting an IP Address to an IP Number is relatively simple. For example take the IP Address 192.168.1.0 - To convert it to an IP Number you would do the following.

Number = (256*256*256*192) + (256*256*168) + (256*1) + (0)

Unfortunately MS SQL doesn't provide any native Split functionality to split the decimal separated ip address into the small pieces of data that we could easily work with. We thought we were going to have to do some nasty string dissection using Substring and CharIndex and then we stumbled upon the beautiful Parsename function. Apparently this function was originally designed to help developers navigate through the MS SQL naming structure (ie databasename.dbo.tablename). For our purposes it worked great to pull apart our decimal separated string so we could perform calculations on each piece of data.

update IPTable set IPNumber = 
      256 * 256 * 256 * CAST(PARSENAME(@ipaddress, 4) AS float) + 
      256 * 256 * CAST(PARSENAME(@ipaddress, 3) AS float) + 
      256 * CAST(PARSENAME(@ipaddress, 2) AS float) + 
      CAST(PARSENAME(@ipaddress, 1) AS float)

Happy coding!

Automatic Table of Contents

Any long page of content with distinct and well marked up content can benefit from a table to contents. A table of contents provides a quick way to jump down the page to the desired section. Of course you can create a table of contents manually, but it may be smart to build it dynamically on-the-fly with JavaScript. This is true for several reasons:

  • It's easier - write the JavaScript once and it can create the Table on Contents on every page you need it.
  • It's more reliable - the JavaScript isn't subject to authoring errors.
  • It's still accessible - A table of contents is good for the general concept of accessibility, but it is a bonus (not having it doesn't ruin the page) and nearly all screen readers run JavaScript.

This kind of thing has been done many times and many ways. But this time is ours! Plus it makes for a good tutorial.

HTML: Headers and IDs

A long page of different parts you wish to link to could be marked up a bunch of ways. Perhaps a FAQ page could be a <dl>. It could literally be <section> after <section>. In our case, we'll assume this structure:

<article>
   <h3 id="question-one">Title of Question</h3>
   <!-- whatever other content, probably some paragraphs and stuff. -->

   <h3 id="question-two">Another Question</h3>
   <!-- whatever other content, probably some paragraphs and stuff. -->

   <!-- etc -->
</article>

A perfectly legit page full of headers with IDs and the content between them. Note the ID's. They are unique, as any good ID ought to be. This is required because it gives us a link target.

A link like this:

<a href="#question-one">Link to Question One</a>

Will jump down the page when clicked until the element with the ID "question-one" is in view.

Building the Table of Contents with jQuery

Our goal is to inject HTML on the page in the form of a table of contents. Like this:

<nav role="navigation" class="table-of-contents">
  <h2>On this page:</h2>
  <ul>
    <li><a href="#question-one">Question One</a></li>
  </ul>
</nav>

Step 1: A string of HTML

We'll build this entirely dynamically. Perhaps it would be smart to use some kind of JavaScript templating for this. But hey, this is so simple, let's just build a big string and append that.

var ToC =
  "<nav role='navigation' class='table-of-contents'>" +
    "<h2>On this page:</h2>" +
    "<ul>";

Step 2: Loop through the headers

The <h3>'s on our page indicate each section we wish to link to, so we'll find them all with a jQuery selector, then loop through each of them.

$("article h3").each(function() {
  // loop
});

Step 3: Get the bits of data we need

We need 1) the text of each header, which we will turn into a link and 2) the ID of each header which we can turn into a href attribute for that link.

var el, title, link;

$("article h3").each(function() {
  el = $(this);
  title = el.text();
  link = "#" + el.attr("id");
});

Inside of that loop, "this" refers to the header element currently targeted, so to speak. we set "el" to a jQuery version of it, so we can use jQuery methods on it to extract that text and ID.


Step 4: Create a new list item and append to string

var newLine, el, title, link;

$("article h3").each(function() {
  el = $(this);
  title = el.text();
  link = "#" + el.attr("id");

  newLine =
    "<li>" +
      "<a href='" + link + "'>" +
        title +
      "</a>" +
    "</li>";

  ToC += newLine;
});

The "+=" there means "append this new string to the already existing string stored in this variable.


Step 5: Close the "template"

ToC +=
   "</ul>" +
  "</nav>";

Step 6: Inject HTML onto page

Now you'll need to decide just exactly where you want this newly formed table to contents to be injected onto the page. Putting at the top of the page is probably smart.

Our example uses <article> to wrap everything, so to inject at the top of that, we would do:

$("article").prepend(ToC);

In "real life", perhaps you'd target a header and use insertAfter or another of jQuery's fancy DOM insertion methods.

See the Pen Automatic Table of Contents by Enrico (@erossini) on CodePen.

MOBI Mime Type

How to setting IIS for .mobi extensions?

  1. Open IIS and click on its name

    IIS_Home

  2. Double click on MIME

    IIS_MIME

  3. Then right click and in the menu click on Add.

    IIS_MIME_Add

  4. Then add as file name extension .mobi and as MIME type application/x-mobipocket-ebook

Change a character in a list of list with PowerShell

How do I delete certain characters or replace certain characters with other characters by some batch file execution, for filenames of all files in a Windows folder in one go, is there a PowerShell command for that?

I've shown how to batch rename all the files and directories in the current directory that contain spaces by replacing them with _ underscores.

Dir | Rename-Item -NewName { $_.Name -replace "-", "_" }

Optionally, the Where-Object command can be used to filter out ineligible objects for the successive cmdlet (command-let). The following are some examples to illustrate the flexibility it can afford you:

To skip any document files

Dir |
Where-Object { $_.Name -notmatch "\.(doc|xls|ppt)x?$" } |
Rename-Item -NewName { $_.Name -replace " ","_" }

To process only directories (pre-3.0 version)

Dir |
Where-Object { $_.Mode -match "^d" } |
Rename-Item -NewName { $_.Name -replace " ","_" }

PowerShell v3.0 introduced new Dir flags. You can also use Dir -Directory there.

To skip any files already containing an underscore (or some other character)

Dir |
Where-Object { -not $_.Name.Contains("_") } |
Rename-Item -NewName { $_.Name -replace " ","_" }

Happy coding!

Advertsing

125X125_06





TagCloud

MonthList

CommentList