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

zondag 11 januari 2015

Set a PeoplePicker Field without a GUID !


A new function that lot's of people may help if they want to set a value of a People Picker field. 
There are examples to find on the internet how you may do it by using the GUID of the field. This because the People Picker field is made of different html parts. You can't set a value in the field directly by calling his Title property like most of the other SharePoint Fields.
But next function by calling the label of the field (the text you have giving on the screen), and a value (Full name of a person or the userid of a person)


Enjoy the new function !! 

Remark, the function only works for setting one value to the people picker field. 
test
// call the new function Set PeoplePicker.
//
SetPeoplePicker (title, userid);

function SetPeoplePicker(My_Title, userid)
{
        try{
                 var ppID = $($('nobr:contains("' + My_Title + '")').closest("td").next("td").find('div')[0]).attr('id');
                 var ppID_userfield = ppID.substring(0,ppID.indexOf("_upLevelDiv"));
                 var a_ppID = ppID_userfield.split('_');
                 var a_ppID_Length = a_ppID.length;
                 var ppID_userfield2 = a_ppID[0] + '$' +  a_ppID[1] + '$' +  a_ppID[2] ;
                 for ( i = 3; i < a_ppID_Length - 4; i++)
                 {
                       ppID_userfield2 = ppID_userfield2 + '_' + a_ppID[i];
                 }
                 ppID_userfield2 = ppID_userfield2 + '$' +   a_ppID[a_ppID_Length - 4] + '$' +   a_ppID[a_ppID_Length - 3] + '$' +   a_ppID[a_ppID_Length - 2] + '$' +   a_ppID[a_ppID_Length - 1] ;
        
                $('#' + ppID ).text(userid);
                //recognize the people picker driver name
                if(!ValidatePickerControl(ppID_userfield )){
                        ShowValidationError();
                        return false;
                }
                var arg=getUplevel(ppID_userfield );
                var ctx = ppID_userfield ;
                EntityEditorSetWaitCursor(ctx);
                WebForm_DoCallback(ppID_userfield2 ,arg,EntityEditorHandleCheckNameResult,ctx,EntityEditorHandleCheckNameError,true);
        }catch(err){
                $('#' + ppID).text("");
        }
}


zaterdag 13 september 2014

Create a Sharepoint Group and add a PermissionLevel to that new Sharepoint Group


In a previous blogpost you saw how to break the inheritance of a site. Well by completing the request
of my customer, I wrote some code for also creating a own Sharepoint Group and give it 
a specific permission level. 

Enjoy my next custom code for creating a group and adding a permission level to it. 

  

      
 

 

function addGroup( )
{
   var groupsname = "FILL IN HERE THE NAME OF YOUR SHAREPOINT GROUP";
   var groupsOwner = "DOMAIN/USERID";
   var groupsDesc = "FILL IN HERE THE DESCRIPTION FOR YOUR SHAREPOINT GROUP"; 
   var soapEnv ="";
   soapEnv =            '';
   soapEnv = soapEnv  + '';
   soapEnv = soapEnv  + '';
   soapEnv = soapEnv  + '';
   soapEnv = soapEnv  + ''+ groupsname + '';
   soapEnv = soapEnv  + '' + groupsOwner + '';
   soapEnv = soapEnv  + 'user';
   soapEnv = soapEnv  + '' + groupsOwner + '';
   soapEnv = soapEnv  + '' + groupsDesc + '';
   soapEnv = soapEnv  + '  ';
   soapEnv = soapEnv  + '';
 
  $.ajax({
        url: "URL OF YOUR SITE BY STARTING HTTP /_vti_bin/UserGroup.asmx",
        type: "POST",
 async : false,
        dataType: "xml",
        beforeSend: function(xhr) {
           xhr.setRequestHeader("SOAPAction",
               "http://schemas.microsoft.com/sharepoint/soap/directory/AddGroup");
           },
        data: soapEnv,
        error: processMyError,
        complete: processResultAddGroep,
        contentType: "text/xml; charset=\"utf-8\""
  }); 

}


function processMyError(xhr, error)
{
  alert(xhr);
  alert("dd "+error);
}


function processResultAddGroep (xData, status)
{ 
// adding the Permissionlevel to your group. If you don't do this, the Sharepoint Group will be created, 
// but will not be visible in the list of Groups. 
  callAddRole();
}


function callAddRole ()
{
  var soapEnv ="";
  var groupsName = "FILL IN HERE THE NAME OF YOUR SHAREPOINT GROUP";
  var roleName = "FILL IN HERE THE NAME OF THE PERMISSION LEVEL, EX Contribute";

  soapEnv =            '';
  soapEnv = soapEnv  + '';
  soapEnv = soapEnv  + '';
  soapEnv = soapEnv  + '';
  soapEnv = soapEnv  + '' + groupsName  + '';
  soapEnv = soapEnv  + '' + roleName +  '';
  soapEnv = soapEnv  + '  ';
  soapEnv = soapEnv  + '';
  $.ajax({
         url: "FILL IN HERE THE URL OF YOUR SITE /_vti_bin/UserGroup.asmx",
         type: "POST",
         async: false, 
         dataType: "xml",
         beforeSend: function(xhr) {
                          xhr.setRequestHeader("SOAPAction",
                          "http://schemas.microsoft.com/sharepoint/soap/directory/AddGroupToRole");
                     },
         data: soapEnv,
         error: processMyError,
         complete: processResultAddRole,
         contentType: "text/xml; charset=\"utf-8\""
  });

}

function processResultAddRole(xData, status)
{ 
  alert("status: " + status);
  $('#error').val(status);
  alert("response: "+ xData.responseText);
  $('#errormessage').val(xData.responseText);

} 

woensdag 10 september 2014

Break site permission inheritance in code


Break site permission inheritance in code

Sometimes your want to allow your customer to create a site or a subsite with a simple click. 
And you want that same click to break the permission inheritance of its parent site.

Well, it has taken me some research but I have found a solution to do exactly that in code. 
Just put this code on a Sharepoint page. 
Or include the Sharepoint client object model into your custom page.

Enjoy the power of scripting ! 

  

      
 
function BreakRole()
{
   var copyRoleAssignments = true;
   var clearSubscopes = true;
   var clientContext = new SP.ClientContext.get_current();
   // or if your want to break another sites inheritance
   // var clientContext = new SP.ClientContext("/sites/YourSitecollection/yourSite");
   var oWebsite = clientContext.get_web();
   var $v_0 = new SP.ClientActionInvokeMethod(oWebsite, 'BreakRoleInheritance', [ copyRoleAssignments, clearSubscopes ]);
   clientContext.addQuery($v_0);
   clientContext.executeQueryAsync();
}
 

donderdag 28 november 2013

Set Focus on a sharepoint Field in scripting

To setting the focus of an input field in jquery, it was simple. But when you have a peoplepicker field
you think that you also are dealing with an input field, but less is true.
A sharepoint People Picker field isn't that easy made.
But we won't be a developer, if we could make a function that put's the focus also 
on a people picker field.
Below you find my function. It can be extended with other fields if necessary. 
You call it not by using the GUID, but by using the display name. Which is more flexible and easier, 
because you don't need to search for the GUID in the source code. 
 
You can call it by the next function. You only need the Field Display Name and the Type of field. 
The type can be at this moment, an Input field, a People Picker, or a  Select field. 

This you can use by example when you want to check values in the PreSaveAction function and 
you want to put the focus on a field that has to be changed.  
 
Have fun with it... and if you need an extention, don't hesitate to ask... 

 
function FirstfocusExtended(veldnaam, type)
{
                switch (type.toLowerCase())
                {
                               case "input" :
                                               $(":input[title='" + veldnaam + "']").focus();
                                               break;
                               case "peoplepicker" :
                                               $("nobr:contains('" + veldnaam + "')").closest("td").next("td").find("div").focus();
                                               break;
                               case "select" :
                                               $(":select[title='" + veldnaam + "']").focus();
                                               break;
                               default :
                                               break;
                }
}

zaterdag 12 oktober 2013

Check if a Multi Selectable Sharepoint Choice Field value is Checked.


I'm starting to write my own sharepoint helperclass with functions 
that can be called without knowing the ID's of the Sharepoint Fields, 
but by using the field Display Names. 

This function is to know if a certain value of a multi selectable 
choice field is checked or not.


// call the function
// CheckChoiceFieldValue ("DISPLAYNAME", 1) check of first value is checked
// CheckChoiceFieldValue ("DISPLAYNAME", 2) check of second value is checked
  
function CheckChoiceFieldValue(titel, index)
{
 var TD = $('nobr:contains("'+ titel + '")').closest("td").next("td").find('input');
    var bTD = false;
    if (index <= TD.length + 1)
    {
  return TD[index-1].checked;
 }
    return false;
}
 

vrijdag 11 oktober 2013

Disable a Hyperlink field without knowing the ID of your Sharepoint Field


I'm starting to write my own sharepoint helperclass with functions 
that can be called without knowing the ID's of the Sharepoint Fields, 
but by using the field Display Names. 

This function is to Disable or Enable a Sharepoint Hyperlink Field.


// call the function
// DisableHttpLink ("DISPLAYNAME", True) to disable the field
// DisableHttpLink ("DISPLAYNAME", False) to enable the field
  
function DisableHttpLink(titel, b_disable)
{
 var TD = $('nobr:contains("'+ titel + '")').closest("td").next("td").find('input');
    for(var i = 0; i < TD.length;i++)
    {
  $("#" + TD[i].id).attr("disabled",b_disable);
    }
}
 

donderdag 10 oktober 2013

Disable a Choice field without knowing the ID of your Sharepoint Field


I'm starting to write my own sharepoint helperclass with functions 
that can be called without knowing the ID's of the Sharepoint Fields, 
but by using the field Display Names. 

This function is to Disable or Enable a Sharepoint Choice Field.


// call the function
// DisableAChoiceField ("DISPLAYNAME", "input|select", True) to disable the field
// DisableAChoiceField ("DISPLAYNAME", "input|select", False) to enable the field
  
function DisableAChoiceField(titel, type, b_disable)
{
    if (type == "input")
  var TD = $('nobr:contains("'+ titel + '")').closest("td").next("td").find('input');
    if (type == "select")
  var TD = $('nobr:contains("'+ titel + '")').closest("td").next("td").find('select');
    for(var i = 0; i < TD.length;i++)
    {
  $("#" + TD[i].id).attr("disabled",b_disable);
    }
}
 

woensdag 9 oktober 2013

Disable a PeoplePicker Field without knowing the ID of your Sharepoint Field


I'm starting to write my own sharepoint helperclass with functions 
that can be called without knowing the ID's of the Sharepoint Fields, 
but by using the field Display Names. 

This function is to Disable or Enable a Sharepoint PeoplePicker Field.


// call the function
// DisablePeoplePicker ("DISPLAYNAME", True) to disable the field
// DisablePeoplePicker ("DISPLAYNAME", False) to enable the field
  
function DisablePeoplePicker( titel, b_disable)
{
    $('nobr:contains("'+titel+'")').closest("td").next("td").find("div").attr("contentEditable",false);
    if (b_disable)
    {
        $('nobr:contains("'+titel+'")').closest("td").next("td").find("div").css("backgroundColor","silver");
        $('nobr:contains("'+titel+'")').closest("td").next("td").find("img").hide();
    }
    else
    {
        $('nobr:contains("'+titel+'")').closest("td").next("td").find("div").css("backgroundColor","white");
        $('nobr:contains("'+titel+'")').closest("td").next("td").find("img").show();
    }
}
 

dinsdag 27 november 2012

LCID Dec values for the XSLT FormatDate function

Use the LCID Dec values for the FormatDate function.
ddwrt:FormatDate(string(@Date), 1033, 1)
Language - Country/RegionLCID HexLCID Dec
Afrikaans - South Africa04361078
Albanian - Albania041c1052
Alsatian04841156
Amharic - Ethiopia045e1118
Arabic - Saudi Arabia04011025
Arabic - Algeria14015121
Arabic - Bahrain3c0115361
Arabic - Egypt0c013073
Arabic - Iraq08012049
Arabic - Jordan2c0111265
Arabic - Kuwait340113313
Arabic - Lebanon300112289
Arabic - Libya10014097
Arabic - Morocco18016145
Arabic - Oman20018193
Arabic - Qatar400116385
Arabic - Syria280110241
Arabic - Tunisia1c017169
Arabic - U.A.E.380114337
Arabic - Yemen24019217
Armenian - Armenia042b1067
Assamese044d1101
Azeri (Cyrillic)082c2092
Azeri (Latin)042c1068
Bashkir046d1133
Basque042d1069
Belarusian04231059
Bengali (India)04451093
Bengali (Bangladesh)08452117
Bosnian (Bosnia/Herzegovina)141A5146
Breton047e1150
Bulgarian04021026
Burmese04551109
Catalan04031027
Cherokee - United States045c1116
Chinese - People's Republic of China08042052
Chinese - Singapore10044100
Chinese - Taiwan04041028
Chinese - Hong Kong SAR0c043076
Chinese - Macao SAR14045124
Corsican04831155
Croatian041a1050
Croatian (Bosnia/Herzegovina)101a4122
Czech04051029
Danish04061030
Dari048c1164
Divehi04651125
Dutch - Netherlands04131043
Dutch - Belgium08132067
Edo04661126
English - United States04091033
English - United Kingdom08092057
English - Australia0c093081
English - Belize280910249
English - Canada10094105
English - Caribbean24099225
English - Hong Kong SAR3c0915369
English - India400916393
English - Indonesia380914345
English - Ireland18096153
English - Jamaica20098201
English - Malaysia440917417
English - New Zealand14095129
English - Philippines340913321
English - Singapore480918441
English - South Africa1c097177
English - Trinidad2c0911273
English - Zimbabwe300912297
Estonian04251061
Faroese04381080
Farsi04291065
Filipino04641124
Finnish040b1035
French - France040c1036
French - Belgium080c2060
French - Cameroon2c0c11276
French - Canada0c0c3084
French - Democratic Rep. of Congo240c9228
French - Cote d'Ivoire300c12300
French - Haiti3c0c15372
French - Luxembourg140c5132
French - Mali340c13324
French - Monaco180c6156
French - Morocco380c14348
French - North Africae40c58380
French - Reunion200c8204
French - Senegal280c10252
French - Switzerland100c4108
French - West Indies1c0c7180
Frisian - Netherlands04621122
Fulfulde - Nigeria04671127
FYRO Macedonian042f1071
Galician04561110
Georgian04371079
German - Germany04071031
German - Austria0c073079
German - Liechtenstein14075127
German - Luxembourg10074103
German - Switzerland08072055
Greek04081032
Greenlandic046f1135
Guarani - Paraguay04741140
Gujarati04471095
Hausa - Nigeria04681128
Hawaiian - United States04751141
Hebrew040d1037
Hindi04391081
Hungarian040e1038
Ibibio - Nigeria04691129
Icelandic040f1039
Igbo - Nigeria04701136
Indonesian04211057
Inuktitut045d1117
Irish083c2108
Italian - Italy04101040
Italian - Switzerland08102064
Japanese04111041
K'iche04861158
Kannada044b1099
Kanuri - Nigeria04711137
Kashmiri08602144
Kashmiri (Arabic)04601120
Kazakh043f1087
Khmer04531107
Kinyarwanda04871159
Konkani04571111
Korean04121042
Kyrgyz (Cyrillic)04401088
Lao04541108
Latin04761142
Latvian04261062
Lithuanian04271063
Luxembourgish046e1134
Malay - Malaysia043e1086
Malay - Brunei Darussalam083e2110
Malayalam044c1100
Maltese043a1082
Manipuri04581112
Maori - New Zealand04811153
Mapudungun04711146
Marathi044e1102
Mohawk047c1148
Mongolian (Cyrillic)04501104
Mongolian (Mongolian)08502128
Nepali04611121
Nepali - India08612145
Norwegian (Bokmål)04141044
Norwegian (Nynorsk)08142068
Occitan04821154
Oriya04481096
Oromo04721138
Papiamentu04791145
Pashto04631123
Polish04151045
Portuguese - Brazil04161046
Portuguese - Portugal08162070
Punjabi04461094
Punjabi (Pakistan)08462118
Quecha - Bolivia046B1131
Quecha - Ecuador086B2155
Quecha - Peru0C6B3179
Rhaeto-Romanic04171047
Romanian04181048
Romanian - Moldava08182072
Russian04191049
Russian - Moldava08192073
Sami (Lappish)043b1083
Sanskrit044f1103
Scottish Gaelic043c1084
Sepedi046c1132
Serbian (Cyrillic)0c1a3098
Serbian (Latin)081a2074
Sindhi - India04591113
Sindhi - Pakistan08592137
Sinhalese - Sri Lanka045b1115
Slovak041b1051
Slovenian04241060
Somali04771143
Sorbian042e1070
Spanish - Spain (Modern Sort)0c0a3082
Spanish - Spain (Traditional Sort)040a1034
Spanish - Argentina2c0a11274
Spanish - Bolivia400a16394
Spanish - Chile340a13322
Spanish - Colombia240a9226
Spanish - Costa Rica140a5130
Spanish - Dominican Republic1c0a7178
Spanish - Ecuador300a12298
Spanish - El Salvador440a17418
Spanish - Guatemala100a4106
Spanish - Honduras480a18442
Spanish - Latin America580a22538
Spanish - Mexico080a2058
Spanish - Nicaragua4c0a19466
Spanish - Panama180a6154
Spanish - Paraguay3c0a15370
Spanish - Peru280a10250
Spanish - Puerto Rico500a20490
Spanish - United States540a21514
Spanish - Uruguay380a14346
Spanish - Venezuela200a8202
Sutu04301072
Swahili04411089
Swedish041d1053
Swedish - Finland081d2077
Syriac045a1114
Tajik04281064
Tamazight (Arabic)045f1119
Tamazight (Latin)085f2143
Tamil04491097
Tatar04441092
Telugu044a1098
Thai041e1054
Tibetan - Bhutan08512129
Tibetan - People's Republic of China04511105
Tigrigna - Eritrea08732163
Tigrigna - Ethiopia04731139
Tsonga04311073
Tswana04321074
Turkish041f1055
Turkmen04421090
Uighur - China04801152
Ukrainian04221058
Urdu04201056
Urdu - India08202080
Uzbek (Cyrillic)08432115
Uzbek (Latin)04431091
Venda04331075
Vietnamese042a1066
Welsh04521106
Wolof04881160
Xhosa04341076
Yakut04851157
Yi04781144
Yiddish043d1085
Yoruba046a1130
Zulu04351077
HID (Human Interface Device)04ff1279
List copied from http://msdn.microsoft.com/en-us/goglobal/bb964664

donderdag 11 oktober 2012

Check if Sharepoint Richt Text Editor Field is empty or not (works in IE, Firefox and Chrome)


Found out this week that the code for checking the content of a multi-line rich text field was 
not working for other than IE-browsers.
So after some debugging in Chrome I found a solution that works in Chrome and in Firefox.
I hope that it's also working in other browsers... but I don't have them to my position at work.
Have fun with my new code... 



 firefox/chrome bugfix...
    var scomments = "";
    if ($.browser.msie) 
 {     
  // IE browser, check on language needed because Sharepoint and IE Translates the IFrame name in different languages.   
  if (_spPageContextInfo.currentLanguage == 1036) 
  {
            var systemDescriptionRTE = $("textarea[title='Comments']").closest("span").find("iframe[Title='Éditeur de texte enrichi']").contents().find("body");
            scomments = $(systemDescriptionRTE).text();
        }
        else
        {
            if (_spPageContextInfo.currentLanguage == 1043) 
   {
                var systemDescriptionRTE = $("textarea[title='Comments']").closest("span").find("iframe[Title='RTF-editor']").contents().find("body");
                scomments = $(systemDescriptionRTE).text();
            }
            else
            {
                var systemDescriptionRTE = $("textarea[title='Comments']").closest("span").find("iframe[Title='Rich Text Editor']").contents().find("body");
                scomments = $(systemDescriptionRTE).text();
            }
        }
 }
 else
 {
 // if other browser
        var systemDescriptionRTETextArea = $("textarea[Title='Comments']"); 
        scomments = $(systemDescriptionRTETextArea).val(); 
 }
  

Now you can check with the 'scomments' variable is it is empty or containing some values.

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();
        }
 

 

zondag 24 juni 2012

Value of approvalStatus changes in function of MUI Language


Believe it or not, but I was supprised that technical fields from Sharepoint are translated when
you change your MUI Language.

I discovered it by accident when a user called me, that my draft image was always visible
even when the document was approved. 
So after some debugging I saw that the approvalStatus field of sharepoint was translated in the
language of the MUI. 

In our configuration, we have English, Dutch and French. So the approvalStatus field is getting
in English the value "approved", in Dutch : "goedgekeurd" and in French : "approuvé" !

If you do equal stuff, I have coded next script in a Content Editor Webpart for my users : 
 

 //show draft image if topic is not approved
            if (document.getElementById('approvalStatus').innerHTML.toLowerCase() == 'approved' 
      || document.getElementById('approvalStatus').innerHTML.toLowerCase() == 'approuvé' 
      || document.getElementById('approvalStatus').innerHTML.toLowerCase() == 'goedgekeurd')
            {
                document.body.background = '';
            }
            else
   {
    document.body.style.backgroundPosition="center";
    document.body.style.backgroundImage="url(../../SiteCollectionImages/watermark-draft.png)";
    document.body.style.backgroundRepeat="no-repeat";
            }

 

Get User Roles, Security groups on Client site


Last week I figgered out how to know in which security group the logged-on user has access to 
in order to show or hide some fields or ribbon items. 
For example to prevent to show All Site Contents in the action menu.

Below some code that does the work for you... have fun with it ;)
 

<script src="/scripts/jquery-1.7.min.js" type="text/javascript"></script>
<script src="/scripts/jquery.SPServices-0.7.0.js" type="text/javascript"></script>
<script type="text/javascript">

 getCurrentUserRole();
 function getCurrentUserRole() {
  $().SPServices({
   operation: "GetGroupCollectionFromUser",
   userLoginName: $().SPServices.SPGetCurrentUser(),
   async: false,
   completefunc: function (xData, Status) {

    if( Status == "success") {
     //alert(xData.responseText);
     $(xData.responseXML).find("Group").each(function () {
      if ($(this).attr("Name") == "DevSite Owners")
      {
       alert("write access");
      }
      else
      {
       // wrong access hide some stuff... for example the Site Action link.
       $("#siteactiontd").hide();
       // hide the global navigation folder
       $("#GlobalBreadCrumbNavPopout-anchor").hide();
      }//alert($(this).attr("Name"));
     });
    }
   }
  });
 }
</script>
 

donderdag 14 juni 2012

SharePointblog.co.uk is doing a 100 days/100posts on Business Analysis


Yust saw next big news in Balestra's Blog :

The people over at SharePointblog.co.uk are going to post 100 blogposts in the next 100 days 
about Business analysis to improve SharePoint requirements gathering. 

Some will be quick tips, other big posts.

They also have a twitter hashtag: #bamasterclass .

Don't miss it!!

Check if Sharepoint Richt Text Editor Field is empty or not


Today I had some problems to do a check wether a Rich Text Editor field is filled in or not. 
I found out that sharepoint also translates the Title of the Rich Text Editor field. 
That was really unexpected because the iframe is dynamically constructed in the browser. 
So you would expect that changing the MUI language would translate the 
Title propertie of the RTE field.
So for Frensh, Dutch and English MUI languages you could do the check like below.


var scomments = "";
if (_spPageContextInfo.currentLanguage == 1036) {
    var systemDescriptionRTE = $("textarea[Title='Comments']").closest("span").find("iframe[Title='Éditeur de texte enrichi']").contents().find("body");
    scomments = $(systemDescriptionRTE).text();
}
else
{
 if (_spPageContextInfo.currentLanguage == 1043) {
        var systemDescriptionRTE = $("textarea[Title='Comments']").closest("span").find("iframe[Title='RTF-editor']").contents().find("body");
        scomments = $(systemDescriptionRTE).text();
    }
    else
    {
        var systemDescriptionRTE = $("textarea[Title='Comments']").closest("span").find("iframe[Title='Rich Text Editor']").contents().find("body");
        scomments = $(systemDescriptionRTE).text();
    }
}

 
 
Bugfix available at this new blogpost :
 http://andydevelopments.blogspot.com/2012/10/check-if-sharepoint-richt-text-editor.html 

maandag 9 april 2012

Update or Insert Sharepoint ListItems in a List Library


Looking for a way to update a Sharepoint ListItem by using the Lists.asmx webservice...
For doing this you need to create your function to create your Xml Layout
and afterwards call the function below UpdateSPList.
 

 XmlDocument xmlDoc = new XmlDocument();
 XmlElement elBatch = xmlDoc.CreateElement("Batch");
 elBatch.SetAttribute("OnError", "Continue");
 // this because if one of the methods gives an error it will continue with the next method
 elBatch.SetAttribute("ViewName", Sharepoint_ViewId);
 elBatch.InnerXml = strBatch;
 
 returncode = UpdateSPList( sSiteUrl,  sSiteList,  elBatch);


 
strBatch containing for example:
        
<Method ID='0' Cmd='Update'>
    <Field Name='ID'> SharepointListItem.ows_ID </Field>
</Method>
<Method ID='1' Cmd='Update'>
    <Field Name='ID'>OtherSharepointListItem.ows_ID </Field>
</Method>
<Method ID='0' Cmd='New'>
            <Field Name='ID'>New</Field>
            <Field Name='Title'>YOUR TEXT HERE</Field>
</Method>
<Method ID='1' Cmd='New'>
            <Field Name='ID'>New</Field>
            <Field Name='Title'>YOUR TEXT HERE</Field>

 



Remark: The next Chars must be translated in the text values for your Fieldtag:
    "&" ==> "&"
    "<" ==> "<"
    ">" ==> ">"
    "\"" ==> """
    "'" ==> "'"

Below you find my Function that I have created that actualy does 
the update or insert into your List.
It requires three parameters : 
- the Site Url you are working on
- the List name on which you want to add or update one or more items
- the XML that contains the Batch Element

You will see that the function also uses the next global parameters
- sTechnicalUser
- sTechnicalPw
- sDomain
- bDefaultLogon (if true you will connect to the webservice with the 
user that is executing the program, otherwise use the technical user with it's
password and domain.  
This is done for giving the possibility to let shedule the program. 
         
 private Boolean UpdateSPList(string sSiteUrl, string sSiteList, XmlElement elBatch)
        {
            Boolean retcode = true;

            REFERANCENAME.Lists list = new REFERANCENAME.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);
            }
            logThis("Start updateSPList " + sSiteUrl + " " + sSiteList + " ...");
            try
            {
                XmlNode ndReturn = list.UpdateListItems(sSiteList, elBatch);
                logThis(sSpaces + "return " + ndReturn.OuterXml);
                // 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
                        this.logThis("Update operation failed for " + sSiteList + ": " + sError + ".");
                        // If you want to trip the Try…Catch, throw and exception of whatever type suits you
                        iFailedUpdatedRecords++;
                    }
                    else
                    {
                        iUpdatedRecords++;
                    }
                }
           }
            catch (Exception e)
            {
                logThis(sSpaces + "Error UpdateSPList ", e);
                retcode = false;
            }
            finally
            {
                list.Dispose(); // important!!!! always dispose your sharepoint objects !!!!!
                logThis("End updateSPList " + sSiteUrl + " " + sSiteList);
            }
            return retcode;
        }
 


maandag 2 april 2012

View SharePoint Attachments in Display Pages


When creating a Custom Page of the Type Display, Sharepoint does not include
the attachments in your page.

To display attachments that dissapear in a custom display form,
simply add a new row in the custom display form 
and add the following line within that row in the code view.


<SharePoint:AttachmentsField ControlMode="Display" FieldName="Attachments" runat="server" Visible="true"/>
 

Enyoi your attachments in your Display ASPX pages ;-)

vrijdag 30 maart 2012

Customizing the Search Results Page (XSLT) – Add highlighting


Thanks to Tobias Zimmergren I found out how to add Word Highlighting your Search Result Page.

 
Customizing the Search result page xslt by adding Highlighting

What you have to do is to adapt the XSL code in the XSLT Editor of the Core Search Result 
webpart and locate the the following section (It already exist):


<xsl:template name="Hithightlighting">
 

And since this template exists from the beginning, all you really have to do is to customize 
the style attribute and add a color property of the <b> tag 
(I replaced it with a <strong> tag instead, for sake of standards)

Then you can simply specify the styles for each highlighted word like following:
 <xsl:template match="c0">
 <strong style="color:blue;"><xsl:value-of select="."/></strong>
 </xsl:template>
 

It’s simple as that. I hope this helped some of you to get started 
on some basic Search Core Results XSLT customizations. 


For customizing the result itself you can take also a look 
at the blog of customize the search result using Sharepoint Designer.

dinsdag 27 maart 2012

Full screen width SharePoint Rich Text Editor


It can be frustrating in SharePoint when the "Rich Text Editor" on the edit page 
of Wiki's, Blogs, Edit pages is set to fixed column width by default Sharepoint.  

We get frequently the question to enlarge the width of the editor. This because
it's easier to fill in text in a fullscreen-width editor!
 
Here's the CSS to make it happen (warning, this syntax applies to ALL rich text editors!). 

The first does all normal forms and wikis:

<style> 
#onetIDListForm, #onetIDListForm .ms-formbody, #onetIDListForm iframe[title="Rich Text Editor"]{
 width:100% !important;
}
</style> 
 
And this does the same for Blogs!
<style> 
.ms-formbody span span div iframe, .ms-formbody span span table.ms-long{
 width:100%; text-align:left;
}

</style>
 


You just to need to put the code in a Content Editor Webpart on your page.

I hope that your customers enyoi the full width Rich Text Editors like ours...