Welcome to MSDN Blogs Sign in | Join | Help

MOSS 2007 : WSS 3.0 : How do you add items into Choice Site Column type.

Here is the sample code,

                SPWeb web = new SPSite("http://karthick64:4040/").OpenWeb();
                SPField spField = web.Fields["MyChoice"];
                SPFieldChoice choiceFields = (SPFieldChoice)spField;
                string[] choices = new string[3] {"x", "y", "z"};
                foreach (string choice in choices)
                {
                    choiceFields.Choices.Add(choice);
                }
                choiceFields.Update();

Keep Exploring... :)

Posted by Karthikeyan | 1 Comments
Filed under:

MOSS 2007 : WSS 3.0 : How do you add a new Site Column to a Content Type using the MOSS object model?

How do you add a new Site Column to a Content Type using the MOSS object model? 

Here is the sample code

   SPWeb web = new SPSite("http://localhost:4040").OpenWeb();

   SPContentType myCT = web.ContentTypes["myNewContentType"];

   myCT.FieldLinks.Add(new SPFieldLink(web.Fields["abc"]));

   myCT.Update();

 

Note :

The following MSDN article speaks about “Updating Child Content types”.

http://msdn2.microsoft.com/en-us/library/ms442695.aspx

The example given in the article uses the SPFieldCollection object (SPContentType.Fields) to add columns to the content type. But when we use the sample given in the article we end up with the error message “SPException: This functionality is unavailable for field collections not associated with a list.”. I found that the columns are not added into content type and that are referenced in content type from the following article.

 

http://msdn2.microsoft.com/en-us/library/aa543526.aspx

 

Also the above article “How to: Reference a Column in a Content Type” says,

 

The Fields property returns an SPFieldCollection object. Each SPField in this collection represents a "merged view" of the base column definition and any overwritten properties specified in the column reference in the content type. Because of this, you cannot add columns directly to this collection. Attempting to do so results in an error.

 

 

Keep Coding...

Posted by Karthikeyan | 2 Comments

MOSS 2007: WSS 3.0: How to add/delete/update site columns by using SharePoint WebService

SharePoint's Webs webservice can be used to add/delete/update site columns. Unfortunatley MSDN/SDK doesnot has the sample yet. Here I provide the sample code.

            //webs webservice object

            localhost.Webs websService = new ContentTypeAndSiteColumn.localhost.Webs();

            //url for the webservice

            websService.Url = "http://localhost:4040/_vti_bin/Webs.asmx";

            //credential

            websService.Credentials = System.Net.CredentialCache.DefaultCredentials;

 

            //xmldocument object

            XmlDocument xDoc = new XmlDocument();

            //Fields to be added

            XmlElement newFields = xDoc.CreateElement("Fields");

            //Fields to be edited

            XmlElement updateFields = xDoc.CreateElement("Fields");

            //Fields to be deleted

            XmlElement deleteFields = xDoc.CreateElement("Fields");

 

            newFields.InnerXml = "<Method ID='1'><Field Name='FieldName' DisplayName='FieldDisplayName' Group='Group Name' Type='Text'/></Method>";

            newFields.InnerXml = "<Method ID='2'><Field Name='FieldName' DisplayName='FieldDisplayName' Group='Group Name' Type='Text'/></Method>";

            deleteFields.InnerXml = "<Method ID='3'><Field Name='FieldName'/></Method>";

 

            XmlNode returnValue = websService.UpdateColumns(newFields, updateFields, deleteFields);

            MessageBox.Show(returnValue.OuterXml);

 

Related Links

----------------

http://msdn2.microsoft.com/en-us/library/webs.webs.updatecolumns.aspx

http://msdn2.microsoft.com/en-us/library/ms451470.aspx

http://msdn2.microsoft.com/en-us/library/ms437580.aspx

http://msdn2.microsoft.com/en-us/library/webs.webs.getcolumns.aspx

Keep Coding.... :)

Posted by Karthikeyan | 4 Comments
Filed under:

MOSS 2007 : CMS 2002 Migration Issue : How to rename a resource Gallery Item?

Unfortunately MCMS 2002 Site Manager doesnt allow you to rename the resource gallery item. In some situation you may end up duplicate entries in the resource gallery item names. MCMS 2002 allows you to have multiple resource items with same name. The items will be differentiated by using their guids. But this will endup a problem when you are migrating to MOSS 2007, and you will get "Leaf names are not unique." error message. And the suggestion is you have to rename the resource gallery item. Here is the sample code to rename the resource gallery item.

// Get the MCMS application context.

                CmsApplicationContext cmsContext = new CmsApplicationContext();

 

                // Logon to MCMS:

                // Assumes that you have Windows Authentication turned on.

                WindowsIdentity ident = WindowsIdentity.GetCurrent();

 

                // Make sure to set the context to Update mode (which means you can write

                // back to MCMS using PAPI).

                cmsContext.AuthenticateUsingUserHandle((System.IntPtr) ident.Token.ToInt32(),PublishingMode.Update);

 

                ResourceGallery rsg = cmsContext.Searches.GetByPath("/Resources ") as ResourceGallery;

                Resource res = rsg.Resources[“Content Development”];

                res.Name = "EMP1.gif";

                res.DisplayName = "EMP1.gif";

 

                // Commit changes back to MCMS.

                cmsContext.CommitAll();

Keep coding :)

Posted by Karthikeyan | 1 Comments

WSS 2.0 : How to upload images by using Imaging WebService

Here you go for the sample code.

                 try
                 {
                             //create imaging web service object
                             localhost.Imaging img = new ImagingTest.localhost.Imaging();
                             //set url
                             img.Url = http://localhost:8081/sites/site1/_vti_bin/Imaging.asmx;
                             //Set credential
                             img.Credentials = System.Net.CredentialCache.DefaultCredentials;
                             //for results
                             System.Xml.XmlDocument resdoc= new System.Xml.XmlDocument();
                             System.Xml.XmlNode resnode = resdoc.CreateNode(System.Xml.XmlNodeType.Element,"Result","");
                                                               
                            System.IO.FileStream fs = new System.IO.FileStream("c:\\n15.jpg",  System.IO.FileMode.Open, System.IO.FileAccess.Read);
                            //Get the content
                            byte[] content = new byte[fs.Length];

                            //store the content
                            fs.Read(content, 0, (int) fs.Length);
                                                
                            //Upload the file - specify "" for root folder, for sub folders specify 1, 2, 3 relative to the folder number
                            resnode = img.Upload("123", "", content, "n15.jpg", true);
                            MessageBox.Show(resnode.OuterXml);
                 }
                 catch(Exception ex)
                 {
                        MessageBox.Show(ex.ToString());
                 }

Posted by Karthikeyan | 0 Comments
Filed under:

WSS 2.0 : "Getting unauthorized access" error when ‘User must change password at next logon’ is enabled

Problem Background : When you enable "user must change password at next logon", then the corresponding user will face the unauthentication issues.

To resolves this, you may enable IISADMPWD for WSS

How to enable the IISADMPWD for WSS?

  • To register iispwchg.dll, follow these steps:
    • Click START, and then click RUN
    • In the open box type the following and then press ENTER:
             Regsvr32 “%systemroot%\system32\inetsrv\iisadmpwd\iispwchg.dll
  • To create the IISADMPWD virtual directory, follow these steps:
    • In the Internet Services Manager Microsoft management Console (MMC), expand Web Sites, right-click the <SharePoint Site>, select New, and then select Virtual Directory.
    • When the Virtual Directory Creation Wizard starts, follow the instructions to create the virtual directory with the alias IISADMPWD. Point the path to the local %systemroot%\System32\Inetsrv\Iisadmpwd directory. For the Access Permissions allow both Read and Run Script privilages.
  • To execlude IISADMPWD from WSS Managed path, follow these steps:
    • Click start, point to All Programs, point to Administrative Tools, and then click SharePoint Central Administration
    • On the Central Adminitstration Page, under Virtual Server Configuration, click Configure virtual server settings
    • On the virtual server List Page, select the virtual server you want to configure
    • On the virtual server settings page, under Virtual server Management, click Define Managed paths.
    • Under Add a New Path, type iisadmpwd, and in Type select “Excluded Path” and then click OK
  • To set the PasswordChangeFlags value in the IIS metabase, do the following:
    • From a command prompt browse to the C:\Inetpub\Adminscripts directory.
    • Type adsutil.vbs, and then press the ENTER key. If this is the first time that Adsutil.vbs has been run, you may get error messages stating that Cscript is not registered. Follow the prompts and choose Yes to register Cscript.
    • Type adsutil.vbs set w3svc/<THE ID FOR SHAREPOINT SITE>/PasswordChangeFlags 1
      Note : The id for the SharePoint site can be identified from the IIS manager. In IIS manager select websites and you can identify the identifier for individual site from the right pane.

Now you will be able to get the IIS password management page when the “User must change password at next logon” selected.

[Keep Using SharePoint]

Posted by Karthikeyan | 1 Comments
Filed under:

WSS 2.0 : How to enable document library eventhandlers by default

  • Open the Site definition folder. If you use default Site definition, STS, then open the folder from the following location. “C:\program files\common files\Microsoft Shared\web server extensions\60\template\1033\STS

Note: Modifying the default files is not supported by Microsoft. Microsoft recommends using custom Site Definition.

  • Open the List Definition folder. If you use default list definition for document library, then open the “DOCLIB” folder in the LISTS folder
    Open the “SCHEMA.XML” file in notepad or visual studio· Modify the LIST node by adding the EventSingAssembly, EventSinkClass, and
    EventSinkData

<List xmlns:ows="Microsoft SharePoint" Name="CustomDocuments" Title="Custom Shared Documents" Direction="0" Url="Custom Shared Documents" BaseType="1" EventSinkAssembly="TestEventHandler, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=614ce6399d917f80" EventSinkClass="TestEventHandler.MyEventHandler" EventSinkData = "">

Note:Here I hardcoded the EventSinkAssembly for sample. Could you please change it according to your component.

  • Restart IIS.

After configuring the details, if you create new document library based on the list definition, then the document library event handler will be automatically
configured.

Posted by Karthikeyan | 0 Comments
Filed under:

WSS 2.0 : stsadm - can't delete wppack with slash in its name

If you install a wppack by using stsadm with slash "/", then you will not be able to uninstall it by using the stsadm tool :( . The story not endup here, you will not be able to install the latest version of your webpart :(. However SharePoint object model helps us to resolve the problem. Run the following code to remove the wppack that has "/" in the path. Then install your webpart by using stsadm by using the "\" in the path.

Example, running the following command will endup with the above problem.

              stsadm -o addwppack -filename "Helloworld/TestDeploy.CAB"

SPGlobalAdmin oGA = new SPGlobalAdmin();
oGA.RemoveWPPack("helloworld/testdeploy.cab",0,null,null);

 

Posted by Karthikeyan | 0 Comments
Filed under:

WSS 2.0 : How to programmatically enable/disable the rights at Virtual server level?

To enable all rights at the virtual server level
            vServer.Config.Properties["virtualserverpermsmask"] = "-1";


To disable the “Manage Site Groups” permission at the virtual server level
            vServer.Config.Properties["virtualserverpermsmask"] = "2113867535";

Keep Coding ;)

Posted by Karthikeyan | 0 Comments

WSS 2.0 : How to save properties of webpart from webpart code

There are two methods, SaveChanges and SaveProperties provided by WSS which sometimes misleading users. Here I provide details for which method to use and when to use.

SPWebPartCollection.SaveChanges()  - This method is used to save the changes made in the web part from out side the web part code. For e.g., the console application, windows application etc..,

SPWebPartCollection.SaveProperties - This method is used to save the properties within the web part code.

Posted by Karthikeyan | 0 Comments
Filed under:

WSS 2.0 : Technical details about localizing webpart and .dwp file

Problem :

You are localizing the SharePoint web parts. You localiz display text and custom property names/descriptions using the ResourceManager and satellite
assemblies. However, the web part “dwp” files in the cab file contain a title and description for each web part. You want to localize these values as per the msdn article.
“Packaging and Deploying Web Part for Microsoft Windows SharePoint Services”
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odc_sp2003_ta/html/sharepoint_deployingwebparts.asp

However, when you change the locale in SharePoint, it is not using the localized dwp files. It is using the localized display text and property names/descriptions.

Details :


- There are language templates used to create sites/webs. For example, 1033 folder is for English, 1031 is for German and etc. A site should be created by using anyone of this language template. SharePoint uses this language template and render the site based on the template. The site navigation, site data and Add Web Parts dialog all these settings uses the language template. Once we created the site by using the language template we cannot change these settings.
- The localized web parts can be created according to the language template we used.
- The wpcatalog folder is a place to install the *.dwp files. The files found in this directory will be used to display the details in the “Add Web Parts” window
- Any sub folder found in the wpcatalog folder with language name (en-US, de-DE, etc..) will be used to display the web part list in the “Add Web Parts” window according to the language template used to create the site. For example, if we create any site by using the German language template (1031), then the files under the de-DE folder will be displayed in the “Add Web Parts” window and the files under the en-US and other language will not be displayed. The files found in the wpcatalog root folder will be displayed for all the sites.
- If you want to localize the *.dwp files then in your particular scenario you have to create two sites one is by using the 1033 template and another one is by using the 1031 template. Obviously you will end up having two different sites and one is for English and another one is for German.
- The “regional settings” under the site settings option is used for setting the date format, and currency formats. Changing the regional settings wont affect the site settings such as “Site Navigation”, “Site data” and the “Add Web Parts dialog box”
- The .net code in the web parts and the web controls use the “regional settings” found in the site and renders accordingly

 

Posted by Karthikeyan | 1 Comments
Filed under:

WSS 2.0 : How to reset Password in WSS - Account Creation Mode

Consider the following scenario. You installed WSS in Account Creation Mode. If a user forgets their password, they currently have to contact the admin and
they in turn need to go into the site administration and manually reset the password. This issue has become more prevalent and will detract the Admin from normal duties.

So I would like to have a way to automate password rests for the users. Users will be provided a webpart of other link that will reset the password and send out an email with the new password to the users account email address.

Here you go for a sample code.

  public class MyChangePassword : Microsoft.SharePoint.WebPartPages.WebPart
 {

  //Button for Change Password
  Button btnChangePassword;

  string strError = "";

  protected override void CreateChildControls()
  {
   //Create button
   btnChangePassword= new Button();
   btnChangePassword.Width = 100;
   btnChangePassword.Text = "Change Password";
   btnChangePassword.Click += new EventHandler(btnChangePassword_Click);
   this.Controls.Add(btnChangePassword);
  }

  private void btnChangePassword_Click(object sender, EventArgs e)
  {
   try
   {
    //Gets the context of the web
    SPWeb webContext = SPControl.GetContextWeb(Context);   
    string strLoginName = webContext.CurrentUser.LoginName;
    //Get the impersation context
    WindowsImpersonationContext wic = CreateIdentity("username", "domain", "password").Impersonate();
    SPUtility.ChangeAccountPassword(webContext, strLoginName, "", "newpassword");
    //undo the impersonation context
    wic.Undo();
    strError = "Password Changed";
   }
   catch(Exception ee)
   {
    strError += ee.ToString();
   }
  }


  protected override void RenderWebPart(HtmlTextWriter output)
  {
   btnChangePassword.RenderControl(output);
   output.Write(strError);

  }
  protected static WindowsIdentity CreateIdentity(string User, string Domain, string Password)
  {
   // The Windows NT user token.
   IntPtr tokenHandle = new IntPtr(0);

   const int LOGON32_PROVIDER_DEFAULT = 0;
   const int LOGON32_LOGON_NETWORK = 3;

   tokenHandle = IntPtr.Zero;

   // Call LogonUser to obtain a handle to an access token.
   bool returnValue = LogonUser(User, Domain, Password,
    LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT,
    ref tokenHandle);

   if (false == returnValue)
   {
    int ret = Marshal.GetLastWin32Error();
    throw new Exception("LogonUser failed with error code: " +  ret);
   }

   System.Diagnostics.Debug.WriteLine("Created user token: " + tokenHandle);

   //The WindowsIdentity class makes a new copy of the token.
   //It also handles calling CloseHandle for the copy.
   WindowsIdentity id = new WindowsIdentity(tokenHandle);
   CloseHandle(tokenHandle);
   return id;
  }

  [DllImport("advapi32.dll", SetLastError=true)]
  private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
   int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

  [DllImport("kernel32.dll", CharSet=CharSet.Auto)]
  private extern static bool CloseHandle(IntPtr handle);
 }


 

Posted by Karthikeyan | 1 Comments
Filed under:

WSS 2.0 : Explicit Impersonation cannot work with SPRoleCollection

The following code will fail if the user doesnot have Admin previlage

       SPRoleCollection RC =  CurrentWeb.CurrentUser.Roles;

The CurrentWeb.CurrentUser.Roles method requires Manage Site Groups permission and the impersonation does not work with SPRoleCollection

RESOLUTION:
-Write a custom sharepoint webservice and pass the administrator (networkcredentials) credentials to the webservice to retrieve the roles.

Posted by Karthikeyan | 0 Comments

MCMS 2002 : You cannot add NT Authority domain and Authenticated users in CMS

PROBLEM:
You cannot add NT Authority domain and Authenticated users in MCMS 2002 Site Manager

RESOLUTION:
1. Create a local user group
2. Add the Authenticated users to the newly created local user group
3. Add the local user group in CMS
Posted by Karthikeyan | 0 Comments

MCMS 2002 : Getting “Unable to cast object of type system.net.filewebresponse

PROBLEM
========
Getting “Unable to cast object of type system.net.filewebresponse to type system.net.httpwebresponse” error message in client side import scirpt

RESOLUTION
============
The sdo package path has been specified as standard windows physical file format as “E:\folder\sdofilename.sdo”

ROOTCAUSE
==========
The SDAPI import method reads the sdo file path and it process afterward. It’s expecting a path format that compatible with HttpWebResponse. When we use x:// notation, .net might interpret it as a FileWebResponse and that’s could be what causes the InvalidCastException.
More Posts Next page »
 
Page view tracker