Follow in Twitter & Facebook


Like in Facebook

Powered By Blogger Widgets

Free Download

FREE Tools


Featured Posts

Sunday, July 30, 2017

Create a web api and deploy in Microsoft Azure for SharePoint online using visual studio 2015

- No comments
We can create a web api using visual studio 2015 and we can deploy in Microsoft Azure for SharePoint online site using visual studio 2015.

This article I have already published in EnjoySharePoint.com site also.

Follow below steps to Create Web Api for SharePoint Online:

Open visual studio 2015, File -> New Project...

In the New Project dialog box, expan Installed -> Templates -> Visual C# -> Web and then choose ASP.NET Web Application like below. Give a name for the project as well as make sure .NET Framework 4.5.2 is selected like below:


Then in the New ASP.NET Project dialog box, choose Empty project template. Then select the "Web Api" check box. And in the hosting section, check the "Host in the cloud" Microsoft Azure check box And select the Web Api option from drop down list like below:


Then in the Configure Microsoft Azure Web App dialog box, enter the Microsoft Azure details. First click on Add an account and then enter the Azure credentials.


Then give a Azure web app name. Then you can choose to create a new App service plan or create a new service plan. Similarly choose an existing Resource group or create a new group. Then choose the Region. The whole dialog box looks like below:


Now the solution looks like below:


Then we need to add controller class. Right click on the Controller folder Add -> Controller like below:


Then choose "Web API 2 Controller - Empty" and click on Add like below:


Then you can give a name for the Controller or you can use existing name (DefaultController) for the Controller.


Here when accessing the URL, we have to use "Default" for the Controller.

The DefaultController class will look like below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace MyDemoWebAPI.Controllers
{
    public class DefaultController : ApiController
    {
    }
}

Here in this class we are going to add one simple method which will accept one parameter and return something.

I have added one action known as MyAction like below:

 [HttpGet]
        public string MyAction(string testParameter)
        {
            return testParameter;
        }

The controller class looks like below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace MyDemoWebAPI.Controllers
{
    public class DefaultController : ApiController
    {
        [HttpGet]
        public string MyAction(string testParameter)
        {
            return testParameter;
        }
    }
}

Then we need to add the MapHttpRoute attribute inside the "WebApiConfig" which is presented inside the App_Start folder.

 config.Routes.MapHttpRoute(
               name: "MyAction",
               routeTemplate: "api/{controller}/{action}/{testParameter}",
               defaults: new { controller = "DefaultController", action = "MyAction", testParameter = ""}

           );

Here name:"MyAction"  -- Name of the Action that we have added in the DemoController class.
routeTemplate: "api/{controller}/{action}/{testParameter}",

While accessing the url, we have to pass our controller name in the place of {controller}, our action name in place of {action} and our input parameter name in place of {testParameter}.

defaults: new { controller = "DefaultController", action = "MyAction", testParameter = ""}

And in the above line we are passing the default values.

It looks like below:


Now it is time to deploy the web api. Here we will use the Import option to publish to Microsoft Azure.

Before proceding further we need to make sure we have created an Azure web app and also we have downloaded the published file.

Right click on the Project and then click on Publish...


Then click on "Import" options like below:


Now select the PublishSettings file which you have downloaded by following the above article.


Then make sure to give https in the destination url and also you can click on Validate Connection button to validate the connection like below:


Then in the next screen click on Next button like below:


Then in the next window click on preview button to see the preview or else you can directly click on the Publish button to publish to Azure.


Now once the deployment successful, we can access the web api url which will return the value. We can access like below:

https://mysharepointwebapi.azurewebsites.net/api/Default/MyAction?testParameter=Bhawana

Here we are passing the parameter like ?testParameter=Bhawana

And it will return like below:


Hope this will be helpful.

Friday, July 28, 2017

Retrieve all users from SharePoint group using C#.Net object model code in SharePoint online

- No comments
We can retrieve all users from a SharePoint group using .Net managed object model code in SharePoint online. We have a SharePoint group which has few users in it, the below code will display all the user's email id in comma separated string.

We are doing everything inside a console application. We are trying to connect to a SharePoint online site from the console application. For this we have stored the Email Address and Possword inside the App.Config file. Those informations we are retrieving using the below methods.
GetSPOAccountName()
GetSPOSecureStringPassword()

And then passing as a credentials inside the code.

public static string GetPortalOwnerEmail(string URL)
        {
            string ownerEmail = string.Empty;
            using (ClientContext context = new ClientContext(URL))
            {
                context.AuthenticationMode = ClientAuthenticationMode.Default;
                context.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
                context.Load(context.Web, w => w.ServerRelativeUrl);
                context.Load(context.Web, w => w.Title);
                context.ExecuteQuery();            
                Microsoft.SharePoint.Client.Group group = context.Web.SiteGroups.GetByName("My Custom SharePoint Group");

                context.Load(context.Web, w => w.Title);
                context.Load(group, grp => grp.Title, grp => grp.Users, grp => grp.Owner);
                context.ExecuteQuery();
                foreach (User usr in group.Users)
                {
                    ownerEmail += usr.Email+",";
                }

            }        
            return ownerEmail;
        }



     private static SecureString GetSPOSecureStringPassword()
        {
            try
            {              
                var secureString = new SecureString();
                foreach (char c in ConfigurationManager.AppSettings["SPOPassword"])
                {
                    secureString.AppendChar(c);
                }              
                return secureString;
            }
            catch
            {
                throw;
            }
        }

        private static string GetSPOAccountName()
        {
            try
            {              
                return ConfigurationManager.AppSettings["SPOAccount"];
            }
            catch
            {
                throw;
            }
        }

The above code will give all the users email address as a string separated by comma.

Retrieve the exact site url from the ServerRelativeUrl in SharePoint online

- No comments
We can retrieve the exact site url from the ServerRelativeUrl in SharePoint online using .Net managed object model code (C#.Net). Here we are doing in a console application and we are trying to connect to SharePoint online site.

Here my requirment is if the site url is: https://onlysharepoint2013.sharepoint.com/sites/Bhawana
It should return me onlu "Bhwana"

If the site url is https://onlysharepoint2013.sharepoint.com/sites/Bhawana/SubSite1

It should return me onlu "SubSite1"

Here in the GetSiteURL function we are taking the context and spliting the ServerRelativeUrl with "/" and returning the last element from the array.

Below is the full code:



 using (ClientContext context = new ClientContext(URL))
            {
                context.AuthenticationMode = ClientAuthenticationMode.Default;
                context.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
                context.Load(context.Web, w => w.ServerRelativeUrl);
                context.Load(context.Web, w => w.Title);
                context.ExecuteQuery();
                string siteTitle = GetSiteURL(context);
}

 private static string GetSiteURL(ClientContext context)
        {
            string siteTitle;
            string[] strArray = context.Web.ServerRelativeUrl.Split('/');
            int j = strArray.Length;
            siteTitle = strArray[j - 1].ToString();
            return siteTitle;
        }

Hope this will be helpful.

Tuesday, July 25, 2017

SharePoint online visual studio workflow development step by step guide

- No comments
Here we will discuss how we can create workflow using visual studio 2015 for SharePoint online site and also we will see how we can deploy to host web list or library. This is going to be a very simple workflow but we are going to understand how to do this with steps.

Since we are going to develop as an SharePoint hosted add-in, make sure you have a developer site is ready which you. You can check an article on how to create a developer site for SharePoint online Office 365.

Follow below steps:
Open visual studio 2015 and then File -> New -> Project. And then in the New Project dialog box, choose SharePoint Add-in from Templates ->Visual C# -> Office/SharePoint like below:


Then in the Add-in settings dialog box, give SharePoint online developer site url and choose the host type for SharePoint Add-in as "SharePoint-hosted".


Then it will ask for credentials to connect to SharePoint online site. Once entered successfully, it will show the below screen.




Now the SharePoint Add-in project will look like below:


To make the workflow available in the host web we need to choose "Integrated App" project properties to true. But since we have not added Workflow yet, you will not be able to see the "Integrated App" project properties.


Next we will add a the Workflow to the project. Right click on the Project, Add -> New Item. And in the Add New Item dialog box, choose Visual C# Items -> Office/SharePoint. And then choose Workflow template like below:


Then in the next screen, give a workflow name and choose List Workflow in the type of workflow like below:



Then in the Select the lists you will use when debugging screen, uncheck the check box and do not select anything like below:


Then the workflow will be added to the project and it looks like below:


Now click on F4 in the project to open the Project properties and there change the Integrated App property to True like below:


Now in the workflow search for a WriteToHistory action and click on the Message in the Properties box. There write some message as a string like below:


So this is a very simple workflow having one activity only. Now open the AppManifest.xml file and give Web to manage or full control permission like below:


Now we will try to publish the workflow to the SharePoint online site. Right click on the Project and click on Publish... like below:


This will open the Publish your add-in page, here click on Package the add-in which will generate the .app file like below:


Now we need to open the .app file using 7-zip or similar tool like below:


Then open the WorkflowManifest.xml file and check if the below tag is there or not.

<IntegratedApp>true</IntegratedApp>

If not add it and save the file.

Now it is the time to upload the .app file into the App Catalog site. Once it is uploaded to the App Catalog site, We can add into any SharePoint site, Site Contents > Add an App > Select your app and add it to your Team Site.



If it ask to trust, Trust it.

Now open any list and from the ribbon click on List Settings -> Workflow Settings and then click on Add a Workflow. In that screen you will see two options in Available Apps. One is for This List and another one as your App name (Here in my case it is ApprovalListWFHostWeb). In the Workflow details Click on the <Workflow Name>(in my case the name is ListApprovalWorkflow) like below:


Then give a name for the workflow and also you can select Task List & History List. Also choose the Start Options like when you want to start the workflow.


Now if you will again go back to the Workflow settings page, you can see the workflow is attached to the list like below:


Now it is time to start the workflow manually for one item in the list. For this select an item from the list, then click on ECB menu -> Advanced -> Workflows.


Then click on the workflow app and then you can see the workflow under Start a New Workflow like below:

Once the workflow got started successfully, you can see it will write the message which we have added inside the WriteToHistory activitity like below:


Hope this will be helpful.

Monday, July 24, 2017

the name configurationmanager does not exist in the current context

- No comments
We were developing a console application to connect to our SharePoint online sites. Here we have save the credentials inside App.Config file and we were retrieving like below:

  private static string GetSPOAccountName()
        {
            try
            {
                return ConfigurationManager.AppSettings["SPOAccount"];
            }
            catch
            {
                throw;
            }
        }

But it shows the error like below:

The name 'ConfigurationManager' does not exists in the current context.


Solution:
To resolve this issue we need to add System.Configuration dll. If you have .Net framework installed, then we can add it from local drive from the .NET tab.

But here I have added from NuGet package. Right click on the References folder -> Manage NuGet Packages... like below:


Then in the NuGet screen, search for System.Configuration in the Browse tab and then from there add select System.Configuration.Abstractions and click on Install like below:


Then the error will not come. Hope this will be helpful.

Sunday, July 23, 2017

Connections to the SharePoint server are currently disabled because the project is in Offline mode

- No comments
While developing and deploying SharePoint add-in using visual studio 2015 I got the error which says:

Connections to the SharePoint server are currently disabled because the project is in Offline mode. To connect to the SharePoint server, switch to Online mode by setting the project's server connection property to Online, an then try the opertaion again. The full error looks like below:


Solution:
Open Visual Studio 2015 solution -> Select the Project -> Click F4->Properties->Server Connection


Now we can deploy the project without any error.

SharePoint online Rest API Microsoft.SharePoint.Client.InvalidClientQueryException The expression is not valid. Bad Request

- No comments
Recently while working with Rest API in SharePoint online to delete all items from a list I got the below error. I have added the code inside a script editor web part in a web part page in SharePoint online. When I run the code it gave the below error:

{"readyState":4,"responseText":"{\"error\":{\"code\":\"-1, Microsoft.SharePoint.Client.InvalidClientQueryException\",\"message\":{\"lang\":\"en-US\",\"value\":\"The expression \\\"Web/Lists/getByTitle('Announcements')/getItemById(item.ID)\\\" is not valid.\"}}}","responseJSON":{"error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"The expression \"Web/Lists/getByTitle('Announcements')/getItemById(item.ID)\" is not valid."}}},"status":400,"statusText":"Bad Request"}


Solution:



In the Rest API code I was writting like below:

     var items = data.d.results;
        for(var item in items){
            var url = "/_api/Web/Lists/getByTitle('MyList')/getItemById(item.ID)"
            deleteItem(url);
        }

Here into the url variable I was passing like item.ID which I have put inside double quote as a string.

Then I have modified like below and it started working.

$.each(data.d.results, function (key, value) {    
var id=value.ID;
var url = "/_api/Web/Lists/getByTitle('Announcements')/getItemById("+id+")";
            deleteItem(url);
    });    

Hope this will be helpful.

Saturday, July 22, 2017

Delete all items from SharePoint online list using Rest API

- No comments
We can delete all items from SharePoint online list using Rest API. We can add the code into a script editor web part which we can add in a web part page in SharePoint online. The same code will work for SharePoint 2013, SharePoint 2016 and SharePoint online also.

Here is the first function we are getting the items and then we are building the rest api url for deleting an items and passing it to the deleteItem(url) method.

The full code looks like below:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<input type="button" id="btnDeleteAllItems" value="Delete All Items" />
<script>
$(function () {
    bindButtonClick();
});
function bindButtonClick() {
    $("#btnDeleteAllItems").on("click", function () {
        $.ajax({
    url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Announcements')/items",
    type: "GET",
    headers: {
        "accept": "application/json;odata=verbose",
    },
    success: function (data) {
        var items = data.d.results;
 $.each(data.d.results, function (key, value) {    
var id=value.ID;
var url = "/_api/Web/Lists/getByTitle('Announcements')/getItemById("+id+")";
            deleteItem(url);
    });    
    },
    error: function (error) {
        alert(JSON.stringify(error));
    }
});
    });
}

function deleteItem(url) {
$.ajax({
    url: _spPageContextInfo.webAbsoluteUrl + url,
    type: "DELETE",
    headers: {
        "accept": "application/json;odata=verbose",
        "X-RequestDigest": $("#__REQUESTDIGEST").val(),
        "If-Match": "*"
    },
    success: function (data) {
    },
    error: function (error) {
        alert(JSON.stringify(error));
    }
});
}
</script>

Once you save the page and click on the button, it will delete all items from the Announcements list.

Asp.Net senior developers job openings in TEKSystems

- No comments
Here is an asp.net senior developer job openings in TEKSystems.

Experience: 8 - 13 years
Job Location: Bengaluru/Bangalore

Job Description:
Experience working in an Agile/SCRUM environment.
Experience leading a team of developers.
Proven track record demonstrating ability to achieve stretch goals in a highly innovative and fast paced environment.
Strong sense of ownership, urgency, and drive.
Sharp analytical abilities and proven design skills.
Quick learner with motivation to learn new languages, technologies and frameworks (you will get opportunity to play with a lot of new technologies).
Experience building customer facing applications deployed on cloud environment (AWS, Azure or similar).
Experience working in building e-commerce web software.
Experience building public Web Services such as REST, SOAP.
Expertise in most of the following Web API, C#.Net, .Net Framework, Web Services, JSON, SOAP, REST, JQuery.
Experience in AngularJS is must
Object Oriented Programming.
Software development experience with Asp.NET and C#.Net
Experience with SQL and NoSQL Databases
Excellent Verbal and Communication skills.
Performance improvements / tuning of applications

If this opportunity is a good match to your profile, kindly mail in your updated profile to sbalakri@teksystems.com at the earliest with the below mentioned details:
Total Experience:
Relevant Experience:
Current & Expected CTC:
Notice Period:

Asp.Net job openings in Tech Mahindra

- No comments
Here is a Asp.Net job openings in Tech Mahindra,

Job Role: .Net Developer/Sr. Developer/Lead
Experience: 5 - 12Years

Job Description:
1. .Net Framework 4.6/Core, C#.Net, LINQ, ASP.Net MVC, Web API, MS SQL Server
2. UI: HTML, CSS, JavaScript, TypeScript, JQuery
3. Frameworks: Angular 2.0, Bootstrap, Azure PaaS experience, Entity Framework
4. Application & Database designing experience
5. Excellent communication skills & quick learner

If interested, kindly send your updated resume at s.sheetal@pinakitech.com mentioning the following mandatory details:-
Total Yrs Exp: /Rel Exp
Current CTC: /Expected CTC:
Notice Period: /Current Location:
DOB: /Father Name
Highest Qualification with Passing Year:
Please mention Passport No with Expiry date- MUST

Friday, July 21, 2017

SharePoint hosted Add-in error Failed to get web title Error Access denied You do not have permission to perform this action or access this resource

- No comments
While working with SharePoint hosted add-in to access some data from SharePoint site collection you might get access denied issue. Recently while working in a sample SharePoint hosted add-in for our SharePoint online site, we got access denied issue like below:

The error comes as:
Failed to get web title. Error. Access denied. You do not have permission to perform this action or access this resource. See fig below:


Solution:
We need to provide at least read access for the site collection.

Open the AppManifest.xml file in the SharePoint add-in project. The in the Scope select Site Collection and give Read permision like below:


Now when you deploy the Add-in, it will ask you to trust the Add-in. Click on Trust It button and then you will be able to see the title without error.


Hope this will be helpful.

Tuesday, July 18, 2017

Update SharePoint app registration in SharePoint online site

- No comments
Hi folks in my previous post we had seen how to registered an app for the first time in the SharePoint 2013/2016/Online site collection. Today we’ll see if we need to update an app which was already registered in the destination site what are the steps to follow in order to update same app like App Domain, Redirect URL. Title etc.

In below example I have registered an app by using below URL which generated Client Id, Client Secret etc for an app.
http://sitecollection/_layouts/15/appregnew.aspx

Once registered next time suppose I want to update hosting site URL or title of an app then below is the URL.This will ask App Id which is nothing but Client Id which was generated during 1st registration.

http://sitecollection/_layouts/15/appinv.aspx

Add the ClientId and click on Lookup, it will fill up other properties for an app as shown below.
As required update other fields not ClientId and click on Create Button.



Hope this will be helpful.