Showing posts with label Visual Studio. Show all posts
Showing posts with label Visual Studio. Show all posts

Saturday, 22 June 2013

Changing the name and URL of a document in Sharepoint using c#

Changing a document's name in Sharepoint programatically, particularly in a webpart for example, is not a trivial process.  In theory, we can use the SPListItem.Item("Name") property and update this.  However you may find that non-administrative users can receive  "permission denied" error when they save this back to the database (using a web.Update()).

This is generally because in order to move (rename) a file in Sharepoint, the user must have "delete" permission on list.
Provided the users have enough permission, then the code below works.  The trick here is to use an SPFile object to update the "Name" property, whilst using an SPListItem object to control the files checkin/out status.

Keen readers will see that I am doing a ValidateFormDigest() in order to prevent the "Page Validation" error if this is caused from a form's POST action, but there is also a "web.AllowUnsafeUpdates = true;" command.  I would prefer not to allow unsafe updates and would recommend you keep this line uncommented, but I have left it in in order to give you an option if you find that this still does not work properly in your situation.


 using (SPSite site = new SPSite(SPContext.Current.Web.Url))
 {
     using (SPWeb web = site.OpenWeb())
     {
         try
         {
             SPUtility.ValidateFormDigest();
             SPListItem target = web.GetListItem(fileUrl);  // fileURL should be set to the full path of the document you are changing

             if (target.File.CheckOutType == SPFile.SPCheckOutType.None)
             {
                  //web.AllowUnsafeUpdates = true;         // Shouldn't need this with the validateformDigest
                  try
                  {                      target.File.CheckOut();
                      SPFile filet = web.GetFile(target.Url);
                      filet.Item["Name"] = newName;     // newName is the new name of the file                               
                                            
                      target.Update();                                            
                   }
                   catch (Exception ex)
                   {
                       web.AllowUnsafeUpdates = false;
                       target.File.UndoCheckOut();
                       ShowErrorMessage("Error validating document: " + ex.Message);  // Deal with error
                       return;
                   }
                   target.File.CheckIn("", SPCheckinType.MajorCheckIn);  // Make major version
                                           
                   web.Update();
                   web.AllowUnsafeUpdates = false;

              } 

            catch (Exception ex)
            {
                ShowErrorMessage("Error: " + ex.Message);  //Deal with error
                //throw;
            }
            finally
            {
                web.AllowUnsafeUpdates = false;
            }

        }
    }

Friday, 8 June 2012

Unexpected Error when deploying web part pages using Visual Studio solution

It is good practice to wrap any Sharepoint web part pages you develop in a feature, and deploy them as a solution using Visual Studio. There are many walkthroughs on how to do this on the net, including this excellent Microsoft effort so I won't go into the details here.

If you follow this technique, the basic steps to developing a deployable feature are:
  1. Make your web part page in the Sharepoint front end or Sharepoint designer 
  2. Once development complete, export the page to a site solution file 
  3. Copy the appropriate section to your Sharepoint deployment soluting project
At this point you will end up with something like this:



Note that my solution includes much more than just a web part page - it also has a masterpage, many images, CSS and javascript/jQuery - in other words all the things you need to make a nice custom web part page all in one deployable feature.

So everything is fine, but then you deploy the solution, and ARGHH! it throws an error! Worse, it throws an "Unexpected Error". This is the least useful error message you can imagine. So whats the solution?

Well after going through all the XML for my features I found the following:

The highlighted line is:






This is the ID of the web part file WHEN IT WAS EXPORTED.

When you deploy this solution to a site, the ID of the file is whatever the next ID available (it's basically an incremental integer). Therefore by leaving in this piece of declarative XML, we are attempting to force the file to use this ID. This is what is causing the "Unexpected error" on deployment.

Simply comment out this line and your solution will deploy. 


Sunday, 27 February 2011

Deploy Office 2003 VSTO add in to All Users using Visual Studio 2008

Deploying VSTO add-ins can be a real pain, at least if you are not using 2010.  Having just successfully deployed my first add-in, I thought it would be useful to explain how I did and the resources I used.

Firstly, it is important that you follow the instructions for the appropriate version of Office and Visual Studio that you are using.  My example is for a legacy solution using Office 2003, created with VSTO Second Edition (Visual Studio 2008).  The general  principles are the same for other editions, but the specifics may be subtly different.

To get started, look at the walkthrough here:

http://msdn.microsoft.com/en-us/library/bb332052.aspx
This is another useful collection of resources:
http://xldennis.wordpress.com/2007/03/04/creating-and-deploying-managed-com-add-ins-with-vsto-2005-se-part-vi/

This explains how to configure a deployment project in Visual Studio 2008 and set up the additional security package required to grant the add-in full trust.  I would recommend you follow the steps in here to create a brand new simple package and get that working first.  I created a simple Word 2003 add-in package to test, rather than the suggested Outlook.

The security package can be downloaded from MSDN here:
http://code.msdn.microsoft.com/VSTO3MSI
Unpackage the download and you should find a .SLN file that has everything pre-configured.  Copy the "SetSecurity" package from here and add it to your solution as explained in the walkthrough.  Configure the Setup project's outputs as described, and you should end up with a package that looks something like this:


Once you have built your setup package, you can find the .MSI and .EXE files in solution bin/debug (or bin/release) directory.   Run the .exe and you should have installed your add-in onto your development machine.  Run the appropriate Office application to check that the pop up message appears to confirm this.  Your development computer should have all the pre-requisites installed, so if this doesn't work you have probably missed something in the walkthrough, or have perhaps used an incorrect version of the setup project, so go back and double check everything.   It is vital that you get a simple version working at this stage, or it will cause you all sorts of problems down the line.

Once you have a simple install project working you can go about making it available to ALL USERS on the machine.  This is not  covered in the walkthrough,  although there is mention of it for newer versions of Office in this excellent blog here:
http://blogs.msdn.com/b/mshneer/archive/2008/04/24/deploying-your-vsto-add-in-to-all-users-part-iii.aspx

In Office 2003, deploying to all users is actually really simple:  all we have to do is copy the registry keys that have automatically been generated for us by Visual Studio in the Setup project from HKCU to HKLM.  In practice, this mean highlighting your setup project (called Word2003AddInSetup in my example), right click and choose "View" and "Registry":
This will open up the registry editor.   Now, expand all, and renambe the "Software" key in HKLM to some temporary name (say "SoftwareTESTTESTTEST").

You can now drag the "Software" key from the HKCU leaf to the HKLM leaf.  Once done, drag your renamed "SoftwareTESTTESTTEST" key from HKLM to HKCU, and rename this back to "Software".  You should now have something that looks like this:
One thing that is not really very well documented at all, and kept me scratching my head for many days, is that you must set the "InstallAllUsers" property on the setup package to "True".  This is obvious, but not mentioned anywhere! 


That's it!  Build your setup solution and re-install it (you will have to un-install your original version first).  You should now find that any user that logs into the machine will have the add in enabled.

Please note that if you are using Office 2007, this technique does not work - you will have to refer to the blog post linked above to learn how to set up the appropriate registry keys.