Wednesday, July 16, 2014

Something went wrong SharePoint App issue

Problem: 

Whenever SharePoint hosted or Auto hosted app code or html  is updated and you upload it to app catalog, and add the newly updated app into site you get the Something Went wrong error message.

Resolution

1) When you remove the app from the web, it will go into the recycle bin of that web and the site collection of that web. You need to remove it from the web recycle bin and site collection's recycle bin. In site collection recycle bin choose "Deleted from end user recycle bin" and then delete the app

2) Second method is to create a new GUID for the app and then open Appmanifest.xml with code and then replace the Product ID with the newly created GUID. In this way app will be registered with a different product id.

3) Third is change the version of app and then upload it again to app catalog site.

Happy Programming !!!

Tuesday, June 3, 2014

Create a basic Auto-hosted SharePoint App

Here i am going to demonstrate how to create a Auto-hosted SharePoint 2013 app using client side object model. I have deployed this app in SharePoint 2013 online environment. I used the Visual Studio 2013 to build this app.

Let's start

Start visual studio 2013, click File ->New->Project. Select the Apps template and select App for SharePoint 2013 as shown below and give it a proper name.



Specify the URL of SharePoint Site where you want to deploy this app and choose Autohosted as shown below


This will create as solution with two project as shown below




Every autohosted app have two projects, One Project contains the App itself and other web based project contains the code, pages and other logic.Open the default.aspx page under the web project to add html and code you want.
I have created this app that shows the current logged in user name. In the default.aspx page put the below html code.You must use the Jquery file in order to render the chrome container. The below java script creates chrome and app setting link and contact URL's
 <script type="text/javascript" src="../Scripts/jquery-1.9.1.js"></script>
    <script type="text/javascript">
        var hostweburl;

        // Load the SharePoint resources.
        $(document).ready(function () {

            // Get the URI decoded app web URL.
            hostweburl =
                decodeURIComponent(
                    getQueryStringParameter("SPHostUrl")
            );

            // The SharePoint js files URL are in the form:
            // web_url/_layouts/15/resource.js
            var scriptbase = hostweburl + "/_layouts/15/";

            // Load the js file and continue to the
            //   success handler.
            $.getScript(scriptbase + "SP.UI.Controls.js", renderChrome)
        });

        // Function to prepare the options and render the control.
        function renderChrome() {

            // The Help, Account, and Contact pages receive the
            // same query string parameters as the main page.
            var options = {
                "appIconUrl": "../Images/AppIcon.png",
                "appTitle": "My First Test App",
                "appHelpPageUrl": "Help.html?"
                    + document.URL.split("?")[1],
                "settingsLinks": [
                    {
                        "linkUrl": "specify any link url/",
                        "displayName": "display of link url "
                    },
                    {
                        "linkUrl": "mailto:specify your mail",
                        "displayName": "Contact us"
                    }
                ]
            };

            var nav = new SP.UI.Controls.Navigation(
                                    "chrome_ctrl_placeholder",
                                    options
                              );
            nav.setVisible(true);
        }

        // Function to retrieve a query string value.
        // For production purposes you may want to use
        // a library to handle the query string.
        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];
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div id="divSPChrome"></div>
        <div id="chrome_ctrl_placeholder"></div>
        <asp:Label ID="lbltitle"  runat="server"></asp:Label>
        <asp:Button Text="Click this" ID="btnclick" runat="server" OnClick="btnclick_Click" />
</form>
</body>

In defaault.aspx.cs use the below code on button click event use this code

 protected void btnclick_Click(object sender, EventArgs e)
        {
                      var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
           {
               clientContext.Load(clientContext.Web.CurrentUser);
                clientContext.ExecuteQuery();
                lbltitle.Text = "Welcome "+clientContext.Web.CurrentUser.Title;
             
            }
}

Double click on the AppManifest.xml and set the Query string as shown below.


Query string tokens are used to get some properties like host site URL, logo URL etc on the app page. We can use these token in java script or client object model. For more on this read at http://msdn.microsoft.com/en-us/library/office/jj163816(v=office.15).aspx


Also on the permissions tab set the appropriate permission setting for this app






Now build web project and then build the app project itself. Now right click on the first project i..e. app project and select Publish

This will  open the screen and then select publish and then click publish the app. Now your app is ready to be uploaded to app catalog. App contains the .app extension file and upload this file to your app catalog on SharePoint Online environment or on premises.

On any site choose add an app from the top and then choose app from your organizations and then select the newly uploaded app. Test it and make changes accordingly.

Please let me know if you face any issue. Happy coding, cheers :) 

Thursday, May 29, 2014

Get Choice Field values using Client Side Object Model in SharePoint 2013

Folks,

In this post i will explain you how to retrieve choice field values in Client Side Object Model (CSOM) in SharePoint 2013. I have tested this code in Auto hosted app on SharePoint online environment. You can use this code snippet to get values from choice field for custom filter and search conditions.

 var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                List queslist = clientContext.Web.Lists.GetByTitle("YourListTitle");
                Field choice = queslist.Fields.GetByInternalNameOrTitle("FieldName");

                FieldChoice fldChoice = clientContext.CastTo<FieldChoice>(choice);
                clientContext.Load(fldChoice, f => f.Choices);
                clientContext.ExecuteQuery();
                foreach (string  item in fldChoice.Choices)
                {
                    ddltopic.Items.Add(item.ToString());
//add choices to dropdown list
                }
}

You have to get the SharePoint context, then get the list field and then get that field choice and use the choice fields as per your needs, i have added the choice values in a drop-down list.

Let me know if you face any problem..

Happy Coding :)

Friday, May 9, 2014

Search SharePoint List items using jQuery/JavaScript and Web Service

You can use jquery/javascript to search items from a SharePoint list. You can define you CAML query and based on that result will be displayed. Lists.asmx web service is used in this case. You can use this to search items both on SharePoint online or on-premises versions.

List.asmx service is called and post method is called provided with soap envelope and in return we get the list items in from of xml. You can also highlight the searched keyword in the result.

Tuesday, March 25, 2014

How to create folder and sub folders inside Document Library using web service in SharePoint

In this post i will explain how we can use the UpdateListItems method of Lists web service to create folder and sub folder inside a document library. I will give you the code snippet and using this you can create folders and sub folders inside document library.

Here is the code snippet

 private void CreateFolder(string listName, string rootSubFolderName, string newFolderName)
        {
       
       
            string rootFolder = rootSubFolderName.Length > 0 ? string.Format("/{0}/{1}", listName, rootSubFolderName) : listName;
       
            string xmlCommand = string.Format("<Method ID='1' Cmd='New'><Field Name='FSObjType'>1</Field><Field Name='BaseName'>{1}</Field></Method>", rootFolder, newFolderName);
         
            XmlDocument doc = new XmlDocument();
            System.Xml.XmlElement batchNode = doc.CreateElement("Batch");
            batchNode.SetAttribute("OnError", "Continue");
            //Insert / to front as it is required by web service.
            if  (!rootFolder.StartsWith("/"))
                rootFolder = string.Format("/{0}",rootFolder);
//if you are having different site collection use  rootFolder = string.Format("/sites/sitename/{0}",rootFolder);

            if(rootSubFolderName.Length>0)
                rootFolder = string.Format("/{0}", rootFolder);
//if sub folder is to be created inside a folder

            batchNode.SetAttribute("RootFolder", rootFolder);
            batchNode.InnerXml = xmlCommand;
            XmlNode resultNode =listsservice.UpdateListItems(listName, batchNode);

            if ((resultNode != null) && (resultNode.FirstChild.FirstChild.InnerText == FOLDER_EXISTS) || (resultNode.FirstChild.FirstChild.InnerText == SUCCESS))
            {
                // success
            }
            else
            {
                //failure
                throw new Exception("Create new folder failed for: " + newFolderName + ". Error Details: " + resultNode.OuterXml);
            }
        }

Usage: You can call this function to create folders and sub folders as described below:

1)  CreateFolder("Your Document Library Title", "","Folder Name");
 This will create the folder inside "Your Document Library Title" with the Name "Folder Name" as no rootSub folder name parameter is specified.
 2)  CreateFolder("Your Document Library Title", "RootFolder","Folder Name");
 This will create the sub folder inside "Your Document Library Title", inside "RootFolder"
In this case hierarchy of the folders will be:Your Document Library Title/RootFolder/Folder Name