Tuesday, 21 July 2015

How to prevent duplicate files to be uploaded in to Document libray in sharepoint

scenario :
I want to  prevent to add duplicate files to document library in sharepoint . when we are uploading document it will verify the all Doclib Files then if file name is exists it will show alertbox.

Then I have written some sample code for this issue:
/// <summary>
       /// An item is being added.
       /// </summary>
       public override void ItemAdding(SPItemEventProperties properties)
       {
           string fileUrl = properties.BeforeUrl;
           string fileName = fileUrl.Substring(fileUrl.LastIndexOf('/') + 1);
           if (IsExisted(properties.List, fileName))
           {
                 properties.Cancel = true;
               properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
               properties.RedirectUrl = "/_Layouts/MyEventError.aspx";


           }
       }

       /// <summary>
       /// An item is being updated.
       /// </summary>
       public override void ItemUpdating(SPItemEventProperties properties)
       {
           string fileUrl = properties.BeforeUrl;
           string fileName = fileUrl.Substring(fileUrl.LastIndexOf('/') + 1);
           if (IsExisted(properties.List, fileName))
           {
               properties.Cancel = true;
               properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
               properties.RedirectUrl = "/_Layouts/MyEventError.aspx";
           }
       }

       private Boolean IsExisted(SPList list, string fileName)
       {
           bool isExisted = false;
           SPQuery query = new SPQuery();
           query.Query = string.Format(
               "<Where><Eq><FieldRef Name='FileLeafRef'></FieldRef><Value Type='Text'>{0}</Value></Eq></Where>",
               fileName);
           query.ViewAttributes = "Scope=\"Recursive\"";
           SPListItemCollection itemColl = list.GetItems(query);
           if (itemColl.Count > 0)
           {
               isExisted = true;
           }
           return isExisted;

       }

Friday, 17 July 2015

How do I know my worker process id

How to Attach Particular worker Process.


STEPS:-

1 :- Deploy  (Code base) SharePoint Solution 

2. Start -> Run -> Enter inetmgr (Enter)
3. Click on Server (Left Hand Site Below Start Page)
4. After That Filter ( Middle ) -Enter Worker Process .
5. Find Out Your Deployed Site Url and Process Id .
6. Go to Visual Studio And Attach That Process Id.


It Will Attach Only Required Worker Process .  :)


you Can Use Also command prompt commands :-

Step 1: open cmd prompt
Step 2: cd inetsrv
Step 3: appcmd list wps



Monday, 13 July 2015

CRUD operations in SharePoint hosted apps using Javascript Object Model (JSOM)

Code in App.js

var context = SP.ClientContext.get_current();
var hostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
var appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
var hostcontext = new SP.AppContextSite(context, hostUrl);
var web = hostcontext.get_web();
var lists = web.get_lists();


$(document).ready(function () {
    var scriptbase = hostUrl + "/_layouts/15/";
    $.getScript(scriptbase + 'SP.Runtime.js',
    function () {
        $.getScript(scriptbase + 'SP.js',
       function () {
           $.getScript(scriptbase + 'SP.RequestExecutor.js', execCrossDomainRequest);
       });
    });
});

function getQueryStringParameter(paramToRetrieve) {
    var params = document.URL.split("?")[1].split("&");
    var strParams = "";
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve)
            return singleParam[1];
    }
}

function execCrossDomainRequest() {
    var context;
    var factory;
    var appContextSite;
    var mylist;
    context = new SP.ClientContext(appweburl);
    factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
    context.set_webRequestExecutorFactory(factory);
    appContextSite = new SP.AppContextSite(context, hostUrl);
    this.web = appContextSite.get_web();
    mylist = this.web.get_lists().getByTitle('Employee');
    var camlQuery = new SP.CamlQuery();
    camlQuery.  set_viewXml('<View><RowLimit>10</RowLimit></View>');
    var collListItem = mylist.getItems(camlQuery);
    context.load(mylist);
    context.load(collListItem);
    context.executeQueryAsync(
     Function.createDelegate(this, successHandler),
     Function.createDelegate(this, errorHandler)
    );



    function successHandler() {
        var listItemInfo = '<div><table class="hovertable"> <tr><th width=100px; align=center;>Title</th><th width=100px>First Name</th><th width=100px>Last Name</th><th width=100px>Edit</th><th width=100px>Delete</th><th width=100px>View</th></tr>';
        var listItemEnumerator = collListItem.getEnumerator();
        while (listItemEnumerator.moveNext()) {
            var oListItem = listItemEnumerator.get_current();

            //listItemInfo += "<li style='height: 20px;'>" + oListItem.get_item('Title') + " " + oListItem.get_item('FirstName') + " " + oListItem.get_item('LastName') + "</li>";
            listItemInfo += '' +
                //"<tr> <td>" + oListItem.get_item('Title') + "</td> <td>" + oListItem.get_item('FirstName') + "</td> <td>" + oListItem.get_item('LastName') + "</td> <td><a href=" + hostUrl + "/Lists/OOB/EditForm.aspx?ID=" + oListItem.get_id() + " class='popup' >Edit</td> <td><a href=" + hostUrl + "/Lists/OOB/EditForm.aspx?ID=" + oListItem.get_id() + " class='popup' >Delete</a></td> <td><a href=" + hostUrl + "/Lists/OOB/DispForm.aspx?ID=" + oListItem.get_id() + " class='popup' >View</a></td> </tr></table>";
                '<tr> <td>' + oListItem.get_item('Title') + '</td> <td>' + oListItem.get_item('FirstName') + '</td> <td>' + oListItem.get_item('LastName') +

                '</td> <td><input type=button value=Edit onClick=edititem(' + oListItem.get_id() + ')> </td> <td><input type=button value=Delete onclick=deleteitem(' + oListItem.get_id() + ')></td> <td><input type=button value=View onclick=viewitem(' + oListItem.get_id() + ')></td></tr>';

            //document.getElementById("message").innerHTML = '<h1>' + mylist.get_title() + '</h1><br/>';
            //document.getElementById("message").innerHTML += listItemInfo.toString();
        }
        listItemInfo = listItemInfo + '<tr><td cellpadding=3><input type=button value=AddNew onClick=addnew()> </td></tr></table></div>'
        $('#spapp').html(listItemInfo);
    }
}
   
function addnew() {
    var html = '<div id=addform>  <h2 align=center color=#F28772>Add New Item</h2>' +
        '<table class="hovertable">' +
        '<tr>' +
            '<td >Title</td>' +
            '<td ><input type="text" id="newtitle"/></td>' +
        '</tr>' +

        '<tr>' +
            '<td >First Name</td>' +
            '<td ><input type="text" id="newfirstname"/></td>' +
        '</tr>' +
        '<tr>' +
            '<td >Last Name</td>' +
            '<td ><input type="text" id="newlastname"/></td>' +
        '</tr>' +
        '<tr>' +
            '<td >&nbsp;</td>' +
            '<td ><input type="button" value="Save" onClick="saveNewItem()"></td>' +
        '</tr>' +
    '</table>';
    $.colorbox({ html: html });

}

function saveNewItem() {
    var context;
    var factory;
    var appContextSite;
    var mylist;
    context = new SP.ClientContext(appweburl);

    factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
    context.set_webRequestExecutorFactory(factory);
    appContextSite = new SP.AppContextSite(context, hostUrl);
    this.web = appContextSite.get_web();
    mylist = this.web.get_lists().getByTitle('Employee');

    var itemCreateInfo = new SP.ListItemCreationInformation();
    this.oListItem = mylist.addItem(itemCreateInfo);

    oListItem.set_item('Title', $("#newtitle").val());
    oListItem.set_item('FirstName', $("#newfirstname").val());
    oListItem.set_item('LastName', $("#newlastname").val());

    oListItem.update();
    context.load(mylist);
    context.load(oListItem);

    context.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {

    alert('Operation Completed, Item Id : ' + oListItem.get_id());
    execCrossDomainRequest();
}

function onQueryFailed(sender, args) {

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


function edititem(id) {

    var context;
    var factory;
    var appContextSite;
    var mylist;
    context = new SP.ClientContext(appweburl);

    factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
    context.set_webRequestExecutorFactory(factory);
    appContextSite = new SP.AppContextSite(context, hostUrl);
    this.web = appContextSite.get_web();
    mylist = this.web.get_lists().getByTitle('Employee');

    this.oListItem = mylist.getItemById(id);

    context.load(mylist);
    context.load(oListItem);
    context.load(oListItem);
    context.executeQueryAsync(Function.createDelegate(this, function(){loadEdit(id);}), Function.createDelegate(this, this.onQueryFailed));
}

function loadEdit(id) {
    var html = '<div id=editform> <h2 align=center color=#F28772>Edit Item</h2> <table class="hovertable">' +
               
                '<tr>' +
                    '<td >Title</td>' +
                    '<td ><input type="text" id="edittitle" value="' + oListItem.get_item('Title') + '"/></td>' +
                '</tr>' +

                '<tr>' +
                    '<td >First Name</td>' +
                    '<td ><input type="text" id="editfirstname" value="' + oListItem.get_item('FirstName')+ '"/></td>' +
                '</tr>' +
                '<tr>' +
                    '<td >Last Name</td>' +
                    '<td ><input type="text" id="editlastname" value="' + oListItem.get_item('LastName')+'"/></td>' +
                '</tr>' +
                '<tr>' +
                    '<td >&nbsp;</td>' +
                    '<td ><input type=button value=Save onClick=saveEditItem('+id+') ></td>' +
                '</tr>' +
            '</table>';


    $.colorbox({ html: html });
}




function saveEditItem(id) {
    var context;
    var factory;
    var appContextSite;
    var mylist;
    context = new SP.ClientContext(appweburl);

    factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
    context.set_webRequestExecutorFactory(factory);
    appContextSite = new SP.AppContextSite(context, hostUrl);
    this.web = appContextSite.get_web();
    mylist = this.web.get_lists().getByTitle('Employee');

    this.oListItem = mylist.getItemById(id);

    oListItem.set_item('Title', $("#edittitle").val());
    oListItem.set_item('FirstName', $("#editfirstname").val());
    oListItem.set_item('LastName', $("#editlastname").val());

    oListItem.update();
    context.load(mylist);
    context.load(oListItem);

    context.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function deleteitem(id) {
    debugger;
    var context;
    var factory;
    var appContextSite;
    var mylist;
    context = new SP.ClientContext(appweburl);

    factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
    context.set_webRequestExecutorFactory(factory);
    appContextSite = new SP.AppContextSite(context, hostUrl);
    this.web = appContextSite.get_web();
    mylist = this.web.get_lists().getByTitle('Employee');
    this.oListItem = mylist.getItemById(id);
    oListItem.deleteObject();
    mylist.update();
    context.load(mylist);
    context.executeQueryAsync(Function.createDelegate(this, this.onDeleteSucceeded), Function.createDelegate(this, this.onQueryFailed));
 }

function onDeleteSucceeded()
{
    alert("Item Deleted Successfully");
    execCrossDomainRequest();
}

    function viewitem(id) {
        //var list = lists.getByTitle("Employee");

        var context;
        var factory;
        var appContextSite;
        var mylist;
        context = new SP.ClientContext(appweburl);

        factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
        context.set_webRequestExecutorFactory(factory);
        appContextSite = new SP.AppContextSite(context, hostUrl);
        this.web = appContextSite.get_web();
        mylist = this.web.get_lists().getByTitle('Employee');

        this.oListItem = mylist.getItemById(id);

        context.load(mylist);
        context.load(oListItem);
        context.load(oListItem);
        //clientContext.load(oListItem, 'Title');
        //context.executeQueryAsync(Function.createDelegate(this, function(){loadEdit(id);}), Function.createDelegate(this, this.onQueryFailed));
        context.executeQueryAsync(Function.createDelegate(this, this.loadView), Function.createDelegate(this, this.onQueryFailed));
    }

    function loadView(id) {
        var html = '<div id=editform> <h2 align=center color=#F28772> View Item</h2>' +
            ' <table class="hovertable">' +

                    '<tr>' +
                        '<td >Title</td>' +
                        '<td ><input type="text" readonly="readonly" id="edittitle" value="' + oListItem.get_item('Title') + '"/></td>' +
                    '</tr>' +

                    '<tr>' +
                        '<td >First Name</td>' +
                        '<td ><input type="text" readonly="readonly" id="editfirstname" value="' + oListItem.get_item('FirstName') + '"/></td>' +
                    '</tr>' +
                    '<tr>' +
                        '<td >Last Name</td>' +
                        '<td ><input type="text" readonly="readonly" id="editlastname" value="' + oListItem.get_item('LastName') + '"/></td>' +
                    '</tr>' +
                '</table>';


        $.colorbox({ html: html });
    }


    function errorHandler() {
       
        alert('Error');
    }

Friday, 3 July 2015

Create Group, Add/Remove Permission To Group,Add User in Group programmatically




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.SharePoint;

namespace AddGroupAndPermission
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Add_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(cbGroupName.Text) || string.IsNullOrEmpty(txtUserName.Text))
            {
                lblMsg.Text = "Please Enter Some Values";
                lblMsg.ForeColor = System.Drawing.Color.Red;
            }
            else
            {
                using (SPSite oSPsite = new SPSite(txtUrl.Text))
                {
                    using (SPWeb oSPWeb = oSPsite.OpenWeb())
                    {
                        //oSPWeb.AllowUnsafeUpdates = true;

                        SPGroup group = oSPWeb.Groups[cbGroupName.Text];
                        SPUser user = oSPWeb.EnsureUser(txtUserName.Text);
                        group.AddUser(user.LoginName, user.Email, user.Name, user.Notes);
                        oSPWeb.Update();
                        lblMsg.Text = txtUserName.Text + " - User Added to Group Successfully";
                        lblMsg.ForeColor = System.Drawing.Color.Green;
                        cbMyRole.Text = string.Empty;
                        txtUserName.Text = string.Empty;
                    }
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //bindGroup();
        }

        public void bindGroup()
        {
            string strGrpName, strGrpID;
            using (SPSite oSPsite = new SPSite(txtUrl.Text))
            {
                using (SPWeb oSPWeb = oSPsite.OpenWeb())
                {
                    SPGroupCollection oGroups = oSPWeb.SiteGroups;

                    foreach (SPGroup oGroupsInner in oGroups)
                    {
                        strGrpID = oGroupsInner.ID.ToString();
                        strGrpName = oGroupsInner.Name;
                        cbGroupName.Items.Add(strGrpName);
                        //strGrpDesc = oGroupsInner.Description;
                  }

                    //cbGroupName.DataSource = oGroups;
                    //    cbGroupName.Text="Name";

                 
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            bindGroup();
            bindList();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(cbGroupName.Text) || string.IsNullOrEmpty(cbMyRole.Text))
            {
                lblMsg.Text = "Please Enter Some Values";
                lblMsg.ForeColor = System.Drawing.Color.Red;
            }
            else
            {
                using (SPSite oSPsite = new SPSite(txtUrl.Text))
                {
                    using (SPWeb oSPWeb = oSPsite.OpenWeb())
                    {
                        //oSPWeb.AllowUnsafeUpdates = true;
                        SPGroup group = oSPWeb.SiteGroups[cbGroupName.Text];
                        SPRoleDefinition roleDefinition;
                        roleDefinition = oSPWeb.RoleDefinitions[cbMyRole.Text];

                        SPRoleAssignment roleAssignment = new SPRoleAssignment(group);
                        roleAssignment.RoleDefinitionBindings.Add(roleDefinition);

                        //add role to web
                        oSPWeb.RoleAssignments.Add(roleAssignment);
                     
                        oSPWeb.Update();

                        lblMsg.Text = cbMyRole.Text + " - Role Added to Group Successfully";
                        lblMsg.ForeColor = System.Drawing.Color.Green;
                    }
                }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtNewGroup.Text))
            {
                lblMsg.Text = "Please Enter Some Values";
                lblMsg.ForeColor = System.Drawing.Color.Red;
            }
            else
            {
                using (SPSite oSPsite = new SPSite(txtUrl.Text))
                {
                    using (SPWeb oSPWeb = oSPsite.OpenWeb())
                    {
                        //oSPWeb.AllowUnsafeUpdates = true;
                        oSPWeb.SiteGroups.Add(txtNewGroup.Text, oSPWeb.CurrentUser, oSPWeb.CurrentUser, txtNewGroup.Text);
                        //oSPWeb.Groups.Add(groupname, checkehat , checkwhat , groupdescription);
                        oSPWeb.Update();
                        lblMsg.Text = txtNewGroup.Text + " - Group Created Successfully";
                        lblMsg.ForeColor = System.Drawing.Color.Green;
                        txtNewGroup.Text = string.Empty;
                        txtNewGroup.Text = string.Empty;
                    }
                }
            }
        }

        private void btnRemovePermission_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(cbGroupName.Text) || string.IsNullOrEmpty(cbList.Text))
            {
                lblMsg.Text = "Please Enter Some Values";
                lblMsg.ForeColor = System.Drawing.Color.Red;
            }
            else
            {
                using (SPSite oSPsite = new SPSite(txtUrl.Text))
                {
                    using (SPWeb oSPWeb = oSPsite.OpenWeb())
                    {
                       // SPWeb web = SPContext.Current.Web;
                        SPGroup group = oSPWeb.SiteGroups[cbGroupName.Text];
                        SPPrincipal principal = (SPPrincipal)group;
                        SPRoleAssignment rAssignment = new SPRoleAssignment(group);
                        SPList list = oSPWeb.Lists[cbList.Text];
                        list.BreakRoleInheritance(true);
                        list.RoleAssignments.Remove(principal);
                        list.Update();
                        lblMsg.Text = cbGroupName.Text + " - Group Removed Successfully for " + cbList.Text + " List";
                        lblMsg.ForeColor = System.Drawing.Color.Green;
                        lblMsg.Text = string.Empty;
                        lblMsg.Text = string.Empty;
                     
                    }
                }
            }

        }

        public void bindList()
        {
            string strListName;
            using (SPSite oSPsite = new SPSite(txtUrl.Text))
            {
                using (SPWeb oSPWeb = oSPsite.OpenWeb())
                {

                    SPListCollection list = oSPWeb.Lists;

                    foreach (SPList myList in list)
                    {
                        //strListID = myList.ID.ToString();
                        strListName = myList.Title.ToString();
                        cbList.Items.Add(strListName);
                    }

                   
                }
            }
        }

       
    }
}

How to deploy .wsp using power shell