Friday, September 21, 2018

Setting up Office 365 Development environment QuickStart

Setting up Office 365 Development environment QuickStart

1) Install latest version of Node JS
2) Install Visual Studio Code
3) Install latest version of node package manager

npm install -g nom@next

4) Install latest windows build tools

npm install -g windows-build-tools


5) Install Yeoman and Gulp

npm install -g yo gulp

6) Install Yeoman SharePoint Generator

npm install -g @microsoft/sharepoint-generator


To check the list of all global packages

npm list -g

To check whether a specific package is installed globally for example gulp

npm list -g gulp


Wednesday, January 4, 2017

Learning Docker on windows and troubleshooting the errors - part 1

1) Download and install the docker tookbox from
https://www.docker.com/products/docker-toolbox

This installs multiple products, docker engine, docker swarm, oracle virtual box, kitematics, etc.


2) Launch the Docker quick start terminal as administrator

Usually, Note: If the CPU virtualization is not enabled in the BIOS, you get the below error (). Else, you will see no errors.

Creating CA: C:\Users\<<mylogonname>>\.docker\machine\certs\ca.pem
Creating client certificate: C:\Users\<<mylogonname>>\.docker\machine\certs\cert.pem
Running pre-create checks...
Error with pre-create check: "This computer doesn't have VT-X/AMD-v enabled. Enabling it in the BIOS is mandatory"
Looks like something went wrong in step ´Checking if machine default exists´... Press any key to continue...

Follow this article to resolve the above error
https://github.com/docker/machine/issues/2256


--------------------
3) docker-machine

This will show you a help guide with the list of commands as shown below

$ docker-machine
Usage: docker-machine.exe [OPTIONS] COMMAND [arg...]

Create and manage machines running Docker.

Version: 0.8.2, build e18a919

Author:
  Docker Machine Contributors - <https://github.com/docker/machine>

Options:
  --debug, -D                                                   Enable debug mode
  --storage-path, -s "C:\Users\<<username>>\.docker\machine"    Configures storage path [$MACHINE_STORAGE_PATH]
  --tls-ca-cert                                                 CA to verify remotes against [$MACHINE_TLS_CA_CERT]
  --tls-ca-key                                                  Private key to generate certificates [$MACHINE_TLS_CA_KEY]
  --tls-client-cert                                             Client cert to use for TLS [$MACHINE_TLS_CLIENT_CERT]
  --tls-client-key                                              Private key used in client TLS auth [$MACHINE_TLS_CLIENT_KEY]
  --github-api-token                                            Token to use for requests to the Github API [$MACHINE_GITHUB_API_TOKEN]
  --native-ssh                                                  Use the native (Go-based) SSH implementation. [$MACHINE_NATIVE_SSH]
  --bugsnag-api-token                                           BugSnag API token for crash reporting [$MACHINE_BUGSNAG_API_TOKEN]
  --help, -h                                                    show help
  --version, -v                                                 print the version

Commands:
  active                Print which machine is active
  config                Print the connection config for machine
  create                Create a machine
  env                   Display the commands to set up the environment for the Docker client
  inspect               Inspect information about a machine
  ip                    Get the IP address of a machine
  kill                  Kill a machine
  ls                    List machines
  provision             Re-provision existing machines
  regenerate-certs      Regenerate TLS Certificates for a machine
  restart               Restart a machine
  rm                    Remove a machine
  ssh                   Log into or run a command on a machine with SSH.
  scp                   Copy files between machines
  start                 Start a machine
  status                Get the status of a machine
  stop                  Stop a machine
  upgrade               Upgrade a machine to the latest version of Docker
  url                   Get the URL of a machine
  version               Show the Docker Machine version or a machine docker version
  help                  Shows a list of commands or help for one command

Run 'docker-machine.exe COMMAND --help' for more information on a command.

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

3)  Now, pulling a helloworld image from docker hub (https://hub.docker.com/)
Note: You can use the Kitematics (to perform the same using a GUI instead of command line)

docker pull kitematic/hello-world-nginx

You may run into below error.
---------------------------------
$ docker pull kitematic/hello-world-nginx
Using default tag: latest
Pulling repository docker.io/kitematic/hello-world-nginx
Network timed out while trying to connect to https://index.docker.io/v1/repositories/kitematic/hello-world-nginx/images. You may want to check your internet connection or if you are behind a proxy.

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

Don't worry, to resolve this, sometimes you need to just restart the environment

$ docker-machine restart default      # Restart the environment
$ eval $(docker-machine env default)  # Refresh your environment settings

-------------------
4) to check the list of images installed
docker images

5) to run a container from the image (nginx, a reverse proxy, load balancer server for example)
-------------------
docker run kitematic/hello-world-nginx

----------------------
6) to check the list of active containers
docker ps -a to check the status all containers

Note: use doc


7) to stop the container

docker stop <<imagename>>

docker stop nostalgic_mcclintock
-----------------------
8) to remove the container and leave the image as is

docker rm <<containerId>>

 docker rm 2b

----------------------------
9) to run the container on a specific port in daemon mode for example, 

 docker run -d -p 5000:80 kitematic/hello-world-nginx

Here, 5000 is external port and 80 is internal port

10) You can now try launching the instance in the browser
using 

http://192.168.99.100:5000

Saturday, December 24, 2016

Your web part will not appear in the toolbox - Office 365

Your web part will not appear in the toolbox - Office 365

You get below error when you try to load the webpart in the Office 365 workbench (for the first time in the workbench.aspx) after you perform "gulp serve"

----------------------------------
Your web part will not appear in the toolbox. Please make sure "gulp serve" is running in a web part project. Please refresh the page once "gulp serve" is running.
--------------------------------

To resolve this error, you will be to first run the below command to install the certificate (note that the certification error in the local workbench also disappears after this)

gulp trust-dev-cert

After this, you can run gulp serve to again see the local workbench and then launch the office 365 tenant site to see if your locally developed webpart is available to be added on the workbench.aspx

Monday, February 1, 2016

Extract WSP file from SharePoint Central Admin Web app

$farm = Get-SPFarm
$file = $farm.Solutions.Item("nameofwsp.wsp").SolutionFile
$file.SaveAs("C:\temp\nameofwsp.wsp");

Saturday, September 19, 2015

1. TapeEquilibrium - Codility solution

Source:

Task description
A non-empty zero-indexed array A consisting of N integers is given. Array A represents numbers on a tape.
Any integer P, such that 0 < P < N, splits this tape into two non-empty parts: A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1].
The difference between the two parts is the value of: |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])|
In other words, it is the absolute difference between the sum of the first part and the sum of the second part.
For example, consider array A such that:
A[0] = 3 A[1] = 1 A[2] = 2 A[3] = 4 A[4] = 3We can split this tape in four places:
  • P = 1, difference = |3 − 10| = 7 
  • P = 2, difference = |4 − 9| = 5 
  • P = 3, difference = |6 − 7| = 1 
  • P = 4, difference = |10 − 3| = 7 
Write a function:
class Solution { public int solution(int[] A); }
that, given a non-empty zero-indexed array A of N integers, returns the minimal difference that can be achieved.
For example, given:
A[0] = 3 A[1] = 1 A[2] = 2 A[3] = 4 A[4] = 3the function should return 1, as explained above.
Assume that:
  • N is an integer within the range [2..100,000];
  • each element of array A is an integer within the range [−1,000..1,000].
Complexity:
  • expected worst-case time complexity is O(N);
  • expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.

Solution

using System;
// you can also use other imports, for example:
// using System.Collections.Generic;

// you can write to stdout for debugging purposes, e.g.
// Console.WriteLine("this is a debug message");

class Solution {
    public int solution(int[] A) {
        // write your code in C# 6.0 with .NET 4.5 (Mono)
        int count = A.Length;
        if(count>100000||count<=1){
            throw new Exception("Not a valid range");
        }
        int []temp= new int[count];
        int sum =0;
        for(int i=1;i<A.Length;i++){
            sum+=A[i];
        }
        int diff = A[0]-sum;
        if(diff<0){
            diff = -diff;
        }
        temp[0]= diff;
        int firstsum=A[0];
        for(int i=1; i<A.Length-1;i++){
            sum -= A[i];
            firstsum+=A[i];
            int diff2 = firstsum-sum;
            if(diff2<0){
                diff2=-diff2;    
            }
            temp[i] = diff2;
        }
        int min=temp[0];
        for(int i=1; i<temp.Length-1;i++){
                if(temp[i]<min){
                    min=temp[i];    
                }
        }
        
        return min;
    }    
}


Thursday, August 20, 2015

1. CountDiv Compute number of integers divisible by k in range [a..b].

Source: https://codility.com/demo/take-sample-test/count_div/
Task description
Write a function:
class Solution { public int solution(int A, int B, int K); }
that, given three integers A, B and K, returns the number of integers within the range [A..B] that are divisible by K, i.e.:
{ i : A ≤ i ≤ B, i mod K = 0 }
For example, for A = 6, B = 11 and K = 2, your function should return 3, because there are three numbers divisible by 2 within the range [6..11], namely 6, 8 and 10.
Assume that:
  • A and B are integers within the range [0..2,000,000,000];
  • K is an integer within the range [1..2,000,000,000];
  • A ≤ B.
Complexity:
  • expected worst-case time complexity is O(1);
  • expected worst-case space complexity is O(1).

Solution:

using System; // you can also use other imports, for example: // using System.Collections.Generic; // you can use Console.WriteLine for debugging purposes, e.g. // Console.WriteLine("this is a debug message"); class Solution { public int solution(int A, int B, int K) { if(K==0) return 0; int left = A/K; int right = B/K; int modLeft = A%K; int modRight = B%K; if((modLeft==00 || modRight==0)) return (B-A)/K +1 ; return right-left; } }

Tuesday, March 24, 2015

Javascript: Get query string value by name

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

Monday, August 11, 2014

Social media buttons

<a href="//www.pinterest.com/pin/create/button/?url=http%3A%2F%2Fwww.flickr.com%2Fphotos%2Fkentbrew%2F6851755809%2F&media=http%3A%2F%2Ffarm8.staticflickr.com%2F7027%2F6851755809_df5b2051c9_z.jpg&description=Next%20stop%3A%20Pinterest" data-pin-do="buttonPin" data-pin-config="above"><img src="//assets.pinterest.com/images/pidgets/pinit_fg_en_rect_gray_20.png" /></a>
<!-- Please call pinit.js only once per page -->
<script type="text/javascript" async src="//assets.pinterest.com/js/pinit.js"></script>

<!-- Place this tag where you want the share button to render. -->
<div class="g-plus" data-action="share" data-annotation="none"></div>

<!-- Place this tag after the last share tag. -->
<script type="text/javascript">
  (function() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/platform.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
  })();
</script>

<a href="http://www.tumblr.com/share" title="Share on Tumblr" style="display:inline-block; text-indent:-9999px; overflow:hidden; width:129px; height:20px; background:url('http://platform.tumblr.com/v1/share_3.png') top left no-repeat transparent;">Share on Tumblr</a>

<a href="https://twitter.com/share" class="twitter-share-button">Tweet</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>

<div id="fb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.0";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

<div class="fb-like" data-href="http://sp13dev01:4444/Pages/socialtest.aspx" data-layout="button" data-action="like" data-show-faces="true" data-share="true"></div>

Sunday, June 22, 2014

SharePoint Foundation Field Types


Field Type
 Display Name
Text
 Single Line Of Text
 Note
 Multiple Lines Of Text
 Choice
 Choice
 Integer
 Integer
 Number
 Number
 Decimal
 Decimal
 Currency
 Currency
 DateTime
 Date And Time
 Lookup
 Lookup
 Boolean
 Yes/No
 User
 Person Or Group
 URL
 Hyperlink Or Picture
 Calculated
 Calculated

SharePoint Foundation List Templates

Template Name
 Template Type
 Template Type ID
Custom List
 GenericList
100
 Document Library
 DocumentLibrary
101
 Survey
 Survey
102
 Links List
 Links
103
 Announcements List
 Announcements
104
 Contacts List
 Contacts
105
 Calendar
 Events
106
 Tasks List
 Tasks
107
 Discussion Lists
 DiscussionBoard
108
 Picture Library
 PictureLibrary
109
 Form Library
 XMLForm
115
 Wiki Page Library
 WebPageLibrary
119

Useful resources on SharePoint administration

Programming custom editor part SharePoint 2013

Programming custom editor part SharePoint 2013


This example shows how to create a custom editor part.
In the editor part, a ListBox control is binded to the list of the Lists in the current web and on selecting multiple lists, all the items from all the lists aggregated are shown in the webpart as depicted below.



Below is the code for custom webpart class with properties having the [WebBrowsable(false)]
-------------------------------------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections.Generic;

namespace DemoEditorParts.DisplayMultipleItems
{
    [ToolboxItemAttribute(false)]
    public class DisplayMultipleItems : WebPart
    {

        private List<string> listIDs;

        [WebBrowsable(false)]
        [WebDescription("Multiple Lists")]
        [Personalizable(PersonalizationScope.Shared)]
        public List<string> ListIDs
        {
            get
            {
                return listIDs;
            }
            set
            {

                listIDs = value;
            }
        }

        Dictionary<string, List<string>> allItemTitles = new Dictionary<string, List<string>>();

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            try
            {

                if (null == ListIDs)
                {
                    return;
                }
                SPWeb currentWeb = SPContext.Current.Web;

                foreach (var listId in ListIDs)
                {
                    SPList list = currentWeb.Lists[new Guid(listId)];
                    if (null == list)
                    {
                        continue;
                    }
                    if (!allItemTitles.ContainsKey(list.Title))
                    {
                        allItemTitles.Add(list.Title, new List<string>());
                    }
                    SPListItemCollection allItems = list.Items;
                    foreach (SPListItem item in allItems)
                    {
                        allItemTitles[list.Title].Add(item.Title);
                    }
                }


            }
            catch (Exception ex)
            {
                this.Controls.Add(new LiteralControl(ex.Message));
            }
        }

        protected override void RenderContents(HtmlTextWriter writer)
        {
            base.RenderContents(writer);
            foreach (var list in allItemTitles)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Ul);
                writer.Write(list.Key);
                foreach (var title in list.Value)
                {
                    writer.RenderBeginTag(HtmlTextWriterTag.Li);
                    writer.Write(title);
                    writer.RenderEndTag();
                }
                writer.RenderEndTag();
            }
        }

        public override EditorPartCollection CreateEditorParts()
        {
            List<EditorPart> editors = new List<EditorPart>();
            DisplayListsEditorPart editor = new DisplayListsEditorPart();
            editor.ID = this.ID + "_DisplayListsEditorPart";
            editor.Title = "Display Lists EditorPart";
            editors.Add(editor);

            return new EditorPartCollection(base.CreateEditorParts(), editors);
        }

    }
}
----------------------------------------------------------------------------------------
The below is the code for custom editor part
---------------------------------------------------------------------------------------

using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;


namespace DemoEditorParts
{
    public class DisplayListsEditorPart : EditorPart
    {
        private ListBox drpLists;

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            drpLists = new ListBox();
            drpLists.SelectionMode = ListSelectionMode.Multiple;
            drpLists.ToolTip = "All Lists";

            SPWeb currentWeb = SPContext.Current.Web;
            SPListCollection allLists = currentWeb.Lists;

            foreach (SPList list in allLists)
            {
                drpLists.Items.Add(new ListItem()
                {
                    Text = list.Title,
                    Value = list.ID.ToString()
                });
            }
            this.Controls.Add(drpLists);
        }

        public override bool ApplyChanges()
        {
            EnsureChildControls();
            DisplayMultipleItems.DisplayMultipleItems webpart
                = this.WebPartToEdit as DisplayMultipleItems.DisplayMultipleItems;

            ListItemCollection drpItems = drpLists.Items;
            List<string> selectedItems = new List<string>();
            foreach (ListItem item in drpItems)
            {
                if (item.Selected)
                {
                    selectedItems.Add(item.Value);
                }
            }
            webpart.ListIDs = selectedItems;
            return true;
        }
        public override void SyncChanges()
        {
            EnsureChildControls();
            DisplayMultipleItems.DisplayMultipleItems webpart
               = this.WebPartToEdit as DisplayMultipleItems.DisplayMultipleItems;
            List<string> lists = webpart.ListIDs;
            if (null == drpLists)
            {
                return;
            }
            ListItemCollection drpItems = drpLists.Items;
            if (null == lists)
            {
                return;
            }
            foreach (var list in lists)
            {
                ListItem drpItem =
                    drpItems.FindByValue(list);
                if (null == drpItem)
                {
                    continue;
                }
                drpItem.Selected = true;
            }
        }
    }
}

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




Custom Editor Part skeleton

The below code block shows the custom editor part skeleton.

 public class CustomEditorPart : EditorPart     { 
        public CustomEditorPart()             : base()         {         } 
        protected override void CreateChildControls()         {
            base.CreateChildControls();       
   } 
        public override bool ApplyChanges()         {
             EnsureChildControls();            
  return true;        
  } 
        public override void SyncChanges()         {            
  EnsureChildControls();        
  }    
}

Webpart properties [WebBrowsable(true)]


The following controls are generated for the webpart properties OOB for each property type when [WebBrowsable(true)] attribute is used for the webpart property

Type
Control
Boolean
Checkbox
String
TextBox
Enum
DropDown
Int, Float
TextBox
DateTime
TextBox
Unit
TextBox

Webpart Zone

The following are the modes which are available for every webpart placed inside a webpart zone.

• Browse: This is default mode, showing the final page layout.
• Design: In this mode, you can minimize or move Web Parts.
• Edit: In this mode, you can edit the properties of the currently selected Web Part.
• Catalog: This mode shows additional Web Parts that you can add to any zone.

• Connect: This mode allows you to add data connections between Web Parts. 

SharePoint Webpart Life cycle events

SharePoint Webpart Life cycle events

Event
 Source
Description
OnInit
 Control
 Fired after initialization.
OnLoad
 Control
 Fired after loading is completed.
CreateChildControls
 Control
 Creates child controls.
EnsureChildControls
 Control
 Called to ensure that CreateChildControls has executed.
OnPreRender
 Control
 Fired after all internal processing and before the controls render. This is the last step you can use to modify controls.
PreRenderComplete
 Page
 Fires if the page is executed asynchronously , and shows that rendering can be completed.
Render
 Control
 Renders the Web Part,  including the outer elements and chrome. RenderContents Control Renders the Web Part inside the outer elements and with styles,  but no chrome


Page Life cycle vs Webpart Life cycle