Showing posts with label VS 2008. Show all posts
Showing posts with label VS 2008. Show all posts

Thursday, 5 July 2012

Value does not fall within the expected range

Currently working on SharePoint and yep, running into strange problems and errors. A better name will be ShareProblems or SharePointless. However, just kidding a bit. But seriously, I run into the following situation:
Situation:
Running a webservice outside SharePoint which will receive data from a webform (on another server) in JSON format. The received data will be saved in a SharePoint list by using the client side object model. So far so good. The initial test where run by the administrator account (used for the installation and configuration of SharePoint). It worked fine. Because I have to run a workflow on 'new item created' on the SharePoint list, I needed a 'normal' account. The admin and service accounts are not allowed to start workflows. So, new AD account defined, gave the appropriate rights and voila... uh, not really.
Problem: 
Part of the code:

ListItemCreationInformation lici = new ListItemCreationInformation();
ListItem item = list.AddItem(lici);

item["Title"] = HttpUtility.UrlDecode(name);
item["Category"] = (categorie == "0") ? 15 : int.Parse(categorie);
item["Street"] = HttpUtility.UrlDecode(street);
item["Postal_x0020_Code"] = HttpUtility.UrlDecode(postalcode);

item.Update();
_clientContext.ExecuteQuery();


I got the return message: Value does not fall within the expected range.
The callstack was something like this:

at Microsoft.SharePoint.Client.ClientRequest.ProcessResponseStream(Stream responseStream) at Microsoft.SharePoint.Client.ClientRequest.ProcessResponse() at Microsoft.SharePoint.Client.ClientContext.ExecuteQuery() at DnmWebServices.MessagingService.SendRtvRequest(String name, String category, String street, String postalcode) in c:\inetpub\wwwroot\DnmWebServices\App_Code\MessagingService.cs:line 128
Line 128 in my case points to the _clientContext.ExecuteQuery.
Solution(s):
It seems there can be several causes.
1). Use of invalid field name. You need to use the internal field name! However, that was not the case in my situation.
2). Change the List View Lookup Threshold value of the web application. Default value is 8, I changed it to 20 and big surprise: it worked! Thanks to this post.
Note: My item has some lookup fields some of which some have more than 8 items.
Little conclusion: So it seems that when using (one of) the system admin accounts, this list view lookup threshold is ignored in one way. By using non-system admin accounts, it can be a show stopper.
Steps to edit this value:

  • Go to Central Administration > Application Management > Manage web applications
  • Select the appropriate web application (in my case the SharePoint - 80)
  • In the ribbon bar, select General Settings > Resourse Throttling
  • Search for the List View Lookup Threshold and change the value to 20.

Wednesday, 12 May 2010

A Solution for: SharePoint 2007 Workflow 'Failed on start'

The Problem:
I struggled some time to get my out-of-the-box (OOB) workflow working on a MOSS 2007 environment (Win2K3 64-bit). I got always the error 'Failed on Start'. The log file on the 12-hive shows two records like this:

w3wp.exe (0x0AF4) 0x0724 Windows SharePoint Services Workflow Infrastructure 72fs Unexpected RunWorkflow: System.ArgumentException: Value does not fall within the expected range. at Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties..ctor(SPWorkflow workflow, Int32 runAsUserId, String associationData, String initiationData) at Microsoft.SharePoint.Workflow.SPWinOEWSSService.MakeActivation(SPWorkflow workflow, SPWorkflowEvent e) at Microsoft.SharePoint.Workflow.SPWinOeEngine.RunWorkflow(Guid trackingId, SPWorkflowHostService host, SPWorkflow workflow, Collection`1 events, TimeSpan timeOut) at Microsoft.SharePoint.Workflow.SPWorkflowManager.RunWorkflowElev(SPWorkflow originalWorkflow, SPWorkflow workflow, Collection`1 events, SPRunWorkflowOptions runOptions)


w3wp.exe (0x0AF4) 0x0724 Windows SharePoint Services Workflow Infrastructure 98d7 Unexpected System.ArgumentException: Value does not fall within the expected range. at Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties..ctor(SPWorkflow workflow, Int32 runAsUserId, String associationData, String initiationData) at Microsoft.SharePoint.Workflow.SPWinOEWSSService.MakeActivation(SPWorkflow workflow, SPWorkflowEvent e) at Microsoft.SharePoint.Workflow.SPWinOeEngine.RunWorkflow(Guid trackingId, SPWorkflowHostService host, SPWorkflow workflow, Collection`1 events, TimeSpan timeOut) at Microsoft.SharePoint.Workflow.SPWorkflowManager.RunWorkflowElev(SPWorkflow originalWorkflow, SPWorkflow workflow, Collection`1 events, SPRunWorkflowOptions runOptions)

The Solution:
I search a lot, but didn't find a working solution. Finally I found it. It turns out that I had changed the account for the SharePoint - 80 application pool (don't remember why, but I did). But, I did this on IIS 7 and not using the Central Administration (CA).
Well, this was a wrong action. Changing the account of one of the SharePoint application pools must be done using the Central Administration (Serviceaccounts on the 'operations' page inside the CA).
And again, a big SharePoint miracle occured: the workflows started to work!

Friday, 7 May 2010

Work around ServerContext en UserProfile troubles

I struggled some time with working with the UserProfile and ServerContext inside SharePoint (MOSS 2007).
I wrote a web part to show more details of a sitecontact. For that, I needed to get details from the UserProfile. The UserProfile was obtained from the UserProfileManager.
The code (web part) was running fine on the SharePoint server itself, but it failed on a client machine.
After struggling a lot, trying different suggestions (like fake SPContext and so on) today I found the solution. You need to use the SPSecurity.RunWithElevatedPrivileges method. RunWithElevatedPrivileges runs the code in the brackets under the SharePoint System Account.
So here is the piece of code I am using:

try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(SPContext.Current.Site.ID))
{
ServerContext context = ServerContext.GetContext(site);
HttpContext currentContext = HttpContext.Current;
HttpContext.Current = null;

UserProfileManager profileManager =
new UserProfileManager(context);

UserProfile user =
profileManager.GetUserProfile("domain\\accountname");

PropertyCollection propCollection =
user.ProfileManager.Properties;

if (user != null && propCollection != null)
{
\\ do your stuff with the 'user'
}
HttpContext.Current = currentContext;
}
});
}
catch (Exception)
{
\\ handle the exception
}


I used this code for retrieving userprofile details. I didn't try to edit the user profile. But I assume it should work as well.

Wednesday, 5 May 2010

Deployment of a class library with WSPBuilder

This topic contains some points about deployment class library with WSPBuilder. For a couple of weeks I am working with WSPBuilder (http://www.codeplex.com/wspbuilder) for creating SharePoint web parts.
Due to the lack of some functionality, I wrote a class library which contains some extension methods for the SPWeb object. At that time the problems began.
Situation:
  • VMWare machine with MOSS 2007 on a Win2003 machine for development and test purposes
  • Visual Studio 2008 with WSPBuilder extension
  • Solution with several WSPBuilder web part projects
  • Custom class library SPExtensions.dll
Three of the WSPBuilder projects in my solution are using this class library with the extension methods in it. That works fine, until you are going to deploy it.
The deployment of the first WSPBuilder project deployed the class library into the GAC. This will affect the build process of the other two WSPBuilder projects. Those two wsp-packages do not have the class library dll in it. This happens even the referenced dll property "copy local" is set to "true". This was/is a real PITA! Because after updating the SPExtensions project, the new dll was not updated in the GAC for the 2nd and 3rd project (because the dll is not included in the wsp file).
So I want the SPExtentions.dll deployed to the WebApplication bin and not in the GAC. After some search and trial and errors I found the solution to get this job done.
  1. Make sure the SPExtensions.dll (or whatever your class library is called) is not present in the GAC anymore. You can use gacutil to uninstall the assembly.
  2. Created a '80' folder with a 'bin' subfolder inside all of the projects (e.g. ..\ProjectFolder\80\bin) that uses the SPExtensions.dll.
  3. Create for each of these project a post build event:
    move /Y "$(TargetDir)SPExtensions.dll" "$(ProjectDir)80\bin"
    NOTE: You should use the "move" command and not the xcopy. The WSPBuilder (by default) sets the DeploymentTarget of the assemblies found in folders, other than GAC and 80\bin to GlobalAssemblyCache. So make sure you move the SPExtensions.dll from the ProjectFolder\bin\release (or debug) to the 80\bin folder created in step 2.
  4. Now you can build the project, create the wsp-files and deploy (or upgrade) them. After step 3, I used the "clean" option, just to be sure that I do not get messed up with some left crap.

Wednesday, 1 October 2008

Building Office 2007 add-in failed due to missing dll's

I had worked some time on a Word 2007 add-in in Visual Studio 2008. After a while, it did not work anymore. I got the following error:



Error 1 The "VerifyClickOnceSigningSettings" task could not be instantiated from the assembly
"Microsoft.VisualStudio.Tools.Applications.BuildTasks, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a". System.TypeInitializationException: The type initializer for
'Microsoft.VisualStudio.Tools.Applications.Hosting.CodeGeneration.VerifyClickOnceSigningSettings'
threw an exception. ---> System.IO.FileNotFoundException:
Could not load file or assembly 'Microsoft.VisualStudio.Tools.Applications.Hosting.v9.0,
Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
or one of its dependencies. The system cannot find the file specified. File name: 'Microsoft.VisualStudio.Tools.Applications.Hosting.v9.0, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' at Microsoft.VisualStudio.Tools.Applications.Hosting.CodeGeneration.VerifyClickOnceSigningSettings..cctor()

Unfortunately, there was almost no documentation on this error. I tried a 'correction' setup and also run the SP1, but that didn't work out. Finally, I found it on http://www.tech-archive.net/. You need to download the Microsoft Visual Studio Tools for the Microsoft Office system (version 3.0 Runtime) (x86) (download here). Run this setup and this will fix the problems.

Don't ask me why it worked before and later on not anymore, I don't know. MS stupidities perhaps? ;)

Tuesday, 24 June 2008

Dynamic assembly loading (.NET framework 2.0)

Introduction


In the .NET framework 3.5, you have a lot of functionality for writing your custom plug-ins of add-ins for your own application. In the .NET framework 2.0 you have not. I was searching a time on the Internet to find out how to do this. Finally I got something, but the description was not completely clear to me, so I figured out how to deal with this. In this post, I wrote in detail how to get your (host) application plug-in enabled. The sample enclosed is written on Visual Studio 2008

The idea is that you have your host application, you plug-in dll and in between an interface. I started with a simple host application, called ThePluginDemo.exe.This application has one form with a menu and a status bar on it. The plugin we will create, add a new menu option called "My Plugins" with a menu item under it called "Plugin Demo". Ok, let's start.

1. Pre-configuration of host application


On the "My Project"details, the root namespace is edited to PluginDemo.Presentation and the Output Path is changed to ..\Output\.

Note: All the projects in this solution will have the same output path, so you don't have to copy/paste the new dll's and stuff when you did a rebuild action.

2. Creating the interface


1. Add a new project to the solution:

An Empty Project was selected, the .NET Framework 2.0 option was selected in the drop down box on the top right corner of the window, and the project was called PluginInterfaces

2. On the "My Project" details , the Root namespace is changed to PluginDemo.Interfaces, the application type is changed to Class Library and also the Output Path is changed to ..\Output\.

3. A new VB-class file was added and the default code was replaced to:

Imports System
Imports System.Windows.Forms

Public Interface IPlugin

  Sub AddMenuItems(ByVal target As MenuStrip)

End Interface

The sub AddMenuItems is the procedure that will be called later on to add the new menu item of the plugin.

Don't forget to add a reference to system.windows.forms.

4. On the project ThePluginDemo (= host application), add a reference to PluginInterfaces.

3. Create the Plug-in project


1. A new, empty project (on .NET framework 2.0) was added to the solution with the name MyPlugin, Root namespace PluginDemo.Plugins, Output Path ..\Output\.

2. References to PluginInterfaces and system.windows.forms were added.

3. A new VB-class file was added, called MyFirstPlugin. The code of the file was edited so it looks like:

Imports PluginDemo.PluginInterfaces
Imports System.Windows.Forms

Public Class MyFirstPlugin

   Implements IPlugin

   Public Sub AddMenuItems( _
       ByVal target As MenuStrip) _
       Implements _
          PluginInterfaces.IPlugin.AddMenuItems

   End Sub

End Class


A procedure was added which will be called when pressing on the menu item created by this plugin:


Public Sub miPluginDemo_Clicked( _
   ByVal sender As Object, _
   ByVal e As EventArgs)

   MessageBox.Show("Plugin Demo menu item clicked!")

End Sub


Note: the parameters sender and e are needed, otherwise the method does not have a signature compatible with delegate 'Delegate Sub EventHandler(...)'.

4. The following code was added to this class and is responsible for adding new menu options:

Private mainMenu As MenuStrip

Public Sub AddMenuItems( _
   ByVal target As MenuStrip) _
   Implements PluginInterfaces.IPlugin.AddMenuItems

   ' Store target menu strip in a local variable
   mainMenu = target
   ' Check if the report plugin menu item already exists
   If Not mainMenu.Items.ContainsKey("miMyPluginDemo") Then
       ' Create the report plugin menu item
       Dim reportMenu As New ToolStripMenuItem("My Plugins")
       reportMenu.Name = "miMyPluginDemo"
       mainMenu.Items.Add(reportMenu)
   End If
   ' Create a ToolStripMenuItem as submenu item with an event
   Dim mi As New ToolStripMenuItem
   mi.Name = "miPluginDemo"
   mi.Text = "Plugin Demo"

   ' Attach a handler that fires a procedure
   AddHandler (mi.Click), AddressOf miPluginDemo_Clicked
   ' Add the toolstripmenuitem to the mainmenu/report
   AddMenuItemToReportMenu(mi)
End Sub

' Procedure to add a ToolStripMenuItem to the mainmenu/report
' location.
Private Sub AddMenuItemToReportMenu( _
   ByVal mi As ToolStripMenuItem)

   Dim tsmi As ToolStripMenuItem
   tsmi = CType(mainMenu.Items.Item("miMyPluginDemo") _
       , ToolStripMenuItem)
   tsmi.DropDownItems.Add(mi)
End Sub

4. Create a plug-in XML file


To load the plugin dynamically, a XML file will be created that lists the available plugins. In this example, just one plugin dll.

1. A new XML file was added to the MyPlugin project and is called PluginList.xml

2. The content was edited, so it looks like:



   
      1
      
          PluginDemo.Plugins.MyFirstPlugin
      
      MyPlugin
   


ID: a sequence number and should be unique when you have more than one plugin you want to use.

Type: the namespace of the MyPlugin project followed by the class name that contains the plugin functionality you want to use.

File: the name of the file created by building the MyPlugin project (without extension).

3. The file properties of this XML file were edited to:

Build action = None; Copy to Output Directory = Copy Always

5. Load plugin in host application


Finally, we edit the host application so it will load the plugin dynamically.

1. Imports to the PluginInterface and to system.reflection were added:


Imports PluginDemo.PluginInterfaces
Imports System.Reflection


2. A new dataset object was added with filename Plugins.xsd.



A DataTable was added and named PluginTool (see also the tag in the xml file)

Three columns were added:

  * Name: ID; DataType: System.Int32; Unique: True

  * Name: Type; DataType: System.String

  * Name: File; DataType: System.String

3. On the mainform, two private variable were declared to hold the content of the XML document as created in step 4.

Private pluginXml As Plugins
Private pluginList As ArrayList

4. Finally, a procedure was added to load the plugin(s). The call to this procedure was placed in the form onload event.

Private Sub LoadPlugins()
   ' Create a new instance of the plugins
   pluginXml = New Plugins

   Try
       ' Try to load the XML file with the
       ' available(plugin(s)) information
       pluginXml.ReadXml("PluginList.xml")

       ' Create a new instance of an ArrayList
       Me.pluginList = New ArrayList

       ' Step through all available PluginTools,
       ' read from the XML file and add them to
       ' the(ArrayList)
       Dim r As Plugins.PluginToolRow

       For Each r In pluginXml.PluginTool
           Dim a As Assembly = Assembly.Load(r.File)
           Dim t As Type = a.GetType(r.Type)
           Dim p As IPlugin = _
               CType(Activator.CreateInstance(t) _
               , IPlugin)
           Me.pluginList.Add(p)
       Next

       For Each o As Object In Me.pluginList
           Dim p As IPlugin = DirectCast(o, IPlugin)
           p.AddMenuItems(Me.MainMenu)
       Next

       ' Show statusbar message when plugin(s)
       ' is (are) (succesfully) loaded
       tsStatus1.Text = "Plugin(s) loaded."

   Catch ex As Exception
       ' Show statusbar message when loading
       ' plugin(s) failed
       tsStatus1.Text = "Plugin(s) not loaded."
   End Try

End Sub

5. This is it! We are done. Running the application shows the plugin loaded.

The complete solution can you download here: ThePluginDemo.zip.


Good luck!