SharePoint Get Emails for Users Associated to SPListItem

Challenge

On a recent project, I needed a way to build a list of emails for a given SPListItem. Considering most of you just want the code, here it is:

Solution

public List GetEmailsForUsersAssociated(SPListItem item)
        {
            //list for emails
            List emails = new List();

            //omitted for brevity...

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    using (SPSite ospSite = new SPSite(siteUrl))
                    {
                        using (SPWeb currentWeb = ospSite.OpenWeb())
                        {
                            SPListItem p_Item = currentWeb.GetListItem(dataSiteName + "/" + itemUrl);

                            SPRoleAssignmentCollection usersOrGroups = p_Item.RoleAssignments;
                            foreach (SPRoleAssignment userOrGroup in usersOrGroups)
                            {
                                if (userOrGroup.Member.GetType().ToString() == "Microsoft.SharePoint.SPUser")
                                {
                                    //Get user and add to email list
                                    SPUser user = (SPUser)userOrGroup.Member;
                                    if (!String.IsNullOrEmpty(user.Email))
                                        if (!emails.Contains(user.Email))
                                            emails.Add(user.Email);
                                }
                                else if (userOrGroup.Member.GetType().ToString() == "Microsoft.SharePoint.SPGroup")
                                {
                                    String groupName = userOrGroup.Member.ToString();
                                    SPGroup group = currentWeb.SiteGroups[groupName];
                                    SPUserCollection users = group.Users;

                                    foreach (SPUser user in users)
                                    {
                                        if (!String.IsNullOrEmpty(user.Email))
                                            if (!emails.Contains(user.Email))
                                                emails.Add(user.Email);
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
            });

            return emails;

Additionally, if you would like to remove duplicate emails, you can do so with some quick LINQ:

string bcc = emails.Distinct().ToList().Aggregate((First, Second) => First + ";" + Second);
Share and Enjoy:
  • RSS
  • del.icio.us
  • StumbleUpon
  • Digg
  • Twitter
  • Mixx
  • Facebook
  • LinkedIn
  • Reddit
  • Yahoo! Buzz
  • Technorati
  • co.mments
Posted in C#, LINQ, SharePoint | Tagged , , | Leave a comment

When to Use AJAX

Consider Your Goals

When considering implementing an AJAX pattern on a website or web application, you should first consider your goals. While there are several good reasons to implement AJAX, there are also several bad reasons. This all depends on what you’re trying to accomplish.

AJAX the Wrong Way

There are a lot of pitfalls if you choose to implement AJAX on something like a blog or a company site. For example, you implement AJAX so that when a user clicks on a top-level navigation link, the main content of the page changes. While this may seem like a relatively spiffy thing to do, it is not a good practice for several reasons:

  1. Search Engine Optimization (SEO) is not optimized.  Search engine crawlers will not be able to follow the JavaScript and read content that is injected to the DOM.  However, an article posted by David Pireck gives us some insight on how to workaround this issue.
  2. Users may have trouble navigating the site. Users might not be able to bookmark pages or access the history via the browsers back and forward buttons properly.  Reluctantly, I found this jQuery history plugin to assist with this matter.
  3. Your website may be less compatible with other browsers.

AJAX the Right Way

Albeit quirky at times, the Facebook chat widget is a wonderful implementation of AJAX. The widget uses AJAX to retrieve a list of your friends, displays whether they are idle, and allows you to communicate with them without refreshing the entire page. All of this is a reflection of using the right tool for the right job.

Let’s assume you create a company website for your insurance company. The company website offers a wizard for users to request a quote. Implementing AJAX may be a smart decision if you:

  1. Do not wish to display a portion of the wizard in search results.
  2. Implement a client-side mechanism that allows the user to navigate to a step with the browser’s back or forward buttons.
  3. Display a progress bar indicating the users place in the wizard.

Favorite Examples

Lastly, here are some public facing websites featuring some of my favorite AJAX implementations:

In Conclusion

I hope the above information and examples were of use to you. If you feel you can contribute to this article, feel free to post a comment below!

Share and Enjoy:
  • RSS
  • del.icio.us
  • StumbleUpon
  • Digg
  • Twitter
  • Mixx
  • Facebook
  • LinkedIn
  • Reddit
  • Yahoo! Buzz
  • Technorati
  • co.mments
Posted in AJAX, Best Practices | Tagged , | Leave a comment

Doxygen Generate C# Documentation

Challenge

I recently had the task to create an API library for software I designed for a client. I was looking for a simple way to generate C# documentation using the XML comments in Visual Studio. I work tirelessly to comment each of my functions, and wanted to see my comments put to good use.

Research

I spent several days researching various tools; trying to find the best fit. The first tool I used was NDoc. NDoc was easy to install but appeared to be a dead project as it was only compatible up to .Net 1.1.

Next, I looked into docu. Keeping in mind that docu was in alpha phase, I didn’t expect a full product. I installed this tool on Windows 7 and Windows Server 2003. Neither installation of the tool was successful.

Solution

After experiencing slight defeat, I discovered Doxygen. I was pleased to see the tool had several output formats. This was something of value I could offer to my clients. In addition, I was also pleased to see that Doxygen was compatible with several other languages such as C++, Java, Objective-C, Python, PHP, and others.

I will likely be using Doxygen on future projects. You can get it here.

Recommendations?

If you’ve had a challenge with a similar endeavor, feel free to share your experience and any recommendations for other tools below. Happy coding!

Share and Enjoy:
  • RSS
  • del.icio.us
  • StumbleUpon
  • Digg
  • Twitter
  • Mixx
  • Facebook
  • LinkedIn
  • Reddit
  • Yahoo! Buzz
  • Technorati
  • co.mments
Posted in C#, Software Documentation | Tagged , | 1 Comment

WiTricity, a Stock to Watch

What is it?

WiTricity is an emerging technology that will enable hardware devices to receive electricity wirelessly. The technology uses coupling between electromagnetic resonant objects, and has proven to charge a 60 watt light bulb using two 5-turn copper coils of 24 in, that were 7 ft away, at roughly 45% efficiency.

Who’s Behind It?

An MIT research team led by Professor Marin Soljačić, founded WiTricity Corp., located in Watertown, MA in late October of 2007.

See WiTricity in Action

Get excited and checkout this video:

Investment Advice

Because WiTricity uses copper coils, many are speculating that there will be a rise in demand for copper worldwide. In addition, there is also speculation that GE will align with MIT to incorporate WiTricity into new product lines.

When WiTricity makes their big IPO, the WiTricity stock symbol can be found here through Google.

Share and Enjoy:
  • RSS
  • del.icio.us
  • StumbleUpon
  • Digg
  • Twitter
  • Mixx
  • Facebook
  • LinkedIn
  • Reddit
  • Yahoo! Buzz
  • Technorati
  • co.mments
Posted in Emerging Technology, Investing | Tagged , , | 1 Comment

SharePoint List and LINQ using jQuery and IhttpHandler

Challenge

I was looking for a simple way to use jQuery and a few parameters to retrieve data from a SharePoint List in JSON format. Here’s my approach…

Javascript

In the below method, I pass in the list name, url to handler, and some query parameters:

//request menu items
$.ajax({
    dataType: 'json',
    url: '_layouts/data/list.ashx',
    data: {query: 'get', list: 'navigation'},
	success: function(data){
		//omitted
	}
});

Visual Studio 2008 SharePoint Project

I created a new SharePoint project in Visual Studio 2008. The .ashx file contains a page directive with the same class as the .cs file. In order for the handler to work, I added the following file structure to the project:

  • Templates/
    • LAYOUTS/
      • Data/
        • List.ashx
        • List.cs

C# Namespaces

My handler class (List.cs) uses the following namespaces:

using Microsoft.Office.Server;
using Microsoft.Office.Server.Administration;
using Microsoft.Office.Server.UserProfiles;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

The class must inherit from the IhttpHandler:

public class List : IHttpHandler

C# IhttpHandler

Don’t forget to implement IsReusable

#region IHttpHandler Members

    public bool IsReusable
    {
        // Return false in case your Managed Handler cannot be reused for another request.
        // Usually this would be false in case you have some state information preserved per request.
        get { return true; }
    }

C# Process Request

The code below simply gets the parameter “query” and uses it to map to a specific function. You will also notice I am using the JavaScriptSerializer class to return the JSON. This pattern allows me to easily use jQuery to query SharePoint Lists. The only thing more efficient would obviously be implementing a REST pattern.

    public void ProcessRequest(HttpContext context)
    {
        string query = context.Request.Params["query"];

        context.Response.Clear();
        context.Response.ContentType = "application/json";

        if (!string.IsNullOrEmpty(query))
        {
            try
            {
                IEnumerable items = null;
                switch (query)
                {
                    case "GetUser":
                        GetUser(context);
                        return;
                    case "get":
                        items = GetItems();
                        break;
                    //omitted
                }

                JavaScriptSerializer ser = new JavaScriptSerializer();
                context.Response.Write(ser.Serialize(items));

            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
        }
    }

    #endregion

C# LINQ

The code below is used to return a 2-dimensional list. It retrieves the list via a request header parameter known as “list”.

private IEnumerable GetItems()
    {
        string listName = HttpContext.Current.Request.Params["list"].ToString();
        SPList list = SPContext.Current.Web.Lists[listName];

        var items = from SPListItem item in list.Items
                    select new { Name = item.Name, Value = item["value"].ToString() };

        return items;
    }

If this code was of use to you, leave me some love. Recommendations are also appreciated.

Share and Enjoy:
  • RSS
  • del.icio.us
  • StumbleUpon
  • Digg
  • Twitter
  • Mixx
  • Facebook
  • LinkedIn
  • Reddit
  • Yahoo! Buzz
  • Technorati
  • co.mments
Posted in LINQ, MOSS, SharePoint, jQuery | Tagged , , , | 2 Comments

One or more field types are not installed properly. Go to the list settings page to delete these fields. SharePoint Error.

Problem

Our test team is working hard and we finally had ironed out all the bugs on our development and test server. Unfortunately, upon deploying to our production server we ran into this error:

One or more field types are not installed properly. Go to the list settings page to delete these fields.

In my research I read an article that explains that this issue may occur if a field name has been misspelled or removed. Considering we had not modified our field names between development and test I had a strong feeling this recommendation would not fix our problem.

Solution

I had our build manager redeploy the build to production and this fixed the issue. I’m not sure exactly what caused the problem but it was entirely related to our configuration and build procedure. My guess is that the build manager may have incorrectly imported a list template or added extra space into the name of the list.

I hope this article provides you some insight.

Share and Enjoy:
  • RSS
  • del.icio.us
  • StumbleUpon
  • Digg
  • Twitter
  • Mixx
  • Facebook
  • LinkedIn
  • Reddit
  • Yahoo! Buzz
  • Technorati
  • co.mments
Posted in MOSS, SharePoint | Tagged , , | 1 Comment