Sunday 21 July 2013

Setting up HttpHandler in IIS 7 or IIS 8 integrated mode

I spent hours troubleshooting a 404 problem with it and it turned out to be one of those doh! moments when I finally figured it out. I thought it was worth posting something about it here because during my research into the matter I found a lot of scattered and contradicting information about it on the web. Some said you have to strongly name and sign your assembly and deploy to the GAC in order to use a custom httphandler with IIS, which is not true, and others had some downright way of going about it.

In any case it's very very simple. All you need to do is declare your handler under web.config under <system.webserver> like this:

<system.webserver>
 <add name="MyHandlerClass" path="MyHandlerMethod" verb="GET" type="FullNamespace.ClassName, FullNamespace.SyncServer" resourceType="Unspecified" preCondition="integratedMode" />
</system.webserver>

Notes:

1)You must declare this inside the <system.webserver> not <systerm.web> and in fact make sure you do not include a declation for the same handler unser <system.web> otherwise it'll get confused

2)the name must match the name of your HttpHandler class

3)the path is the method in your httphandler class that you want to call which is also part of the path when invoking it

4)type is just the full assembly name for your custom header including the class name for your custom httphandler

5)resourceType is the equivalent to "verify that file exists"in II 6. leaving it as undefined prevents IIS from checking for a file specifically which may be what you need particularly if your handler just maps to a path rather than serving a file

6)this tells IIS to run the handler in integrated mode

now the most important one, for me, anyway and what kept me troubleshooting this for hours:

7)If it's an MVC project... MAKE SURE TO ADD IT TO YOUR IGNORE ROUTES CONFIGURATION!

Tuesday 2 July 2013

How to calculate the closest date to now in a collection using C#

there are a lot of unnecessarily over-complicated ways out there showing different ways of doing this so I thought I'd post what I think is the simplest and best solution for this.

Just a bit of context first: my scenario is that I want to find out which files in the collection that I have the closest publishing date to today based on the date set on the filet set they belong to.

 var now = DateTime.Now;
                
var closestDiff  = activeFiles.Min(x => Math.Abs((x.Fileset.PublishDate - now).Ticks));

                files = activeFiles.Where(x => Math.Abs((x.Fileset.PublishDate - now).Ticks) == closestDiff  ).ToList();

one important pointer:

make sure to save the DateTime.Now or whatever date you're comparing to in a variable first if you are using a dynamic date like that.

Don't forget that milliseconds count when dealing with datetime so you if you just use that statement inline the code will never match anything since the Ticks result will be different in the next code line and the closestDiff won't match anything


               

Monday 24 June 2013

Unable to start debugging on the web server. IIS does not list a web site that matches the launched URL.


if you're encountering this error it's because you haven't started Visual Studio in Administrator mode. This will particularly be true for Visual Studio 2012 with Windows 8 users.



so start Visual Studio again in Administrator mode and this cryptic error should go away.

Sunday 23 June 2013

Ajax.BeginForm displaying System.Web.Mvc.Html.MvcForm on View

if you're using Ajax.BeginForm() on your view MVC view don't forget to wrap it with a using statement otherwise it will print System.Web.Mvc.Html.MvcForm which is really annoying.

so just make sure that your statement looks like this:

@using(Ajax.BegindForm(....))
{

}

Monday 17 June 2013

Prioritize your wifi connections in Windows 8

Microsoft still refuses us to gives us a GUI to do something as simple as prioritizing what WiFi connections you want prioritized. However, it's easy enough to do.

1)Open command prompt and type: "netsh wlan show profiles"

2)Type the following filling in the parameters with the information displayed on the previous output:
netsh wlan set profileorder name="name of wifi you want to prioritize" interface="name of the wifi interface which you can find on the previous output" priority=1 

obviously replace 1 by whatever priority you want to give that wifi connection.

Thursday 13 June 2013

Handler "ExtensionlessUrlHandler-Integrated-4.0" has a bad module "ManagedPipelineHandler" in its module list

This is most likely due to the second stupid decision of whoever is leading the IIS team at Microsoft (see my previous post for the first one).

If you install IIS 8.0, it will not by default install the ASP.Net 4.5 module with it. It won't even prompt you though it looks like you have set up everything as it's tucked under the Application Development Features which is semi checked so you'd just assumed that it picked sensible defaults. not so.

They have dropped aspnet_regiis so what you have to do is:

1)Go to Control Panel -> Programs and Features
2)Find IIS 8.0
3)Click on Turn Windows Features on/off
4)Expand the Internet Information Services
5)Expand the World Wide Web Services
6)Expand the Application Development Features
7)Tick Asp.Net 4.5 (and whatever else you may need for that matter)

screenshot:




The requested page cannot be accessed because the related configuration data for the page is invalid.

This error usually means that your applicationhost.config which is the base config installed by IIS on your windows/system32 dir which provides default configuration for .net web sites is denying override for a particular configuration section that you are using in your web.config on your web site.

This error has suddenly become very widespread because in IIS 8.0 in Windows 8.0 the default override setting for the <handlers> section is Deny which means you can't have it in your web.config. Considering that every web site template generated by Visual Studio has the <handlers> section with a few things in it, I can only fathom the logic behind this decision, other than consider it a blunder.

In any case, easy enough to fix. 

1)navigate to windows\system32\inetsrv\config and open applicationhost.config

2)find the section that you need to use in your web.config (this error usually outputs a helpful message telling which section is erroring) and change the setting from Deny to Allow. 

Monday 10 June 2013

Query for listing all foreign key constraints for a table

Here is an sql query you can use to list all foreign keys for a given table:

SELECT
K_Table = FK.TABLE_NAME,
FK_Column = CU.COLUMN_NAME,
PK_Table = PK.TABLE_NAME,
PK_Column = PT.COLUMN_NAME,
Constraint_Name = C.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
SELECT i1.TABLE_NAME, i2.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
) PT ON PT.TABLE_NAME = PK.TABLE_NAME
AND PK.TABLE_NAME='tablename'

Sunday 9 June 2013

"An error occurred while processing your request." using Windows Azure

If you're getting the message "An error occurred while processing your request." and you want to see the error in your Azure deployment you have to make sure of two things:

1)turn custom errors off by adding this under <system.web>:

<customErrors mode="Off"/>

2)if it's an MVC project it most likely set up an error handler filter for you so find the App_Start folder find FilterConfig.cs and comment out the following line like this:

//filters.Add(new HandleErrorAttribute());


Wednesday 5 June 2013

Accessing dynamic types from difference assemblies

When you set up a dynamic type in one assembly, you usually can't access it in another one by default. 
However, there is a way. You just have to declare explicitly on your AssemblyInfo to which assemblies you want to expose your dynamic data to by using the InternalsVisibleTo statement.

so, in your AssemblyInfo.cs (or dot whatever else if you're not into C# which makes you a dirty sinner), declare:

[assembly: InternalsVisibleTo("MyAssembly.WhichShouldSeeMyDynamicData")]

Saturday 1 June 2013

"Error 3027: No mapping specified for the following EntitySet/AssociationSet ..." - Entity Framework headaches

If you are developing model-first with Entities Framework (EF) then you may run into this annoying error at times:

Error 3027: No mapping specified for the following EntitySet/AssociationSet [Entity or Association Name]

This may make no sense when everything looks fine on the EDM, but that's because this error has nothing to do with the EDM usually. What it should say is "regenate your database files".

You see, Entities checks against the SSDL and MSL during build so if you just changed your EDM but doesn't use "Generate Database Model..." then it complains that there's stuff missing in your sql scripts.

so, in short, the solution is:

Don't forget to  "Generate Database Model..." every time after you update your EDM if you are doing model first development!

Wednesday 29 May 2013

Retrieve full img url from sitecore for display on site

sitecore can be quite counter intuitive at times and this is one big example of it. 

If you want the actual img url to display on your web site using an <img src="" /> you won't find that in the metadata carried with the MediaItem object. 

Instead you have to make a separate call to sitecore like this:

Sitecore.Resources.Media.MediaManager.GetMediaUrl(mediaItem)

and remember you can always get a MediaItem from an ImageField if that is what you have by doing imageField.MediaItem. 

Sunday 26 May 2013

Creating a git repository in an existing directory with files

Git is pretty smart and will let you very easily hook up existing source code to a new repository without making you go through some awkward copy and paste process.

all you have to do is navigate to your directory with the source files and type:

git init

then you need to tell git which repository to hook it up to:

git remote add origin [repository url]

lastly you want to add an upstream so it knows which branch to hook the code to. you can always commit on the fly to any given branch, however, you may want to set your upstream for convenience and you can do it all in one go when you do your first push like this (this example sets the master branch as the default upstream):

git push --set-upstream origin master

all done! gotta love git.

Saturday 25 May 2013

Calculating age in C#

This is a silly one, but it's amazing how often it comes up.

so if you want to know how what's the best algorithm for calculation someone's age based on date of birth, her goes. it's in C# but it can be easily adapted.

DateTime today = DateTime.Today;
int age = today.Year - bday.Year;
if (bday > today.AddYears(-age)) age--;
return age;

Friday 24 May 2013

HttpModules not firing under Cassini

If you are using Visual Studio 2010 this could be because 2010 Cassini uses IIS 6.0 syntax to register the HTTP modules. So if you have IIS 7 syntax in your config it'll just happily ignore it without flagging it.

check your config and update your syntax to IIS 6.0 and it should all work again.

Tuesday 21 May 2013

Git : Quick Reference


If you're new to git follow this to get up and running in a min:

set up a new repository: git clone repository_url

(code... code... code...)
 
check pending changes: git status -s

add files to the changeset: git add .
Notes:
1) not restricted to new files only; all files including existing modified ones need to be explicitly added before being commited
2) The dot in the end is part of it, not a typo. It just makes it recursively add all changed files from this dir and its subdirs

committing to the local repo: git commit -m "a message"
 
pull latest code from remote repository: git pull

(merge... merge... merge...)

push to the remote repository : git push

voila!

a few other ones that may be helpful: 

check what branch you're on: git branch

switch to a different branch: git checkout branch_name

happy git!

Bypassing publishing when updating items programatically in Sitecore

if you want to just update items in the Sitecore database without having to publish the changes all you need to do is deal directly with the master database by switching Sitecore.Context to point to it by using the Sitecore built-in factory like this:

 Sitecore.Context.Database = Factory.GetDatabase("master");

now whenever you access Sitecore.Context it'll act upon the master database. you may need to do a security override depending on what you are doing. check my previous post for instructions on how to do that.

Editing items programatically from sitecore : security exception


When using Sitecore.Context to update items you may run into a security exception saying that the ASP.Net process doesn't have permission to update the database.

You can get around that very easily by using a security override by wrapping your code in this block:

 using (new Sitecore.SecurityModel.SecurityDisabler())
{
  //retrieve item

  item.Editing.BeginEdit();

  //update item

 item.Editing.EndEdit();
}

This is likely to happen if you are using the Sitecore master database directly so as to bypass publishing



Wednesday 8 May 2013

Finding friends in Spotify

Love Spotify but gotta say it's really dumb of them to come up with so good as the friend following feature but forget to include a way to find friends. oh well, for what is worth the functionality is there it's just the front enders that slacked on the job.

so until they implement a nice little user-friendly friend search function, if you wanna find someone on Spotify that you want to follow simply:

Go on the search box and type: spotify:user:USERNAME

obviously replace USERNAME with the name of the friend you're looking for.