Wednesday, October 31, 2007

Another simple code snippet - using the user field


A user field in a list allows people to choose a user for each list item.


When looking at the value that is stored, we can see it is a lookup field - and is stored using the format ID#useraccount. For example:

listitem["User Name"] will have "1#development\ishai"
Click on the image below to see it in action in visual studio:





Where does this number come from? well, everytime you create a site in sharepoint, sharepoint creates a list for users. Each user gets an ID in the list, and when you add a user column to a list in that site, it is infact a special case of a lookup column into the users list. So in each site the same user will have a different ID.



So how do we use this field in code?

Get a user from a list item:



To get a user we use the SPFieldUserValue class, which accepts a SPWeb and a string value as parameters. The string value is the value from the list that contains the ID and the account name. Once we have that, we can use the SPFieldUserValue to get information about the user.

Example:


 using (SPSite site = new SPSite("http://portal"))

            {

                using (SPWeb web = site.OpenWeb())

                {

                    SPList list = web.Lists["Example For Users"];

                    SPListItem item = list.Items[0];

 

                    SPFieldUserValue userValue = new SPFieldUserValue(web, item["User Name"].ToString());

                    if (userValue.User.LoginName == web.CurrentUser.LoginName)

                    {

                        //do something!

                    }

                }

            }







Adding a value to a user field



This is the same, but in reverse. We use the same class (SPFieldUserValue ) and give it the values we want for the user.



using (SPSite site = new SPSite("http://portal"))

            {

                using (SPWeb web = site.OpenWeb())

                {

                    SPList list = web.Lists["Example For Users"];

                    SPListItem item = list.Items[0];

 

                    SPFieldUserValue userValue = new SPFieldUserValue(web, web.CurrentUser.ID, web.CurrentUser.LoginName);

                    item["User Name"] = userValue;

                    item.Update();

                }

            }



The image below shows the list after I updated the list item:






Monday, October 29, 2007

Failed to instantiate file "default.master"

I was building a new solution package that deployed a site definition, and when I created a new site from that definition I got the error "Failed to instantiate file "default.master" from module "DefaultMasterPage": Source path "default.master" not found.".
It turns out that I wrote the wrong folder name in the webtemp xml file. Thank you Bjarne L. Gram for writing about this.

Wednesday, October 24, 2007

Code Practices - getting\setting values from\to the lookup and the hyperlink fields

How to get data from a field that is a lookup? how to set data into a field that is a hyperlink?
I don't believe I didn't write about this yet. It's so common!

For both cases, sharepoint object model exposes classes to help us get or set the data we want. These are the SPFieldLookupValue and the SPFieldUrlValue.

Example 1: Set the url field of a link


Use the SPFieldUrlValue class to create an object that holds the url to link to, and the title to display:

SPList list = web.Lists["Links"];

SPListItem newLink = list.Items.Add();

SPFieldUrlValue value = new SPFieldUrlValue();

value.Description = "test";

value.Url = "http://www.microsoft.com/sharepoint";

newLink["URL"] = value;

newLink.Update();

Example 2: Get the url field of a link


Use the SPFieldUrlValue class to create an object that gets the url and description:

SPList list = web.Lists["Links"];

SPListItem existingLink = list.Items[0];

SPFieldUrlValue value = new SPFieldUrlValue(existingLink["URL"].ToString());

string linkTitle = value.Description;

string linkURL = value.Url;

Example 3: Set the value of a lookup field for a known title and ID


In the following example I am using SPFieldLookupValue to set the value of a lookup field ("Group Name") to item "Program Operations", whose ID is 14:

SPList list = web.Lists["Branches"];

SPListItem newBranch = list.Items.Add();

newBranch["Title"] = "A New Branch";

SPFieldLookupValue newValue = new SPFieldLookupValue(14,"Program Operations");

newBranch["Group Name"] = newValue;

newBranch.Update();

Example 4: Get the value of a lookup field from an item


Here I am reading the value of the group name field (which is a lookup field in the branches list):

SPList list = web.Lists["Branches"];

SPListItem existingBranch = list.Items[0];

SPFieldLookupValue group = new SPFieldLookupValue(existingBranch["Group Name"].ToString());

int lookedUpItemID = group.LookupId;

string lookedUpItemTitle = group.LookupValue;

Sunday, October 21, 2007

Performing joins between SharePoint lists (link)

Check it out: Performing joins between SharePoint lists by fellow MVP Sahil Malik, explains how to use sharepoint designer to show two linked lists as one. I was going to write about it, but he beat me to it.
Maybe next time I won't go bush-walking on the weekend and write more?


Oh, about the weekend - I found some MOSS that I thought would interest you:



Red Moss (Seratadon?)





Wednesday, October 17, 2007

Using the SharePoint People Picker


A long time ago (beta2 time) I published a post about the people picker control (MOSS 2007 controls - have a bit of fun with the "people editor" form control!).
Lately I had many comments on that post from people who have been having issues getting the value the user selected, and asked for another demo of using the control.
So here it is:



The code creates three controls - a PeopleEditor (from the Microsoft.SharePoint.WebControls namespace), a button and a textbox. The button has an click event that itirates over the users picked in the PeopleEditor and writes them to the text box. Simple!





public class PeoplePickerWebPart : System.Web.UI.WebControls.WebParts.WebPart

    {

        PeopleEditor pe;

        TextBox t;

        Button b;

 

        protected override void CreateChildControls()

        {

            base.CreateChildControls();

            pe = new PeopleEditor();

 

 

            this.Controls.Add(pe);

            b = new Button();

            b.Text = "Click me to see the users";

            this.Controls.Add(b);

            b.Click += new EventHandler(b_Click);

            t = new TextBox();

            t.TextMode = TextBoxMode.MultiLine;

            this.Controls.Add(t);

        }

 

        void b_Click(object sender, EventArgs e)

        {

            foreach(string ent in pe.CommaSeparatedAccounts.Split(','))

            {

                t.Text += ent + Environment.NewLine;

            }

        }








Results:

The web part as the page loads





The web part does "check names"





The web part after the click of the button







Using the SharePoint date control in a web part


After a lot of requests in comments in this blog, I figured this must be very hard to implement. So I tried, and found it quite easy. Here is a code sample of a web part that uses the sharepoint date control



The code is simple - three controls - a DateTimeControl from the Microsoft.SharePoint.WebControls namespace, a button and a text box.
The button has a click event. On click, the event sets the text box to display the date that was selected in the DateTimeControl.





public class DatePickerWebPart : System.Web.UI.WebControls.WebParts.WebPart

    {

        DateTimeControl dtc;

        TextBox t;

        Button b;

 

        protected override void CreateChildControls()

        {

            base.CreateChildControls();

            dtc = new DateTimeControl();

            dtc.ID = "dtc" + this.UniqueID;

            this.Controls.Add(dtc);

            b = new Button();

            b.Text = "Click me to see the date";

            this.Controls.Add(b);

            b.Click += new EventHandler(b_Click);

            t = new TextBox();

            this.Controls.Add(t);

        }

 

        void b_Click(object sender, EventArgs e)

        {

            t.Text = dtc.SelectedDate.ToLongDateString();

        }

    }






Here is the result:

This is the web part when the page first loads






This is the web part when you click on the date picker






This is the web part when you click on the button




See? it is simple!

Tuesday, October 16, 2007

Ajax in SharePoint

Fellow MVP Daniel Larson will be hosting a live conference to show the SharePoint Ajax Toolkit. Read about it in Daniell's blog post.

Why be a sharepoint developer?

Sorry, can't resist posting the following link to Tony's post " I don’t care if you don’t want to develop on SharePoint, and neither does your boss". So true...
Bob Mixon also wrote a nice article about what is required from a sharepoint person Are You Ready For SharePoint

Monday, October 15, 2007

SharePoint by Day, SharePint by Night @ SharePoint Connections in Vegas!

Andrew Connell posted an invite in his blog for an "informal SharePoint conversation" at the Coral Reef Bar in the Mandalay hotel during SharePoint Dev Connections in Vegas.
I will be there, so if you want to have a chat, come on in!

Wednesday, October 10, 2007

Email Alerts not getting sent, while other emails are

Had this recently at a customer's - the server would send emails if you added a user to a site, or if you registered for an alert - you'd get the email saying the alert was activated. But when someone added an item to the list, you didnt get the email for the alert.

Looking in the Timer Job Status list in central admin showed that we had two front end servers, and on one of them the "Immediate Alerts" job was always on "failed". After much research and head banging, a collegue of mine suggested I look into the relay settings of the SMTP server.
When I opened the relay settings I found to my surprise that the IP addresses that were configured to allow relay did not include the IP address for one of the front end servers. Adding that IP address resolved the problem.

Now the alerts are working, but for some reason the " Send e-mail when ownership is assigned" on a task list is not working. Wish I knew how to fix that...

Monday, October 08, 2007

Blogrush - removed

After a few days evaluating blogrush, I reviewed it and decided that it is a more of a service for people with general BS blogs, and not professional, audience targeted ones. Why should people see links to blogs about starwars in a sharepoint blog?
So it is removed, and now my blog is more usable...

Monday, October 01, 2007

Business Data Columns : updating programmatically

When you create or update a list item programmatically, and one of the fields you want to set is a BDC field that displays several columns, setting the field does not set the additional columns - just the selected ID. This puzzled me, So I sent the question out to all the MVP's and sure enough - Nick Swan had an answer and was happy to share it with all of us.