Showing posts with label Pankaj Srivastava. Show all posts
Showing posts with label Pankaj Srivastava. Show all posts

Monday, February 8, 2016

Hiding a Site Content Link from Setting Icon in SharePoint 2013

Hello Everyone,

Recently I received a  requirement from client to hide Site Content Links from only one site page which 

comes along with Setting Wheels from Corner. I have tried a lot to achieve it from OOTB  but I did't get any solution,I have gone through many blogs and articles they are suggesting to make a changes in Master Page which does not make sense to do the changes for only one Page. so I have decided to use JQuery and REST to achieve my requirement. I hope this will help you a lot .

Please use below code to hide the site content Link

//get the current LoggedIn User Id

var userID=_spPageContextInfo.userId;

//Function to check If User Is Site Admin then then Site Content Link should be visible as it is if not then hide.

function CheckUserIsAdmin() {
$.ajax
({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetUserById(" + userID + ")",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
dataType: "json",
async: true,
success: function (data) {

//if loggedIn user is not a site Admin then hide the site content
var Obj=data.d.IsSiteAdmin;
var element;
if(!Obj)
{
var element=$("#siteactiontd").children().children().children()[4];
element.remove();
}
}
});
}

</script>

Thanks,

Pankaj Srivastava


by Pankaj Srivastava via Everyone's Blog Posts - SharePoint Community

Monday, December 14, 2015

Retriving all the workflows from MOSS 2007 site using Powershell Script

Hi All,

If you would like to retrieve all the workflow which is running in Moss 2007 you can use below PS script to list out all the workflow in CSV file.

#Load SharePoint 2007 Assemblies
[void][system.reflection.assembly]::load("Microsoft.sharepoint, version=12.0.0.0, culture=neutral, publickeytoken=71e9bce111e9429c")

# Script variables
$date = get-date -format "yyyy-MM-dd_HH-mm"

# Workflow Variables
$WFExport = "c:\\scripts\\exports\\Workflows_$date.csv"

# Main Body
# Creating Export File
out-file -filepath $WFExport -inputobject "|"

# Looping through Web Applications, Site Collections, Webs and Lists
$Farm = [Microsoft.SharePoint.Administration.SPFarm]::Local
$Service = $Farm.Services | Where{$_.TypeName -eq "Windows SharePoint Services Web Application"}
$WebApps = $Service.WebApplications
Foreach ($WebApp in $WebApps)
{
$Sites = $WebApp.Sites
Foreach ($Site in $Sites)
{
$Webs = $Site.AllWebs
Foreach ($Web in $Webs)
{
$Lists = $Web.Lists
Foreach ($List in $Lists)
{
$Workflows = $List.WorkflowAssociations
Foreach ($Workflow in $Workflows)
{
If ($Workflow.Name -notlike "Previous Version*")
{
out-file -filepath $WFExport -append -inputobject($Workflow.Name + "|" + $Workflow.InternalName + "|"+ $WebApp.Name + "|" + $Site.RootWeb.Title + "|" + $Web.Title + "|" + $Web.URL + "|" + $List.Title + "|")
}
}
}
}
}
}

Happy Coding !!

Thanks
Pankaj Srivastava


by Pankaj Srivastava via Everyone's Blog Posts - SharePoint Community

Saturday, December 12, 2015

How to retrive all pageLayout in CSV from sharepoint site using Powershell

clear
filter Get-PublishingPages {
$pubweb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($_)
$query = new-object Microsoft.SharePoint.SPQuery

$query.ViewAttributes = "Scope='Recursive'"
$pubweb.GetPublishingPages($query)
}
$FilePath="D:\\Pankaj\\PageAndLayouts.csv"
 
$str = Read-Host "Enter Site URL:"
if($str -eq $null )
{
Write-Host "Enter a valid URL”
return
}

$site = Get-SPSite -Identity $str
if($site -eq $null)
{
Write-Host "Enter a valid URL"
return
}

$allweb = $site.Allwebs
foreach($web in $allweb )
{
Write-Host $web.Title;
$web | Get-PublishingPages | select Uri, Title, @{Name='PageLayout';Expression={$_.Layout.ServerRelativeUrl}}|Export-CSV -Append $FilePath
}


by Pankaj Srivastava via Everyone's Blog Posts - SharePoint Community

Wednesday, December 9, 2015

How to filter List Items based on Date Time using REST in SharePoint Online

Hi All,

If you have requirement to filter data from a SharePoint Online List based on "fromdate" and "todate" using REST - please use below code

var fromDate=$("#txtdate").val();

var toDate=$("txttodate").val();

var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + ListName + "')/items?" +
                                "$select=ID,Title,DateOfEntry,Hours,Comments,AuthorId,Author/Title" +
                              "&$filter=DateOfEntry ge datetime'" + fromDate + "' and DateOfEntry le datetime'" + toDate + "' &$expand=Author/Title";
                $.ajax({
                    url: url,
                    type: "GET",
                    headers: { "accept": "application/json;odata=verbose", },
                    success: function (data) {
                        var results=  data.d.results;
                       //do whatever u want
                           
                        }

                    },
                    error: function (xhr) {
                        alert(xhr.status + ': ' + xhr.statusText);
                        console.log(xhr.status + ': ' + xhr.statusText);
                    }
                });


by Pankaj Srivastava via Everyone's Blog Posts - SharePoint Community

How to check if the currently logged-in user belongs to a group in SharePoint Online using REST

Hi Guys,

If you want to check that the currently logged-in user belongs to a group please find out how to do this using my code below, hopefully it will help you a lot!

var groupName;
function getCurrentUserPermission(userID) {
    $.ajax
    ({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetUserById(" + userID + ")/Groups",
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        dataType: "json",
        async: true,
        success: function (data) {
            /* get all group's title of current user. */
            for (var i = 0; i < data.d.results.length; i++) {
                if (data.d.results[i].Title == "Users") {
                    groupName = data.d.results[i].Title;
                  //do your hide/and show activity
                }
                else if (data.d.results[i].Title == "Admin") {
                    groupName = data.d.results[i].Title;
                   //do your hide/and show activity
                }
                else if (data.d.results[i].Title == "Operation") {
                    groupName = data.d.results[i].Title;
                   //do your hide/and show activity
                }
            }
        }
    });
}

Happy Coding !!

Thanks

Pankaj Sriavstava


by Pankaj Srivastava via Everyone's Blog Posts - SharePoint Community

How to provision a SharePoint Group using - Jquery/REST in a SharePoint Hosted App

Hi Guys,

If you are new to SharePoint Hosted App and you have a requirement to provision Groups In SharePoint online using REST Please use below code to accomplish your requirement.

function createSharepointGroup() {
    var groupName = [];
    groupName.push({ title: 'Admin', desc: "Admin Groups users in this group has full rights" });
    groupName.push({ title: 'Operation', desc: "Operation Group" });
    groupName.push({ title: 'Users', desc: "Users Group" });
    for (var i = 0; i < groupName.length; i++) {
        var spGroup = {
            "__metadata": {
                "type": "SP.Group"
            },
            "Title": groupName[i].title,
            "Description": groupName[i].desc,
        };

        $.ajax({
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/SiteGroups",
            type: "POST",
            contentType: "application/json;odata=verbose",
            data: JSON.stringify(spGroup),
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val()
            },
            success: function (data) {
                //success(data);
            },
            error: function (data) {
                //failure(data);
            }
        });
    }

}

Thanks,

Pankaj Srivastava


by Pankaj Srivastava via Everyone's Blog Posts - SharePoint Community

Working with Remote Event Receivers in a Provider Hosted App

Hi All, I would like to share my experiences while working on provider-hosted App Eemote Event Receiver. When I was working with Remote Event Receiver's for the first time I faced a lot of challenges. For example, I was not able to find why my Remote Event Eeceiver was not triggering and after a lot of investigation, I found the cause of the problem. If you are new to provider-hosted App Remote Event Receiver's this article will help you a lot.

1.  Right click on your HostWebProject add new Remote Event receiver - I am using here Item added event

2. Now as you can see your event receiver will be added to solution so once you will add event receiver one RemoteEventReciver1.svc file will be created in AppWeb Solution.

3. Once your RemoteEventReceiver has been added to solution, open your element.xml file update your  .svc Location URL

4. .svc file will be created in your AppWebProject 

Now Write your code on RemoteEventReciver1.svc.cs

I have written my code on ProcessOnWayEvent that fires after an action occurs, such as after a user adds an item to a list (because I have chosen on ItemAdded)

Now your event receiver will be created and when you run "deploy" this will not work! I was facing exactly the same problem with my Event Receiver not triggering,  so the question is - how do we overcome from this issue? Okay, so lets move ahead.

Now, right-click on your HostWeb Project - double click on "Handle App Installed" (if you want to Perform something when your App Installed).

When "Handle App Installed" is "true" then it will generate a new AppEventReceiver.svc in the AppWebProject

Open AppEventReceiver.svc.cs file add below code

Now I have written my code on AppInstalled Event-  which will attached RemoteEventReceiver1 to My List

-------------------------------------------------

  private void HandleAppInstalled(SPRemoteEventProperties properties)
        {
            try
            {
                using (ClientContext clientContext = TokenHelper.CreateAppEventClientContext(properties, false))
                {
                    if (clientContext != null)
                    {
                        List olist = clientContext.Web.Lists.GetByTitle("TestCustom");
                        clientContext.Load(olist, o => o.EventReceivers);
                        clientContext.ExecuteQuery();
                        bool isReRExsist = false;
                        foreach (var receiver in olist.EventReceivers)
                        {
                            if (receiver.ReceiverName == "RemoteEventReceiver1")
                            {
                                isReRExsist = true;
                                break;
                            }
                        }
                        if (!isReRExsist)
                        {

                            string remoteUrl = "http://ift.tt/1XVQcYr";
                            EventReceiverDefinitionCreationInformation eventReDefCreation = new EventReceiverDefinitionCreationInformation()
                            {

                                EventType = EventReceiverType.ItemAdded,
                                ReceiverAssembly = Assembly.GetExecutingAssembly().FullName,
                                ReceiverName = "RemoteEventReceiver1",
                                ReceiverClass = "RemoteEventReceiver1",
                                ReceiverUrl = remoteUrl,
                                SequenceNumber = 15000
                            };
                            olist.EventReceivers.Add(eventReDefCreation);
                            clientContext.ExecuteQuery();

                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }

        }

and detaching my EventReceiver from List when my app will uninstalled from site

private void HandleAppUnistalled(SPRemoteEventProperties properties)
        {
            using (ClientContext clientContext = TokenHelper.CreateAppEventClientContext(properties, false))
            {
                var list = clientContext.Web.Lists.GetByTitle("TestCustom");
                clientContext.Load(list);
                clientContext.ExecuteQuery();
                EventReceiverDefinitionCollection eventRColl = list.EventReceivers;
                clientContext.Load(eventRColl);
                clientContext.ExecuteQuery();
                List<EventReceiverDefinition> toDelete = new List<EventReceiverDefinition>();
                foreach (EventReceiverDefinition erdef in eventRColl)
                {
                    if (erdef.ReceiverName == "RemoteEventReceiver1")
                    {
                        toDelete.Add(erdef);
                    }
                }

                //Delete the remote event receiver from the list, when the app gets uninstalled
                foreach (EventReceiverDefinition item in toDelete)
                {
                    item.DeleteObject();
                    clientContext.ExecuteQuery();
                }
            }
        }


Now deploy your code it will work fine....

I hope my article will help you guys pls. drop your comment if you will face any issue.

Happy Coding !!!

Thanks,

Pankaj Srivastava


by Pankaj Srivastava via Everyone's Blog Posts - SharePoint Community

Open Provider hosted Apps in SharePoint Model Dialog Using Custom Action

Hi Guys,

If you are new to provider hosted App and you have requirement to open list item in your popup model dialog from SharePoint Online  as per Microsoft http://ift.tt/1NFPurw  there is only one way to pass item id using custom action.  But I have found another tricks to open your model dialog without using custom Action and you can pass  item id from there as well.

So if you want to open model dialog the you need to add three property as below code

          HostWebDialog="true"
           HostWebDialogHeight="800"
           HostWebDialogWidth="850"

-----------------------------------------------------------------

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://ift.tt/sQmbje">
  <CustomAction Id="6465cfae-e358-47ef-a41e-570f628318a4.openDialog"
                RegistrationType="List"
                RegistrationId="{$ListId:Lists/customlist;}"
                Location="EditControlBlock"               
               Sequence="399"
               Title="Create Freight Request"

             HostWebDialog="true"
           HostWebDialogHeight="800"
           HostWebDialogWidth="850">

    <UrlAction Url="http://ift.tt/1NFPuYz?{StandardTokens}" />
  </CustomAction>
</Elements>


by Pankaj Srivastava via Everyone's Blog Posts - SharePoint Community

Tuesday, December 8, 2015

Close The Modal Dialog in Provider-Hosted App from code Behind

Hi Guys,


if you are facing a challenge while closing a model dialog in provider hosted app from code behind then pls . use below script it will help you to achieve your requirements

Close The Modal Dialog Of A Provider-Hosted App from code Behind

1. If you want to refresh your parent window after closing your dialog then use below script

  HttpContext.Current.Response.Write("<script language='JavaScript'>window.parent.postMessage('CloseCustomActionDialogRefresh', '*');</script>");

2. if you don't want to refresh your parent page after closing your dialog then use below script

HttpContext.Current.Response.Write("<script language='JavaScript'>window.parent.postMessage('CloseCustomActionDialogNoRefresh', '*');</script>");

I hope this will help you a lot...

Happy coding.... :)

Regards!!

Pankaj Srivastava


by Pankaj Srivastava via Everyone's Blog Posts - SharePoint Community

Open Provider hosted Apps in SharePoint Model Dialog

Hi All ,

If you are new to SharePoint Provider hosted Apps and you want to open your Provider hosted Apps in SharePoint Model dialog then Microsoft suggest you use custom Action to achieve this functionality. 

I was struggling a lot and I did'nt want to use custom action to open Provider hosted App In Model dialog so I was dive deep into the custom action functionality and I was found the Js function that custom action internally use to open Provider hosted App in Model Dialog and I finally achieve the success without using Custom Action  I have used below script to open my Provider hosted in Model dialog on click on anchor tag .


<a href="#" onclick="javascript:LaunchApp('13f91bd6-b83d-85cb-921a-v418368ae07a', 'i:0i.t|ms.sp.ext|f4df267v-3sa2-6406-a46c-1ba3b94d0715@1d586085-556e-2af5-244b-31c7481vc6a3', 'https:\u002f\u002fxyz.azurewebsites.net\u002fPages\u002fDefault.aspx?{StandardTokens}', {width:900,height:800,title:'Create Request'});">Open My Provider hosted App</a>

And its working perfectly without using custom action ... you can pass your Item Id as well to provider hosted App from SharePoint model dialog.

I hope it will help you a lot for any question and query get in touch with me .

Happy Coding !!!

Thanks,

Pankaj Srivastava


by Pankaj Srivastava via Everyone's Blog Posts - SharePoint Community