Welcome to MSDN Blogs Sign in | Join | Help

Code snippet to add / modify columns in a list

It iterates through a whole site collection and wherever the list with name “test” it finds, It will do the changes.

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Text;
   4:  using Microsoft.SharePoint;
   5:   
   6:  namespace ConsoleApplication1
   7:  {
   8:      class Program
   9:      {
  10:          static void Main(string[] args)
  11:          {
  12:              using (SPSite site = new SPSite("http://ms9:101"))
  13:              {
  14:                  foreach (SPWeb web in site.AllWebs)
  15:                  {
  16:                      SPList list = web.Lists["test"];
  17:                      SPFieldCollection col = list.Fields;
  18:                      SPField field = col.GetField("Trigger");
  19:                      field.Type = SPFieldType.Choice;
  20:                      field.Update();
  21:                      col.Add("Cost", SPFieldType.Currency, false);
  22:                      
  23:                      col.Add("Due Date", SPFieldType.DateTime, false);
  24:                      list.Update();
  25:                      web.Dispose();
  26:                  }
  27:              }
  28:          }
  29:      }
  30:  }

image

Posted by TejasRathod | 0 Comments

Code sample to aggregate the text from "append changes" column to Multiline text field.

This is a code sample to copy all of the text from the “col1” column to “col2” column. To note again, “col1” is an "append changes" column so the previous edits of the comments field are stored in previous versions of the list item.

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Text;
   4:  using Microsoft.SharePoint;
   5:   
   6:  namespace ConsoleApplication1
   7:  {
   8:      class Program
   9:      {
  10:          static void Main(string[] args)
  11:          {
  12:              SPSite site = new SPSite("http://ms9:101");
  13:              SPWeb web = site.OpenWeb();
  14:              SPList list = web.Lists["list1"];
  15:              string accumulate = "";
  16:              foreach (SPListItem item in list.Items)
  17:              {
  18:                  accumulate = "";
  19:                  foreach (SPListItemVersion ver in item.Versions)
  20:                  {
  21:                      if (ver["col1"] != null)
  22:                          accumulate += ver["col1"].ToString();
  23:                  }
  24:   
  25:                  item["col2"] = accumulate;
  26:                  item.Update();
  27:              }
  28:              web.Dispose();
  29:              site.Dispose();
  30:   
  31:              Console.WriteLine("Done!");
  32:              Console.ReadLine();
  33:          }
  34:      }
  35:  }

image
Posted by TejasRathod | 0 Comments

Ways to pass security credentials to web service call

[1]

   1:  WS.Credentials = new System.Net.NetworkCredential(userName, password, domain);

If you want to pass explicit credentials and filter the record after that.

 

[2]

http://support.microsoft.com/kb/813834

   1:  myProxy.Credentials = System.Net.CredentialCache.DefaultCredentials

It will pick up the current logged in users’ credentials and return the data for him/her.

 

[3]

Using SharePoint object model, setting up our custom web service on SharePoint box and access it.

   1:              SPUser spUser = null;
   2:              string authError = "Could not authenticate user";
   3:              try
   4:              {
   5:                  spUser = web.AllUsers[impUser];
   6:                  if (spUser == null)
   7:                  {
   8:                      writer.Write(string.Format("spUser = web.AllUsers[impUser]; failed<br/>"));
   9:                      throw new UnauthorizedAccessException(authError);
  10:                  }
  11:              }
  12:   
  13:                  SPUserToken token = spUser.UserToken;
  14:              using (SPSite impSite = new SPSite(SPContext.Current.Site.ID, token))
  15:              {
  16:                  impSite.CatchAccessDeniedException = false;
  17:                  using (SPWeb impWeb = impSite.OpenWeb(SPContext.Current.Web.ID))
  18:                  {
  19:                      writer.Write(string.Format("Success with impersonated site context. {0}:<br/>", impWeb.CurrentUser.LoginName));
  20:                      SPList list = null;
  21:                      
  22:                      try
  23:                      {
  24:                          list = web.Lists[this.ListName];
  25:                      }
  26:                      catch (ArgumentException ex)
  27:                      {
  28:                          writer.Write(string.Format("Couldn't access list web.Lists[this.ListName]<br/>"));
  29:                          writer.Write(ex.ToString());
  30:                          writer.Write(string.Format("<br/>"));    
  31:                      }
  32:   
  33:                      try
  34:                      {
  35:                          list.CheckPermissions(SPBasePermissions.ViewListItems);
  36:                          context.Response.Write("<p>OK! :) Succesfully checked permissions.</p>");
  37:                      }
  38:                      catch(Exception ex)
  39:                      {
  40:                          context.Response.Write("Security check failed.<br/>");
  41:                          context.Response.Write(string.Format("Current user: {0}<br/>", list.ParentWeb.CurrentUser.LoginName));
  42:                          context.Response.Write(ex.ToString());
  43:                          context.Response.Write("<br/>");
  44:                      }
  45:                      return;
  46:                  }
  47:              }

[4]

   1:  SPSite oSite1 = new SPSite("http://eka:9001");
   2:  SPWebApplication oWebApp = oSite1.WebApplication;
   3:  SPApplicationPool oAppPool = oWebApp.ApplicationPool;
   4:              
   5:  string[] strUserIno = oAppPool.Username.Split('\\');
   6:  string strDomain = strUserIno[0].ToString();
   7:  string strUserName = strUserIno[1].ToString();
   8:  string strPassword = oAppPool.Password;
Posted by TejasRathod | 0 Comments

Code to subscribe the User for alert notifications from a list

   1:          SPWeb web = SPContext.Current.Web;
   2:   
   3:          SPList list = web.Lists["Pages"];
   4:   
   5:          SPUser user = web.CurrentUser;
   6:   
   7:          SPAlert alert = user.Alerts.Add();
   8:   
   9:          alert.Title = "My Alert";
  10:   
  11:          alert.AlertType = SPAlertType.List;
  12:   
  13:          alert.EventType = SPEventType.All;
  14:   
  15:          alert.List = list;
  16:   
  17:          alert.AlertFrequency = SPAlertFrequency.Immediate;
  18:   
  19:          alert.AlwaysNotify = true;
  20:   
  21:          alert.Update(true); // Subscription notification will be sent to user
  22:   
  23:          //alert.Update(false); // Subscription notification will not be sent to user
Posted by TejasRathod | 0 Comments

In SPS 2003, Use custom template to create the document workspace through ECB menu link.

In SPS 2003, In the ECB menu of the documents we get an option “Create Document Workspace”. This link uses the OOB document workspace STS#2 to create the document workspace. There was a requirement to use our own custom template to create the document workspace through this ECB menu link.

Resolution

We started troubleshooting the issue by following the link in the ows.js. It navigates to the Createws.aspx and this page creates the document workspace using the STS#2 template implicitly. The code behind of the this page is existing in the Microsoft.SharePoint.ApplicationPages.DWSCreatePage and the STS#2 is hard coded in this class.

We can create a custom application page based on the Createws.aspx and implement the method to create a document workspace based on the custom template.

The method to implement in the custom Createws.aspx is as follows :

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Text; 
using System.Windows.Forms; 
using Microsoft.SharePoint; 

namespace CreateSite 
{ 
    public partial class Form1 : Form 
    { 
        public Form1() 
        { 
            InitializeComponent(); 
        } 

        private void button1_Click(object sender, EventArgs e) 
        { 
            if (CreateSite("<http://ms9:501/sites/501>", "test11", "test1", "tj.stp")) 
                MessageBox.Show("Done"); 
            else 
                MessageBox.Show("Not Done"); 
        } 

        public static bool CreateSite(string parentSiteURL, string siteURLRequested, string siteTitle, string siteTemplateName) 
        { 
            bool returnCondition = false; 
            const Int32 LOCALE_ID_ENGLISH = 1033; 

            using (SPSite siteCollection = new SPSite(parentSiteURL)) 
            { 
                SPWeb parentWeb = siteCollection.OpenWeb(); 
                SPWebTemplateCollection Templates = siteCollection.GetWebTemplates(Convert.ToUInt32(LOCALE_ID_ENGLISH)); 
                parentWeb.Webs.Add( 
                    siteURLRequested, 
                    siteTitle, 
                    "", 
                    Convert.ToUInt32(LOCALE_ID_ENGLISH), 
                    siteTemplateName, 
                    false, false); 

                returnCondition = true; 
            } 
            return returnCondition; 
        } 
    } 
} 

 

In MOSS 2007, you will have control over ECB menu of the document item so you can add or remove a link in it which can point to a new page. Right now in SPS2003, we have to modify ows.js to point it to a new page and then we are actually breaking the product. The implementation of the page which will create the document workspace from your template, will be almost similar in MOSS and SPS, code will be the same.

Posted by TejasRathod | 0 Comments

How To: Access item metadata from workflow when associated in document library

Problem

There is a workflow which accesses the item metadata on workflow activated. In case of document library, when you upload a document, if the workflow is set to start on ItemAdded, it will start just after upload is done and before you completely fill up the metadata information of the item. Since it is starting before metadata is available and it is trying to access it, it fails with null reference exception.

Resolution

We found that when a workflow is associated with a doc lib to start on item created then it would start before all the metadata is entered while uploading a document. This is by design behavior and reason behind it is to cover all the document library’s functionalities, including multiple uploads.

An event handler can be associated with a library and from there we can initiate the workflows.
Workflows can be configured to start on item updated.

You can find out the associated workflow instances from document library’s object and then workflow template and workflow associations.

You can attach an event handler to the document library from your configuration screen and you need not to reset IIS for that.
Also,
while associating workflow to a doc lib, you can execute the following code.
            SPBaseType theBaseType = this._sharePointListAttachedTo.BaseType;
            if (theBaseType == SPBaseType.DocumentLibrary)
            {
                this._paramAutoStartWF_OnItemCreate = false;
            }
I noticed the changed event always fires on an upload in a document library. With the code above I set the OnItemCreate to false so only the change event fires and the workflow seems to work fine.

Posted by TejasRathod | 0 Comments

How to: Enable Edit option for non anonymous comments in blogs

We have implemented an internal blog site using the MOSS 2007 blog template. One of the requirements was to support anonymous comments.

Since this is not an out-of-the-box feature, we searched and found a solution on the Microsoft SharePoint Team Blog site, http://blogs.msdn.com/sharepoint/archive/2007/08/06/anonymous-comment-feature-for-sharepoint-blog-now-available-on-codeplex.aspx

We implemented the custom web part, which is working out great. Unfortunately, there is one feature that the custom web part does not have, that the original New Comment web part does. This is the ability for the users to edit their own comments, once the comment has been posted. When the comment is posted anonymously, it makes sense that the user should not be able to edit the comment, since any association with the user is broken. However, if the user decides not to post the comment anonymously, then the requirement is to allow them to edit any of their previous comments.

 

Resolution 

Modify the JavaScript in the webpart as below.

var divElements = document.getElementsByTagName("div");
var accountNameDiv = null;
var annncount = "";
var cnt = 0;

for (var i = 0; i < divElements.length; i++) {
    var currentDivClassName = divElements[i].className.toLowerCase();
    accountNameDiv = divElements[i];
    // remove account name
    if (currentDivClassName.indexOf('ms-commentfooter') != -1) {
        cnt++;
        if (accountNameDiv.innerText.toLowerCase().indexOf('system account') != -1) {
            var innerHTMLField = accountNameDiv.innerHTML;
            var firstIndex = innerHTMLField.indexOf('</NOBR> at ');
            var secondIndex = innerHTMLField.length;
            var htmlDate = innerHTMLField.substring(firstIndex + 11, secondIndex);
            accountNameDiv.innerHTML = "Anonymous at " + htmlDate;
            annncount = annncount + " ," + cnt;
        }
        else if (accountNameDiv.innerText.toLowerCase().indexOf('chris stetkiewicz (alt)') != -1) {
            var aElements = accountNameDiv.getElementsByTagName("a");
            aElements[0].innerText = "Editor";
            aElements[0].href = "<http://my/Person.aspx?accountname=REDMOND%5Ccstek>";
        }
    }
}

var count = 0;
var tableElements = document.getElementsByTagName("table");
for (var k = 0; k < tableElements.length; k++) {
    if (tableElements[k].className.toLowerCase().indexOf('ms-commenttable') != -1) {      //alert('ss');
        var tdElements = tableElements[k].getElementsByTagName("td");
        for (var m = 0; m < tdElements.length; m++) {
            if (tdElements[m].className.toLowerCase().indexOf('ms-blogedit') != -1) {
                count++;
                if (annncount.indexOf("," + count) != -1)
                    tdElements[m].innerHTML = "";
            }
        }
    }
}

Posted by TejasRathod | 0 Comments

Resolution: Problems with Ajax development/ Page does post back

If the you have applied bluband.master then we need to do changes in bluband.master per the solution step [2]

[1]
Webpart change
Add following code in your webpart and call it in CreateChildControls

//in CreateChildControls method
//Fix for the UpdatePanel postback behaviour.
            EnsurePanelFix();

private void EnsurePanelFix()
        {
            if (this.Page.Form != null)
            {
                String fixupScript = @"
                                         _spBodyOnLoadFunctionNames.push(""_initFormActionAjax"");
                                         function _initFormActionAjax()
                                         {
                                           if (_spEscapedFormAction == document.forms[0].action)
                                           {
                                             document.forms[0]._initialAction =
                                             document.forms[0].action;
                                           }
                                         }
                                         var RestoreToOriginalFormActionCore =
                                           RestoreToOriginalFormAction;
                                         RestoreToOriginalFormAction = function()
                                         {
                                           if (_spOriginalFormAction != null)
                                           {
                                             RestoreToOriginalFormActionCore();
                                             document.forms[0]._initialAction =
                                             document.forms[0].action;
                                           }
                                         }";
                ScriptManager.RegisterStartupScript(this,
                  typeof(TjWP), "UpdatePanelFixup",
                  fixupScript, true);
            }
        }


[2]
blueband.master change

<body class="body" onload="javascript:if (typeof(_spBodyOnLoadWrapper) != 'undefined') _spBodyOnLoadWrapper();">
<form runat="server" onsubmit="return _spFormOnSubmitWrapper();">
<WebPartPages:SPWebPartManager runat="server"/>
<asp:ScriptManager runat="server" ID="ScriptManager1"></asp:ScriptManager>

 

Keywords

Postback happens for AJAX enabled Web part, SharePoint, Ajax, blueband.master, Publishing site template

Posted by TejasRathod | 0 Comments

Resolution: Trouble setting appropriate permissions on SharePoint user

We wanted to setup Created by and Modified by fields for each and every item in the site programmatically without using STSADM command.

Resolution

Through object model you can back up the created by and modified by fields.

You can set the values for the created by and modified by fields using the below code snippet.

private void button3_Click(object sender, EventArgs e)
        {
            SPSite oSite = new SPSite("<http://terminator:94/sites/Migration/>");
            SPWeb oWeb = oSite.OpenWeb();
            SPList oList = oWeb.Lists["TestList"];
            SPListItemCollection oListCollection = oList.Items;
            foreach (SPListItem oListItem in oListCollection)
            {
                SPFieldUserValue oUser = new SPFieldUserValue(oWeb, oWeb.CurrentUser.ID, oWeb.CurrentUser.LoginName);
                oListItem["Author"] = oUser;//created by column
                oListItem["Editor"] = oUser;//modified by column
                oListItem.Update();               
            }
            oWeb.Update();
         }


You can access the SPListItem object. Using this object you will be able to retrieve the information of all the fields (Ex. created by, modified by, Id etc..) of the list item.

Again you can retrieve the user information through OM. You can check the condition to get the user you want.
Something like this…
SPUserCollection uc = web.Users;
//condition
uc[i].ID;
uc[i].LoginName;

 

As per my understanding, possible ways to achieve this task should be

1.    Side by side approach

First you should restore the site without created by and modified by fields, then access the source site, loop through each list, loop through each item in the list, fetch the created by and modified by values and set those values for the related item in the destination site.

2.    Collect everything and then restore at once

Store everything first, create an XML (or whatever else you feel suitable) file with the created by and modified by fields of the each list item under the lists and execute the code which can read the XML and set the created by and modified by at the appropriate list items in destination site.

 

Questions

1.    Can we get the relative URL or ID of a list item, then look up the list item in the second site collection by that URL? For example, we have the list item that can be viewed at <http://server/Lists/listname/dispform.aspx?ID=2> - will list item 2 on the imported list be the same item as on the original list? Additionally, can we get /Lists/listname/?ID=2 at a code level, then match that back across to the other site collection, setting the author and editor field appropriately?
Ans.
It seems possible, however I think this is not the good way of accessing the items. As long as you keep restoring the items in the same order to your destination sites, it will maintain the ID. But, you never know when you will lose the track. Example. In your source you might have ids in order 1, 2, 3, 6, 9, 10 because of deleting some of the items in between where in your destination site while restoring it’s going to be straight 1,2,3,4,5,6,7….

2.    As an alternate method, is there a backup method that you know of that preserves item/list GUIDs but not security data, so we can simply match the GUIDs? Can we even look up list items by database GUID, in this case?
Ans.
Through SharePoint OM , you can access the item’s GUID but I don’t think so you can set the GUID for an item.

3.    The Author and Editor list fields reference a SPUser object. Can we set that as an domain login name (domain\login) or do we need the SPUser object to exist, then do a lookup to associate that?
Ans.
It requires User to pre-exist in site. [At least for my code to run which I have provided you]

Posted by TejasRathod | 0 Comments

Resolution: Workflow is not loading the newer version of definition file.

Some times visual studio loads the older version of the workflow definition while debugging, even though you might have deleted an activity from the workflow, when you debug the code the definition file shows the older version where we the old activity will be still present.

Resolution

Visual studio loads the workflow definition from the dll which is available in GAC so in case we add/remove or do any modifications related to activities in the workflow, it is a good practice to uninstall the old dll from GAC and restart the VS so it can pick up the latest details.

Also you could clean up the browser history to avoid the any xml’s/ other files’ caching related issues.

Posted by TejasRathod | 0 Comments

Resolution: Search.asmx returns no result for custom query

Search.asmx returns no result (ERROR_NO_RESULTS_FOUND) for custom query.

 

Cause

Search permission settings were required to be properly configured.

 

Resolution

  • Initially we checked ifilters for PDF document. They were properly installed on the servers. Then we tried to search word document to confirm whether the issue happens with word document too. And we found that for all types of documents we were not able to get the result.
  • We tried to work with SP Query Tool and checked our custom query but that doesn’t return any result.
  • We verified the custom query. Everything was proper.
  • We did the full as well as incremental crawling and checked the search.asmx, SP Query Tool but didn’t get the result.
  • Finally we found that we were able to search the documents from the WSS site but not from the portal. After further investigation, we found the root cause that we needed to modify the permission settings for search.
  • From the crawl log we found that there were some addresses which were not found during crawling.
  • We removed the directory entry for "clientstatements" and created a new entry with proper user id.
  • To check the proper crawling we stopped the crawling, reset the timer and started the full crawling.
  • After the completion of the full crawling, Now we are able to get the result.

Path : Portal -> Site settings –> Search settings and Indexed content -> Manage crawls of the site directory -> Provide the proper links with proper permissions

 

Keywords

Search, SharePoint 2003, Search is not working, Search.asmx, no result, SPS 2003, Search keyword doesn't return any result.

Posted by TejasRathod | 0 Comments

Resolution: SharePoint throws an error while adding to lists

Cause

Column name's internal name is different than the column name

 

Resolution

We modified the list column names in the code sample by checking the actual column names from the list setting and after that we were able to add new items in the list.

To identify the column name
List -> Modify settings and columns -> column -> properties -> in URL we will have field value

To identify the view Guid
List -> Modify settings and columns -> Click on the view ( select your view, Ex. All items) -> In URL you will find something like this “View=%7B1F3EA68A%2D0212%2D4ECC%2D9958%2D5F8886A5D918%7D”

Replace
%7B  with {
%7D  with }
%2D  with -

 

Code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace ListUpdate
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //method1();
            //method2();
            CustomerCode();
        }

        private void CustomerCode()
        {
            string elements = @"<Method ID='1' Cmd='New'>
                        <Field Name='ID'>New</Field>
                        <Field Name='Title'>Tj</Field>
                        <Field Name='Entry_x0020_ID'>0D502EBD184B89</Field>
                        <Field Name='Status'>Not Started</Field>
                        <Field Name='Description'>Please open the attached document.</Field>
                        </Method>";

            string documentPath = @"C:\check.pdf";
            string strRowID = "";

            SendDocument(elements, documentPath, ref strRowID);
        }

        public void SendDocument(string elements, string documentPath, ref string strRowID)
        {
            XmlDocument xmlDoc = new System.Xml.XmlDocument();
            System.Xml.XmlElement updates = xmlDoc.CreateElement("Batch");
            updates.SetAttribute("OnError", "Continue");
            updates.SetAttribute("ListVersion", "1");
            ////v3
            //updates.SetAttribute("ViewName", "{1F3E238A-0212-42CC-9958-5F2BB565D918}");

            //v2
            updates.SetAttribute("ViewName", "{62E66878-5D1C-4R25-A2F8-AA71888A55FF}");
            updates.InnerXml = elements;
            XmlNode node = null;
            //XmlNode items = null;
            //System.Xml.XmlNode _n = null;

            MyLists.Lists listService = new MyLists.Lists();
            listService.Credentials = System.Net.CredentialCache.DefaultCredentials;
            ////v3
            //listService.Url = "http://terminator:30030/s1/_vti_bin/Lists.asmx";

            //v2
            listService.Url = "http://terminator:2004/sites/t2/_vti_bin/Lists.asmx";

            string listName = "Customer";
            ////v3
            //string listServiceURL = "http://terminator:30030/s1/_vti_bin/Lists.asmx";

            //v2
            string listServiceURL = "http://terminator:2004/sites/t2/_vti_bin/Lists.asmx";

            if (listServiceURL.Length > 0)
                listService.Url = listServiceURL;
            try
            {
                if (strRowID == "")
                {
                    node = listService.UpdateListItems(
                    listName,
                    updates);
                    XmlDocument rtnListItems = new XmlDocument();
                    rtnListItems.LoadXml(node.OuterXml);
                    XmlNamespaceManager nsmListItems = new XmlNamespaceManager(rtnListItems.NameTable);
                    nsmListItems.AddNamespace("foo", "http://schemas.microsoft.com/sharepoint/soap/");
                    XmlNode ndTemp = rtnListItems.SelectSingleNode("//*/*/*/@ows_ID", nsmListItems);
                    if (ndTemp != null)
                    {
                        strRowID = ndTemp.InnerText;
                    }
                    else
                        throw new Exception("The row ID could not be determined after the update of the list!");
                }
                System.IO.FileStream fStream =
                System.IO.File.OpenRead(documentPath);
                string fileName = System.IO.Path.GetFileName(fStream.Name);//fStream.Name.Substring(42);
                byte[] contents = new byte[fStream.Length];
                fStream.Read(contents, 0, (int)fStream.Length);
                fStream.Close();
                try
                {
                    string addAttach =
                    listService.AddAttachment(listName, strRowID, fileName, contents);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error" + ex.Message.ToString());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error" + ex.Message.ToString());
            }

            MessageBox.Show("Done!");
        }

    }
}

Posted by TejasRathod | 0 Comments

Resolution: SendEmailNotification=true does not send an email

SendEmailNotification=true does not send an email, it was not sending email on time.

Cause
There are two different methods on which SendEmailNotification=true and SendEmailActivity work.

Details

1.    I noticed that I was able to get the email from SendEmailActivity but where SendEmailNotification=true was there in code that email I was getting after every five minutes.
3.    So I found that SendEmailNotification=true is dependent on the SharePoint’s Alerts, SharePoint Timer service.
4.    I changed the timer interval to 1 minute and after that I was getting emails every one minute from the SendEmailNotification=true.
5.    SendEmailActivity is not dependent on the timer service so it sends the email immediately.

Commands to set/get timer interval
·    stsadm -o getproperty -pn job-workflow -url <URL>
·    stsadm -o setproperty -pn job-workflow -pv "every 1 minutes between 0 and 59" -url <URL>

 

Keywords

Email notification is delayed, SharePoint timer service, SendEmailActivity, Workflow foundation

Posted by TejasRathod | 0 Comments

Resolution: Issue - Error 403 - Forbidden while connecting to OOB web service on forms based authenticated sites

When you connect to the web service that is running in FBA site, you get the 403 - forbidden error

 

Resolution

1.    Extend the FBA web application to a new application that is set up to use NTLM. then set up an NT user with full access rights.
2.    Now when we test our code with the web services pointing to this new web application and passing our domain credentials to the web service, we are able to get everything working.
3.    This is actually expected since the web services will still try to run with the domain credentials but FBA site uses and accepts different credentials.
4.    Conclusion is, to use web services of the FBA site, we need to have extended site setup in NTLM and we should connect to the web services of the extended site using NT user.

 

Please follow the following steps to extend the SharePoint site in Windows mode and to check the solution.
1.    Go to SharePoint Central Administration > Application Management > Create or Extend Web Application > Extend Web Application to Another IIS Web Site
2.    Select the web site which you want to extend.
3.    Provide the new port and necessary details. Also select the zone(last drop down list) as intranet.
4.    You can verify that the site is extended in windows authentication by checking at Central Administration > Application Management > Authentication Providers > Edit Authentication.

Posted by TejasRathod | 1 Comments

Resolution: Issue with upgrading the schema.xml for a library

Issue

The issue was about upgrading the schema.xml for a library. If we do not do any change in document library settings then it uses schema.xml file but when we create a column in document library it stops using schema.xml file thereafter.

 

Details

We found that this behavior is by design. When you have not done any changes to document library it will use schema.xml and when you have done some changes in document library then SharePoint will make the document library unghosted to preserve the personalization settings of document library and it will not use schema.xml thereafter.

 

Following are the couple of possible workarounds…

1.    Maintain all document libraries through feature only (Schema.xml) and avoid using UI to create any new columns if you anticipate any future changes in document libraries.

2.    In code, you get the node for the column from the schema.xml file and add it through SPField class in your document library. You can take a help of SharePoint’s object model to prepare a complete code for your workaround using classes like SPSite, SPWeb, SPList etc...

The following code example iterates through all the lists in all the subsites under a site and, if it finds a list with a specified name, updates the title, default value, and description for a field.

SPWebCollection sites = siteCollection.AllWebs["Site_Name"].Webs;
foreach (SPWeb site in sites)
{
    SPListCollection lists = site.Lists;
    for (int i=0; i<lists.Count; i++)
    {
        if (lists[i].Title == "List_Name")
        {
            SPField fieldChange = lists[i].Fields["Field_Name"];   
            fieldChange.DefaultValue = "Default_Value";
            fieldChange.Description = "Description";
            fieldChange.Title = "New_Field_Name";
            fieldChange.Update();
        }
    }
}

Posted by TejasRathod | 0 Comments
More Posts Next page »
 
Page view tracker