Friday, 1 July 2016

SharePoint 2013 - Upload a file with metadata using javascript CSOM

Uploading a file using javscript is possible using sharepoint 2013 API and HTML 5 supported javascript FileReader object but there are some cases where we need add metadata also along with file.

Here I'm showing how to upload file with Metadata/Fields in a Document Library.

function CreateFile()
{
    //ensure file selection
    if ( document.getElementById("fupUpload").files.length === 0) {
        alert('No file was selected');
        return;
    }
    else{
       // Ensure the HTML5 FileReader API is supported
   if (window.FileReader)
   {
       input = document.getElementById("fupUpload");
       
       if (input)
       {
           file = input.files[0];      
   fr = new FileReader();
           fr.onload = receivedBinary;
           fr.readAsDataURL(file);
       }
   }
   else
   {
       alert("The HTML5 FileSystem APIs are not fully supported in this browser.");
   }
}

}

// Callback function for onload event of FileReader
function receivedBinary()
{
    // Get the ClientContext for the app web
    var clientContext = new SP.ClientContext.get_current();
    
    //get lib from its name
    var parentList = clientContext.get_web().get_lists().getByTitle("Documents");

    //File Object
    var fileCreateInfo = new SP.FileCreationInformation();

    //set file properties
    fileCreateInfo.set_url(file.name);
    fileCreateInfo.set_overwrite(true);
    fileCreateInfo.set_content(new SP.Base64EncodedByteArray());

    // Read the binary contents of the base 64 data URL into a Uint8Array
    // Append the contents of this array to the SP.FileCreationInformation
    var arr = convertDataURIToBinary(this.result);
    
    for (var i = 0; i < arr.length; ++i)
    {
        fileCreateInfo.get_content().append(arr[i]);
    }

    // Upload the file to the root folder of the document library
    newFile = parentList.get_rootFolder().get_files().add(fileCreateInfo);
 
    //file MetaData
    var oListItem = newFile.get_listItemAllFields();
    
    //set item properties
    oListItem.set_item('Description0',"Some text");
    
    //Lookup Column
    var depValue = new SP.FieldLookupValue();
depValue.set_lookupId("1");
oListItem.set_item('Department', depValue);
    
    //update item
    oListItem.update();

    //load and execute query
    clientContext.load( newFile );
    clientContext.executeQueryAsync( onSuccess, onQueryFailed );
}

function onSuccess(){
alert('File added successfully');
location.reload();
}

function onQueryFailed(sender, args) {

    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

// Utility function to remove base64 URL prefix and store base64-encoded string in a Uint8Array
// Courtesy: https://gist.github.com/borismus/1032746
function convertDataURIToBinary(dataURI)
{
    var BASE64_MARKER = ';base64,';
    var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
    var base64 = dataURI.substring(base64Index);
    var raw = window.atob(base64);
    var rawLength = raw.length;
    var array = new Uint8Array(new ArrayBuffer(rawLength));

    for (i = 0; i < rawLength; i++)
    {
        array[i] = raw.charCodeAt(i);
    }
    return array;
}




Note: Browser should be HTML 5 supported.


Friday, 7 March 2014

Change Active Directory Password C#

Introduction: 

Any company which uses SharePoint , there is always a need for the User where they can change their AD password and change the password to something which they easily remember.

But changing the AD password is not that easy and there are certain restriction on this, as each Company has its own policies. Here, we will discuss how we can change AD password using .NET/C#.

Approach:

There are two sets of .NET classes that can be used to change AD password.
1.System.DirectoryServices
2. System.DirectoryServices.AccountManagement

I have found the first approach as the best and easy to use, although it is obsolete.

CODE:

        protected void Change_AD_Password(string serviceAccntName, string serviceAccntPass, string userName,string newPassWord )
        {
            try
            {
                //the LDAP server path, it can be an IP Address of the server or web-address anything
                string _path = "LDAP://192.128.0.1/DC=domain,DC=net";

                //We are using service account to authenticate to LDAP server and only service account will have the rights to change AD password
                System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry(_path, serviceAccntName, serviceAccntPass);

                System.DirectoryServices.DirectorySearcher mySearcher = new System.DirectoryServices.DirectorySearcher(entry);
                mySearcher.Filter = ("(objectClass=User)");
                SortOption option = new SortOption("Mail", System.DirectoryServices.SortDirection.Ascending);
                mySearcher.Sort = option;

                foreach (System.DirectoryServices.SearchResult resEnt in mySearcher.FindAll())
                {
                    System.DirectoryServices.DirectoryEntry de = resEnt.GetDirectoryEntry();

                    //the user whose password needs to be changes
                    if (de.Properties["sAMAccountName"].Value.ToString().ToLower() == userName.ToLower())
                    {
                        de.Invoke("SetPassword", new object[] {newPassWord });
                        
                        de.CommitChanges();
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
              throw ex;
            }

        }

Points to Remember:
1. Password must follow the password policy remember it (like no. of characters, how many times a user can change the password, new password should not be from the old password). Consult the admin and check the password policy.
2. There is an Admin settings which disables the user to change AD Password.(when we go to AD server open the user properties , we can see a check-box which says User can't change their password)
3. The application pool should be given permission to access LDAP server.
 

Wednesday, 4 September 2013

Sharepoint 2013 - Get SP List Title, ID, RelativeURL using CSOM

There may be some condition where we need to get SP List properties like ID, relative URL.

Following is the CSOM code to get SP List properties.

<script type="text/javascript">

var list;
var listRootFolder;
ExecuteOrDelayUntilScriptLoaded(init, "sp.js");

function init() {

    //load site
   var currentcontext = new SP.ClientContext.get_current();
   list = currentcontext.get_web().get_lists().getByTitle('LIST_NAME');
   listRootFolder= list.get_rootFolder();

    currentcontext.load(list, 'Title', 'Id');
    currentcontext.load(listRootFolder);
    currentcontext.executeQueryAsync(Function.createDelegate(this, result), Function.createDelegate(this, oncListQueryFailed));
}

function result() {
var listID = list.get_id();
    var listName= list.get_title();
var listURL = listRootFolder.get_serverRelativeUrl();
alert(listID + listName + listURL);
}

function oncListQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }

</script>


Check all the properties for SP List.

Sunday, 7 July 2013

SharePoint 2013 - Community Site


In SharePoint 2013, a Community Site is a new site template that provides a forum experience in the SharePoint environment. Use communities to categorize and cultivate discussions among a broad group of people across organizations in a company. 

1. How to create : As with any site template in SharePoint, Community template can be created in two ways:
1.1 Site Collection level
1.2. Site level

1.1 Site-Collection level (Community Portal template) : It has nothing but a home page which provides search - driven results( content search web-part)  to display any sites that use the Community Site template in the SharePoint farm.

You can edit the Community Portal Home page to add other Web Parts and customize the page. When deployed in the same environment as My Sites, users can access the Community Portal from the Sites link on their My Sites. 

You can have only one Community Portal per SharePoint farm.




This is a sample community portal template and it has a search driven web-part which is showing 2 community site, with each community site you will also see the respective numbers of discussions/members/replies . And if you click on the site you will be redirected to that community site.

1.2. Site level (Community Site Template) : The Community Site template is a collaboration site template that is based on the Team Site template, and contains the same base features such as lists and libraries, a wiki-page editing experience, and so on.

There are two ways to create a community site template:
1.2.1 Create a fresh new Community Site:
1.2.2 Activate Community feature in existing site:

1.2.1 Create a fresh new Community Site : Go to Site Contents >> Create new sub-site >> Select community template.

1.2.2 Activate Community feature in existing site : If you have a site which is created from other site template like Team Site, Project Site etc , in that site also we can have community site template features.

Here , the advantage is we can have features of two site template in one.

Go to Site Settings >> Site Features >> Activate feature Community Site Feature
           

1.2.3 Features of Community Site: Once we create a community site template using either of the above two steps , the following features we get here.

Home Page : This is the home page of a community site where we have community web-parts , we can customize the home page if we want.
Discussion web-part : The web-part at the center of the page is discussion web-part. Here, you can add a new discussion, like/reply to previous discussion. We have sub menus inside the web-part where we can view recent discussion,Whats Hot Discussion ,My Discussion etc . 

There are other web-parts also at right side of home page.


Categories : Category helps in organizing the discussion. We can segregate the discussion according to its category.

Each category have its name, description , picture associate to it..
Also you can keep track of the no. of discussion/replies.




Members : It gives the list of all the users who have joined the community or done some activity in community site.

The members page also shows the no. discussion started, replied, best replied and member Joining date.




Reputation Settings :   Reputation helps us to identify experts in community and also helps us to identify the contribution of each members.


Microsoft has defined inbuilt achievement points for each post, like/reply, best reply and then according to a member points a member is assigned level against his account.

We can customize the achievement / level settings and give our own set of points system.

Community Settings : Here we can define community established date, Auto approval of permission request and reporting of offensive content.

As with social sites not everybody like each other and can post abusive content against a member.
To prevent this, administrator can enable reporting of offensive content and see it on Forum.

So if a member sees a discussion/post being offensive he/she can report it as offensive and Administrator then have the option to permanently delete or reinstate the content.


Bottom-Line : SharePoint 2013 has nice social / micro-blogging features as compared to 2010 , which helps us to increase enterprise collaboration in any organization.
Also search is so powerful here and especially Content-by-search web-part which is used in Community Portal template home page.

Sunday, 9 June 2013

Sharepoint 2013 Search - Adding a hover panel to a content search webpart display template.

In sharepoint 2013 there is a new powerful webpart called Content By Search Webpart which is a substitute  of CQWP and also get rids of XSLT and uses search instead.

In Content Search WebPart there are in total 7 default display templates like Two Lines, Video,Picture on top 3 lines on bottom etc.

But all of the these template does not have a hover panel like we see in a search results. See below image





So to add hover panel to content search display templates we need to customize the template.

Open designer.
1.Go To >> All files >> _catalogs >> master page >> display templates >> content webparts >> your template ( in my case item_pictureontop.html)
2. right-click, and select Edit File in Advanced Mode:
3. Paste this code at the top as shown in the image below:

var id = ctx.ClientControl.get_nextUniqueId();
var itemId = id + Srch.U.Ids.item;
var hoverId = id + Srch.U.Ids.hover;
var hoverUrl = "~sitecollection/_catalogs/masterpage/Display Templates/Search/Item_Site_HoverPanel.js";
$setResultItem(itemId, ctx.CurrentItem);
ctx.currentItem_ShowHoverPanelCallback = Srch.U.getShowHoverPanelCallback(itemId, hoverId, hoverUrl);
ctx.currentItem_HideHoverPanelCallback = Srch.U.getHideHoverPanelCallback();

Notice I am using the out-of-the-box Item_Site_HoverPanel.js .As i want my results to display like a site item.You can use any OOTB hover js file or you create new one also.

4. Next, scroll down to the main <div> and change the id to use _#= $htmlEncode(itemId) =#_
Add the following code to that very same <div> tag:

onmouseover="_#= ctx.currentItem_ShowHoverPanelCallback =#_" onmouseout="_#= ctx.currentItem_HideHoverPanelCallback =#_"


5. Now add the following <div> after the first <div>:
<div id="_#= $htmlEncode(hoverId) =#_" class="ms-srch-hover-outerContainer"></div>
Inside this div the hover content will be rendered for each item.
Save the changes to the template.
This is how we can add a hover panel to content search webpart display templates.

Saturday, 8 June 2013

CSS + Center align HTML element content using CSS

In case we need to center align HTML element content using CSS.
Using below ways we can do it.

1. If element contains text, then we can do it using text-align property
text-align:center;

2. If element contains child HTML elements inside it.
position:relative;
float:left;
left:50%; 

Saturday, 1 June 2013

Sharepoint 2013 - Get all Site templates using Client object model

Code to get all site templates both inbuilt and custom site template ID using CSOM.


var templateCollection ;
function GetWebTemplates()
{

var context = new SP.ClientContext.get_current();
var web = context.get_web();

templateCollection = web.getAvailableWebTemplates(1033, false);

context.load(templateCollection);
context.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
}

function success() {

var Templates = "";
var siteTemplatesEnum = templateCollection.getEnumerator();

while(siteTemplatesEnum.moveNext())
{
var siteTemplate = siteTemplatesEnum.get_current();
Templates +=  siteTemplate.get_name() +   ',';
}

alert("Site Templates - " + ',' + Templates);
}

function failed(sender, args) {
alert("Failed");
}


While you can get all the inbuilt site template ID from below link

And custom site template would have a format like this.
{GUID}#TemplateName