Tuesday 23 December 2014

Upgrade a SharePoint App after list field modification by its build version


It was quite challenging to upgrade  an app by its build version if some changes are made in the list structure.

Suppose I have an app which creates two lists(ListA,ListB) when it is deployed to a site collection. Now, I have deleted two columns in ListA and after some changes I would like to upgrade the app in that site collection.

Let me tell you, it will not allow you to upgrade that and after a while it will generate an error "taking too long time."

To solve this, you have to write your changes in Feature1.Template.xml as below:

<?xml version="1.0" encoding="utf-8" ?>
<Feature xmlns="http://schemas.microsoft.com/sharepoint/" Version="1.0.0.4">
  <UpgradeActions
    <VersionRange BeginVersion="1.0.0.3" >
      <ApplyElementManifests>
        <ElementManifest Location="PLinksInstance\Elements.xml" />
        <ElementManifest Location="PLinks\Elements.xml" />
        <ElementManifest Location="UserPLinkSettingsInstance\Elements.xml" />
        <ElementManifest Location="UserPLinkSettings\Elements.xml" />
      </ApplyElementManifests>
    </VersionRange>
  </UpgradeActions>

</Feature>

And Obviously you need to change the permission at AppManifest.xml as shown below:



Now Rebuild the project and publish to get the app package(.app file) and try to upgrade the app in "Apps In Testing" in the Site Contents of the site collection.

Hopefully, it will successfully upgrade the app.

Wednesday 17 December 2014

Create a Graphical Bar Chart in SharePoint Apps

The Graphical Case Overview gets the number of items in a list where the "MyColumn" column have a specific value. These counts are then displayed in a graph. A prototype have been implemented using Chart.js (http://www.chartjs.org/) which works very well.


Suppose we have a list named "MyList" and a Column named "MyColumn". The following figure illustrates the scenario:



Now, we need to create a graphical chart app (sharepoint hosted) by counting distinct value of the "My Column".


For that we need to get the items of specific column from the above list. We shall use JavaScript Object Model(JSOM) for this purpose:


function getDistinctItemsFromList() {

    //Get the SharePoint Context object based upon the URL
    var ctx = new SP.ClientContext(appWebUrl);

    //Get the List based upon the Title 
    var oList = ctx.get_web().get_lists().getByTitle('MyList');

    var camlQuery = new SP.CamlQuery();

    camlQuery.set_viewXml('');
    this.collListItem = oList.getItems(camlQuery);

    ctx.load(collListItem);
    ctx.executeQueryAsync(
        Function.createDelegate(this, this.onSuccess),
        Function.createDelegate(this, this.onFail)
    );
}



function onSuccess(sender, args) {

    var itemCount = collListItem.get_count();

    var itemsarry = new Array(parseInt(itemCount) - 1);

    var ListEnumerator = collListItem.getEnumerator();

    ColumnName = 'MyColumn';

    // adding values to array
    for (i = 0; i < itemCount; i++) {
        itemsarry[i] = new Array(0);
        itemsarry[i][0] = collListItem.get_item(i).get_item(ColumnName);
    }

    // getting count of unique values from array
    var uniqueItemsCount = 0;
    var uniqueItems = {};
    $.each(itemsarry, function () {
        var num = this[0];
        uniqueItems[num] = uniqueItems[num] + 1 || 1;
        uniqueItemsCount++;
    });

    //uniqueItems is your array with Column value and the associated Count.

    //uniqueItemsCount is how many of these distinct values exist which is 3 in            our case (Category A, Category B  and Category C)

    //Now to extract the values from this array use the snippet below
   
    $.each(uniqueItems, function (itemValue, noOfItems) {
        if (itemValue != 'undefined');
        {
            
           //Array of data to generate chart
            _arrayOfData.push(noOfItems);

            //Array of labels to generate chart
            _chartLabels.push(itemValue);
          
        }
     
     //Generates the graphical bar chart
     CreateChart(_arrayOfData,_chartLabels);

    });

   
    
}
function onFail(sender, args) {
    $("#results").html('<p>Error: ' + args.get_message() + '</p>');
}

And please add the following html structure in  .aspx page of your app part.

<body>
    <div id="results">

    </div>
    <div id="divChart">
    <canvas id="myChart" width="600" height="400"></canvas>
    </div>
</body>


And in the CreateChart function, assign the _arrayOfData and _chartLabels to another variable chartData.



function CreateChart(_arrayOfData,_chartLabels)
{

  var chartData = 
   {
     labels: _chartLabels,
     datasets: [
        {
            label: "My First dataset",
            fillColor: "rgba(151,187,205,0.5)",
            strokeColor: "rgba(151,187,205,0.8)",
            highlightFill: "rgba(151,187,205,0.75)",
            highlightStroke: "rgba(151,187,205,1)",
            data: _arrayOfData
        }
     ]
  };

var chartOptions =
 {
            scaleOverride: true,
            //set the maximum scale
            scaleSteps: Math.max.apply(Math, _arrayOfData), 
            scaleStepWidth: 1,          //set scale interval along Y axis
            scaleStartValue: 0,         // set starting scale value
            showLegend: true
}

       // Get context with jQuery - using jQuery's .get() method.

    var ctx = $("#myChart").get(0).getContext("2d");
    
   
    //Create instance of the Chart class with chartData and chartOptions

    var myBarChart = new Chart(ctx).Bar(chartData , chartOptions );

    $('#mychart').html(myBarChart);
}



And in the .aspx page, don't forget to put the references of the below links to generate the the chart properly.

 <!--jQuery library-->

    <script src="https://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js" type="text/javascript"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/0.2.0/Chart.min.js" type="text/javascript"></script>


Call the getDistinctItemsFromList() method in appropiate place of the apps. It can be in apps.js file or your own js file as below:


// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model

$(document).ready(function () {

    appWebUrl = decodeURIComponent(manageQueryStringParameter('SPAppWebUrl'));
  

    //CreateChart by getting distinct elements and their counts from a sharepoint list
    getDistinctItemsFromList();

});


Finally, you should get the chart shown below if everything is putted in right place of the sharepoint apps.




Happy SharePointing................!!!







Tuesday 23 September 2014

Show/Hide Font Colors in Rich Text Ribbon in SharePoint 2013


Few days ago, we faced a requirement of  SharePoint Ribbon for customizing the font colors for rich text element. The scenario is illustrated in the figure below:





First of all we tried to get the id of the section by using Firebug as follows:




After getting the id we tried to hide it by writing some CSS in the custom CSS file as written below:

#Ribbon.EditingTools.CPEditTab.Font.FontColor.MenucustomColor-Menu
 {
display: none;
 }


It should work. But it was not working. After some R&D, we get the solution that an extra ("\") is needed to identify the id of the section used in the ribbon. The perfect CSS for the purpose is given below:

#Ribbon\.EditingTools\.CPEditTab\.Font\.FontColor\.MenucustomColor-Menu
 {
display: none;
 }


And it is hiding perfectly as follows:



Similarly, we can hide the "Standard Colors" and "Theme Colors" section by writing the following CSS in the custom CSS file respectively:

#Ribbon\.EditingTools\.CPEditTab\.Font\.FontColor\.Menu\.Ms
{
      display: none;
}

and


#Ribbon\.EditingTools\.CPEditTab\.Font\.FontColor\.Menu\.MsTheme
{
      display: none;
}


Now, we moved to a detailed requirement  to add some more color box in the "Standard Colors" sections. This can also be done by adding the following CSS:


.ms-rteForeColor-11 {
  color: darkred;
  -ms-name: "";
  -ms-color:"Dark Red";
}

and

.ms-rteForeColor-12 {
  color: darkred;
  -ms-name: "";
  -ms-color:"Dark Red";
}



The result is shown in the following screenshot:



But what if we want to hide the color boxes that are previously added as shown below:



Suppose, we want to hide the first two colors of the "Standard Colors" section. For this we have to write following two CSS respectively in the custom CSS file as follows:

#Ribbon\.EditingTools\.CPEditTab\.Font\.FontColor\.Menu\.Ms tr:first-child td:first-child
{
display:none;
}

and

#Ribbon\.EditingTools\.CPEditTab\.Font\.FontColor\.Menu\.Ms tr:first-child td:nth-child(2)
{
display:none;
}

Observe that the first two color boxes are hidden. Following screenshots illustrates the scenario:



 Happy SharePointing....:) 




Tuesday 26 August 2014

Using InfoPath with SharePoint 2013



InfoPath is designed to make it easy to build rich forms-based applications on the Microsoft SharePoint Server platform. Microsoft InfoPath 2013 in conjunction with Microsoft SharePoint Server 2013 and InfoPath Forms Services have many features for developers. InfoPath Forms Services, which is available in SharePoint Server 2013, enables you to deploy an InfoPath form template to a SharePoint Server so that users without the InfoPath rich client can open and fill out InfoPath forms in a Web browser.
Form templates created using InfoPath 2013 continue to support business logic written against the classes and members of the Microsoft.Office.InfoPath namespace, which works the same way for a form opened in the InfoPath filler and in a form opened in a Web browser. 


Capturing and displaying data is a critical part of SharePoint. InfoPath helps end users modify those views quickly.  The key advantage of InfoPath is that it provides an easy-to-use interface for structured forms and provides rich developer functionality for adding business logic. To create and display forms, SharePoint 2013 uses a service on the server called InfoPath Forms Services. This service is designed to enable end users to use their browsers to fill out InfoPath forms and enable administrators to manage those forms. SharePoint provides a full object model for the InfoPath client, InfoPath forms, and InfoPath server administration. This enables developers to build enterprise business processes and forms that can be sophisticated yet easy to create. This has enabled the development of powerful business applications such as dashboards, data capture forms, and many more.

Creating the Sample List

To create powerful forms with SharePoint and InfoPath you need to create the SharePoint lists and libraries that you can work with. To create the training list, start by creating a new custom list and add the following fields:

➤ Title — A title for the training events; a single line of text.
➤ Class Code — Each class has a unique identifier for the training class (unique eight- character fixed); a single line of text.
➤ Description — The description of the training; a single line of text. Start Date — The training start date; date and time.
End Date The training end date; date and time.
Cost The cost of the training (in dollars); currency.
Level The difficulty level associated with the training (a number from 1 to 5); number.
Enrollment Deadline The date that enrollment ends; date and time.
Address The address of the training facility (multiple lines of text); multiple lines of text.
Additional Information Optional information about the training itself (enhanced rich text with pictures, tables, and hyperlinks); multiple lines of text.
Figure -1 illustrates all the fields of the new Trainings list, their types, and whether they are required when submitting to the list.




Figure -1

Customizing SharePoint List Forms

SharePoint 2013 provides a simple and easy-to-use way of customizing SharePoint list forms. The forms created in InfoPath 2013 can be used and embedded into SharePoint to build dynamic sites. One of the exciting features in InfoPath 2013 is the ability to extend or enhance the forms used by SharePoint lists for creating, editing, or showing list items. You can modify list form layouts, set validation rules, or create additional views using little or no code. When you finish modifying the list forms, reflecting your changes back to SharePoint is just a matter of using the one-click publishing capability that comes out of the box with the list form.


To customize the list forms in SharePoint 2013, navigate to a list or library, and click Customize Form in the Customize List section of the List tab that appears on the Ribbon, as shown in Figure -2.




Figure -2




This launches InfoPath Designer in SharePoint list mode, and a basic form is auto-created from the fields specified in the list’s schema. You can see the fields in the Fields task pane on the right side of the design canvas in which mandatory fields are designated with a red asterisk. When you click one of the existing form fields, the control tools’ contextual Ribbon appears on the top and gives you the ability to interact with the list columns inside of InfoPath Designer. Any changes at this point will be persisted later to the SharePoint list when the form is published. For example, if you change a control’s binding to a new field, that field will be automatically added to the list’s schema when the form template is published to SharePoint. The controls placed on the forms are selected based on the field type of that column. Figure -3 shows the sample list created with text and Date/Time columns already added to the form for each field. The Date and Time Picker control enables you to type a date and time or selects a date from a calendar display.


Figure -3

In addition to auto-generating the form through the SharePoint Ribbon buttons, you can launch InfoPath Designer by going to the New tab on the File menu and choosing SharePoint List as the template. You then enter the URL of the wanted list and the same InfoPath form auto-generates for you.

InfoPath Controls

A number of InfoPath controls can be placed into your form with InfoPath 2013. Each field type maps to one of the InfoPath controls when the form generates. The controls are part of categories that define how they work on your form; these categories are Input, Objects, and Containers. The controls used to map to fields will be from the Input category. You can see all the Input category controls listed here.

Text Box
Rich Text Box
Drop-Down List Box
Combo Box
Check Box
Date Picker
Date and Time Picker
Multiple-Selection List Box
List Box
Person/Group Picker

Changing the form and controls is easy as you can see by extending the form based on the scenario. By using a container called a Section or Optional Section, you can group controls together. For this example, you create an Optional Section to meet the requirements that the training coordinator will want to save real estate on the form, and only enter the information if needed. Add the Optional Section to your form using the following: 1. Click the auto-generated Rich Text Box next to the Additional Information text, and press Delete. (The control will have a label of Additional Information.) 2. In the Fields task pane, click Show Advanced View. 3. Then click the drop-down menu next to the Additional Information field, and choose Optional Section with Controls.

Now you have the Optional Section and the same Rich Text Box bound to the Additional Information file inserted into the form, as shown in Figure -4.


Figure - 4


Creating Business Logic with Rules and Views

Programming has evolved dramatically over the last decade with technologies like XML and XSD. These standards have made it possible to separate data and presentation layers, especially on the web. This is the foundation that InfoPath is built on, and two components of InfoPath use these technologies to help build the business logic of the InfoPath forms. These technologies are called Rules and Views that together create the User Interface for displaying data, and the logic to make the user interface and data behave as needed.

Rules

Rules in InfoPath are a set of one or more actions used to create a dynamic experience for the users of the form when they fill it out. There is always an event that triggers a rule, and in response, the rule performs some action such as a format change or a validation check: Adding rules to a form is straightforward. You use the following sample rules based on the scenario to build some sample rules on your form:

➤  If End Date < Start Date, show a validation error message.
➤  If Enrollment Deadline > Start Date, show a validation error message.
➤  Only the Address and Additional Information fields can be edited after the training is created.

To add these rules follow these steps:

1. Click the End Date control (Date Picker) to select it.
2. Next on the Home tab in the Ribbon, click Manage Rules. (This will open the Rules task pane.)
3. Click the New button and then Validation.
4. Give the rule a name such as RuleEndDate.
5. Click the None hyperlink in the Condition section.
6. Define the rule to run when the condition in Table - 1 is true.




 Table - 1

7. Enter a ScreenTip for the error message.


Repeat the steps for the Enrollment Deadline control using Table -1. Figure -5 shows what the RuleEndDate Condition will look like.


Figure -5





Views

Views provide a way to have different layouts of the same information in a single form, and depending on the view shown to the user, they see the layout for only that view. Views are just a presentation of the data in the form, and the same fields can be displayed in multiple views using separate controls. Views are a great way to present your form differently to the users based on different states that the form is in. The view can be changed based on rules or actions triggered by the user during run time of the form.

 You can create a new view from the Page Design tab, but you need to add the controls and layout to the new form after it is created. Using the scenario, you will make the fields that need not be edited read only. To do this you will create a different view that will be used when the user edits a list item. To create the views follow these steps:

 1. Click the Page Design tab on the Ribbon, and in the Views group, click New.
 2. Enter a name for the view; for the example, use Edit Training and click OK.
 3. To re-create the default controls and layout, copy (Ctrl+C) the entire layout and controls, and paste (Ctrl+V) them onto the second view.
4. Add a meaningful title to the top of the form for both the default and Edit Training views (that is, New Training and Edit Training).
 5. In the Edit Training view, remove the attachment row.
 6. Change the Date Picker controls to Text Box controls because the Date Picker control can- not be set to read-only. Right-click Start Date Change Control, and then select the Text Box control, as shown in Figure -6.
 7. Repeat step 6 for Start Date, End Date, and Enrollment Deadline.
 8. Right-click the Title Text Box. Click Text Box Properties Display tab. Then check the Read-only check box.
 9. Repeat step 8 for the following fields: Title, Class Code, Description, Cost, and Level.






Figure -6

At this point your Edit Training view should look like Figure -7.





Figure -7

To change between the views using the form, you need to set up the actions to change between the views based on the conditions set. After you perform the following steps, you have a rule that runs when the form loads:

 1. Navigate to the Data tab; then click the Form Load button. This brings up the Rules menu again with the Form Load as the rule type.
 2. Click the New button and select Action.
 3. Then type an appropriate name for the rule; use RuleSwitchToEditView.
 4. Change the condition of the rule to show the Edit page when the list item has an ID assigned to it. By setting the rule to ID, the comparison to it is not blank.
  5. Click the Add button to set the condition, and select the Switch Views action.
 6. In the View drop-down box, specify Edit Training view. Now you have customized the input form and provided the needed logic for the training form.




Publishing List Forms


 When you finish designing your forms, you need to publish them to SharePoint. This is the step that creates the connection between SharePoint and InfoPath. The form that has been created can be published directly to the SharePoint list generated using the File tab, and then the Info tab or Publish tab. Figure -8 shows the current state of the form. Also, InfoPath already knows which list to publish to because you opened the InfoPath Designer directly from SharePoint. This means that there is no additional configuration required when publishing this form to SharePoint. Just verify that the publishing location is correct, click the button that says Quick Publish, and you are done.




FIGURE -8


And it will show the following message:




After a form is published to a SharePoint list you may want to save the form locally. In this case do not close the form, but instead click the Save As option, and save the template to your local drive. The important point to remember here is that saving a form template locally or on a network share is a totally different process from publishing it. Publishing versus saving a form template is covered in greater detail in the section “Publishing InfoPath Forms,” but for now know that there are two types of finalized forms: Publishing and Saving. After the form has been successfully published and its template is locally saved, you can test that all the design and dynamic logic work as expected in SharePoint. Return to the SharePoint list in the site, and create a new list item to view the recently published forms. The default ASPX page is replaced with the default view of the form template you just customized and published. After filling out the form (see Figure 11-9), you can submit it by clicking Save on the top of the Ribbon. At this point, the form applies the appropriate rules to validate your input and adds a new list item to the SharePoint list.

If you closely look at the URL of the rendered form, you see that the form, unlike uncustomized list forms, is not loaded by the NewForm.aspx page. Instead, it is loaded by another out-of-the-box web part page called newifs.aspx. The newifs.aspx, displayinf.aspx, and editifs.aspx pages are part of the list’s infrastructure in SharePoint 2013. These pages were added in SharePoint 2010 to provide tighter integration with InfoPath forms directly into lists. They are all web part pages that can be customized via the browser. All three pages are accessible from the List tab Form Web Parts drop down on the Ribbon, as shown in Figure -10. Each page hosts an instance of the InfoPath Form web part that knows how to locate and load the form template associated with the SharePoint list.




FIGURE -9



FIGURE -10

When editing an existing list item, you see that the rule you placed in the Load event of the form kicks in and switches the view from New Training to Edit Training (see Figure -11), where you can edit the last two fields of the form only.





         Figure -11

If you want to undo everything and revert to the out-of-the-box ASPX forms after you have customized the forms, you can do this quickly without any issues. Browse to the List Settings page of the SharePoint list, click Form Settings, select Use the Default SharePoint Form, and click OK. Optionally, if you leave the Delete the InfoPath Form from the server unchecked, the InfoPath form you customized remains on the server. The next time you click Customize Form, the saved InfoPath form will be used in the InfoPath Designer instead of a new one being auto-generated from scratch. Two things about SharePoint list forms to consider: First, custom code is not supported in a customized list form using InfoPath 2013. If you open any of the forms that have been auto-generated from a SharePoint list, there is no Developer tab on the Ribbon to launch the coding tools. Second, you can publish a list form only to the list it belongs to. This also means that converting your list form to a form library is not possible.