Turn Off Feed Read Preview to Show XML in Internet Explorer

Last night I was creating a sample application to demonstrate how to add OData to an ASP.NET MVC application.  Every time I went to the URL in Internet Explorer (IE9) it kept showing the xml with the RSS style sheet. 

Here is what you see:

image

This is not what I want to see.  I searched for a couple of hours on how to turn that off and nothing.  Finally, this morning I just started diving through the Internet Explorer settings and finally found it.

To force Internet Explorer to display the XML instead of the stylized view do the following:

  • Open Tools->Internet Options
  • Select the Content tab
  • Click the “Settings” button in the Feed and Web slices section
  • Uncheck Turn on feed reading view
  • Click “OK” to save the settings

Here is what you see know:

image

This makes it much easier to make sure I am getting what I expected in the xml return.  I don’t use any browser for reading my RSS feeds and have always found it annoying that it kept trying to show me the xml in a format I didn’t want to see.  Know I see the XML, gravy!

SharePoint Development Tip: Clear Browser Cache with Post Build Event

sharePointLogo

Recently I have been working on a customization of Project Server 2010, which is over course built on SharePoint 2010.  One of the frustrating things I encountered was that changes to my JavaScript files didn’t seem to take affect.  Every time I made an adjustment to the script and then debugged the solution on my SharePoint development machine it would deploy the files but it wouldn’t always pick up the changes in the JavaScript files. 

I did finally figure out that if I started the solution in debug mode and when the browser launched I would to go Tools->Internet Options and clear the the browser history and then refresh the page it would pick up my changes.  But, oh my gosh, what a pain to have to do that every time I wanted to test something.

While looking for a sample about I watched the MSDN Webcast: Project 2010 JS Grid Extensibility: Project Web App (Part 1 of 3), there at the end was the answer I had been looking for. 

The solution use the Solutions Post-Build event to clear the cache before the browser launches, BRILIANT!  Not only was the tip great but it gave the command to add as well.

rundll32.exe InetCpl.cpl, ClearMyTracksByProcess 8

Presto, chango, it worked like a champ, all are cleared from the cache before the browser starts.  I have had the issue since I add this.

If you are interested in watching al three videos you can find them here on the Project Programmability and Business Intelligence blog.

Happy SharePointing…

Real Simple Discovery Made Easy with the JaySmith.RealSimpleDiscovery Library

Recently I have been spending a lot of time writing blog features for several applications I am working on.  I always have to wire up some of the same handlers for exposing API endpoints for services such as MetaWeblogAPI, Blogger, LiveJournal, etc.  So, being the lazy coder that I am I started looking at ways to make them easier to share between projects. 

In this post I am going to cover a configuration based approach I have developed for handing the first step in exposing those services, Real Simple Discovery.

Real Simple Discovery as described from the RFC posted here is as follows:

Really Simple Discovery is a way to help client software find the services needed to read, edit, or "work with" weblogging software.  Although I talk about weblogging software, there's no reason this format can't apply to other forms of web client/system software that I wasn't considering, or may not even exist as of this writing.  This format is simple but flexible. One of the design goals was to ensure that it would be human writeable. This was my "test" for ensuring that the format was easy for everyone to implement.

What is the benefit of using a handler versus just putting it in an rsd.xml file at your web root?

If you are creating a simple site that is for a single URL and will never be used by others then using an rsd.xml file is an ideal solution.  On the other hand, if you are creating a project that you expect others to install on their own domain they will have to modify the rsd.xml file to provide the full URL to each handler.  This is something you would expect a developer to know how to do but not someone who has just download your code and installed it.  They expect to deploy and it just to run.

Dynamically generating this information allows for a zero config setup where the code that generates the XML can figure out the correct URL’s to provide without the need of manual configuration.  The developer sets up the protocols they want to implement in the web.config file and the real simple discovery handler generates the xml based on that config.  In this scenario the user of the site does not have to setup anything to get it to work

Example rsd.xml from my blog using Blogengine.NET

  <rsd version="1.0">
  <service>
    <engineName>BlogEngine.NET 1.6.1.0</engineName>
    <engineLink>http://dotnetblogengine.com</engineLink>
    <homePageLink>http://jaysmith.us/</homePageLink>
    <apis>
      <api name="MetaWeblog" preferred="true" apiLink="http://jaysmith.us/metaweblog.axd" blogID="http://jaysmith.us/"/>
      <api name="BlogML" preferred="false" apiLink="http://jaysmith.us/api/BlogImporter.asmx" blogID="http://jaysmith.us/"/>
    </apis>
  </service>
</rsd>

Installing JaySmith.RealSimpleDisovery via NuGet

This approach will work for both WebForms and MVC applications since it uses a handler to basically bypass the UI layer.

Example of the config

<realSimpleDiscovery>
    <apis>
      <add name="Atom" preferred="false" apiLink="atom.axd" />
      <add name="Blogger" preferred="false" apiLink="blogger.axd" />
      <add name="MetaWeblog" preferred="true" apiLink="metaweblog.axd" />
      <add name="Manila" preferred="false" apiLink="manila.axd" />
      <add name="MetaWiki" preferred="false" apiLink="metawiki.axd" />
      <add name="LiveJournal" preferred="false" apiLink="livejournal.axd" />
    </apis>
</realSimpleDiscovery>

Navigating to http://[MyHost]/rsd.axd will display the following:

<?xml version="1.0" encoding="utf-8" ?> 
<rsd version="1.0">
  <service>
    <engineName>JaySmith.RealSimpleDiscovery Engine v1.0</engineName> 
    <engineLink>https://github.com/JaySmith/RealSimpleDiscovery</engineLink> 
    <homePageLink>http://localhost:4104/</homePageLink> 
    <apis>
      <api name="MetaWeblog" preferred="True" apiLink="http://localhost:4104/metaweblog.axd" blogID="http://localhost:4104/" /> 
      <api name="Atom" preferred="False" apiLink="http://localhost:4104/atom.axd" blogID="http://localhost:4104/" /> 
      <api name="Blogger" preferred="False" apiLink="http://localhost:4104/blogger.axd" blogID="http://localhost:4104/" /> 
      <api name="Manila" preferred="False" apiLink="http://localhost:4104/manila.axd" blogID="http://localhost:4104/" /> 
      <api name="MetaWiki" preferred="False" apiLink="http://localhost:4104/metawiki.axd" blogID="http://localhost:4104/" /> 
      <api name="LiveJournal" preferred="False" apiLink="http://localhost:4104/livejournal.axd" blogID="http://localhost:4104/" /> 
    </apis>
  </service>
</rsd>

Another feature is that the implementation is flexible enough to handle new APIs as they become available.  To expose a new api all you have to do is add it to the web.config file and the end point of the new api will be generated just like all the rest.

Example of new API

  <realSimpleDiscovery>
    <apis>
      <add name="Atom" preferred="false" apiLink="atom.axd" />
      <add name="Blogger" preferred="false" apiLink="blogger.axd" />
      <add name="MetaWeblog" preferred="true" apiLink="metaweblog.axd" />
      <add name="Manila" preferred="false" apiLink="manila.axd" />
      <add name="MetaWiki" preferred="false" apiLink="metawiki.axd" />
      <add name="LiveJournal" preferred="false" apiLink="/api/livejournal.axd" />
      <add name="MyNewApi" preferred="false" apiLink="/mynewapi.axd" />
    </apis>
  </realSimpleDiscovery>

Output with new API after navigation to http://[myhost]/rsd.axd

<?xml version="1.0" encoding="utf-8" ?> 
<rsd version="1.0">
<service>
  <engineName>JaySmith.RealSimpleDiscovery Engine v1.0</engineName> 
  <engineLink>https://github.com/JaySmith/RealSimpleDiscovery</engineLink> 
  <homePageLink>http://localhost:4104/</homePageLink> 
 <apis>
  <api name="MetaWeblog" preferred="True" apiLink="http://localhost:4104/metaweblog.axd" blogID="http://localhost:4104/" /> 
  <api name="Atom" preferred="False" apiLink="http://localhost:4104/atom.axd" blogID="http://localhost:4104/" /> 
  <api name="Blogger" preferred="False" apiLink="http://localhost:4104/blogger.axd" blogID="http://localhost:4104/" /> 
  <api name="Manila" preferred="False" apiLink="http://localhost:4104/manila.axd" blogID="http://localhost:4104/" /> 
  <api name="MetaWiki" preferred="False" apiLink="http://localhost:4104/metawiki.axd" blogID="http://localhost:4104/" /> 
  <api name="LiveJournal" preferred="False" apiLink="http://localhost:4104/api/livejournal.axd" blogID="http://localhost:4104/" /> 
  <api name="MyNewApi" preferred="False" apiLink="http://localhost:4104/mynewapi.axd" blogID="http://localhost:4104/" /> 
  </apis>
 </service>
</rsd>

You can see that the new MyNewApi endpoint has been included.

Looking for feedback

I am really looking for feedback on this approach so if you are creating applications that need to use Real Simple Discovery please give this a test drive and let me know of any improvements you would like to see.

Resources on Real Simple Discovery:

RFC: Really Simple Discoverability 1.0

http://archipelago.phrasewise.com/display?page=oldsite/1330.html

http://cyber.law.harvard.edu/blogs/gems/tech/rsd.html

Generic Repository for Entity Framework

*UPDATED 9/6/2012*
Thanks to Stephen Dooley for bringing to my attention that Mikael’s post is no longer available.  I have updated the post to include the extension methods that he had originally posted.  You can find them at the end of the post.
*End Update*

I have started trying to learn how to leverage the Entity Framework for a the re-write of the GiveCamp Starter Site and wanted to implement a generic repository for data access like I use on most of my projects.  I started with the example given by Mikael Henriksson’s Post Generic Repository for Entity Framework for Pluralized Entity Set.  I modified it to fit my standard Repository interface and took the liberty of simplifying it in a few places.

I have run this through several test and haven’t found any issues. I would love those with a critical eye to give this a look over and let me know if I am missing anything.

The IRepository Interface

 1: public interface IRepository : IDisposable
 2:    {
 3:      T Get<T>(int id) where T : IEntityWithKey;
 4:      T Get<T>(Expression<Func<T, bool>> predicate) where T : IEntityWithKey;
 5:        IQueryable<T> Find<T>(Expression<Func<T, bool>> predicate) where T : IEntityWithKey; 
 6:      T Save<T>(T entity) where T : IEntityWithKey;
 7:      T Delete<T>(T entity) where T : IEntityWithKey;
 8:    }

I did use the ObjectContextExtensions from Mikael’s post because they did such a good job of solving the issue of getting the EntitySetName. I am not going go into a lot of detail explaining what is going on because a feel the class pretty much explains itself.

The Repository Class:

 1: public class EntityFrameworkRepository : IRepository   
 2: {
 3:     private readonly ObjectContext context;
 4:     public EntityFrameworkRepository()
 5:     {
 6:         context = new WmdDemoEntities();
 7:     }
 8:      
 9:     public EntityFrameworkRepository(ObjectContext entityContext)
 10:     {
 11:         context = entityContext;
 12:     }
 13:     
 14:     public T Get<T>(int id) where T : IEntityWithKey
 15:     {
 16:         IEnumerable<KeyValuePair<string, object>> entityKeyValues = new[] { new KeyValuePair<string, object>("Id", id) };
 17:         var key = new EntityKey(context.GetEntitySet<T>().Name, entityKeyValues);
 18:         return (T)context.GetObjectByKey(key);
 19:     }
 20:     
 21:     public T Get<T>(Expression<Func<T, bool>> predicate) where T : IEntityWithKey
 22:     {
 23:         return context.CreateQuery<T>("[" + context.GetEntitySet<T>().Name + "]")
 24:         .Where(predicate)
 25:         .FirstOrDefault();
 26:     }
 27:     
 28:     public IQueryable<T> Find<T>(Expression<Func<T, bool>> predicate) where T : IEntityWithKey
 29:     {
 30:         return context
 31:         .CreateQuery<T>("[" + context.GetEntitySet<T>().Name + "]")
 32:         .Where(predicate);
 33:     }
 34:      
 35:     public T Save<T>(T entity) where T : IEntityWithKey
 36:     {
 37:         object originalItem;
 38:            if (context.TryGetObjectByKey(entity.EntityKey, out originalItem))
 39:             context.ApplyPropertyChanges(entity.EntityKey.EntitySetName, entity); 
 40:         else
 41:             context.AddObject(entity.EntityKey.EntitySetName, entity);
 42:        
 43:        context.SaveChanges();
 44:        return entity;
 45:     }
 46:     
 47:     public T Delete<T>(T entity) where T : IEntityWithKey
 48:     {
 49:         context.DeleteObject(entity);
 50:         context.SaveChanges();
 51:         return entity;
 52:     }
 53:     
 54:     public void Dispose()
 55:     {
 56:         context.Dispose();
 57:     }
 58:  }
 

Here is an example of usage in a console application

 1: class Program
 2:  {
 3:    static void Main(string[] args)
 4:    {
 5:      IRepository repository = new EntityFrameworkRepository();
 6:        var page = repository.Get<Page>(x => x.PageId == 1);
 7:        Console.WriteLine("Title: {0}", page.Title);
 8:      Console.WriteLine("Content: {0}", page.Content);
 9:        repository.Dispose();
 10:        Console.ReadLine();
 11:    }
 12:  }

I love taking this approach to persistence because it is so flexible and allows me to swap out repository implementations with little issue.

Again love to hear some feedback on this approach.

Mikael Henriksson’s Original Extension Methods

 1: using System.Data.Metadata.Edm;
 2: using System.Data.Objects;
 3: using System.Data.Objects.DataClasses;
 4:  
 5: public static class ObjectContextExtensions
 6: {
 7:     internal static EntitySetBase GetEntitySet<TEntity>(this ObjectContext context)
 8:     {
 9:         EntityContainer container = context.MetadataWorkspace
 10:                                                         .GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace);
 11:         Type baseType = GetBaseType(typeof(TEntity));
 12:         EntitySetBase entitySet = container.BaseEntitySets
 13:                                                     .Where(item => item.ElementType.Name.Equals(baseType.Name))
 14:                                                     .FirstOrDefault();
 15:  
 16:         return entitySet;
 17:     }
 18:  
 19:     private static Type GetBaseType(Type type)
 20:     {
 21:             var baseType = type.BaseType;
 22:             if (baseType != null && baseType != typeof(EntityObject))
 23:             {
 24:                 return GetBaseType(type.BaseType);
 25:             }
 26:             return type;
 27:     }
 28: }

Enums: Learn to love them

So, I was dredging around in a some old code I inherited looking for that one magical place to make my new change when I came across a piece of code that, well, just made me laugh and then cry.

Here it is:

 1: switch (ddlRollupInterval.SelectedValue) 
 2: { 
 3:     case "Daily": 
 4:         r.RollupInterval = Report.Interval.Daily; 
 5:         break; 
 6:     case "Weekly": 
 7:         r.RollupInterval = Report.Interval.Weekly; 
 8:         break; 
 9:     case "Monthly": 
 10:         r.RollupInterval = Report.Interval.Monthly; 
 11:         break; 
 12:     default: 
 13:         r.RollupInterval = Report.Interval.Yearly; 
 14:         break; 
 15: } 

Looking at the code it is very obvious what it is doing, it is setting an enum value based on the string value of a dropdown.  But did it really take that much code to do it.  Well of course not. 

An enumeration type (also named an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable. For example, assume that you have to define a variable whose value will represent a report interval. There are only 4 meaningful values which that variable will ever store. To define those values, you can use an enumeration type, which is declared by using the enum keyword.

 1: enum ReportInterval
 2: {
 3:     Daily,
 4:     Weekly,
 5:     Monthly,
 6:     Yearly
 7: }
The above enum was declared and then an instance was used on the Report object.
 
Enums are extremely flexible and can be used in a number of ways.  Lets look at a few ways you can use enums.
 

Get the Names from the Enum

Lets take the ReportInteval enum we created above and look how we would get an Array of strings that represent the names of each valid enum.

 1: var enumNames = Enum.GetNames(typeof (ReportInterval));

This would allow us to populate that ddlRollupInterval dropdown with all the possible values from the enum

 1: ddlRollupInterval.DataSource = Enum.GetNames(typeof (ReportInterval));
 2: ddlRollupInterval.DataBind();

Ok, so now we have a dropdown filled with the names from the enum, how do we clean up that code we found.  You remember that ugly switch statement that started this whole thing. Once a user selects something in the dropdown and clicks save we want to set the enum based on the string that was selected right? Lets look at how to do that next.

Likewise you can also get the values with the following code:

 1: Array enumValues = Enum.GetValues(typeof(ReportInterval));

Get an Enum from a String

This too is much easier than one would think.  Using the Enum.Parse() method provides a quick way to convert from a string to an instance of the desired Enum.

 1: ReportInterval interval = (ReportInterval)Enum.Parse(typeof(ReportInterval), testString);

This works great in our case because we filled the dropdown with only valid values.  But what if you weren’t sure if the value was valid for the enum or not.  You know those pesky users sometimes give us data that doesn’t fit our model.  ;-)  You can use the Enum.IsDefined() which returns an indication letting us know if a constant with the specified value exists in a specified enumeration.

If our user was able to add a value, say ‘Quarterly’ to our dropdown by some other part of the application and then selected it we would want to test the string we were provided to make sure we don’t throw an unwanted exception.

 1: var ourUserInputString = "Quarterly"
 2:  
 3: if (Enum.IsDefined(typeof (ReportInterval), outUserInputString)
 4: {
 5:     // It is ok go ahead and pase the enum
 6: }
 7: else
 8: {
 9:     // Alert the user an invalid string was selected.
 10: }

Get an Enum from an Integer

Getting an enum instance form an integer is even easier just cast the integer to the desired Enum.

 1: ReportInterval interval = (ReportInterval) testInt;

Of course we would never let our users add values to the dropdown because we want to constrain the valid values to be one that is on the enum, but I wanted to show you that it can be done.

Limit Method Call Arguments

Another usage for an enum is to limit the values a developer can pass to a method on your object.  Using our ReportInterval enum as an argument to a LoadReport method on our Report call gives us the safety net to know we are only going to get a valid value.  Where as if we just used a string we could get a value that doesn’t make sense.

 1: var status = RunReport(ReportInterval.Daily);

Another great part of this is a that Visual Studio will start complaining that the value is in valid unless it is from the enum, further more the compiler will  an argument '1': cannot convert from 'string' to 'EnumTest.ReportInterval'  exception.  I don’t know about your but I like that.

Summary

So what was the final result of fixing the code smell you say?  I replaced that huge 15 line switch statement with the two lines of code, one to verify that the value was correct, remember this is a very, very legacy application and I can not trust that the values were actually loaded to the dropdown from the enum, and one to set the ReportInterval if it checked out good.

I hope that this has shown you just a few ways that the simple Enum can enhance you programming life.

References:

C# Programming Guide: Enumeration Types

How Do Your Convert a String Into an Enum? – Tim Sneath

Calendar

<<  November 2017  >>
MonTueWedThuFriSatSun
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar

Month List