29 October 2011

value does not fall within the expected range

Did you have the following situation? Access to the sharepoint list. Operations in any action, then try to contact list again, but this time, and receive the following message

value does not fall within the expected range.


What to do?

You need to refrash the web and the list!

Use this code:

/// <summary>
/// Refresh a List
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
public static SPList RefreshList(SPList list)
{
     return RefreshWeb(list.ParentWeb).Lists[list.ID];
}

/// <summary>
/// Return the web
/// </summary>
/// <param name="web"></param>
/// <returns></returns>
public static SPWeb RefreshWeb(SPWeb web)
{
     web = new SPSite(web.Site.ID).OpenWeb(web.ID);
     web.AllowUnsafeUpdates = true;
     web.Lists.IncludeRootFolder = true;
     return web;
}

Here is an example of using the code - I had a problem in this case without using Refresh List.

using (SPSite site = new SPSite(siteUrl))
{
  using (SPWeb web = site.OpenWeb(webId))
  {
    // Get a list.

    SPList list = web.Lists[listId];
    SPView view = list.Views[viewId];
    SPQuery query = new SPQuery(view);
    String FieldsXml =  "<FieldRef Name=… />";
    query.ViewFields = FieldsXml;
    SPListItemCollection items = list.GetItems(query);
    foreach (SPListItem item in items)
    {    
       
list = Lists.RefreshList(list);
        SPListItem item1 = list.GetItemById(item.ID);
        foreach (SPListItemVersion itemVer in item1.Versions)
        { 

           
        }

    }
  
 }// dispose web 
}// dispose site


Yours,
Roi

19 October 2011

Update SharePoint Master Page with Code (C#)

This time I brought a code which allows you to update SharePoint master page on console project (with C#.Net and not with SPD).

We look for a site that starts with "http://moss2007/Test-Base/", check that the masterpage had the old version, and we will update the new masterpage.

For this subject, we'll have to save the masterpage on a physical file (C:). In addition, we have to approve the masterpage.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint.Administration;

namespace Roi.SharePoint.UpdateMasterPage
{
  class Program
  {
    private const string oldMasterPage = "workgroup.master";
    private const string newMasterPage = "NewMaster.master";
    static void Main(string[] args)
    {
      SPWebApplication wepApp = SPWebApplication.Lookup(new Uri("http://moss2007/"));
      foreach (SPSite site in wepApp.Sites)
      {
        using (SPWeb web = site.RootWeb)
        {
          // Get the current "SPWeb" object
          if (web.Url.StartsWith("http://moss2007/Test-Base/"))
          {
            try
            {
              if (web.MasterUrl.ToLower().Contains(oldMasterPage))
              {
                //read file and upload content as bytre array
                FileStream fileReader = new FileStream(@"C:\" + oldMasterPage, FileMode.Open, FileAccess.Read);
                byte[] fileContent = ReadFully(fileReader, fileReader.Length);
                SPFile file = site.GetCatalog(SPListTemplateType.MasterPageCatalog).RootFolder.Files.Add(newMasterPage, fileContent);
                file.CheckIn("File Check In", SPCheckinType.MajorCheckIn);
                file.Approve("File Approve");
                if (PublishingWeb.IsPublishingWeb(web))
                {
                  // open publish site
                  PublishingWeb pub = PublishingWeb.GetPublishingWeb(web);
                  // change the Master Page
                  pub.MasterUrl.SetValue(pub.MasterUrl.Value.ToLower().Replace(oldMasterPage, newMasterPage), true);
                  pub.CustomMasterUrl.SetValue(pub.MasterUrl.Value, true);
                  pub.MasterUrl.SetInherit(false, true);
                  pub.CustomMasterUrl.SetInherit(false, true);
                  // save changes
                  pub.Update();
                }
                else
                {
                  // change the Master Page
                  web.MasterUrl = web.MasterUrl.ToLower().Replace(oldMasterPage, newMasterPage);
                  web.CustomMasterUrl = web.MasterUrl;
                  // save changes
                  web.Update();
                }
              }
              else // if not workgroup.master
              {
              }
              web.Update();
              System.Console.WriteLine("The web was update.");
            }
            catch (Exception ex)

            {
              System.Console.WriteLine("Error:");
              System.Console.WriteLine(ex.Message);
            }
          }
        }
      }
      // Return to calling environment : Success
      Environment.Exit(0);
    }
    /// <summary>
    /// Reads data from a stream until the end is reached. The
    /// data is returned as a byte array. An IOException is
    /// thrown if any of the underlying IO calls fail.
    /// </summary>
    /// <param name="stream">The stream to read data from</param>
    /// <param name="initialLength">The initial buffer length</param>
    public static byte[] ReadFully(Stream stream, long initialLength)
    {
      try
      {
        // If we've been passed an unhelpful initial length, just
        // use 32K.
        if (initialLength < 1)
        {
          initialLength = 32768;
        }
        byte[] buffer = new byte[initialLength];
        int read = 0;
        int chunk;
        while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0)
        {
          read += chunk;
          // If we've reached the end of our buffer, check to see if there's
          // any more information
          if (read == buffer.Length)
          {
            int nextByte = stream.ReadByte();
            // End of stream? If so, we're done
            if (nextByte == -1)
            {
              return buffer;
            }
            // Nope. Resize the buffer, put in the byte we've just
            // read, and continue
            byte[] newBuffer = new byte[buffer.Length * 2];
            Array.Copy(buffer, newBuffer, buffer.Length);
            newBuffer[read] = (byte)nextByte;
            buffer = newBuffer;
            read++;
          }
        }
        // Buffer is now too big. Shrink it.
        byte[] ret = new byte[read];
        Array.Copy(buffer, ret, read);
        return ret;
      }
      catch (IOException ex)
      {
        System.Console.WriteLine("Error:");
        System.Console.WriteLine(ex.Message);
        return null;
      }
    }
  }
}

Cheers,
Roi Kolbinger

12 October 2011

Daily alerts do not work at SharePoint

Did you encounter a problem alerts list?

Something strange happened to me (hurray sharepoint ...).
Alerts were working fine - just a list daily alerts stopped working. I really do not know why this list.

After searching on google - I realized that take care stsadm commands such problems.

All you have to do is make those commands in the order (and of course replace the http://YOURSITE to your site).

stsadm -o updatealerttemplates -url http://YOURSITE -f "c:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\XML\alerttemplates.xml" -LCID 1037

stsadm.exe -o setproperty -url http://YOURSITE -pn alerts-enabled -pv true

stsadm.exe -o setproperty -url http://YOURSITE -pn job-immediate-alerts -pv "every 5 minutes"

I would like to thank Noam - helped me find the solution and fix the problem.

Your,
Roi