Wednesday, December 10, 2014

require.js conflicts with chart.js when AMD loading

When attempting to use chart.js on my web site, the chart would not load correctly and the following error appeared in the browser console:
Error: Mismatched anonymous define() module: function (){
"use strict";
return Chart;
}
http://requirejs.org/docs/errors.html#mismatch
The problem arises when using an AMD loader for JavaScript modules and the fact that the chart.js source is an anonomous function (like follows):
 (function(){
// code in here
}).call(this);
The solution is not to reference the chart.js in the HTML markup but to simply  require and use it when needed (when interacting with the charts) in the jQuery.
require(['path/to/Chart.js'], function(Chart){
// Use Chart.js as normal here.

// Chart.noConflict restores the Chart global variable to it's previous owner
// The function returns what was previously Chart, allowing you to reassign.
var Chartjs = Chart.noConflict();
});
Don't forget to remove any references to chart.js in the HTML or the errors will still occur.

AngularJS grouping radio buttons on a form

HTML input elements of radio button type are grouped together using the name attribute. With AngularJS forms (and form validation), the name attribute is generally set as a unique identifier. To get grouped radio buttons to work correctly on a form using AngularJS you simply need to set a value to each radio button.


In the example above the two checkboxes are in the same group and share the same angular model. The active value controls which one is set to checked - although this is in textual form and not numeric.

jQuery replace all spaces in a string

In jQuery to replace all occurrences of a space in a given string (and not just the first one), the following code will work.
var myString = "a simple string";
myString.replace(/ /g, '');
in this example the string will go from "a simple string" to "asimplestring".

Thursday, November 27, 2014

jQuery disable paste on a form field

In the case of a form where the user is asked to re-enter a field to ensure accuracy, it is a good idea to disable paste functionality on the second field. This is to ensure the user does not enter the data incorrectly then copy/paste it into the second field.

The following jQuery will achieve this.

Monday, November 24, 2014

JavaScript RegEx to check for strong password

The following code will match RegEx against a password to check if it meets strong password complexity requirements (Passwords must be at least eight characters including at least one number and one special character (punctuation, symbol or upper/lower case character).

Tuesday, November 18, 2014

Error creating the Web Proxy specified in the configuration section.

I came across the following error when calling a WCF service:
Error creating the Web Proxy specified in the 'system.net/defaultProxy' configuration section.
This error was being generated because the project was stored on a network drive. After moving the project to local disk it called the service correctly and no error was generated.

Monday, November 17, 2014

Referencing a TIBCO WSDL service in .NET

When adding a TIBCO WCF service to a .NET project (via 'Add Web Reference'), the service may not be discovered correctly and the following error is encountered: "The HTML document does not contain Web service discovery information.".


The solution to this issue is to take the WSDL generated by TIBCO and place it in the local file system, this can then be used to add the WSDL (and it will be picked up correctly).


The URL to the service could then be changed inside web.config/app.config or at runtime.

Sitecore items missing from web database

An error occurs when not logged into sitecore and browsing the web site (so web database is being used) and the site won't load due to missing items (such as layout or template). The content editor may also not load when web database is selected.

In this case the error was traced back to the "Sitecore/Templates/System/Layout" folder not having a version, which meant that the entire folder and it's contents never got published to the web database (potentially only the original publish of this folder was available in web). Therefore if an item is missing in the web database but appears in the master database, check that a version exists - and if it doesn't create one and try publishing again.



This then caused the web database to be out of sync and there were problems browsing the site/accessing content editor (when web database is selected).

Thursday, October 30, 2014

Desktop application to find all 404 links on a web site

When developing a new web site or even re-creating an existing one, it is almost guaranteed that there will be a number of broken links (both internal and external) across the web site. There are a number of on line tools (including Google Webmaster Tools) that can be of help on production web sites. However when it comes to web sites still in production, those which aren't available externally or perhaps web sites that utilize the hosts file, a desktop application would be of help.

Xenu's Link Sleuth is a great desktop tool for finding broken links, and has been around for a number of years. The basic functionality is that it checks a web site for any broken links (across all media types, pages and even scripts/resources). It then gives a report that sorts the broken links by broken link or by page (that has broken links). Another great feature is the ability to disable the checking of external links.

Xenu's Link Sleuth Running
I have found this tool particularity helpful when migrating existing web site, as there are often links in the content to previous URL structures. It's also handy for checking links on internal intranets.

Sitecore MVC disable web edit of fields output on page

When you output a field to a page, in the case of a title field going into the head as the page title for instance. When in page editor more, that filed will appear as editable - and in the case of meta tags mess up the look of the page editor and put code as the page title.

You can disable web editing on a case by case basis for fields with the following code:
@Html.Sitecore().Field("Field Name", new { DisableWebEdit = true })

Sitecore get the URL of an image stored in the media library

When a template uses the image field, any images the user references (and uploads) go into the Sitecore media library. This can of course be rendered using the sitecore control, however for more custom implementations and MVC projects, the image URL itself is enough. The following method takes in an object of type ImageField and outputs a string with the URL to this image.

If the image is not rendering and your site is set-up to replace any spaces in URLs with dashes, then please see Sitecore media (images) not rendering.

Sitecore get URL for LinkField

A Sitecore template field of General Link type, can link to various items of various types (internal, external, media items and so on). Because each type would be rendered differently, when accessing these links in code, the different types need to be taken into account. The following method (found online) would take in a LinkField and output the URL as a string.

A LinkField comes from accesing a Sitecore item's template field liek follows: LinkField link = item.Fields["Field Name"]; This object can then be passed into the following method to get the correct URL:

Basic Search Index and Search Code in Sitecore 7.5

Setting up search in Sitecore can be a learning curve, especially when the configurations change from version to version (such as 6.xx - 7.5). The following is a basic implementation which I used to set-up lucene search on a Sitecore implementation with two main content (page) types: content pages and blog posts.

Setting up the index

The first step is to create a custom search index, this is created in root/Website/App_Config/Include -  an example configuration file is available in there called Sitecore.ContentSearch.Lucene.Indexes.Sharded.Core.config.example. Using this example I modified it to the following (and saved it in the same location as search.config):

In this example I have named the index content_index and set it to index the web database. It indexes items under the main content item ("/sitecore/content") and will only include the templates declared. All fields are also set to be indexed as well, however you could modify the file to meet any template/field indexing strategies you may have - multiple indexes could also be used for larger implementations with advanced information architecture. The index has also been set to update on publish and async.

Once saving the index xml, I went to the sitecore desktop and loaded the index manager (control panel > indexing > indexing manager). Here the index name was selected and the rebuild button clicked to build the index. If there are any errors in the index's XML, this page will show the stack trace. Once built the index is now accesible in code to complete actual searches.

Making a search

My templates all included fields called Heading and Content, these two fields would be what needed to be actually searched - as they would return the most relevant results. To allow linq to access these fields in the sitecore search I needed to Inherit the SearchResultItem object and add these fields in, this is achieved by using IndexField:


Then the actual search can be made with the following code:

Linq is returning any results from the index where the title is like the search term and the content contains the search term - remember this is very simple search and a search term of "cat" would match "concatenate". The results are then put into a custom object which can be rendered on the front end.

Monday, October 27, 2014

Sitecore media (images) not rendering

In Sitecore 7.5 I have come across an issue where some images in the media library are not rendering. This is occurring with the image URL given by Sitecore.Resources.Media.MediaManager.GetMediaUrl(MediaItem) and that URL will not load. After some investigation I found that in the sitecore web.config I had used the encodeNameReplacements section to rewrite all spaces as hyphens in URLs. That means that any media images with hyphens in the file name will not load because sitecore is then looking up that media with spaces instead of hyphens (and the image is then not found).

The solution is this case was to not use any hyphens in media file names.

Friday, October 24, 2014

Sitecore MVC output rich text field as HTML

One problem I came across when outputting Sitecore template fields (of rich text aka HTML) was that the HTML tags would be encoded and displayed on the page. To fix this, placing Html.Raw around the field value, would then output it correctly in HTML.
@Html.Raw(RenderingContext.Current.Rendering.Item.Fields["HTML Content"])
The example above outputs the 'HTML Content' Rich Text field directly as HTML. This field is a member of the content template which was set as the associated content (data source) for the rendering.

Thursday, October 23, 2014

Sorting a list of custom object in C#

Sorting a list of custom tyupe is not as simple as sorting a list of integers and strings for example. The type needs to be made IComparable and a CompareTo method needs to be added to allow the default .Sort method to work correctly.

The example above shows the MenuType class being made IComparable with itself and the CompareTo method is comparing based on the sort order. In this example the list of MenuItems will be sorted by that SortOrder field.

Wednesday, October 22, 2014

Using perfmon to troubleshoot performance in IIS

When an ASP.NET web site starts having performance issues, in general or when significant load is on the web site (in terms on concurrent users) it can be difficult to narrow down the root cause(s). It often takes several tools to get to the bottom of the issue, and one of the first I tend to use is the Performance Monitor built into Windows aka perfmon.exe

This utility allows you to monitor a very wide variety of system resources: at the basic level such as CPU, memory, network, disk and so on, along with application specific such as IIS, ASP, .NET and even .NET CLR Thread Pool. There are many other variables that can be monitored, too many to list here.

Perfmon Main screen showing live data (processor and memory)
By right clicking on the graph, new counters to monitor can be added by clicking "add counters". In terms of looking at performance problems in IIS, I find the following counters helpful.

  • .NET CLR LocksAndThreads - Useful to see how busy the threads are that are actually processing the code. 

  • Memory, PhysicalDisk, Processor and Network - all provide useful counters for general debugging. For instance, if processor is experiencing high usage and there is memory free, caching may be of use.
  • ASP.NET v 4.0.xxxxx - is helpful to view counters on the requests, session state and worker processes.

Friday, October 17, 2014

Adding MaxPoolSize to a connection string

Max Pool Size is the maximum number of allowed connections for a given connection string. It appears as MaxPoolSize programatically however when setting it in a connection string it needs to have spacing between the words:
string srConnectionString = "server=localhost;database=MyDB;uid=sa;pwd=pass;Max Pool Size=200;";

Monday, October 13, 2014

Increasing IIS performance using a Web Garden

A web farm is where you have multiple servers serving the web site and these servers usually sit behind a load balancer. A Web Garden (introduced in IIS 6), is the concept of a single application pool having multiple worker processes.

In general web gardens are not recommended because they require overhead to operate (each worker process will consume a base level of RAM/CPU) and do not share resources. For example caching and session states are not shared between worker processes in web farms, so there is some duplication of work from that aspect.



However in cases where you have long running processes, that lead to queuing, there may be some performance benefits to using a web garden. As more threads are made available to process these requests, which leads to quicker processing overall.

You can setup web garden at the application pool level in IIS Manager. However before enabling in a production environment I recommend extensive testing to ensure there are no negative impacts to end users (application state/session) and that you don't overload the server (too many worker processes when little CPU/RAM is available).

Web Gardens are not a popular solution due to their overhead, and some people look at them as a band aid to poorly written code. Perhaps that is the case for the vast majority of web applications, yet there are always cases where the positives outweigh the negatives and a Web Garden leads to increased IIS performance.

Friday, October 3, 2014

Sitecore replace spaces in URLs with dashes

Out of the box, Sitecore will display spaces in URLs which can look messy and potentially have negative SEO consequences. However it is possible to replace all of a given character or string in a URL for another. This can be used in this case to replace any occurrence of a space with a dash.

Simply open the web.config file for your Sitecore website and locate the "encodeNameReplacements" section. Here you will see all existing string replacements, and can add the following line:
<replace mode="on" find=" " replaceWith="-"/>
 In this section you could also replace underscores with dashes or potentially entire words with others.

Friday, September 12, 2014

angularJs run code after all elements/page has loaded

In some cases there is jQuery that needs to be run only after other angular directives/the page itself have completed (for example you may need to use the height of a div that changes based on content added by angular, or even access elements by class which is added by ng-class).

In this case, you use an empty timeout function in the angular controller and it will only run after all other angular elements have completed loading/processing.


Thursday, September 11, 2014

jQuery log messages into the console

When debugging jQuery or JavaScript code, alerts are simple ways to output messages or data to see how the code is working and if certain code is being run etc. However there are times where the presence of an alert is not ideal and can break the flow of the code (for example if you are debugging page scroll, the alert stops the scrolling).

That is where console logging can be of assistance. Modern web browsers all have a developer tools menu built-in out of box (generally available by pressing F12). This menu will have a console option which commonly displays JavaScript information and also allows you to interact with the page via command line. There are four different options for manually outputing messages to the console:
console.error("error"); 
console.log("log"); 
console.warn("warn"); 
console.info("info"); 
These then get output as the following:


Wednesday, September 10, 2014

SharePoint Object Model determine if current page is checked out to the current user

In some cases you may only wish to perform a given action if the page is currently checked out to the current user. The SharePoint object model in 2013 has a simple method for determining the checked-out state of the current page.

jQuery convert a variable or string into a JSON object

I came across an example where I was given JSON data (custom object array) as a string in C# code behind. I then made it available to the front end jQuery/angularJs where it would need to be accessed as an object (to allow iteration).

The following line of jQuery will convert the variable into a JSON object which can then be used as such.

jQuery.parseJSON(myString);

Wednesday, September 3, 2014

SharePoint 2013 access image URL for custom image field on a page

When you have a custom field on a SharePoint page's properties (of image type) it can be necessary to simply get the image's URL rather than dealing with an image object. We can access the image URL (as a string) by using the following method.

You can also access other fields of simple types (such as text) by using the following code:
var myTextField = (string)SPContext.Current.File.Item["TextFieldName"];

Friday, August 29, 2014

IE8 and RGBa background colors

Simply put RGBa colors in CSS allow a background color with alpha transparency. As an example the following CSS would produce a somewhat transparent red background:
background: rgba(255, 0, 0, 0.8);
In older browsers such as Internet Explorer 8 and below, the rgba background is not supported and it's presence may cause the element not to appear at all. The solution to this problem is to have a "fallback color" which will display in browsers that do not support RGBa, it browsers that do, the fallback color will be ignored. The following example has a fallback color of red:
background:red;
background: rgba(255, 0, 0, 0.8);

Monday, August 18, 2014

How to add a custom web part property to SharePoint

In the case where you need a web part to behave differently based on a variable set at the page level, the use of a custom web part property can come in handy. It allows you to change a custom setting at the web part level, which can then be used in the code to control the web part's behavior.

The following data types can be used as web part properties: string, bool, int, float, enum, System.DateTime, and System.Drawing.KnownColor and SharePoint will display the selection on the form in a relevant way (drop down box used for enum, etc.).

The folloiwng code example, should be added into the web part class (of type Microsoft.SharePoint.WebPartPages.WebPart). It creates a custom property called display, which is of type enum (custom enum called DisplayEnum). It has a default value, and can be accessed in the code via the "_display" variable.


The property then appears under "miscellaneous" on the web part properties pop-up.


Thursday, August 14, 2014

jQuery/JavaScript detect if browser is mobile (uses touch)

The following jQuery code allows you to detect if the browser is running on a touch device (for Apple iOS, Android, and even Windows phones/tablets). Other solutions I have seen often forget to take into account Windows devices, which while uncommon, it is important to not leave them with a bad user experience.
var TouchDevice = ('ontouchstart' in window) || (window.DocumentTouch) || navigator.userAgent.match(/Touch/i) == "Touch";
Once you detect if they use a touch device, you can then run your code based on that. One example is to assign a special CSS class for touch device which can be used to handle hovers differently (ie do something else instead of hover) on touch devices.

jQuery only run selected code on a given browser width

Sometime you have jQuery code which only needs to be run when the user's browser is a given width (or perhaps in a width range). In the example below I only want the code to run where the browser width is equal to or below 768 pixels.
if ($(window).width() <= 768) {
       // Code Here
};
I have tested this to work on desktop and mobile browsers.

JavaScript redirection examples

There are two common methods for redirecting users in JavaScript (in the current window).

The first method will not affect the browser history (the back button will not take them back to the page you redirect from). This is good for the login page, where you don't want them going back to the login form.
window.location.replace(url);
The second method will redirect the current window and will leave the page you are redirecting from in the browser history (the back button will work).
window.location = url;

Tuesday, August 12, 2014

SharePoint 2013 enable blob cache for Image Renditions

On SharePoint 2013 you may encounter the following error message: "The blob cache is not enabled in this web application. Image renditions will not be generated until the blob cache is enabled. For information on turning on the blob cache, please review the product documentation." when viewing the available image rendition sizes.

The blob cache is simply a disk based caching method which may be utilised on images, videos and other files.

To enable the blob cache on your SharePoint server simply open the web.config file, locate the BlobCache tag (using the find dialog) and change the "enabled" attribute from "false" to "true". You may then need to perform an iisreset for the changes to take affect.

Thursday, August 7, 2014

jQuery detect hover on an element

A navigation menu which expands when the user hovers over it, needs to detect when the user has stopped hovering in order to close the expansion. I came across a simple fix using angularJs which is able to detect the mouse hovering (coming and going) and display the menu accordingly.

The above code uses the angualrJs mouse over (ng-mouseover) and mouse leave (ng-mouseleave) directives to call functions which open and close the expanded menu. The mouse leave function checks if the user is still hovered over a given element and will close the expanded menu if appropriate.

Thursday, July 24, 2014

ReportViewer control not loading correctly in chrome

When viewing the ReportViewer control in Google Chrome, an issue occurs where the ReportViewer toolbar is visible, a loading box appears, but the report content does not load. This is an issue with the div that contains the actual report not being visible.

Setting the width and height of the ReportViewer control itself, will correct this issue, but this is not ideal for dynamic reports where the dimensions can change. I have found that by setting Width/Height to 100% and SizeToReportContent to true, the report will load correctly.

Tuesday, July 1, 2014

Transactions and Entity Framework using TransactionScope

Sometimes you may wish to make a series of database calls in Entity Framework, but may need to reverse these calls if any single one fails. This can be accomplished using TransactionScope and try/catch.

Monday, June 30, 2014

C# autopostback with an update panel on the master page

I have come across an issue where the CMS (such as Ekrtron) uses an update panel on the master page, which may cause postbacks on a control to instead be sent as partial postbacks. This can lead to code not executing as expected.

One fix is to include front-end JavaScript to force a postback, but this can be messy and JavaScript can be disabled by the user.

I have found that you are able to register a control as a postback control (even when you can't access the update panel directly). Simply paste the following line into the page load and reference the control you wish to invoke a full postback.

Thursday, May 22, 2014

SharePoint 2013 add a column to a list via PowerShell

When the requirement to add a new column to a SharePoint list after it's initial creation comes up, using a PowerShell script is a great way of completing the task. It takes away the possibility of user error (naming the field incorrectly across multiple environments for example) and the script can even be checked into source control and used in deployment packages etc.

The following PowerShell code will add a new Boolean field named "Field Name" to the list called "List Name" on the "http://siteurl/" SharePoint installation. The script can of course be modified to add multiple columns, to multiple lists and the various other field types.

Thursday, April 10, 2014

SharePoint 2013 Client-Side Object Model (CSOM) get list items

The client-side object model (or CSOM) which has been available since SharePoint 2010 provides a strong framework for working with SharePoint on the client side. Instead of synchronous calls in server side C# code which can take time and affect the user experience, asynchronous calls can be made client-side which can be quicker and provide a better user experience.

The code above runs CAML query on a SharePoint list and makes an asynchronous call to return the data. If the data is returned successfully a "success function" is run, otherwise the "failure function" is run.

Friday, March 21, 2014

Entity Framework wrapper to return custom objects using LINQ

The complex data types which are automatically generated by Entity Framework are very useful, but sometimes the data may need to be placed in a custom object which is reusable across multiple areas of the code. The entity framework custom type may also have additional unneeded columns or strange naming conventions on the columns which can lead to messy code, so a cleaner custom type is beneficial in this situation.

In the example below there is a wrapper class for getting a single object as well as a list of objects. Instead of using the default complex types (such as SelectEmployeeByDepartment_Result or SelectEmployee_Result), LINQ is used to parse the results into a custom object.


Business logic and other rules can also be placed at this layer (such as converting a SQL bit column into a C# bool object).

Thursday, March 20, 2014

URL Aliasing and Query String in Ektron using Regular Expressions


The Ektron CMS has a powerful URL Aliasing system which can be used to generate more user/search engine friendly URLS. For example instead of having a URL such as: http://mysite.com/Content.aspx?pageid=995&name=Ryan&number=102 you could display it as http://mysite.com/Employees/Ryan/102.

In this example post I am going to show you how to achieve this in Ektron (version 9.0). In this case the page URL and query string (which is validated against Regular Expressions) are formatted into a more friendly URL and the query string is still readable from code behind as with an un-aliased URL.

Firstly log into the Ektron work area and navigate to the 'Settings' tab. Under 'Configuration', then 'URL Aliasing', 'Aliasing Rules' and finally 'RegEx'. Click on 'Add Regular Expression':

The following attributes are required to be filled out before saving:
  • Active: Is the RegEx Alias acitve?
  • Site: Which Ektron site should the rule be applied to?
  • Expression Name: A name for your RegEx Alias.
  • Expression: Enter a RegEx expression that will replace the variables.
  • Expression Map: Enter the original URL with the relevant query string
  • Example URL: Enter an example URL which follows the expression's format.
  • Priority: Assign a priority for your RegEx Alias (the more frequent an alias is used, the higher the priority you would assign).
 In this case I have entered the following values:
  • Active: True
  • Site: Default
  • Expression Name: TestAlias
  • Expression: Employees/(?<name>(\w)/(?<number>([0-9])/
  • Expression Map: Templates/Content.aspx?pageid=995&nameA=${name}&numberA=${number}
  • Example URL: Employees/Ryan/102/
  • Priority: High
The expression contains 2 elements of query string: name which is validated with a regular expression to be a word (\w) and number which is validated with a regular expression to be numeric. You could add any number of query string elements (with advanced regular expression validation), along with static elements (such as 'employees' in this example). If someone attempts to accsess the URL incorrectly, such as http://mysite.com/employees/Jim/alpha they would get a 404 not found error (in this example, it would fail because 'alpha' is not numeric).

The expression map is the location of the actual page in Ektron which you want to place the alias over. In your code you can access the query string using the variables 'nameA' and 'numberA'.

This type of URL aliasing might be useful in a case where you have a code driven page that displays data for a number of elements (such as employees or products) where the query string drives what data is to be displayed.

Thursday, February 6, 2014

C# Session Wrapper

The following C# class is a simple implementation of a wrapper class for sessions. It allows getting, setting and removing of objects (of  a defined type) from the session.

C# Is Email Function

The following snippet is handy when validating if a given string is an email address.
public static bool IsEmail(string emailAddress)
        {
            Regex isEmail = new Regex(@"\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$");
            Match m = isEmail.Match(emailAddress);
            return m.Success;
        }

Monday, January 13, 2014

Team Explorer won't load in Visual Studio 2012

If Team Explorer is no longer loading, allowing check-ins and so on, there may be a corruption in the installation. The activity log for Visual Studio (ActivityLog.xml) is located in the following location: C:\Users\USERNAME\AppData\Roaming\Microsoft\VisualStudio\11.0

If you open this file and scroll to the bottom, you will likely notice errors (which are highlighted in red). The error messages I was getting were:
SetSite failed for package [Microsoft.VisualStudio.TeamFoundation.VersionControl.HatPackage, Microsoft.VisualStudio.TeamFoundation.VersionControl, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a]
End package load [Microsoft.VisualStudio.TeamFoundation.VersionControl.HatPackage, Microsoft.VisualStudio.TeamFoundation.VersionControl, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a]
 This was traced back to a config file located at: "C:\Users\USERNAME\AppData\Local\Microsoft\Team Foundation\4.0\Cache\VersionControl.config" which needed to be deleted.\

After deleting the config file, open up Visual Studio and Team Explorer should now work as expected.