Point Deep

Mundeep’s Tech Blog

Archive for the ‘.NET’ Category

Updating the Created Date of a Document or List Item Programmatically

Posted by mundeep on May 22, 2009

A common tasks developers are required to do with Sharepoint is migrated documents from either legacy systems or older Sharepoint sites into a document library. There are many ways to do this documented out there (most commonly using the Files.Add method of the API), but one of the common requirements during this ‘migration’ is to retain the Created Date or Created By fields. Sowmyan’s blog has a good description of how to set the Created By/Modified By user fields here.

Updating the Created Date of a document or list item in Sharepoint is even easier, simply set the “Created” field of the item to the value you wish to set. For example if using the Files.Add methods in the API (as described by Dave Hunter) then the following code snippet will update the Created Date:

// add the file
SPFile file = docLib.RootFolder.Files.Add(newFileName, inputStream);
// get the list item for that file
SPItem item = file.Item;
//Set the Created Date
item["Created"] = "2009-02-26 15:00:00";
item.Update();

Posted in .NET, Sharepoint | Tagged: , , , | Leave a Comment »

InfoPath 2007 Custom Field Validation (Programmatic)

Posted by mundeep on May 20, 2009

Adding custom (programmatic) field validation to a form in InfoPath 2007 is quite easy. Firstly make sure you have set your programming language of choice by going to the Tools menu then “Form Options” -> “Programming”, and then selecting your preferred language under “Form template code language”. For this example i am going to be using C#.

Back in your form design window right-click on the field you wish to validate, and select “Programming” -> “Validating Event”. This will open a “Visual Studio Tools for Applications” (VSTA) window, and generate the following code snippet:

        public void myFieldName_Validating(object sender, XmlValidatingEventArgs e)
        {
            // Write your code here.
        }

Obviously this code is not doing any validation yet, we just need to insert our validation code in place of the “your code here” comment. Let us try a simple validation of ensure the data entered in the field is at least 3 characters long with the following code.

public void myFieldName_Validating(object sender, XmlValidatingEventArgs e) {
    //Check the Length of the NewValue of the field
    if (e.NewValue.Length < 3) {
        //Report the validation error back to the client on the form
        e.ReportError(e.Site, false, "Please Enter a valid MyField");
    }
}

As mentioned in the comments e.NewValue retrieves the ‘New’ value that is being entered/inserted into the field before it has been set and e.ReportError sends any validation errors back to the form for the client (read the MSDN article for details on the parameters of ReportError).

Unfortunately there is a minor issue with this basic piece of code and that is due to the fact that the validating event also gets fired during the loading of the form and as shown in this kb article we need to check the XmlOperation that is being performed when the validation is fired. This means updating our code to the following.

public void myFieldName_Validating(object sender, XmlValidatingEventArgs e)  {
    //Ensure validation is only done when inserting or changing a value
     if (e.Operation == XmlOperation.Insert || e.Operation == XmlOperation.ValueChange) {
        //Check the Length of the NewValue of the field
        if (e.NewValue.Length < 3) {
            //Report the validation error back to the client on the form
            e.ReportError(e.Site, false, "Please Enter a valid MyField");
        }
    }
}

Save your code changes and while still in VSTA build the project to ensure you don’t have any coding errors (Ctrl+Shift+B, or from the menu “Build” -> “Build ‘MyFormName’”). If you get a “Build succeeded” message in the status bar you can close the VSTA window and then preview your form to see your validation in action.

Posted in .NET, Office | Tagged: , , , , | Leave a Comment »

Checking if a SPFolder Exists

Posted by mundeep on February 24, 2009

Ran into a colleague’s code that was incorrectly trying to check if a folder existed. It was something like:

private bool CheckFolderExists(SPWeb parentWeb, string folderName) {
    SPFolder folder = parentWeb.GetFolder(folderName);
    if (folder == null) {
        return false;
    }
    else {
         return true;
    }
}

however this always returns an actual SPFolder object, and the correct way is to check the Exists property of the returned object ie:

private bool CheckFolderExists(SPWeb parentWeb, string folderName) {
    SPFolder folder = parentWeb.GetFolder(folderName);
    return folder.Exists;
}

NB: Yes, this post is almost identical to my earlier one about checking if an SPWeb object exists.

Posted in .NET, Sharepoint | Tagged: , , | 2 Comments »

Converting InfoPath Forms into Visual Studio Projects

Posted by mundeep on February 16, 2009

I was recently trying to converting some InfoPath froms that had been created as per default in the InfoPath client application (and using Visual Studio Tools for Applications for Code-Behind) into a Visual Studio project to be opened in Visual Stdio 2005 as per the MSDN HowTo. However when i reached the last step and opened the masnifest.xsf it would just me show me the xml contents of the file and not the visual form editing GUI that you see in the InfoPath client. Solution was to install Visual Studio 2005 Tools for Office Second Edition (VSTO 2005 SE) and then reopen the project.

Posted in .NET, Sharepoint | Tagged: , , , , | Leave a Comment »

sgen.exe exited with code 1

Posted by mundeep on February 12, 2009

While developing a Sharepoint solution using WSPBuilder and Visual Studio 2005 i noticed that i would get the following error when trying to compile a Release build (on further examination i noticed that it would occur whenever i switched between release & debug builds):

“sgen.exe exited with code 1″

After doing some research i found a several different suggested solutions:

  1. Remove and re-add the project from the solution as per this forum post.
  2. Turn off the “Generate serialization assembly” option in the Build tab of Project Properties see this blogpost and this one.
  3. Remove the previous version of the assembly from the GAC as per this blogpost.

To determine which solution i should use required some more research on sgen.exe does. As per the MSDN article:

When the XML Serializer Generator is not used, a XmlSerializer generates serialization code and a serialization assembly for each type every time an application is run. To improve the performance of XML serialization startup, use the Sgen.exe tool to generate those assemblies the assemblies in advance. These assemblies can then be deployed with the application.

The XML Serializer Generator can also improve the performance of clients that use XML Web service proxies to communicate with servers because the serialization process will not incur a performance hit when the type is loaded the first time.

These generated assemblies cannot be used on the server side of a Web service. This tool is only for Web service clients and manual serialization scenarios.

If the assembly containing the type to serialize is named MyType.dll, then the associated serialization assembly will be named MyType.XmlSerializers.dll.

This means that as well as being impractical the first solution doesn’t really solve the problem.

The second solution ’solves’ the probelm, however based on the MSDN article it may result in a minor performance hit if the serialization class is required.

In my case i was performing some manual serialization and thus decided to live with the minor annoyance of soltuion #3 and removing the existing assemblies from the GAC whenever i ran into the error.

Posted in .NET, Sharepoint | Tagged: , , , , | Leave a Comment »

How to Html Encode a string in a c# windows application?

Posted by mundeep on August 21, 2008

To HtmlEncode a string from within a Windows application you need to make sure that:

1) You have a reference to System.Web

2) You use the System.Web.HttpUtility.HtmlEncode method.

For example:

using System.Web;

public string MyHtmlEncode(string inputString) {
     return HttpUtility.HtmlEncode(inputString);
}

Posted in .NET | Tagged: , , , | Leave a Comment »

Clearing Active Directory Values in C#

Posted by mundeep on August 5, 2008

To clear values in Active Directory they must be set to NULL and not “” or empty.
This can easily be done by using the Clear() method on the property value collection for the active directory field you wish to update.

using System.DirectoryServices;

public void ClearAdField(string fieldName, DirectoryEntry adEntry) {
  PropertyValueCollection adValue = adEntry.Properties[fieldName];
  adValue.Clear();
  adEntry.CommitChanges();
}

Posted in .NET | Tagged: , | Leave a Comment »

A referral was returned from the server

Posted by mundeep on July 17, 2008

Running some code that updates active directory i ran into the following error message when trying to search for a user “A referral was returned from the server“. The problem was that the LDAP query i had used the wrong DC, and not the one that the user was in.

eg. my LDAP connection was: LDAP://devdcserver01.domain.int/DC=development,DC=domain,DC=int

when it should have been: LDAP://devdcserver01.domain.int/DC=dev,DC=domain,DC=int

This was because while the ‘friendly’ name of the domain you use when logging in was “DEVELOPMENT” however the fully qualified name was dev.domain.int

Posted in .NET | Tagged: , | Leave a Comment »

View All Pending Changes in TFS

Posted by mundeep on May 16, 2008

To view all pending changes (checked out files) in TFS you need to do the following:

  1. Open a Visual Studio Command Prompt (or ensure that the “Microsoft Visual Studio 9.0\Common7\IDE” folder – usually in C:\Program Files – is available in your path).
  2. Change to the root directory of the project you want to search for pending changes (eg. C:\Projects\MyCustomProject)
  3. Run the following command:
    tf.exe status /r /user:*
  4. To output this to a text file (easier to read) simply add “> filename.txt” eg:
    tf.exe status /r /user:* > editedfiles.txt

Posted in .NET | Tagged: | Leave a Comment »

Quickly Generating GUIDs in Visual Studio 2008

Posted by mundeep on March 27, 2008

One of the common tasks involved when creating sharepoint solutions is the generation of GUIDs. Visual Studio comes with a tool called GuidGen that lets you create GUIDs however it is annoying having to leave the Visual Studio environment.

I believe Visual Studio 2005 used to have it as an option under the Tools menu however i haven’t found where i can add the same shortcut in Visual Studio Team System 2008 (though i do notice that Visual Studio 2008 Professional DOES have a “Create GUID” shortcut under Tools – i’d still prefer the macro shortcut for ease of use especially when creating a lot of features).

I have however found a nifty alternate solution by Leon Zandman that describes creating a Macro to insert a guid into your current file. I’d just like to clarify some of the steps for those that haven’t dealt with Macros in Visual Studio 2008 before.

  1. Load Visual Studio 2008 and goto Tools -> Macros -> Macro Explorer (Alt-F8 for short)Macro Explorer
  2. Right-click on “Macros” then select New Macro Project
  3. Name your project (eg. GUIDGenerator) and choose a location to save it (note no space allowed in Project Name).
  4. This should give you a new project with a “Module1″ sitting underneath it. Right-click on “Module1″ and select “Rename” to give it a more meaningful name (eg. GUIDGenModule).
  5. Double-click on the newly renamed module and you should be shown the Visual Studio Macro IDE.
  6. Enter the following code (the “D” in ToString can be customised see Leon’s article):
    •    Sub Create_GUID()
              DTE.ActiveDocument.Selection.Text = System.Guid.NewGuid().ToString("D").ToUpper()
          End Sub
  7. Save and close the Macro IDE.
  8. Back in the main Visual Studio window goto Tools -> Options
  9. Goto the “Keyboard” option under the “Environment” tab.
  10. In the “Show Commands Containing” text box type in “Create_GUID”
  11. Select the Macro sub that you just created from the list (it should be the only one)
  12. Click inside the “Press Shortcut Keys” textbox then press your desired keyboard shortcut for inserting a GUID (eg. Alt+G as Leon suggested makes a lot of sense).
  13. Ensure the “Use Shortcut in” option is “Global” and click on “Assign”
  14. Close the options window and you should be able to start using your keyboard shortcut to quickly insert GUIDs into text!
  15. If you have any other Visual Studio windows open at the time you will need to close them and reload for the macro for the macro to be loaded (or you can goto the Macro Explorer window and manually load your Macro project)

Posted in .NET | Tagged: , , | 9 Comments »