Posts tonen met het label Metadata. Alle posts tonen
Posts tonen met het label Metadata. Alle posts tonen

maandag 7 januari 2013

List of available Sharepoint Services

List of available Sharepoint Services
SharePoint Object Model is a .Net based Application Programming Interface to interact with SharePoint components. But all the applications written using SharePoint Object Model require to be run on the SharePoint Server itself. It is not possible to use it to work remotely with a SharePoint Server.

SharePoint Web Services provides the capability to work with SharePoint server remotely. But SharePoint Web Services are not as much as rich as SharePoint Object Model and all SharePoint features and components are not accessible through Web Services. But it includes Web Services to interact with most commonly used SharePoint features and components. If out-of-the-box SharePoint Web Services doesn’t fit on our requirements, we can also build custom web service on top of SharePoint leveraging the SharePoint Object Model API.
I had prepared a concise list of SharePoint Web Services for my own reference which I am sharing with you:  

1) Administration Web Service (http://<site>/_vti_bin/Admin.asmx): The Administration Web service provides methods that can beused to manage Windows SharePoint Services such as creating or deleting site collections. 
Following are the main methods provided by this service:
  • CreateSite
  • DeleteSite
  • GetLanguages
  • RefreshConfigCache
2) Alerts Web Service (http://<Site>/_vti_bin/Alerts.asmx):
The alerts web service provides methods for working with alert subscriptions
for the listitems in a SharePoint site remotely. Alert subscriptions specify when and how notifications are sent to users when changes are made to content stored on the server. Following are the two main methods provided by this service:
  • GetAlerts
  • DeleteAlerts
3) Copy Web Service (http://<Site>/_vti_bin/Copy.asmx):

This web service provides capability to move files from one list to another within a SharePoint site or between different SharePoint sites. Following are the main methods provided by this service:

  • GetItem
  • CopyIntoItems
  • CopyIntoItemsLocal
4) Document Workspace Web Service (http://<Site>/_vti_bin/Dws.asmx):

This web service provides methods for managing Document Workspace sites and the data they contain. Following are the main methods provided by this service:

a) Managing Document Workspace sites

  • CanCreateDwsUrl
  • CreateDws
  • RenameDws
  • DeleteDws
b) Managing data for the Document Workspace site

  • GetDwsData
  • GetDwsMetaData
  • UpdateDwsData
c) Managing folders in the Document Workspace site

  • CreateFolder
  • DeleteFolder
d) Managing documents in the Document Workspace site

  • FindDwsDoc
e) Managing site users for the Document Workspace site

  • RemoveDwsUser

5) Forms Web Service (http://<Site>/_vti_bin/Forms.asmx):

The Forms service provides methods for returning forms that are used in the user interface when working with the contents of a list. There are following two methods available:

  • GetForm 
  • GetFormCollection
6) Imaging Web Service (http://<Site>/_vti_bin/Imaging.asmx):

The Imaging service provides methods that enable you to create and manage picture libraries. There are following methods that can be utilized with the imaging web service:

  • CheckSubwebAndList
  • CreateNewFolder
  • Delete
  • Download
  • Edit
  • GetItemsByIds
  • GetItemsXMLData
  • GetListItems
  • ListPictureLibrary
  • Rename
  • Upload 

7) Lists Web Service (http://<site>/_vti_bin/Lists.asmx):

The Lists Web service provides methods for working with SharePoint lists, content types, list items, and files. There are following methods that can be utilized with the Lists web service:

  • AddAttachment
  • AddDiscussionBoardItem
  • AddList
  • AddListFromFeature
  • ApplyContentTypeToList
  • CheckInFile
  • CheckOutFile
  • CreateContentType
  • DeleteAttachment
  • DeleteContentType
  • DeleteContentTypeXmlDocument
  • DeleteList
  • GetAttachmentCollection
  • GetList
  • GetListAndView
  • GetListCollection
  • GetListContentType
  • GetListContentTypes
  • GetListItemChanges
  • GetListItemChangesSinceToken
  • GetListItems
  • GetVersionCollection
  • UndoCheckOut
  • UpdateContentType
  • UpdateContentTypeXmlDocument
  • UpdateList
  • UpdateListItems

8) Meetings Web Service (http://<Site>/_vti_bin/Meetings.asmx):

This web service enables you to create and manage Meeting Workspace sites. Following are the main methods available in the web service:

  • AddMeeting
  • AddMeetingFromICal
  • CreateWorkspace
  • DeleteWorkspace
  • GetMeetingWorkspaces
  • GetMeetingsInformation
  • RemoveMeeting
  • RestoreMeeting
  • SetAttendeeResponse
  • SetWorkspaceTitle
  • UpdateMeeting
  • UpdateMeetingFromICal

9) People Web Service (http://<Site>/_vti_bin/People.asmx):

This service provides methods that can be used to associate user identifiers (IDs) with security groups for SharePoint Web site permissions. It contains following methods:

  • GetPrincipalsInGroup
  • ResolvePrincipals
  • SearchPrincipals

10) Permissions Web Service (http://<site>/_vti_bin/Permissions.asmx):

Permissions Web service provides methods for working with SharePoint list and site permissions. Following are the various methods available in this service:

  • AddPermission
  • AddPermissionCollection
  • GetListItemPermissionsByUser
  • GetListPermissionsByUser
  • GetPermissionCollection
  • GetPermissionsByToken
  • GetPermissionsByUser
  • RemovePermission
  • RemovePermissionCollection
  • UpdatePermission

11) SharePoint Directory Management Service (http://<Site>/_vti_bin/sharepointemailws.asmx):

This service provides methods for managing Active Directory e-mail distribution groups and their membership. It provides following main methods:

  • CreateContact
  • DeleteContact
  • ModifyContact
  • CreateDistributionGroup
  • DeleteDistributionGroup
  • ModifyDistributionGroup
  • RenameDistributionGroup
  • ChangeContactsMembershipInDistributionGroup
  • ChangeUsersMembershipInDistributionGroup 

12) Site Data Web Service (http://<Site>/_vti_bin/SiteData.asmx):

The Site Data service provides methods that return metadata or list data from sites or lists in Microsoft Windows SharePoint Services. This web service is read only. Following are the main methods provided by this service:

  • GetList
  • GetListCollection
  • GetListItems 
  • EnumerateFolder
  • GetAttachments
  • GetChanges
  • GetContent
  • GetSite
  • GetWeb 
  • GetSiteAndWeb
  • GetSiteUrl
  • GetURLSegments 

13) Sites Web Service (http://<Site>/_vti_bin/Sites.asmx):

The Sites service provides a method for returning information about the collection of site templates on the virtual server. Following are the main methods provided by this service:

  • ExportWeb
  • ImportWeb
  • GetSiteTemplates
  • GetUpdatedFormDigest

14) Search Web Service (http://<site>/_vti_bin/search.asmx):

The QueryService can be used to query the search indexes in the same way that you would search from the home page of a SharePoint site. Main methods available in this service are as below:

  • Query
  • QueryEx
  • GetPortalSearchInfo
  • GetSearchMetadata
  • Registration
  • Status 

15) Users and Groups Web Service (http://<Site>/_vti_bin/usergroup.asmx):

The Users and Groups Web service provides methods for working with users, role definitions, and groups. It provides huge number of methods which are listed below:

  • AddGroup
  • AddGroupToRole
  • AddRole
  • AddRoleDef
  • AddUserCollectionToGroup
  • AddUserCollectionToRole
  • AddUserToGroup
  • AddUserToRole
  • GenerateXmlMappings 
  • GetAllUserCollectionFromWeb
  • GetGroupCollection
  • GetGroupCollectionFromRole
  • GetGroupCollectionFromSite
  • GetGroupCollectionFromUser
  • GetGroupCollectionFromWeb
  • GetGroupInfo
  • GetHashCode 
  • GetLifetimeService 
  • GetRoleCollection
  • GetRoleCollectionFromGroup
  • GetRoleCollectionFromUser
  • GetRoleCollectionFromWeb
  • GetRoleInfo
  • GetRolesAndPermissionsForCurrentUser
  • GetRolesAndPermissionsForSite
  • GetUserCollection
  • GetUserCollectionFromGroup
  • GetUserCollectionFromRole
  • GetUserCollectionFromSite
  • GetUserCollectionFromWeb
  • GetUserInfo
  • GetUserLoginFromEmail
  • RemoveGroup
  • RemoveGroupFromRole
  • RemoveRole
  • RemoveUserCollectionFromGroup
  • RemoveUserCollectionFromRole
  • RemoveUserCollectionFromSite
  • RemoveUserFromGroup
  • RemoveUserFromRole
  • RemoveUserFromSite
  • RemoveUserFromWeb
  • UpdateGroupInfo
  • UpdateRoleDefInfo
  • UpdateRoleInfo
  • UpdateUserInfo 

16) Versions Web Service (http://<site>/_vti_bin/Versions.asmx):

Versions Web service provides methods for working with file versions in SharePoint document libraries. Methods included in this service:

  • DeleteAllVersions 
  • DeleteVersion 
  • GetVersions 
  • RestoreVersion 

17) Views Web Service (http://<site>/_vti_bin/Views.asmx):

Views Web service provides methods for creating, deleting, or updating list views. Methods included in this service are as below:

  • AddView
  • DeleteView
  • GetView 
  • GetViewCollection 
  • GetViewHtml 
  • UpdateView 
  • UpdateViewHtml

18) Web Part Pages Web Service (http://<Site>/_vti_bin/WebPartPages.asmx):

Web Part Pages service provides methods for working with Web Parts. Following are the various methods provided by this service:

  • AddWebPart
  • AddWebPartToZone
  • AssociateWorkflowMarkup
  • ConvertWebPartFormat
  • DeleteWebPart
  • ExecuteProxyUpdates
  • FetchLegalWorkflowActions
  • GetCustomControlList
  • GetDataFromDataSourceControl
  • GetFormCapabilityFromDataSourceControl
  • GetWebPart
  • GetWebPart2
  • GetWebPartCrossPageCompatibility
  • GetWebPartPage
  • GetWebPartPageConnectionInfo
  • GetWebPartPageDocument
  • GetWebPartProperties
  • GetWebPartProperties2
  • GetXmlDataFromDataSource
  • RemoveWorkflowAssociation
  • RenderWebPartForEdit
  • SaveWebPart
  • SaveWebPart2
  • ValidateWorkflowMarkupAndCreateSupportObjects 

19) Webs Web Service (http://<Site>/_vti_bin/Webs.asmx):

Webs service provides methods for working with sites and subsites. Following are the various methods provided by this service:

  • CreateContentType
  • CustomizeCss
  • DeleteContentType
  • GetActivatedFeatures
  • GetAllSubWebCollection
  • GetColumns
  • GetContentType
  • GetContentTypes
  • GetCustomizedPageStatus
  • GetListTemplates
  • GetWeb
  • GetWebCollection
  • RemoveContentTypeXmlDocument
  • RevertAllFileContentStreams
  • RevertCss
  • RevertFileContentStream
  • UpdateColumns
  • UpdateContentType
  • UpdateContentTypeXmlDocument
  • WebUrlFromPageUrl 

To get the full details of above SharePoint Web Services and their respective Methods please visit SharePoint Web Services MSDN Page @ http://msdn.microsoft.com/en-us/library/ms479390.aspx.

 

 



Visit the Sharepoint Community site for all Sharepoint related info.

Belfius Bank

dinsdag 4 september 2012

Change ContentType and Metadata of your Documents uploaded in a Sharepoint Library


This part for updating a sharepoint contentType for a uploaded Document in a SharePoint Library.
So Once you have uploaded a File into a SharePoint Library, you needs it's ID for changing the
metadata or contentType of a Document.
So first of all call my function below for getting the ID.

    //Call to the function to get the ID
    string sID = sGetID(sSiteUrl, sSiteList, sFileName);
    private string sGetID(string sURL, string sListName, string sFileName) 
    {
        string sID = "";
        SPListsService.Lists list = new SPListsService.Lists();
        list.Url = sSiteUrl + "/_vti_bin/lists.asmx";
  // I have a common Boolean field for determing if I use the current logged on user or to use a Technical User. 
  // attention !!!! The user must have access to your Sharepoint environment.
        if (bDefaultLogon)
            list.Credentials = System.Net.CredentialCache.DefaultCredentials;
        else
        {
            list.PreAuthenticate = true;
            list.Credentials = new System.Net.NetworkCredential(sTechnicalUser, sTechnicalPw, sTechnicalDomain);
        }
        try
        {
   string rowLimit = "99999";
            XmlDocument xmlDoc = new System.Xml.XmlDocument();
            XmlNode listQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
            listQuery.InnerXml = "" + sFileName + "";
            listQuery.InnerXml = listQuery.InnerXml + "\"";
            XmlNode listViewFields = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
            listViewFields.InnerXml = "" +
                                      "";
            XmlNode listQueryOptions = xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");
            listQueryOptions.InnerXml = "";
            XmlNode ndListItems = null;
            Guid g = GetWebID(sSiteUrl); // Function to get the ID of your Web
            ndListItems = list.GetListItems(sSiteList, null, listQuery, listViewFields, rowLimit, listQueryOptions, g.ToString());
            sID = ndListItems.ChildNodes[1].ChildNodes[1].Attributes["ows_ID"].Value;
        }
        catch { }
        finally {
           list.Dispose();
        }
        return sID;
    }    
    /* -- Get the Guid of your List  -- */
    private Guid GetWebID(string webPath)
    {
        SPSiteDataService.SiteData siteDataWS = new SPSiteDataService.SiteData();
        if (bDefaultLogon)
            siteDataWS.Credentials = System.Net.CredentialCache.DefaultCredentials;
        else
        {
            siteDataWS.PreAuthenticate = true;
            siteDataWS.Credentials = new System.Net.NetworkCredential(sTechnicalUser, sTechnicalPw, sDomain);
        }
        SPSiteDataService._sWebMetadata webMetaData;
        SPSiteDataService._sWebWithTime[] arrWebWithTime;
        SPSiteDataService._sListWithTime[] arrListWithTime;
        SPSiteDataService._sFPUrl[] arrUrls;
        string roles; string[] roleUsers; string[] roleGroups;
        siteDataWS.Url = webPath + "/_vti_bin/sitedata.asmx";
        uint i = siteDataWS.GetWeb(out webMetaData, out arrWebWithTime, out arrListWithTime, out arrUrls, out roles, out roleUsers, out roleGroups);
        Guid g = new Guid(webMetaData.WebID);
        return g;
    }
 
 


My Code below will change the ContentType of your Document and also some extra Metadata. 
Now it is posible that you would not want to change the ContentType,
 so if not, put the call in comment.
The reason why you need the change of your ContentType and 
the rest of your Metadata in a different XML update block
is because by changing the ContentType, other Columns/MetaData becomes at your position, 
as examle your colums that you have created in your ContentType 
are not at your position before you have changed your ContentType. 
Only the default Columns are available.


    // Call to the function for update file metadate
 bool ret = UpdateFileDataViaBatch(sID, sSiteUrl, sSiteList, Array_FileMetaData);   

 /* --  Update File columns in Sharepoint List-- */
    private Boolean UpdateFileDataViaBatch(string sId, string sSiteUrl, string sSiteList, DataTable ExtraFileMetaData)
    {
        Boolean retcode = true;
        XmlDocument xmlDoc = new XmlDocument();
        XmlElement elBatch = xmlDoc.CreateElement("Batch");
        elBatch.SetAttribute("OnError", "Continue");
        elBatch.SetAttribute("ViewName", GetViewId(sSiteUrl, sSiteList, ""));
        try
        {
            string strBatch = "";
            int id = 0;
            if (ExtraFileMetaData.Rows.Count > 0)
            {
                DataRow drFileInfo = ExtraFileMetaData.Rows[0];
    // call for creating your xml-element for changing the contentType... If you don't need to change it, put it in comment
                strBatch = changeContentType(id,drFileInfo,  sId);
    // call for creating you xml-element for updating your document with extra info.
                strBatch = strBatch + createXmlUpdateBatch(++id, drFileInfo, sId);
            }
            elBatch.InnerXml = strBatch;
            Boolean retcodeUpdSPList = UpdateSPList(sSiteUrl, sSiteList, elBatch);
        }
        catch { }
        return retcode;
    }

    private string changeContentType(int id, DataRow drFileInfo, string sID)
    {
        String strBatch = "";
        strBatch = strBatch + "";
        strBatch = strBatch + "" + sID + "";
        strBatch = strBatch + "" + replaceSpecialChars(drFileInfo["ContentType"].ToString()) + "";
        strBatch = strBatch + "";
        return strBatch;
    }
    private string createXmlUpdateBatch(int id,  DataRow drFileInfo, string sID)
    {
        String strBatch = "";
        strBatch = strBatch + "";
        strBatch = strBatch + "" + sID + "";
        strBatch = strBatch + "" + replaceSpecialChars(drFileInfo["ExtraFileMetaData1"].ToString()) + "";
        strBatch = strBatch + "" + replaceSpecialChars(drFileInfo["ExtraFileMetaData2"].ToString()) + "";
        strBatch = strBatch + "";
        return strBatch;
    }

    private string replaceSpecialChars(string mystring)
    {
        mystring = mystring.Replace("&", "&");
        mystring = mystring.Replace("<", "<");
        mystring = mystring.Replace(">", ">");
        mystring = mystring.Replace("\"", """);
        mystring = mystring.Replace("'", "'");
        return mystring;
    }

 
 

At least you also need the function for the real update... 
otherwise you have your batch XML document, 
but your data isn't updated yet.
So you also need my function below for executing your 
Batch Element by using the Lists.asmx webservice.


 /* -- Update SharePoint List -- */
    private Boolean UpdateSPList(string sSiteUrl, string sSiteList, XmlElement elBatch)
    {
        Boolean retcode = true;
        SPListsService.Lists list = new SPListsService.Lists();
        list.Url = sSiteUrl + "/_vti_bin/lists.asmx";
        if (bDefaultLogon)
            list.Credentials = System.Net.CredentialCache.DefaultCredentials;
        else
        {
            list.PreAuthenticate = true;
            list.Credentials = new System.Net.NetworkCredential(sTechnicalUser, sTechnicalPw, sDomain);
        }
        try
        {
            XmlNode ndReturn = list.UpdateListItems(sSiteList, elBatch);
            // Instantiate a new XML document object to hold the return value(s) 
            XmlDocument xmlResult = new XmlDocument();
            xmlResult.LoadXml(ndReturn.OuterXml);
            // SharePoint XML always uses a fixed namespace; you'll need your own NamespaceManager object to parse the return values 
            XmlNamespaceManager nsMgr = new XmlNamespaceManager(xmlResult.NameTable);
            nsMgr.AddNamespace("sp", ndReturn.NamespaceURI);
            XmlNode ndRoot = xmlResult.SelectSingleNode("sp:Results", nsMgr);
            // Find the ErrorCode node, which exists for all operations regardless of status. 
            XmlNodeList nlResults = ndRoot.SelectNodes("//sp:Result/sp:ErrorCode", nsMgr);
            // Loop through the node collection and find each ErrorCode entry 
            foreach (XmlNode ndResult in nlResults)
            {
                // Check the value of the node to determine its status 
                if (ndResult.InnerText != "0x00000000")
                {
                    XmlNode ndError = ndResult.NextSibling;
                    string sError = ndError.InnerText;
                    // Set the value of string variable to hold the error code 
                    // If you want to trip the Try…Catch, throw and exception of whatever type suits you 
                }
                else
                {
                    // put your code on success... whatever you want 
                }
            }
        }
        catch (Exception e)
        {
            retcode = false;
        }
        finally
        {
            list.Dispose();
        }
        return retcode;
    }
 
 
 

If you have questions, don't hesitate to contact me... 
I only use the webservices to be undependent of the environment
to run the code on... So it hasn't to be on a sharepoint Environment !
If there are problems with my code, please let me know... 

Upload File from a networkdrive into a Sharepoint Library


Last week I wrote some code for migrating a networkdrive folder content into a SharePoint Library. 
You cannot use the Lists.asmx for uploading the documents because this webservice does not provide
the functionality for uploading files. 
But after a little bit of research I found quickly that you can use the copy.asmx webservice. 
Normally it is used for copying files between two SharePoint Libraries but it also 
work for copying files from a networkdrive into a SharePoint Library.

So you can use the code behind for copying a file on a network drive in a Sharepoint Library.



        SPCopyService.Copy copy = new SPCopyService.Copy();
  copy.Url = sSiteUrl + "/_vti_bin/copy.asmx";
        try
        {
            if (bDefaultLogon)
                copy.Credentials = System.Net.CredentialCache.DefaultCredentials;
            else
            {
                copy.PreAuthenticate = true;
                copy.Credentials = new System.Net.NetworkCredential(sTechnicalUserID, sTechnicalUserPW, sTechnicalUserDomain);
            }

            string destinationUrl = sSharePointDestinationFolder + "/" + sfilename;
            // destinationUrl = SiteUrl + "/" + SiteLibrary + "/" + OptionalFolder + "/" + filename.Extention
            string[] destinationUrls = { destinationUrl };
            SPCopyService.FieldInformation info1 = new SPCopyService.FieldInformation();
            info1.DisplayName = sfilename;
            info1.InternalName = replaceSpecialChars(sfilename);
            info1.Type = SPCopyService.FieldType.Text;
            info1.Value = replaceSpecialChars(sfilename);
            SPCopyService.FieldInformation[] info = { info1 };
            SPCopyService.CopyResult copyResult = new SPCopyService.CopyResult();
            SPCopyService.CopyResult[] copyResults = { copyResult };
            //Reading the document contents in to stream
            FileStream strm = new FileStream(sFilePath + @"\" + sfilename, FileMode.Open, FileAccess.Read);
            byte[] fileContents = new Byte[strm.Length];
            byte[] r = new Byte[strm.Length];
            int ia = strm.Read(fileContents, 0, Convert.ToInt32(strm.Length));
            strm.Close();
            // call the webservice procedure CopyIntoItems       
            uint result = copy.CopyIntoItems(sfilename, destinationUrls, info, fileContents, out copyResults);
            // Check for Errors:     
            foreach (SPCopyService.CopyResult copyRes in copyResults)
            {
                string msg =  "====================================" +
                "\n " + "SharePoint Error:" +
                "\n " + "              Url: " + copyRes.DestinationUrl +
                "\n " + "              Error Code: " + copyRes.ErrorCode +
                "\n " + "              Message: " + copyRes.ErrorMessage +
                "\n " + "====================================";
                if (copyRes.ErrorCode.ToString().Equals("Success"))
                {
                    // code for success if needed...
                }
                else
                {
                    // code for a failure if needed...
                }
                Console.WriteLine(msg);
            }
        }
        catch (Exception e)
        {
            iFailedUpdatedRecords++;
            Console.WriteLine("   Error on upload...");
        }
        finally {
            copy.Dispose();
        }
 

 

dinsdag 6 maart 2012

Copy, Duplicate or Pre-populate Sharepoint Fields


New demand arrived to duplicate items in a custom list. Out of the box, Sharepoint hasn't provided
that functionality.
So, lets develop it our selfs...

Wat you need to do is to provide a custom link on you existing item that provides a parameter,
for example DID (Duplicate ID). Create a custom newform.aspx where you add a new datawebpart that
takes your parameter as filter. Add the fields that you want to duplicate to your page en put them 
in a table that you set hidden.
Once done, you add a content webpart Editor to your page and some next script to your page : 

_spBodyOnLoadFunctionNames.push('SPCC_Dup_fill_AllDefaultValues()');
ExecuteOrDelayUntilScriptLoaded(SPCC_Dup_fill_TaxonomyValues, "scriptforwebtaggingui.js");

// only change this function...
function SPCC_Dup_fill_AllDefaultValues(){          
 // Pre-populate peoplepicker field
 // fillPeoplePicker (ID of Sharepoint Form PeoplePicker_userfield, Name of Sharepoint Form PeoplePicker_userfield, ID of DIV readonly field)
 SPCC_Dup_fill_PeoplePicker("FIELDID_UserField","FIELDNAME$UserField", "REFERENCE_DIV_ID");
 // Pre-populate text Field
 // fillInputField( ID of Sharepoint Form Text Field, ID of DIV readonly field)
 SPCC_Dup_fill_InputField("FIELDID_TextField","REFERENCE_DIV_ID");
 // Pre-populate Lookup/Select Field
 // Fill_Lookup_Select_FromFieldName(Form FieldName, ID of DIV readonly field, type [Lookup, DropDownChoice ] )
 SPCC_Dup_fill_Lookup_Select_FromFieldName("FIELDID_DropDownChoice","REFERENCE_DIV_ID", 'DropDownChoice');
 // Pre-Populate Hyperlink
 // FillHyperlinkField(Form FieldName Url, Form FieldName Description, ID of DIV readonly field);
    SPCC_Dup_fill_HyperlinkField("FIELDID_UrlFieldUrl","FIELDID_UrlFieldDescription", "REFERENCE_DIV_ID");
 // Pre-Populate CheckBox Yes No
 SPCC_Dup_fill_CheckboxFieldYN("FIELDID_BooleanField", "REFERENCE_DIV_ID");
 // Pre-Populate Date Time field.  
 SPCC_Dup_fill_DateTimeField("FIELDID_DateTimeField_DateTimeFieldDate", "REFERENCE_DIV_ID", "mm/dd/yyyy");
 // Pre-Populate RadioButtonlist
 SPCC_Dup_fill_RadioButtonList("FIELDNAME$RadioButtons", "REFERENCE_DIV_ID");
 // Pre-Populate CheckButtonList
 SPCC_Dup_fill_CheckButtonList("FIELDID","REFERENCE_DIV_ID");
 // Pre-Populate Dropdown
 SPCC_Dup_fill_CustomSelect("FIELDID_DropDownChoice","REFERENCE_DIV_ID");
    // Pre-Populate MultiSelect
 SPCC_Dup_fill_MultiSelect("FIELDID_SelectCandidate", "REFERENCE_DIV_ID");        
    // Pre-Populate MetaDataField
 // see SPCC_Dup_fill_TaxonomyValues function
 // Pre-populate Mutli line text Field
 SPCC_Dup_fill_MultiTextField("FIELDID_TextField_inplacerte","REFERENCE_DIV_ID");
}

function SPCC_Dup_fill_TaxonomyValues(){
 // Pre-Populate MetaDataField
 SPCC_Dup_fill_MetaDataFied("FIELDID_ctl02", "REFERENCE_DIV_ID");
}
 

I have written an function for the different types of Sharepoint Fields... if I have missed one, 
don't hesitate to let me know...

Now the important block, the different functions...

two function I use often to get the Field Objects for manipulating the values or innerHTML methods:
// Direct call for getting the element Object by the ID-property of the element
function SPCC_Dup_getTagFromIdentifier(identifier) {  return document.getElementById(identifier); }
// Call for getting the element Object by the TagName and filter them by identifier or the ID-property
function SPCC_Dup_getTagFromIdentifierAndTitle(tagName, identifier, myid){
 var len = identifier.length;
 var tags = document.getElementsByTagName(tagName);
 for (var i=0; i< tags.length; i++)
 {
  var tempString = tags[i].id;
  if( (tags[i].id == myid) && ( (identifier == '') || (tempString.indexOf(identifier) == tempString.length - len)) )
  { return tags[i]; }
 }
 return null;
} 
 

One of the difficult fields to fill in by script was the PeoplePicker. 
This because when you take al look at the source of the generated Sharepoint HTML,
you see that the field exists of different span, div and input fields. 
Also, in the view state of your element you get HTML tags with a link and 
as display the name of the user that you have to put in the PeoplePicker field. 
So first step is to get only the username. 
Second step is to retrieve the element object of the peoplepicker field 
that ends with _upLevelDiv. 
Third step is to put your username in that DIV and at last but not least 
to validate the user. 

function SPCC_Dup_fill_PeoplePicker(myPeoplePicker_ID, myPeoplePicker_Name, newPP_ID){
// STEP 1: Retreive only username of the view PeoplePicker field
 var ppf = document.getElementById(newPP_ID);
 var myppfValue = ppf.innerHTML;
 var ibegin = myppfValue.indexOf('">') + 2;
 var myppfValueUpperCase = myppfValue.toUpperCase();
 var myPPValue = myppfValue.substr(ibegin, myppfValueUpperCase.indexOf('>/A<', ibegin ) - ibegin);
// STEP 2 : get the PeoplePicker field Object to fill in.
 var myPeoplePicker_UpperLevel_ID = myPeoplePicker_ID + '_upLevelDiv';
 var assingedToInput = SPCC_Dup_getTagFromIdentifier(myPeoplePicker_UpperLevel_ID);
// STEP 3 : put the username in the PeoplePicker Field object 
 assingedToInput.innerHTML = myPPValue ;
// LAST STEP : refresh and validate picker control
 if(!ValidatePickerControl(myPeoplePicker_ID))
 {
    ShowValidationError();
 }
 var arg = getUplevel(myPeoplePicker_ID);
 var ctx = myPeoplePicker_ID;
 EntityEditorSetWaitCursor(ctx);
 WebForm_DoCallback(myPeoplePicker_Name,arg,EntityEditorHandleCheckNameResult,ctx,EntityEditorHandleCheckNameError,true);
}
 

One of the easy ones is the normal InputFields. With this field you only have to read and set the values...
function SPCC_Dup_fill_InputField(SPFF_ID, newTF_ID)
{
 var sptf = document.getElementById(newTF_ID);
 var spff = document.getElementById(SPFF_ID);
 spff.value = sptf.innerHTML;
}
 

An other hard one is the Multiline textfield. I have passed half a day for understanding how 
this field is being generated by Sharepoint !!! Not easy to understand, because you only see a
hidden input field and some DIV's that are empty. 

First step I have done is to remove from the view field the surrounded DIV-tag. 
Afterwards convert it as full HTML format, and at least put it in the sharepoint Element and
call a sharepoint function to validate it. This is needed because otherwise your text is removed again.

function SPCC_Dup_fill_MultiTextField(SPFF_ID, newTF_ID){
// STEP 1 : get the content to fill in and remove the parent DIV-tag
            var sptf = document.getElementById(newTF_ID);
            var convertRTE = sptf.innerHTML;
            var ibegin = convertRTE.indexOf('">') + 5;
            convertRTE= convertRTE.substr(ibegin , convertRTE.indexOf('</div>',ibegin)-ibegin);
// STEP 2 : convert the content to full qualified HTML body format
            convertRTE= convertRTE.replace(/</g, "<");
            convertRTE= convertRTE.replace(/>/g, ">");
// STEP 3 : fill in the you multiline textfield with your bodycontent and validate it.
            var spff = document.getElementById(SPFF_ID);
            spff.UseInlineStyle = 'True';
            spff.innerHTML = convertRTE;
            RTE.RichTextEditor.transferContentsToInputField(SPFF_ID);
}
 

An other funny one is the Lookup or Select Fields. 
This because Sharepoint can generate two different type of fields. Or it is an select/option list
or just even an input tag. This depending if there are less or more than 20 elements in the list.
So you need to check the type of field Sharepoint has created, and depending on it populate the
select-tag or input-tag.

function SPCC_Dup_fill_Lookup_Select_FromFieldName(fieldName, newTF_ID, type){
 var value = document.getElementById(newTF_ID).innerHTML;
 if (value == undefined) return;
 var theSelect = SPCC_Dup_getTagFromIdentifierAndTitle("select", type,fieldName);
// if theSelect is null, it means that the target list has more than
 // 20 items, and the Lookup is being rendered with an input element
 if (theSelect == null) {
  var theInput = SPCC_Dup_getTagFromIdentifierAndTitle("input","",fieldName);
  ShowDropdown(theInput.id); //this function is provided by SharePoint
  var opt=document.getElementById(theInput.opt);
  SPCC_Dup_setSelectedOption(opt, value);
  OptLoseFocus(opt); //this function is provided by SharePoint
 } else {
  SPCC_Dup_setSelectedOption(theSelect, value);
 }
}
 
function SPCC_Dup_setSelectedOption(select, value)
{
 var opts = select.options;
 var l = opts.length;
 if (select == null) return;
 for (var i=0; i < l; i++) {
  if (opts[i].value == value) {
   select.selectedIndex = i;
   return true;
  }
 }          
 return false;
}
 

A Hyperlink field gives you in view an array with the link and the description of the link.
so to fill it in your newform you need to fill in two input fields. 
function SPCC_Dup_fill_HyperlinkField(SPFFUrl_ID, SPFFDesc_ID, newTF_ID){
 var sptf = document.getElementById(newTF_ID);
 var spffurl = document.getElementById(SPFFUrl_ID);
 var spffdesc = document.getElementById(SPFFDesc_ID);
 var mySplitResult = sptf.innerHTML.split(", ");
 if(mySplitResult.length > 1)
 {
  spffurl.value = mySplitResult[0];
  spffdesc.value = mySplitResult[1];
 }
 else
 {          
  spffurl.value = mySplitResult[0];
 }
}           
 

Sharepoint provided also a YES_NO field, behind the screen it is just a checkbox. 
function SPCC_Dup_fill_CheckboxFieldYN(SPFF_ID, newTF_ID){
 var sptf = document.getElementById(newTF_ID);
 var spff = document.getElementById(SPFF_ID);
 if (sptf.innerHTML.toUpperCase()=="TRUE"||sptf.innerHTML=="1"){
  spff.checked=true;
    }
    if (sptf.innerHTML.toUpperCase()=="FALSE"||sptf.innerHTML=="0"){
        spff.checked=false;
    }
}
 

Two elements that acts amost the same are the radiobutton list and the checkbutton list. 
Here you need to loop the array of items in your fields and check them if needed.

function SPCC_Dup_fill_RadioButtonList(SPFF_Name, newTF_ID){
 var sptf = document.getElementById(newTF_ID);
 var spff = document.getElementsByName(SPFF_Name);
 if (spff != null)
 {
  for (i=0; i < spff.length;i++)
  {
   if (spff[i].parentNode.innerHTML.indexOf(sptf.innerHTML) >= 0)
    {spff[i].checked = true;}
   else
    {spff[i].checked = false;}
  }                      
 }
}
                       
function SPCC_Dup_fill_CheckButtonList(SPFF_ID, newTF_ID){
 var sptf = document.getElementById(newTF_ID);
 var split_sptf = sptf.innerHTML.split(", ");
 var tags = document.getElementsByTagName('input');
 var identifier =  SPFF_ID.substr(0,SPFF_ID.length -5);
 var found = 0;
 for (var i=0; i< tags.length; i++)
 {   found = 0 ;
  var tempString = tags[i].id;
  if(tempString.indexOf(identifier) >= 0)
  {
   var spff= tags[i];
   for (j=0; j < split_sptf.length; j++)
   {
    if (spff.parentNode.innerHTML.indexOf(split_sptf[j]) >= 0)
    { spff.checked = true; found++;}
    else
       {   if (found == 0){spff.checked = false;}}
   }
  }                      
 }
}
 

The Date Time field of sharepoint is not so easy to fill in. 
This because you get from your field a totaly other format as what you need to fill in sharepoint.
The new fields exists of three blocks of fields. The date-field, the Hour-field and the minutes-field.
So you need to convert your datetime result into three different blocks. 
Also it is possible to fill in the hours as format HH: or HH AM/PM. 
We have put our general site settings for time to 24h option.
So here an example function, but depending your site settings 
it may have to be changed or be completed !
function SPCC_Dup_fill_DateTimeField(setDateFieldId,theDate, sDateFormat){
 // expecting format yyyy-MM-ddTHH:mm:ssZ
    var odate = SPCC_Dup_getTagFromIdentifier(theDate);
    var setDate = SPCC_Dup_getTagFromIdentifier(setDateFieldId);
    var setHours = SPCC_Dup_getTagFromIdentifier(setDateFieldId + "Hours");
    var setMinutes = SPCC_Dup_getTagFromIdentifier(setDateFieldId + "Minutes");
    if (odate != null)
    {
   var ddate = odate.innerHTML;
   if (ddate.length > 0)
   {
  var dDay = ddate.substring(8,10);
  var dMonth = ddate.substring(5,7);
  var dYear= ddate.substring(0,4);
  var dHours= ddate.substring(11,13);
  var dMinutes= ddate.substring(14,16);

  if (setDate != null)
  {
    if (sDateFormat.toLowerCase() == 'dd/mm/yyyy')
    {           setDate.value = dDay + '/' + dMonth + '/' + dYear;}
    if (sDateFormat.toLowerCase() == 'mm/dd/yyyy')
    {           setDate.value = dMonth + '/' + dDay + '/' + dYear;}
    if (sDateFormat.toLowerCase() == 'yyyy/mm/dd')
    {           setDate.value = dYear+ '/' + dMonth + '/' + dDay;}
  }
  if (setHours != null)
  {
    var iHours = parseInt(dHours) + 1;
    if ( iHours <10) {dHours = '0' + iHours;} else {dHours = iHours;}
    setHours.value = dHours +':';
  }
  if (setMinutes != null)
  {
    setMinutes.value = dMinutes;
  }
   }
 }
}

For a Select field, you have the option to choose of an normal selectbox, 
or one where you may fill in a custom text. This means that in case of pre-populate
you need to check if you value exist in the Dropdown field, if not to fill in the
custom inputfield. 

function SPCC_Dup_fill_CustomSelect(fieldID, newTF_ID){
 var value = document.getElementById(newTF_ID).innerHTML;
 if (value == undefined) return;
 var theSelect = document.getElementById(fieldID);
 if (SPCC_Dup_setSelectedOption(theSelect, value) == false)
 {   // value does not exist in the DropDown box. zo fill in the custum field.
  var myNewID = fieldID.replace("DropDownChoice", "ctl01");
  var theInput = document.getElementById(myNewID);
  theInput.value = value;
  var myNewButtonID = fieldID.replace("DropDownChoice", "FillInButton");
  SetChoiceOption(myNewButtonID);
 }
}

A interesting field for prepopulating is also the Multi Select field.
This because you get an array of fields in your result, but in the newform
you receive two multi select boxes. One with the available items and 
one with the selected items.
For making me easy, I created the script to select first the items in the
candidates list and call the sharepoint function to populate them in the selected box.
So I don't have to remove them myself in the candidate list and transfer them manualy in 
the selected items box. 

function SPCC_Dup_fill_MultiSelect(fieldID, newTF_ID){          
 var value = document.getElementById(newTF_ID).innerHTML;
 var fieldbuttonID = eval(fieldID.replace("SelectCandidate", "MultiLookupPicker_m"));
 var split_value = value.split("</a>");
 var theSelect = document.getElementById(fieldID);
 var i = 0;
 for (i=0; i< theSelect.options.length; i++)
 {
  var valuefound = false;
  for(var j=0;j< split_value.length;j++)
  {
   var ibegin = split_value[j].indexOf(">") + 4;
   var myMLPValue = split_value[j].substr(ibegin, split_value[j].length);
   if(theSelect.options[i].text == myMLPValue)
   {
    theSelect.options[i].selected = true;
    valuefound = true;
   }
   else
   {
    if(!valuefound)
    {
     theSelect.options[i].selected = false;
    }
   }
  }
 }
 GipAddSelectedItems(fieldbuttonID);
}

Last function I hope is the MetaData Field (or better known as Termstore or taxonomy-field).
What I thought to be difficult ended very easy to do. 
You just need to fill in a DIV that has your fieldID followed by editableRegion.
put the values in that DIV and call a Sharepoint function 
with as parameter the master Parent of your TermStore field. 
And at least call the validation function to justify your filled in records.
  
function SPCC_Dup_fill_MetaDataFied(fieldID, referenceFieldID){
 var value = document.getElementById(referenceFieldID).innerHTML;
 if (value != '')
 {
  var resetDefault = document.getElementById(fieldID.substr(0,fieldID.length-1) + "1");
  resetDefault.value = "";
  var targetvalue = document.getElementById(fieldID);
  var mydiv = document.getElementById(fieldID);
  var editableRegion = document.getElementById(fieldID + "editableRegion");
  editableRegion.innerHTML = value;  
  var taxonomyParent = editableRegion.parentNode.parentNode.parentNode;  
  var taxonomyObject = new Microsoft.SharePoint.Taxonomy.ControlObject(taxonomyParent);
  taxonomyObject.validateAll();
 }
}

I hope I have handled all different types of fields. 
It has costed me some hours of development, but I hope the functions I have written 
may help you and others. 
I also prefered not to use the JQuery library, this for learning reasons. 
It makes you understand better how Sharepoints generates his fields 
and how there behaviour are.


Spread the words around and forward my blog so many others can save some time on finding solutions.