Wednesday, July 30, 2014

yet more PCI notes

  • This touches on the distinction between SAQ A and SAQ A-EP standards for PCI 3.0 compliance.
  • A QSA is a Quality Security Assessor. These individuals do the actual audits. Typically credit card companies themselves send the QSAs out and pressure others to get audited. Given the legal nature of PCI, the government certainly does not enforce it and the go live of PCI 3.0 on the first day of 2015 can't really mean anything in terms of new national law. The date and the standard that comes with it are all just the trappings of industry standardization.
  • This suggests that the magnetic strip on a credit card holds the cardholder's name, the card number, the expiration date, and the CVV, but not the zip code. Addendum 8/8/2014: My superior mentioned that the magnetic strip does NOT contain the CVV and instead has a different code that it uses. I suppose I do not know what is true.

Addendum 12/1/2014: A coworker found https://www.pcicomplianceguide.org/saq-a-vs-a-ep-what-e-commerce-merchants-service-providers-need-to-know-now/ which has yet more on SAQ A versus SAQ A-EP.

"tickle" as a slang term?

If you Google tickle scripts you'll find TCL which seems to be a specific language. What you will not find is another "slang" definition which I heard Jorge Luna vocalize during my time at AMD. In his version tickle scripts are scripts allowed by an application which come from its users at large. They are injected functionality by Average Joe User which is both allowed and run in good faith by the greater application which has an architecture not written or understood by Average Joe User which is now extended/augmented by Average Joe. A method signature which takes in a Func or an Action in a C# class library which is used as a third party library (.dll) in several other apps is asking to be tickled in this definition. Herein, an outsider may inject their own functionality.

I went to lunch with some of the guys from work yesterday and SQL joins came up in conversation.

  • This touches on Left and Right joins. A Left join will return all results in the first table (the table selected from) and may or may not return matches in the second table (the table joined) if they are there. The column values for the second table will just be empty if they cannot be brought back due to a lack of a dance partner. When people talk of Outer joins or Outer Left joins they just mean Left joins.
  • Apparently there is also a concept of a Right join which will bring back everything in the second table but only what rows it can for the first table.
  • An Inner join will bring back only rows wherein both tables have records.
  • This touches on Cross joins and these seem to take two different record sets and make records for every possible combination of a record from one set with a record from the other set. This is also called a Cartesian join. You get the same data back that you'd have in a matrix in a more sequential shape.

Addendum 8/24/2014: An ambiguous join wherein only the world join is specified in MSSQL does an inner join as it turn out and as further kicked around here. Perhaps my belief that "join" in a generic sense means "left join" is erroneous or of my out of date experience with MySQL.

Set the "Build Action" of an old school .hbm.xml NHibernate mapping file to "Embedded Resource" in the Properties pane in Visual Studio after selecting it in the Solution Explorer.

If you don't, the file will be worthless as a map.

Tuesday, July 29, 2014

Code first with NHibernate and Not.LazyLoad();

Here are some links I've bumped into of late in playing with NHibernate:

Sequence Diagrams

...are those charts which represent classes with vertical lines and show how a method in one class reaches out to another class by drawing horizontal lines with arrows (for the methods) from one vertical line to another. I drew up the sequence diagram below back in my Veterans Affairs days...

Checkmarx

...is a code analysis tool like HP Fortify. Checkmarx finds pitfalls which are not OWASP friendly, security holes, etc. This seems to have some marketing fluff on it.

create an "Application" in IIS

Right-click on the "Default Web Site" node and pick "Add Application..." to make an application. The name you pick for the "alias" is not a host header. It will just work without any DNS trickery. If you pick snafu for the alias then you should be able to "see" the application by going to "http://localhost/snafu/" at the PC at hand. At work my "web server" is a VM on my desktop and from my desktop I would be able to see into the snafu app at the VM with http://jaeschkedev.pmdev.local/snafu/ ...etc.

of Base64 encoding and Modified Base64 encoding

Base64 encoding is a way to encode a string. It's not encryption and thus one may turn around and decode that which is encoded. In Modified Base64 encoding, a Base64 encoded string has all of its forward slashes replaced with underscores and all of its plus symbols replaced with hyphens making it a whole lot more suitable for being passed as a variable at the URL line of a browser.

Monday, July 28, 2014

creating a successful parent-child relationship in Fluent NHibernate

After much heartache, I have finally figured out a way to do this. It is NOT trivial or easy in my opinion and I still wouldn't be surprised if someone else saw this blog posting and pointed out to me that I am yet doing it wrong. Anyways, let's go over what I have. I started with an application which successfully interfaced with one hydrated object called Record. The database was built form this SQL:

CREATE TABLE dbo.Record
   (
   Id uniqueidentifier NOT NULL,
   FirstInput varchar(255) NOT NULL,
   SecondInput varchar(255) NOT NULL,
   Multiplication varchar(255) NOT NULL,
   Time datetime NOT NULL
   ) ON [PRIMARY]
GO
ALTER TABLE dbo.Record ADD CONSTRAINT
   PK_Details PRIMARY KEY CLUSTERED
   (
   Id
   ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
   ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

 
 

Here is my object in C#:

using System;
namespace Yin.Core.Objects
{
   public class Record
   {
      public virtual Guid Id { get; set; }
      public virtual string FirstInput{ get; set; }
      public virtual string SecondInput { get; set; }
      public virtual string Multiplication { get; set; }
      public virtual DateTime Time { get; set; }
   }
}

 
 

...and here is my map:

using FluentNHibernate.Mapping;
using Yin.Core.Objects;
namespace Yin.Infrastructure.Map
{
   public class RecordMap : ClassMap<Record>
   {
      public RecordMap()
      {
         Id(x => x.Id);
         Map(x => x.FirstInput);
         Map(x => x.SecondInput);
         Map(x => x.Multiplication);
         Map(x => x.Time);
      }
   }
}

 
 

...and here is my repository:

using System.Collections.Generic;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using Yin.Core.Interfaces;
using Yin.Core.Objects;
namespace Yin.Infrastructure.Services
{
   public class RecordRepository : IRecordRepository
   {
      public List<Record> GetRecords()
      {
         List<Record> result = new List<Record>();
         using (var sessionFactory = CreateSessionFactory())
         {
            using (var session = sessionFactory.OpenSession())
            {
               foreach (Record record in session.CreateCriteria(typeof(Record)).List())
               {
                  result.Add(record);
               }
               return result;
            }
         }
      }
      
      public void WriteRecord(Record record)
      {
         using (var sessionFactory = CreateSessionFactory())
         {
            using (var session = sessionFactory.OpenSession())
            {
               using (var transaction = session.BeginTransaction())
               {
                  session.Save(record);
                  session.Flush();
                  transaction.Commit();
               }
            }
         }
      }
      
      private static ISessionFactory CreateSessionFactory()
      {
         return Fluently.Configure().Database(MsSqlConfiguration.MsSql2008
               .ConnectionString("server=JAESCHKEDB;database=Whatever;
               Trusted_Connection=Yes;")).Mappings(m => m.FluentMappings
               .AddFromAssemblyOf<RecordRepository>()).BuildSessionFactory();
      }
   }
}

 
 

I interact with the repository like this:

recordRepository.WriteRecord(record);
return ReturnAllRecordsSortedByTime(recordRepository);

 
 

...and this all works great! Alright, how may we get a Record to hold n number of SupportingNote types? Let's go over the SQL first. First and foremost this is NOT good SQL.

CREATE TABLE dbo.Record
   (
   Id uniqueidentifier NOT NULL,
   FirstInput varchar(255) NOT NULL,
   SecondInput varchar(255) NOT NULL,
   Multiplication varchar(255) NOT NULL,
   Time datetime NOT NULL
   ) ON [PRIMARY]
GO
ALTER TABLE dbo.Record ADD CONSTRAINT
   KeyOfRecord PRIMARY KEY CLUSTERED
   (
   Id
   ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
   ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
CREATE TABLE dbo.SupportingNote
   (
   AnotherId uniqueidentifier NOT NULL,
   Record_id uniqueidentifier NOT NULL,
   Information varchar(255) NOT NULL
   ) ON [PRIMARY]
GO
ALTER TABLE dbo.SupportingNote ADD CONSTRAINT
   KeyOfSupportingNote PRIMARY KEY CLUSTERED
   (
   AnotherId
   ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
   ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
ALTER TABLE dbo.SupportingNote ADD CONSTRAINT
   KeyOfCohesion FOREIGN KEY
   (
   Record_id
   ) REFERENCES dbo.Record
   (
   Id
   ) ON UPDATE NO ACTION
   ON DELETE NO ACTION
GO

 
 

What is wrong with it? The composite key. Do not create a parent-child association at SQL itself. This has been my biggest mistake from the beginning in working this stuff out. Here is a better way to go:

CREATE TABLE dbo.Record
   (
   Id uniqueidentifier NOT NULL,
   FirstInput varchar(255) NOT NULL,
   SecondInput varchar(255) NOT NULL,
   Multiplication varchar(255) NOT NULL,
   Time datetime NOT NULL
   ) ON [PRIMARY]
GO
ALTER TABLE dbo.Record ADD CONSTRAINT
   KeyOfRecord PRIMARY KEY CLUSTERED
   (
   Id
   ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
   ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
CREATE TABLE dbo.SupportingNote
   (
   AnotherId uniqueidentifier NOT NULL,
   Record_id uniqueidentifier NOT NULL,
   Information varchar(255) NOT NULL
   ) ON [PRIMARY]
GO
ALTER TABLE dbo.SupportingNote ADD CONSTRAINT
   KeyOfSupportingNote PRIMARY KEY CLUSTERED
   (
   AnotherId
   ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
   ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

 
 

Alright, let's step through everything in the refactoring. Record now looks like this:

using System;
using System.Collections.Generic;
namespace Yin.Core.Objects
{
   public class Record
   {
      public virtual Guid Id { get; set; }
      public virtual string FirstInput{ get; set; }
      public virtual string SecondInput { get; set; }
      public virtual string Multiplication { get; set; }
      public virtual DateTime Time { get; set; }
      public virtual IList<SupportingNote> SupportingNotes { get; set; }
   }
}

 
 

SupportingNote looks like this:

using System;
namespace Yin.Core.Objects
{
   public class SupportingNote
   {
      public virtual Guid AnotherId { get; set; }
      public virtual Record Record { get; set; }
      public virtual string Information { get; set; }
      public virtual Guid Record_id { get; set; }
   }
}

 
 

I'm not in love with the Record_id shape of the naming convention for a dance partner for a parent's id, but some errors I saw before I got everything working tipped me off that this was the default expectation for a name for a Guid tying a child back to a parent. It didn't try to fight it and find another way. I just went with it. My map for Record now looks like this:

using FluentNHibernate.Mapping;
using Yin.Core.Objects;
namespace Yin.Infrastructure.Map
{
   public class RecordMap : ClassMap<Record>
   {
      public RecordMap()
      {
         Id(x => x.Id);
         Map(x => x.FirstInput);
         Map(x => x.SecondInput);
         Map(x => x.Multiplication);
         Map(x => x.Time);
         HasMany(x => x.SupportingNotes).Cascade.All();
      }
   }
}

 
 

My map for SupportingNote:

using FluentNHibernate.Mapping;
using Yin.Core.Objects;
namespace Yin.Infrastructure.Map
{
   public class SupportingNoteMap : ClassMap<SupportingNote>
   {
      public SupportingNoteMap()
      {
         Id(x => x.AnotherId);
         Map(x => x.Information);
         Map(x => x.Record_id);
         References(oi => oi.Record, "Record_id").Not.Insert();
      }
   }
}

 
 

That .Not.Insert() is also supercritical. Moving on, the previous repository is revamped here:

using System.Collections.Generic;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using Yin.Core.Interfaces;
using Yin.Core.Objects;
namespace Yin.Infrastructure.Services
{
   public class RecordRepository : IRecordRepository
   {
      public List<Record> GetRecords()
      {
         List<Record> result = new List<Record>();
         using (var sessionFactory = CreateSessionFactory())
         {
            using (var session = sessionFactory.OpenSession())
            {
               foreach (Record record in session.CreateCriteria(typeof(Record)).List())
               {
                  List<SupportingNote> notes = new List<SupportingNote>();
                  foreach (SupportingNote supportingNote in record.SupportingNotes)
                  {
                     notes.Add(supportingNote);
                  }
                  result.Add(record);
               }
               return result;
            }
         }
      }
      
      public void WriteRecord(Record record)
      {
         using (var sessionFactory = CreateSessionFactory())
         {
            using (var session = sessionFactory.OpenSession())
            {
               using (var transaction = session.BeginTransaction())
               {
                  session.Save(record);
                  session.Flush();
                  transaction.Commit();
               }
            }
         }
      }
      
      private static ISessionFactory CreateSessionFactory()
      {
         return Fluently.Configure().Database(MsSqlConfiguration.MsSql2008
               .ConnectionString("server=JAESCHKEDB;database=Whatever;
               Trusted_Connection=Yes;")).Mappings(m => m.FluentMappings
               .AddFromAssemblyOf<RecordRepository>()).BuildSessionFactory();
      }
   }
}

 
 

Note that all I have to do to return the child objects here is wake them up from not being lazy loaded. I'm actually doing anything with the notes collection once I populate it! My new repository is given here:

using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using Yin.Core.Interfaces;
using Yin.Core.Objects;
namespace Yin.Infrastructure.Services
{
   public class SupportingNoteRepository : ISupportingNoteRepository
   {
      public void WriteRecord(SupportingNote supportingNote)
      {
         using (var sessionFactory = CreateSessionFactory())
         {
            using (var session = sessionFactory.OpenSession())
            {
               using (var transaction = session.BeginTransaction())
               {
                  session.Save(supportingNote);
                  session.Flush();
                  transaction.Commit();
               }
            }
         }
      }
      
      private static ISessionFactory CreateSessionFactory()
      {
         return Fluently.Configure().Database(MsSqlConfiguration.MsSql2008
               .ConnectionString("server=JAESCHKEDB;database=Whatever;
               Trusted_Connection=Yes;")).Mappings(m => m.FluentMappings
               .AddFromAssemblyOf<RecordRepository>()).BuildSessionFactory();
      }
   }
}

 
 

Yay! This all works! I interact with the repositories like so:

recordRepository.WriteRecord(record);
record.SupportingNotes = new List<SupportingNote>() {foo, bar};
supportingNoteRepository.WriteRecord(foo);
supportingNoteRepository.WriteRecord(bar);
return ReturnAllRecordsSortedByTime(recordRepository);

to attach an .mdf

  1. In Windows Server 2008 R2, I put the .mdf and .ldf at: C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA
  2. I right clicked on "Databases" in the Object Explorer of SSMS and I picked "Attach..." from the menu which appeared.

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.

This reveals that this "HTTP Error 500.23 - Internal Server Error" may be bested by placing...

<validation validateIntegratedModeConfiguration="false"/>

 
 

...in the system.webServer portion of Web.config.

another note about restoring a database from a .bak file

Appending to this I want to mention that I found the "Tasks" options for...

Tasks > Restore > Database...

 
 

...by right-clicking on a database in the Object Explorer of SSMS. When I completed a restore however, the guts of the .bak file did not end up in the database I right-clicked upon. Instead, a new database was created with a name defined by what was backed up to begin with.

If you comment on this blog do not put links in your comments.

I will not approve comments with links off to other sites in them. Do your own SEO. Do not piggyback onto mine.

Sunday, July 27, 2014

Is it ideal to keep one ISessionFactory open for a long life in an NHibernate application?

A friend gave me a link to this and it suggests as much. I have been opening and then disposing of a ISessionFactory every time go to the database not unlike a particular session, but I am learning that this is expensive! Perhaps a better way to go is to populate some static state for ISessionFactory at Application_Start() in Global.asax.cs and then use the singleton to get sessions in repositories.

When using an auto-incrementing integer with NHibernate as the unique id for both a C# object and a database table...

Prep the object just as you would an object that uses a Guid except:

  1. Use an integer.
  2. Do not specify the value when saving new objects.

 
 

When you fish objects back out of the database they will hold the appropriate id.

Use the prop-tab-tab-tab-tab trick for making auto-properties in Visual Studio.

  1. Set the cursor where a new auto-property is to be.
  2. Type "prop" for property.
  3. Press Tab.
  4. Type the name of the specific type.
  5. Press Tab twice.
  6. Type the name of the property.
  7. Press Tab one last time.

Saturday, July 26, 2014

strict chutzpah

I saw Ryan Vice give a talk on AngularJS on Monday at the Austin .NET User Group. His talk has been put up to UserGroup.tv by Shawn Weisfeld and you may certainly check it out there. It was a fairly straightforward "What is AngularJS?" talk. There were two interesting things that came up beyond Angular that I find fascinating enough to blog about here. The first is scoping strict mode like so:

(function() {
   'use strict';
   whatever();
})();

 
 

This will keep strict mode from breaking third party libraries in a scope beyond your own code. Ryan Vice offered that his idea comes from Chris Love who is working with Ryan on the team Chander Dhall spearheads at Dell. The other interesting thing beyond Angular that came up in this talk was the running of Jasmine scripts by ReSharper within Visual Studio. In these scenarios, Ryan had many commented out lines of code at the top of tests which looked like this:

/// <reference path="../Scripts/angular-resource.min.js" />

 
 

...which became "uncommented" at runtime as part of the Jasmine with ReSharper test-running process! Chutzpah will, per Ryan, empower this trick in build scripts too, but the powers that be at Dell do not allow its use there so his team has to embrace some creative workarounds instead.

Julia is supposed to do scientific computing with the ease of Phython or R but with the speed of C.

It's an interpreted scripting language as opposed to a compiled one.

  • Julia Ghoulia...

Thursday, July 24, 2014

Demandware

...is yet another way to do eCommerce.

some notes from work

Ways to approach Web API Security
There is a significant difference between MVC Controller types and ApiController types. The former has route-specific actions which may be named anything and the later has verb-specific actions named Get, Post, Put, or Delete. The former has access to session and cookies while the later does not. Cross-talk between an MVC Controller and an ApiController cannot rely upon session (or cookies) for authentication and authorization. So how should authentication and authorization behave?

  • state across a mishmash of session and cache
    Both an MVC Controller and an ApiController may access the cache. The cache is globally accessible without regard to who the user is or which browser at which IP is reaching in. In order to store user specifications in the cache that are not exposed to all users, the key for the cache may be session driven. An ApiController cannot use session, but the key could be handed in to all ApiController actions from the greater MVC application. (There is the assumption here that all controllers, both MVC and Web API, will be kept in the same application at the same subdomain, for as much is a requirement.) A cache entry containing a user's credentials would, for security sake, need a terse (perhaps twenty minutes) time to live before expiration, but the cache setting for a user could also be constantly recreated whenever a new MVC Controller action was hit so that the lifespan of the relevant piece of the cache was bound to the life of the session. Where session was available, an AOP process could, before executing an MVC Controller action, check to see if a unique key (perhaps a GUID) for the session existed and make one should it be lacking. Such an AOP process would also upkeep the cache entry made with the session-specific key, tucking an object inside to represent a user's identity (perhaps an IPrincipal).
     
  • state communicated by web tokens
    MVC controllers may hand Simple Web Token (SWT) type tokens into the Web API to communicate whom the user is. A symmetrical key (same at both the sender and the receiver) would need to kept at both the server and receiver for decoding the messages, but assuming that all MVC and Web API controllers were kept in the same application at the same subdomain, such a key could just be kept in cache for all controllers to reference. Replacement keys would need to be regularly rolled out in the name of security.
     
  • OAuth 2.0
    Complicated mechanics which could not exist independent of a different single sign on implementation (such as Thinktecture's) without clumsy architecture, are offered in the OAuth 2.0 security specification. As this is envisioned to work, a user will have two independent logins at two applications and need the first application to have limited API access to the second while not desiring to outright store the second applications login credentials at the first app. An HMAC (Keyed-Hashing for Message Authentication) token is procured from an authentication server (perhaps Google or Facebook) and used by one application to access another application via an API with selective, context-appropriate permissions. The first app must advertise its own credentials to the authentication server, but the second app does not necessarily need to do so. The credentials affirm that the token, carrying merely a username and some metadata, does not need to be validated every time it is used with a check against a data store. The authorization server then hands the first app an authorization code and the app redirects to the login screen of the second application where the authorization code appears as a variable at the URL. The second app may use the code to know a few things about the process at hand, including the need to redirect back to the first app after granting permission (by way of login) to use the access token.
    In the OAuth 2.0 approach the way in which the access token is validated by the second application at the authorization server is not set in stone. Different implementations may take different approaches. The application giving its credentials to the authorization server, the client, may be given a refresh token at the same time it receives an access token. Access tokens will be short lived while the refresh tokens offer a means to get new access tokens without resubmitting log in credentials. The preceding description of OAuth 2.0 comes from Pro ASP.NET Web API Security by Badrinarayanan Lakshmiraghavan who compares access tokens to valet keys, keys which may open the car door and turn the ignition without allowing access to the glove box or trunk, i.e. keys for a very specific role in contrast to keys which allow blanket access to every lock (which are akin to the direct logins at the "second application" in the example above). Again, one of the goals of OAuth 2.0 is to prevent the exposure of unfettered access to a dependency to a depending party.

Wednesday, July 23, 2014

Why can't I reference a .dll in a C# console app in Visual Studio?

This suggests the fix is:

  1. right-clicking on the console project in the Solution Explorer and picking properties
  2. look at "Target Framework" at the "Application" tab within the properties
  3. look for where it says ".NET Framework 4.0 Client Profile" and change that to ".NET Framework 4.0" or ".NET Framework 4.5.1" instead

 
 

The ".NET Framework 4.0 Client Profile" setting will most likely rear its ugly head by default in Visual Studio 2010 methinks.

Why can't I use a local database with Microsoft SQL Server 2014 Express?

Well, maybe you just got a watered-down version of the installer that doesn't have that option. If you go here and then click "Download" and finally pick "MgmtStudio 64BIT\SQLManagementStudio_x64_ENU.exe" from the list of checkboxes which appears, you will get just such a watered-down installer. It is instead better to use "ExpressAndTools 64BIT\SQLEXPRWT_x64_ENU.exe" and then when you run the installation you should see a checkbox for "LocalDB" like so:

 
 

Afterwards, there will be a step called "Instance Configuration" where you may name the instance. The default is: SQLEXPRESS

 
 

When it's all done, you should be able to connect to:

YOURCOMPUTERNAMEHERE\SQLEXPRESS

Solution not showing in Visual Studio 2010's Solution Explorer?

Just your single project shows right? Yuck. Well, if you can add a second project to the solution, both projects and the solution will appear in the solution explorer and all will be well. To do this, add a project from the File menu at the upper right. When adding the project, you will have to change this drop down to "Add to solution" or else you'll end up making a new solution holding the new project.

Addendum 7/24/2014: I tried this again just tonight and had trouble duplicating the means for adding a project. I was able to add a project by going to: File > Add > New Project...

Debug a WCF web service in Visual Studio 2013?

Well, I found one way to do it. You may set up your uncompiled code as a web site in IIS and then hit the endpoints at the web service from another app to test. If you use this plugin you should be able to pick "Attach to IIS" from the "TOOLS" menu to debug the WCF solution at the IIS web site. Again, you can "touch it" from a different Visual Studio project which just hits the endpoints at IIS. You'll be able to hit a breakpoint back in Visual Studio at the WCF app.

Tuesday, July 22, 2014

I continue to believe that I've onto something in using a mishmash of session and cache to share a user's identity across both MVC Controller and ApiController type controllers.

I wanted to reset the cache's twenty minutes to live, as specified in the example I give here, every time a user changed actions in an MVC Controller. I wanted to set up something AOPesque to do so. I'm not in love with what I have so far, but I have refactored my HomeController to inherit from a base controller called BaseController and look like this:

using System.Security.Principal;
using System.Web.Mvc;
using Security.Utilities;
namespace Security.Controllers
{
   public class HomeController : BaseController
   {
      public ActionResult Index(string id)
      {
         Aop();
         if (id != null)
         {
            GenericIdentity genericIdentity = new GenericIdentity(id);
            GenericPrincipal genericPrincipal = new GenericPrincipal(genericIdentity, new
                  string[] { "User" });
            IdentityUtility.SetIdentity(genericPrincipal, ViewBag.SessionKeyForIdentity);
         }
         return View();
      }
   }
}

 
 

Here is my base controller which every MVC Controller would inherit from and from which every MVC Controller Action would have to call the Aop method upon. This isn't too elegant. I wanted put this code inside an OnActionExecuting inside an ActionFilterAttribute, but it seems that session isn't available there. Boo.

using System;
using System.Threading;
using System.Web.Mvc;
using Security.Utilities;
namespace Security.Controllers
{
   public class BaseController : Controller
   {
      protected void Aop()
      {
         string _sessionKeyForIdentity = "sessionkeyforidentity";
         if (Session[_sessionKeyForIdentity] == null)
         {
            string randomString = RandomStringUtility.GetRandomString();
            Session[_sessionKeyForIdentity] = randomString;
         }
         ViewBag.SessionKeyForIdentity = Session[_sessionKeyForIdentity] as String;
         IdentityUtility.RefreshIdentity(ViewBag.SessionKeyForIdentity);
         IdentityUtility.SetIdentity(Thread.CurrentPrincipal, ViewBag.SessionKeyForIdentity);
      }
   }
}

 
 

The attribute-based approach which I wasn't able to be working would have entailed setting up a class like this with some more substantive mechanics.

using System.Web.Mvc;
namespace Security.Utilities
{
   public class MyAttribute : ActionFilterAttribute
   {
      public override void OnActionExecuting(ActionExecutingContext filterContext)
      {
         string breakpoint = "whatever";
      }
   }
}

The sandbox attribute on an iFrame...

...may forbid the content in the iFrame from affecting the web page hosting it like so:

<iframe src="http://www.example.com/" sandbox=""></iframe>

 
 

...or may be empowered to like so:

<iframe src="http://www.example.com/" sandbox="allow-same-origin"></iframe>

 
 

http://www.w3schools.com/tags/att_iframe_sandbox.asp has more on this.

OPTIONS and HEAD in the ASP.NET Web API

The verbs POST, GET, PUT, and DELETE seem more or less, in my impression, to correspond to the C, the R, the U, and the D in CRUD (create, read, update, and delete) respectively in Roy Fielding's vision for REST. But there are a few other request methods one may utilize per this, and two of them seem to work with the ASP.NET Web API. I did some experimenting just now (in each case trying to specify an item below as an all-caps verb in a jQuery .ajax type parameter while reaching out from the jQuery .ajax implementation to an ApiController method with the same name in Pascal Case which returns a string) and here is what I found:

  1. OPTIONS works perfectly. This is legit! Variables may be handed to the method and one may get a result back. There are no errors.
  2. HEAD lets you reach the ApiController method and hand variables into there, (I know because I set a breakpoint) but you will not get a result back at the jQuery side. This suggests that is perfectly normal and that HEAD is not meant to return stuff in REST. There is not an error in the console on the JavaScript side. The result just comes back as undefined if you try to catch one.
  3. TRACE does nothing. I set a breakpoint in the ApiController and I could not reach it. No error is written to the console and there is also not an ASP.NET exception thrown. We just silently fail.
  4. CONNECT does nothing too. No errors are thrown in either C# or JavaScript, but no code on the C# is ever reached and thus no result is ever returned. This type and the last one do the same sort of nothing.
  5. AMPUTATE throws a "405 (Method Not Allowed)" error up to the console. You cannot invent your own verb.

Addendum 12/17/2014: Some of the verbs which seems to do nothing may just be turned off at the web server (Cassini). I dunno.

Monday, July 21, 2014

Internet Explorer 9 will automatically start up in the "Internet Explorer 9 Compatibility View" Browser Mode instead of the "Internet Explorer 9" Browser Mode when viewing an intranet site.

Yuck.

.getJSON in jQuery

Ooi Soon Hong, a former colleague at AMD, suggested that he prefers to use .getJSON when he can instead of .ajax. Intrigued, I decided I'd try to refactor the following .ajax implementation in this application to a .getJSON implementation.

<button id="touchme">touch me</button>
<div id="response"></div>
@section scripts
{
   <script language="javascript">
      $('#touchme').bind('click', function () {
         $.ajax({
            type: "POST",
            url: "/api/values?magicstring=@ViewBag.SessionKeyForIdentity",
            dataType: "json",
            success: function (result) {
               $("#response").html(result);
            }
         });
      });
   </script>
}

 
 

I ended up with this:

<button id="touchme">touch me</button>
<div id="response"></div>
@section scripts
{
   <script language="javascript">
      $('#touchme').bind('click', function () {
         $.getJSON("/api/values?magicstring=@ViewBag.SessionKeyForIdentity",
               function(result){
            $("#response").html(result);
         });
      });
   </script>
}

 
 

In order for this to work in the previous code I wrote, I had to change the Post method in ValuesController to be a Get method, but that was really more appropriate anyways truth be told.

UNIX time is represented by a single integer that carries the number of seconds that have elapsed since the beginning of 1970 in UTC time.

I am learning of this today in reading about SWT (Simple Web Token) name-value pairs in chapter 10 of Pro ASP.NET Web API Security by Badrinarayanan Lakshmiraghavan. http://www.unixtimestamp.com/index.php has the current time (although you cannot watch it increment in front of you, you have to refresh the browser to see it change) and http://thedude.com/2009/02/unix-time-milestone/ suggests that at 23:31:30 UTC time on 2/13/2009 the time was: 1234567890 ...anyways, you may fish for this stuff in C# like so:

DateTime nineteenSeventy = new DateTime(1970,1,1,0,0,0,0,DateTimeKind.Utc);
TimeSpan timeOnUnixClock = DateTime.UtcNow - nineteenSeventy;
ulong currentUnixTime = Convert.ToUInt64(timeOnUnixClock.TotalSeconds);
ulong halfHourFromNow = currentUnixTime + 1800;

Thinktecture has a way to do Single Sign-on

It should be open source too. This came up at work today. Some links:

Saturday, July 19, 2014

Azure Redis Cache

Has been mentioned to me at Twitter (by @red_square) as the way to mangage the cache in C# at an application shared across numerous VMs (the cloud). I don't know anything about it yet. Some links:

 
 

Cache and Session will both get jacked in an application not hosted by a single environment.

how to get a WCF web service working in a class library project and not your UI project

At first I tried this:

using Yin.Core.Interfaces;
using Yin.Infrastructure.CalculatorServiceReference;
namespace Yin.Infrastructure.Services
{
   public class MathService : IMathService
   {
      public string Multiply(string firstInput, string secondInput)
      {
         ICalculatorInTheSky calculator = new CalculatorInTheSkyClient();
         Calculation calculation = calculator.Act(firstInput, secondInput);
         return calculation.Result;
      }
   }
}

 
 

And it gave me this error:

Could not find default endpoint element that references contract 'CalculatorServiceReference.ICalculatorInTheSky' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.

 
 

I tried setting up the same service reference in Yin.UserInterface instead of Yin.Infrastructure and it worked like a champ there. So what was different? The difference per this is that while there are some notes about how the service reference should work in the Web.config which will get seen and used at runtime for the Yin.UserInterface implementation, the comparable markup at the app.config in the Yin.UserInterface project will never be looked at at runtime! Boo! I then circled back to this which told how to compensate for what lacked. I refactored my way to success like so:

using System.ServiceModel;
using Yin.Core.Interfaces;
using Yin.Infrastructure.CalculatorServiceReference;
namespace Yin.Infrastructure.Services
{
   public class MathService : IMathService
   {
      public string Multiply(string firstInput, string secondInput)
      {
         BasicHttpBinding basicHttpbinding = new
               BasicHttpBinding(BasicHttpSecurityMode.None);
         basicHttpbinding.Name = "BasicHttpBinding_YourName";
         basicHttpbinding.Security.Transport.ClientCredentialType =
               HttpClientCredentialType.None;
         basicHttpbinding.Security.Message.ClientCredentialType =
               BasicHttpMessageCredentialType.UserName;
         EndpointAddress endpointAddress = new
               EndpointAddress("http://yang/CalculatorInTheSky.svc");
         ICalculatorInTheSky calculator = new CalculatorInTheSkyClient(basicHttpbinding,
               endpointAddress);
         Calculation calculation = calculator.Act(firstInput, secondInput);
         return calculation.Result;
      }
   }
}

 
 

Also, note that whenever I have used Ying and Yang in previous examples it has been inappropriate. It is supposed to be Yin and Yang not Ying and Yang. This is as stupid as using effect instead of affect. Weird Al would hit me with a crowbar I think.

Friday, July 18, 2014

Use the data parameter in jQuery's .ajax to bind to a specific C# type in an ASP.NET Web API implementation.

Let's refactor the application I explain here to bind to a new type which looks like this:

using System;
namespace Security.Models
{
   public class Stuff
   {
      public string RandomGibberish { get; set; }
      public DateTime MomentInTime { get; set; }
   }
}

 
 

I have changed up Index.cshtml to look like so:

@using Security.Utilities
<button id="touchme">touch me</button>
<div id="response"></div>
@section scripts
{
   <script language="javascript">
      $('#touchme').bind('click', function () {
         $.ajax({
            type: "POST",
            url: "/api/values",
            dataType: "json",
            data: {
               RandomGibberish: '@ViewBag.SessionKeyForIdentity',
               MomentInTime: '@TimeUtility.GetTime()'
            },
            success: function (result) {
               $("#response").html(result);
            }
         });
      });
   </script>
}

 
 

I have changed up ValuesController also. It looks like this:

using System;
using System.Security.Principal;
using System.Threading;
using System.Web.Http;
using Security.Models;
using Security.Utilities;
namespace Security.Controllers
{
   public class ValuesController : ApiController
   {
      public string Post([FromBody] Stuff stuff)
      {
         try
         {
            IdentityUtility.RefreshIdentity(stuff.RandomGibberish);
            IPrincipal principal = Thread.CurrentPrincipal;
            if (String.IsNullOrEmpty(principal.Identity.Name))
            {
               return "The current user is anonymous.";
            } else {
               return "The current user is: " + principal.Identity.Name + "!";
            }
         }
         catch(Exception exception)
         {
            return "Error at " + stuff.MomentInTime + ": " + exception.Message;
         }
      }
   }
}

 
 

Nice.

concatenating URL variables in jQuery's .ajax and keeping user identities in C#'s cache

Here, I flirt with the idea of making a user's credentials accessible to both MVC Controller and ApiController types in an ASP.NET MVC Web API application while using a session-specific magic string to differentiate users. I don't know yet if this is a bad idea or not. Please feel free to put your hand up if this sucks. Anyhow, I have something minimalistic afloat. I start off by just making the default ASP.NET MVC Web API application which Visual Studio 2013 makes. I then dress up the Index.cshtml view as suggested here, however, some of what I originally had in Index.cshtml is bad and, moreover, it would need to be changed up further even if it wasn't flawed to begin with. I better version of Index.cshtml is:

<button id="touchme">touch me</button>
<div id="response"></div>
@section scripts
{
   <script language="javascript">
      $('#touchme').bind('click', function () {
         $.ajax({
            type: "POST",
            url: "/api/values?magicstring=@ViewBag.SessionKeyForIdentity",
            dataType: "json",
            success: function (result) {
               $("#response").html(result);
            }
         });
      });
   </script>
}

 
 

The "url" value in the .ajax implementation has a variable appended to it named magicstring which will populate the magicstring variable here:

using System;
using System.Security.Principal;
using System.Threading;
using System.Web.Http;
using Security.Utilities;
namespace Security.Controllers
{
   public class ValuesController : ApiController
   {
      public string Post(string magicstring)
      {
         try
         {
            IdentityUtility.RefreshIdentity(magicstring);
            IPrincipal principal = Thread.CurrentPrincipal;
            if (String.IsNullOrEmpty(principal.Identity.Name))
            {
               return "The current user is anonymous.";
            } else {
               return "The current user is: " + principal.Identity.Name + "!";
            }
         }
         catch(Exception exception)
         {
            return exception.Message;
         }
      }
   }
}

 
 

If the method signature were to read (string magicstring, string othermagicstring) then the .ajax implementation could feed in the two variables like this:

url: "/api/values?magicstring=@ViewBag.SessionKeyForIdentity&othermagicstring=foo",

 
 

If you are wondering what @ViewBag.SessionKeyForIdentity is, here is my other controller:

using System;
using System.Security.Principal;
using System.Web.Mvc;
using Security.Utilities;
namespace Security.Controllers
{
   public class HomeController : Controller
   {
      public const string _sessionKeyForIdentity = "sessionkeyforidentity";
      
      public ActionResult Index(string id)
      {
         if (Session[_sessionKeyForIdentity] == null)
         {
            string randomString = RandomStringUtility.GetRandomString();
            Session[_sessionKeyForIdentity] = randomString;
         }
         ViewBag.SessionKeyForIdentity = Session[_sessionKeyForIdentity] as String;
         if (id != null)
         {
            GenericIdentity genericIdentity = new GenericIdentity(id);
            GenericPrincipal genericPrincipal = new GenericPrincipal(genericIdentity, new
                  string[] { "User" });
            IdentityUtility.SetIdentity(genericPrincipal, ViewBag.SessionKeyForIdentity);
         }
         return View();
      }
   }
}

 
 

The above allows for corny mechanics for either setting the user's identity or not doing so. Do you see how the two controllers now share a session-specific magic string? I have three static utilities to round out my code. You really only need to care about the first one though. Here it is:

using System;
using System.Runtime.Caching;
using System.Security.Principal;
using System.Threading;
namespace Security.Utilities
{
   public static class IdentityUtility
   {
      private static ObjectCache _objectCache{ get { return MemoryCache.Default; } }
      
      public static void RefreshIdentity(string sessionKeyForIdentity)
      {
         if (_objectCache[sessionKeyForIdentity] != null)
         {
            IPrincipal principal = _objectCache[sessionKeyForIdentity] as IPrincipal;
            Thread.CurrentPrincipal = principal;
         }
      }
      
      public static void SetIdentity(IPrincipal principal, string sessionKeyForIdentity)
      {
         if (_objectCache[sessionKeyForIdentity] != null)
         {
            _objectCache.Remove(sessionKeyForIdentity);
         }
         CacheItemPolicy cacheItemPolicy = new CacheItemPolicy();
         DateTime twentyMinutesIntoTheFuture = TimeUtility.GetTime().AddMinutes(20);
         cacheItemPolicy.AbsoluteExpiration = twentyMinutesIntoTheFuture;
         _objectCache.Add(new CacheItem(sessionKeyForIdentity, principal),
               cacheItemPolicy);
         Thread.CurrentPrincipal = principal;
      }
   }
}

 
 

Another, less exotic utility follows. This is not how I really recommending walling of the external dependency of timekeeping, but at least I have it marginally isolated.

using System;
namespace Security.Utilities
{
   public static class TimeUtility
   {
      public static DateTime GetTime()
      {
         return DateTime.UtcNow;
      }
   }
}

 
 

Here is my last utility. This is also goofy like the file before it. These last two files aren't really what I was trying to show off in this blog posting.

using System;
namespace Security.Utilities
{
   public static class RandomStringUtility
   {
      public static string GetRandomString()
      {
         return Guid.NewGuid().ToString().Replace("-", "") +
               Guid.NewGuid().ToString().Replace("-", "");
      }
   }
}

Thursday, July 17, 2014

When JavaScript seems outright sabotaged across the board in Internet Explorer...

...it's probably your security. Go to "Internet options" under the "Tools" menu and then go the "Security" tab in the "Internet Options" dialog box which appears. Finally, add your site to "Trusted sites."

Compatibility View in Internet Explorer

...was first introduced in IE8. One could go into the F12 tools to emulate older versions of Internet Explorer.

 
 

...and, yes, one may still do this in IE11, it just looks a little bit different now. When one talks about compatibility view, this is what is meant. There is a historical context. It's not really called compatibility view anymore.

I'm realizing now that something put into the cache in C# is globally accessible to every browser hitting the web application.

It's really the wrong place to keep user identity data. In an ASP.NET MVC Web API implementation, perhaps one could use Session in an MVC Controller to keep a key (in the shape of a GUID perhaps) for a user. This Session unique key could then be used to put stuff into the cache and fish it back out again. The Session unique key would have to be explicitly handed into an ApiController as a variable for there is no Session to be had there. Hmmm. How to share user identity between MVC Controllers and ApiControllers painlessly? Tricky challenge.

Service Unavailable HTTP Error 503. The service is unavailable.

...might just mean that your Application Pool is stopped in IIS. Duh!

Do not confuse data with dataType in jQuery's .ajax.

Per this, in these two example, data should really by dataType to denote json or html.

  1. http://tom-jaeschke.blogspot.com/2014/07/caching-views-which-will-never-change.html
  2. http://tom-jaeschke.blogspot.com/2014/07/do-you-keep-moving-scriptsrenderbundles.html

I screwed up as data (not dataType) is used to pass a JSON object which is not what I intended to do in either scenario.

Wednesday, July 16, 2014

IPrincipal!

One may make an IPrincipal like so:

GenericIdentity id = new GenericIdentity("Tom Jaeschke");
string[] roles = { "Tinker", "Tailor", "Soldier", "Sailor" };
GenericPrincipal part = new GenericPrincipal(id, roles);
SetPrincipal(part);

 
 

SetPrincipal in the example above might do this:

private void SetPrincipal(IPrincipal principal)
{
   Thread.CurrentPrincipal = principal;
   if (HttpContext.Current != null)
   {
      HttpContext.Current.User = principal;
   }
}

 
 

Taking stuff in and out of Thread.CurrentPrincipal might be a good way to manage who is logged in in a traditional web app where the UI has only one thread. In an ASP.NET Web API application however a MVC Controller and an ApiController are not going to have the same thread as the Web API methods may are returned asynchronously.

There are some diagnostics tricks which are the other new feature in C# 5.0 beyond async.

If one bolts...

, [CallerMemberName] string methodName = null, [CallerFilePath] string sourceFile = null,
      [CallerLineNumber] int lineNumber = 0

 
 

...into the end of a method or constructor signature, one will find that the methodName, sourceFile, and lineNumber variables get populated with details revealing what called the method. The name of the method will be in the methodName, the line number within the applicable file will be in lineNumber, and the full path to said file will be in sourceFile. Here is an example of usage. Let's say we have a class like so:

using System.Drawing;
namespace Security.Models
{
   public class Cat
   {
      public string Name { get; set; }
      public Color[] Colors { get; set; }
      
      public Cat()
      {
      }
      
      public Cat(string name, Color color)
      {
         Name = name;
         Colors = new Color[] {color};
      }
   }
}

 
 

If we were to refactor it to be like so...

using System.Drawing;
using System.Runtime.CompilerServices;
namespace Security.Models
{
   public class Cat
   {
      public string Name { get; set; }
      public Color[] Colors { get; set; }
      
      public Cat()
      {
      }
      
      public Cat(string name, Color color, [CallerMemberName] string methodName = null,
            [CallerFilePath] string sourceFile = null, [CallerLineNumber] int lineNumber = 0)
      {
         Name = name;
         Colors = new Color[] {color};
      }
   }
}

 
 

...and then:

  • make a new Cat in another place in code using the second constructor
  • set a breakpoint in Cat's second constructor
  • run the application until you hit the breakpoint

 
 

...we may mouse over the variables in the second constructor's signature to get at the data points. If you don't want to troubleshoot on the fly, perhaps these variables could be integrated into your logging.

Do you keep moving @Scripts.Render("~/bundles/jquery") above @RenderBody() in _Layout.cshtml?

Don't do this. Instead, use the scripts section in an ASP.NET MVC Web API application's view to put jQuery mechanics at the end of the HTML generated. Let me explain what I mean. If you spin up a new instance of an ASP.NET MVC Web API application in Visual Studio 2013, you will notice that _Layout.cshtml starts off like so...

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
   <meta name="viewport" content="width=device-width" />
   <title>@ViewBag.Title</title>
   @Styles.Render("~/Content/css")
   @Scripts.Render("~/bundles/modernizr")
</head>

 
 

...and ends like so:

   @Scripts.Render("~/bundles/jquery")
   @Scripts.Render("~/bundles/bootstrap")
   @RenderSection("scripts", required: false)
</body>
</html>

 
 

Yet, if you are like me, you are going to end up doctoring up _Layout.cshtml so that it starts like so...

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
   <meta name="viewport" content="width=device-width" />
   <title>@ViewBag.Title</title>
   @Styles.Render("~/Content/css")
   @Scripts.Render("~/bundles/modernizr")
   @Scripts.Render("~/bundles/jquery")
</head>

 
 

...and ends like so:

   @Scripts.Render("~/bundles/bootstrap")
   @RenderSection("scripts", required: false)
</body>
</html>

 
 

This change allows one to have a view like this...

<button id="touchme">touch me</button>
<div id="response"></div>
<script language="javascript">
   $('#touchme').bind('click', function() {
      $.ajax({
         type: "POST",
         url: "/api/values/",
         data: 'json',
         success: function (result) {
            $("#response").html(result);
         }
      });
   });
</script>

 
 

...without a JavaScript error being thrown to the console decrying an inability to interpret the dollar sign. This change allows your jQuery code to come after the script tag for jQuery within the HTML that is made which is a necessity if your jQuery code is to work. However instead of moving the jQuery script tag about your jQuery code, you may just place your jQuery code below the jQuery script tag which is normally going to get written at the end of the HTML. If you think about it, like I finally did, this is probably what Microsoft intended, you know? You may just use the scripts section in a view to write content to the point in _Layout.cshtml where @RenderSection("scripts", required: false) sits, which is, by default, below where the jQuery bundle is called for. Make sense? Just do something like so:

<button id="touchme">touch me</button>
<div id="response"></div>
@section scripts
{
   <script language="javascript">
      $('#touchme').bind('click', function () {
         $.ajax({
            type: "POST",
            url: "/api/values/",
            data: 'json',
            success: function (result) {
               $("#response").html(result);
            }
         });
      });
   </script>
}

 
 

Addendum 7/17/2014: My use of data instead of dataType in the jQuery .ajax implementation within this blog posting is inappropriate. I should have used dataType. Please see this.

Tuesday, July 15, 2014

Remove duplicates in Excel

  1. make a selection
  2. go to the "DATA" tab
  3. click the "Advanced" button by the "Filter" button
  4. in the "Advanced Filter" dialog box check the "Unique records only" checkbox
  5. copy your list elsewhere with the power of the "Advanced Filter" dialog box

When handing a payment to a credit card processor you will likely have to specify a currency code.

This has the following pretty good cheat sheet of codes:

 Arab Emirates Dirham  AED 
 Afghanistan Afghani  AFN 
 Albanian Lek  ALL 
 Armenian Dram  AMD 
 Netherlands Antillean Guilder  ANG 
 Angolan Kwanza  AOA 
 Argentine Peso  ARS 
 Australian Dollar  AUD 
 Aruban Guilder  AWG 
 Azerbaijan New Manat  AZN 
 Marka  BAM 
 Barbados Dollar  BBD 
 Bangladeshi Taka  BDT 
 Bulgarian Lev  BGN 
 Bahraini Dinar  BHD 
 Burundi Franc  BIF 
 Bermudian Dollar  BMD 
 Brunei Dollar  BND 
 Boliviano  BOB 
 Brazilian Real  BRL 
 Bahamian Dollar  BSD 
 Bhutan Ngultrum  BTN 
 Botswana Pula  BWP 
 Belarussian Ruble  BYR 
 Belize Dollar  BZD 
 Canadian Dollar  CAD 
 Francs  CDF 
 Swiss Franc  CHF 
 Chilean Peso  CLP 
 Yuan Renminbi  CNY 
 Colombian Peso  COP 
 Costa Rican Colon  CRC 
 Cuban Peso  CUP 
 Cape Verde Escudo  CVE 
 Czech Koruna  CZK 
 Djibouti Franc  DJF 
 Danish Krone  DKK 
 Dominican Peso  DOP 
 Algerian Dinar  DZD 
 Ecuador Sucre  ECS 
 Egyptian Pound  EGP 
 Eritrean Nakfa  ERN 
 Ethiopian Birr  ETB 
 Euro  EUR 
 Fiji Dollar  FJD 
 Falkland Islands Pound  FKP 
 Pound Sterling  GBP 
 Georgian Lari  GEL 
 Pound Sterling  GGP 
 Ghanaian Cedi  GHS 
 Gibraltar Pound  GIP 
 Gambian Dalasi  GMD 
 Guinea Franc  GNF 
 Guinea-Bissau Peso  GWP 
 Guyana Dollar  GYD 
 Hong Kong Dollar  HKD 
 Honduran Lempira  HNL 
 Croatian Kuna  HRK 
 Haitian Gourde  HTG 
 Hungarian Forint  HUF 
 Indonesian Rupiah  IDR 
 Israeli New Shekel  ILS 
 Indian Rupee  INR 
 Iraqi Dinar  IQD 
 Iranian Rial  IRR 
 Iceland Krona  ISK 
 Jamaican Dollar  JMD 
 Jordanian Dinar  JOD 
 Japanese Yen  JPY 
 Kenyan Shilling  KES 
 Som  KGS 
 Kampuchean Riel  KHR 
 Comoros Franc  KMF 
 North Korean Won  KPW 
 Korean Won  KRW 
 Kuwaiti Dinar  KWD 
 Cayman Islands Dollar  KYD 
 Kazakhstan Tenge  KZT 
 Lao Kip  LAK 
 Lebanese Pound  LBP 
 Sri Lanka Rupee  LKR 
 Liberian Dollar  LRD 
 Lesotho Loti  LSL 
 Lithuanian Litas  LTL 
 Latvian Lats  LVL 
 Libyan Dinar  LYD 
 Moroccan Dirham  MAD 
 Moldovan Leu  MDL 
 Malagasy Franc  MGF 
 Denar  MKD 
 Myanmar Kyat  MMK 
 Mongolian Tugrik  MNT 
 Macau Pataca  MOP 
 Mauritanian Ouguiya  MRO 
 Mauritius Rupee  MUR 
 Maldive Rufiyaa  MVR 
 Malawi Kwacha  MWK 
 Mexican Nuevo Peso  MXN 
 Malaysian Ringgit  MYR 
 Mozambique Metical  MZN 
 Namibian Dollar  NAD 
 Nigerian Naira  NGN 
 Nicaraguan Cordoba Oro  NIO 
 Norwegian Krone  NOK 
 Nepalese Rupee  NPR 
 New Zealand Dollar  NZD 
 Omani Rial  OMR 
 Panamanian Balboa  PAB 
 Peruvian Nuevo Sol  PEN 
 Papua New Guinea Kina  PGK 
 Philippine Peso  PHP 
 Pakistan Rupee  PKR 
 Polish Zloty  PLN 
 Paraguay Guarani  PYG 
 Qatari Rial  QAR 
 Guatemalan Quetzal  QTQ 
 Romanian New Leu  RON 
 Dinar  RSD 
 Russian Ruble  RUB 
 Rwanda Franc  RWF 
 Saudi Riyal  SAR 
 Solomon Islands Dollar  SBD 
 Seychelles Rupee  SCR 
 Sudanese Pound  SDG 
 Swedish Krona  SEK 
 Singapore Dollar  SGD 
 St. Helena Pound  SHP 
 Sierra Leone Leone  SLL 
 Somali Shilling  SOS 
 Surinam Dollar  SRD 
 South Sudan Pound  SSP 
 Dobra  STD 
 El Salvador Colon  SVC 
 Syrian Pound  SYP 
 Swaziland Lilangeni  SZL 
 Thai Baht  THB 
 Tajik Somoni  TJS 
 Manat  TMT 
 Tunisian Dollar  TND 
 Tongan Pa'anga  TOP 
 Turkish Lira  TRY 
 Trinidad and Tobago Dollar  TTD 
 Taiwan Dollar  TWD 
 Tanzanian Shilling  TZS 
 Ukraine Hryvnia  UAH 
 Uganda Shilling  UGX 
 US Dollar  USD 
 Uruguayan Peso  UYU 
 Uzbekistan Sum  UZS 
 Venezuelan Bolivar  VEF 
 Vietnamese Dong  VND 
 Vanuatu Vatu  VUV 
 Samoan Tala  WST 
 CFA Franc BEAC  XAF 
 East Caribbean Dollar  XCD 
 East Carribean Dollar  XCD 
 CFA Franc BCEAO  XOF 
 CFP Franc  XPF 
 Yemeni Rial  YER 
 South African Rand  ZAR 
 Zambian Kwacha  ZMW 
 Zimbabwe Dollar  ZWD