Friday, August 16, 2013

Convert web addresses contained in a string to hyperlinks using a regular expression

In the event you ever need to convert web addresses contained within a string to hyperlinks, I stumbled across some code on StackOverflow that will allow you to do this via a regular expression.  The code for this solution is presented as follows:


private string ConvertUrlsToLinks(string msg) 
{
    string regex = @"((www\.|(http|https|ftp|news|file)+\:\/\/)[_.a-z0-9-]+\.[a-z0-9\/_:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])";
    Regex r = new Regex(regex, RegexOptions.IgnoreCase);
    return r.Replace(msg, "$1").Replace("href=\"www", "href=\"http://www");
}

Special thanks goes to a user by the name of "Rob" on StackOverflow for providing this solution to the problem!

Tuesday, August 13, 2013

Using C# to read data from a SharePoint list using the SharePoint REST API

If you're working with a C# application that is required to read information contained in a SharePoint list located on an external SharePoint farm, the SharePoint REST API can provide just the solution that you're looking for.  Here is some sample code that you can use for accessing the information contained in that SharePoint list:

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Web.Script.Serialization;

namespace Sample
{
    public class SharePointListReader
    {
        ...

        public List<SharePointListItem> GetAllSPListItems()
        {
            List<SharePointListItem> posts = new List<SharePointListItem>();
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://webapp/site/_api/web/lists/getbytitle('listName')/items?$select=id,Title");
            request.Method = "GET";
            request.Accept = "application/json;odata=verbose";
            request.ContentType = "application/json;odata=verbose";
            request.Credentials = System.Net.CredentialCache.DefaultCredentials;
            WebResponse response = request.GetResponse();
            Data data = null;

            // Read the returned posts into an object that can be consumed by the calling application
            using (response)
            {
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    try
                    {
                        string jSON = reader.ReadToEnd();
                        data = serializer.Deserialize(jSON);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(string.Format("An error occurred when reading the list items from SharePoint: {0}; {1}", ex.Message, ex.StackTrace));
                    }
                }
            }
            foreach (SharePointListItem post in data.d.results)
            {
                posts.Add(post);
            }
            return posts;
        }
    }

    public class Data
    {
        public Results d { get; set; }
    }

    public class Results
    {
        public SharePointListItem[] results { get; set; }
    }

    public class SharePointListItem
    {
        public string id { get; set; }
        public string Title { get; set; }
    }
}

Wednesday, August 7, 2013

Visual Studio hotkey for formatting XML: Ctrl+k+f

There will inevitably come a time when you're going to obtain some XML output that you need to review that would, in all honesty, be impossible to read without proper formatting.  A good example would be this response from the the YouTube API that provides a list of videos that a specified user has uploaded (i.e. which would appear as follows in Notepad):




In many cases, simply copying and pasting the XML it into Visual Studio might work, but, in the off chance it doesn't, you might get something like this.




If that happens, simply hit Ctrl+k+f and the XML will be displayed in an easy-to-read format:



Tuesday, August 6, 2013

Calculating the number of days since an event took place using Javascript

If you're looking for a way to determine how many days have passed since a given event took place using Javascript, here is a function that will provide you with the basic functionality that you're looking for:

function calculateDaysSinceEvent(eventDateTime) {
    // Obtain the current date and time
    var todaysDateTime = new Date();
    // Calculate the difference in time between today and when the event took place
    var diff = todaysDateTime - eventDateTime;
    // Convert the difference to a value that represents a day and round the value up
    return Math.round(diff/(1000*60*60*24));
}

Wednesday, July 31, 2013

Javascript function for converting a datetime object to a specific format

Chances are very good that at some point during your journey with SharePoint 2013 you're going to need a javascript function that you can use for converting a datetime object into a nice, user-friendly output string for display purposes.  In the code sample I'm about to provide, the javascript function will return an output string that matches the following format:

Wednesday, 7/13/2013

Here's the basic function that will give you the output presented above:

function getDateString(dateTime) {
 var weekday=new Array();
 weekday[0]="Sunday";
 weekday[1]="Monday";
 weekday[2]="Tuesday";
 weekday[3]="Wednesday";
 weekday[4]="Thursday";
 weekday[5]="Friday";
 weekday[6]="Saturday";

 var dayOfWeek = weekday[dateTime.getDay()];
 var month = dateTime.getMonth() + 1;
 var day = dateTime.getDate();
 var year = dateTime.getFullYear();

 return dayOfWeek + ', ' + month + '/' + day + '/' + year;
}


Saturday, July 27, 2013

Good solution for evaluating your web applications on various mobile devices - Ripple Emulator

If you're looking for a quick and easy solution for being able to evaluate the look and feel of your web applications or SharePoint sites across various mobile devices, the Ripple Emulator add-on for Chrome (created by the folks at tinyHippos) is definitely a great tool to have in your toolbox.  Once you activate/enable the add-on against a targeted page of a site, it will allow you to quickly select a target device and instantly view the layout of your page as it would appear on that device.

For SharePoint 2013 device channels, one important note is that the user agent being posted by the emulator doesn't match the device (at least at the time of this writing); therefore, you'll want to specify the channel to use by appending the following line at the end of URL in your browser's address bar:

?DeviceChannel=DeviceUserAgent

An example would be as follows:

http://SPWebApplication/Sites/Site/default.aspx?DeviceChannel=iPhone

Tuesday, July 2, 2013

Obtain all files contained under folders and subfolders within a SharePoint Document Library

If you are looking for a way to programmatically return all documents of a specific content type located within a given SharePoint Document Library regardless of whether they are contained in folders and subfolders within the given library, I've provided the following sample method that will allow you to do just that:

private SPListItemCollection GetDocumentsByContentType(SPList docLibrary, string contentTypeName)
{
    SPQuery query = new SPQuery();
    query.ViewAttributes = "Scope=\"RecursiveAll\"";
    SPListItemCollection documents = null;
    try
    {
        query.Query = string.Format("<where><eq><fieldref name="ContentType"><value type="Text">{0}</value></fieldref></eq></where>", contentTypeName);
        documents = docLibrary.GetItems(query);
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return documents;
}

The key to this code being able to return all documents, including documents contained under folders and subfolders, is that I've set the ViewAttributes property to be Scope="RecursiveAll".  Without this particular setting, the query would have only returned items that were located immediately under the SharePoint Document Library and would have skipped any documents contained under folders and subfolders.