Pages

Saturday, August 15, 2015

Uplaod Files to SharePoint Document Library with Meta Data using ECMA Script

Uplaod files to SharePoint document library using ECMA script (javascript client object model) :

UploadDocuments = function () {
    if (!window.FileReader) {
        alert("Browser does not support the HTML5 File APIs");
        return;
    }
    var call = getDocument();

    call.done(function (buffer, fileName) {
        var call2 = uploadDocument(buffer, fileName);
        call2.done(function (data, textStatus, jqXHR) {
            var call3 = getItem(data.d);
            call3.done(function (data, textStatus, jqXHR) {
                var item = data.d;
                var call4 = getCurrentUser();
                call4.done(function (data, textStatus, jqXHR) {
                    var userId = data.d.CurrentUser.Id;
                    var call5 = updateItemFields(item, userId);
                    call5.done(function (data, textStatus, jqXHR) {
                        var div = jQuery("#msg");
                        div.text("Item added");
                    });
                    call5.fail(failHandler);
                });
                call4.fail(failHandler);
            });
            call3.fail(failHandler);
        });
        call2.fail(failHandler);
    });
    call.fail(function (errorMessage) {
        alert(errorMessage);
    });

    function getDocument() {
        var def = new jQuery.Deferred();

        var element = document.getElementById("fileIdCard");
        var file = element.files[0];
        var parts = element.value.split("\\");
        var fileName = parts[parts.length - 1];

        var reader = new FileReader();
        reader.onload = function (e) {
            def.resolve(e.target.result, fileName);
        }
        reader.onerror = function (e) {
            def.reject(e.target.error);
        }
        reader.readAsArrayBuffer(file);
        return def.promise();
    }
    function uploadDocument(buffer, fileName) {
        var url = String.format("{0}/_api/Web/Lists/getByTitle('ID Card Attachments')/RootFolder/Files/Add(url='{1}', overwrite=true)",
            _spPageContextInfo.webAbsoluteUrl, fileName);
        //alert(url);

        var call = jQuery.ajax({
            url: url,
            type: "POST",
            data: buffer,
            processData: false,
            headers: {
                Accept: "application/json;odata=verbose",
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                "Content-Length": buffer.byteLength
            }
        });
        return call;
    }

    function getItem(file) {
        var call = jQuery.ajax({
            url: file.ListItemAllFields.__deferred.uri,
            type: "GET",
            dataType: "json",
            headers: {
                Accept: "application/json;odata=verbose"
            }
        });
        return call;
    }
    function GetItemTypeForListName(name) {
        return "SP.Data." + name.charAt(0).toUpperCase() + name.slice(1) + "ListItem";
    }
    function getCurrentUser() {
        var call = jQuery.ajax({
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/?$select=CurrentUser/Id&$expand=CurrentUser/Id",
            type: "GET",
            dataType: "json",
            headers: {
                Accept: "application/json;odata=verbose"
            }
        });
        return call;
    }

    function updateItemFields(item, userId) {
        var itemType = GetItemTypeForListName('ID Card Attachments');
        //alert(itemType);
        var now = new Date();
        var call = jQuery.ajax({
            url: _spPageContextInfo.webAbsoluteUrl +
                "/_api/Web/Lists/getByTitle('ID Card Attachments')/Items(" +
                item.Id + ")",
            type: "POST",
            data: JSON.stringify({
                '__metadata': { 'type': 'SP.Data.IdCardAttachmentsItem' },
                'Employee Type': '' + "Permanant"
            }),
            headers: {
                Accept: "application/json;odata=verbose",
                "Content-Type": "application/json;odata=verbose",
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                "IF-MATCH": item.__metadata.etag,
                "X-Http-Method": "MERGE"
            }
        });

        return call;
    }
}
failHandler = function (jqXHR, textStatus, errorThrown) {
    var response = JSON.parse(jqXHR.responseText);
    var message = response ? response.error.message.value : textStatus;
    alert("Call failed. Error: " + message);
}

onQuerySuccess = function () {
alert("Success.!");
}
onQueryFail = function (sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

Read URL Parameter Values in Javascript

JavaScript can access the URL string in browser.

function GetUrlValues() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

Thursday, August 13, 2015

Allow anonymous access to SharePoint application pages

This post has describe for you how to allow anonymous access to application page without forcing user to provide login credentials.

Setup the Project
1. Open Visual Studio 2013 and Create New Project in “Empty SharePoint Project” and Rename it to “MyFirstAnonymousPageProject”
2. Complete the steps as the usual way when creating a SharePoint project in visual studio 2013.

Add Custom Application Page
1. Right click on the project name “MyFirstAnonymousPageProject” > Add > SharePoint “Layouts” Mapped Folder. This will automatically create a folder with the name of your project under Layout folder.
2. Right click on the folder >Add > New Item > Application Page.
3. Name the page “AnonymousPage.aspx”

Setup anonymous access
1. Go to the code behind part of “AnonymousPage.aspx” page
2. You can see that by default, the page is inherited from “LayoutsPageBase”. Change the inheritance by replacing “LayoutsPageBase” to “UnsecuredLayoutsPageBase”.
Ex: – public partial class AnonymousPage : UnsecuredLayoutsPageBase
3. Next override “AllowAnonymousAccess ” method of the UnsecuredLayoutsPageBase, to allow anonymous access. Set “return true” of the “Get” property.
Ex: -
public partial class AnonymousAccess : UnsecuredLayoutsPageBase
{
    protected override bool AllowAnonymousAccess
    {
        get
        {
            return true;
        }
    }

}

Ready the solution
1. Deploy the solution by right clicking on your project name.
2. Browse the page by navigation to your solution URL once the deployment completed.

Saturday, July 18, 2015

“Sign in as Different User” option is missing in SharePoint 2013.


Note that you may have experienced that the “Sign in as a Different User” menu command is missing in SharePoint 2013.
This option is useful when testing applications, but it can lead to problems especially when opening documents, say in Microsoft Word. So, it may be for these reasons that the option has been removed in SharePoint 2013.
You can add the menu item back in by doing this edit on all servers in your SharePoint farm which is this option has missing.

1. Browse the location “C:\Program Files\Common Files\Microsoft Shared\Web Server
    Extensions\15\TEMPLATE\CONTROLTEMPLATES”. 
2. Open “Welcome.ascx” using Notepad (or any text editor).
3. Paste the below code in the “Welcome.ascx” before the existing element with the id of “ID_RequestAccess”

<SharePoint:MenuItemTemplate runat="server" ID="ID_LoginAsDifferentUser"
 Text="<%$Resources:wss,personalactions_loginasdifferentuser%>"
 Description="<%$Resources:wss,personalactions_loginasdifferentuserdescription%>"
 MenuGroupId="100"
 Sequence="100"

 UseShortId="true"/>

4. Save the File.
    Now the menu option should be displayed as below.

Friday, July 10, 2015

Custom Web Part not showing in Web Part Gallery in SharePoint 2013

This happens when deploying solutions from Visual studio to SharePoint.

Follow these steps to solve this issue:
  1. Open the solution using Visual Studio and retract the solution.
  2. Open your site using browser and Go Site Settings > Web Parts and then remove your Custom WebPart from WebPart Gallery.
  3. Open the solution using Visual Studio and deploy the solution.
  4. After you deployed the solution you need to activate the Feature in SP. (This feature adds Web Part to the Web Part gallery). This will done for you automatically by the deployment tools in Visual Studio will do this for you when you deploy the solution in it but you need to check and activate it manually if it has not done.
Note: If you need your Custom WebPart to be save in custom category, you need to edit an attribute in WebPart Element file.

Open elements.xml using Visual Studio and modify it as following:

<Property Name="Group" Value="[Custom_Group_Name]" />

Sunday, June 21, 2015

Get Current Loggin User in SharePoint Programmatically

Get current user using SharePoint SPControl class.

private SPUser GetLoginUser()
{
    SPUser currentUser = null;
    try
    {
        currentUser = SPControl.GetContextWeb(Context).CurrentUser;
    }
    catch (Exception)
    {
        throw;
    }
    return currentUser;
}

Saturday, June 13, 2015

Programmatically Send Mails using SPUtility SharePoint

public bool SendEmail(string To, string cc, string subject, string msg)
{
            bool status = true;

            string sendTo = To;
            string CCTo = cc;

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite oSpSite = new SPSite(SPContext.Current.Web.Url))
                    {
                        oSpSite.AllowUnsafeUpdates = true;
                        using (SPWeb oSPWeb = oSpSite.OpenWeb())
                        {
                            oSPWeb.AllowUnsafeUpdates = true;
                            if (SPUtility.IsEmailServerSet(oSPWeb))
                            {
                                StringDictionary headers = new StringDictionary();

                                headers.Add("to", sendTo);
                                headers.Add("cc", CCTo);
                                headers.Add("subject", subject);
                                headers.Add("fAppendHtmlTag", "True");

                                System.Text.StringBuilder strMessage = new System.Text.StringBuilder();

                                strMessage.Append(msg);
                                status = SPUtility.SendEmail(oSPWeb, headers, strMessage.ToString());
                            }
                            oSPWeb.AllowUnsafeUpdates = false;
                        }
                        oSpSite.AllowUnsafeUpdates = false;
                    }
                });
                return status;
            }
            catch (Exception ex)
            {
                this.Print("SendBulkEmail", ex.Message);
                return false;
            }
}