Thursday, 3 September 2015

Find element using jQuery.

If you want to find html element using jquery this post can be helpful.


  • If you're finding by Contains then it'll be like this

    $("input[id*='ElementID']")

  • If you're finding by Starts With then it'll be like this

    $("input[id^='ElementID']")

  • If you're finding by Ends With then it'll be like this

     $("input[id$='ElementID']")

  • If you want to select elements which id is not a given string

    $("input[id!='ElementID']")

  • If you want to select elements which id contains a given word, delimited by spaces

     $("input[id~='ElementID']")

  • If you want to select elements which id is equal to a given string or starting with that string followed by a hyphen

     $("input[id|='ElementID']")

Friday, 31 July 2015

Responsive Design

Increase of portable device usage requiring dynamic design changes for static site. Currently I have faced some issue with such concept. My requirement was to display a table on a page and make it look dynamic.

Here are some methods that I used to do it.

1) Using pure CSS :

You need to use media queries to make content dynamic. here is my code sample:

// for device Apple iPhone 5 or less, Samsung Galaxy S3 mini or less and Microsoft Lumia phones
@media (max-width: 320px) {
#docsTable{ 
max-width:320px;
}
}

// for device Apple iPhone 6,LG G3,LG Optimus G,Samsung Galaxy Note 2,Samsung Galaxy S3- S5,Samsung Galaxy Nexus

@media (max-width: 480px) {
#docsTable{ 
max-width:480px;
}
}

//for Apple iPad series
@media (max-width: 768px) {
#docsTable{ 
max-width:768px;
}
}

For other device width information  click here. 

But the problem occurs when the device has slightly smaller or larger width. It displays scroll which is not user friendly. Here is a way to handle such thing:

2) using Javascript

In this method we calculate the width by device's width and add width css to control at display time.

<script type="text/javascript">
$(document).ready(function() {
    // run test on initial page load
    checkSize();

    // run test on resize of the window in browser. Also need for screen rotation.
    $(window).resize(checkSize);
});

//Function to the css rule
function checkSize(){
    if(window.innerWidth < 768)
{
var thisObject = $("#docsTable");
var actualWidth = window.innerWidth - 50;
thisObject.css("max-width",actualWidth+"px");
}
});
}
</script>

Monday, 6 July 2015

Display Other site collection List data in current site collection using Client object modal.

A very bad dream in SharePoint 2013 is to "Display Other site collection List data in current site collection" as SharePoint Designer 2013 has deprecated data view web part and content search web part does not give look and feel as we wanted. It might be simple but I will update my self and this blog if I get success in near future with it.

Here is the sample code to display data from other site collection:

1) You need to add a web part page.  Add a "Content Editor Web part " in this page. In this paste below code with your changes.

<div>
   <!-- Table -->
  <table id="docsTable">
    <thead>
    <tr>
<th>ID</th>
<th>Title</th>
<th>Modified</th>
</tr>
</thead>
  </table>
</div>


<script language="javascript" type="text/javascript">
$(document).ready()
{
var folderUrl = document.getElementById('folderpath').value;
var url =document.getElementById('sitepath').value +"/_api/Web/GetFolderByServerRelativeUrl('" + folderUrl + "')?$expand=Folders,Files";


 // Get Folders and Files in single call. You can try using ajax call too. I have tried it but I was forced to call method multiple time.

$.getJSON(url,function(data,status,xhr){

 // Get Folders

    for(var i = 0; i < data.Folders.length;i++){      
        $('<tr>').append(
        $('<td>').html("data.Folders[i].ID"), // Append ID
        $('<td>').html("<a href='"+data.Folders[i].ServerRelativeUrl+"' target='_blank'>"+data.Folders[i].Name+"</a>"), // Apend Name. Click redirect to specific Item
        $('<td>').text(data.Folders[i].TimeLastModified.substring(0, 10))).appendTo('#docsTable'); //Append modified date.
    }

 // Get Files

    for(var i = 0; i < data.Files.length;i++){      
        $('<tr>').append(
        $('<td>').html("data.Files[i].ID"),  // Append ID
        $('<td>').html("<a href='"+data.Files[i].ServerRelativeUrl+"' target='_blank'>"+data.Files[i].Name+"</a>"), // Apend Name. Click redirect to specific Item
        $('<td>').text(data.Files[i].TimeLastModified.substring(0, 10))).appendTo('#docsTable');//Append modified date.
    }
})

}

This is a sample code. You can Add some more functionality like paging, sorting or can change fields as per your need.

JavaScript check if file exist at URL or not.

I was trying simple things lately with client side object modal. Here is one of the main issue I have face

"How to check if image / file exist at given path?"

I have tried using .done,.fail,.success,.complete and many more tricks that I could use. Even I tried Try.. Catch .. finally. But the real issue was if file does not exist at URL it will give exception 404. But not throw it so it won't be cached. Finally I came across a method shown below which gives me 404 error but will return result.

Answer: 

function doesFileExist(urlToFile)
{
    var xhr = new XMLHttpRequest();
    xhr.open('HEAD', urlToFile, false);
    xhr.send(); // Here it will generate 404
   
    if (xhr.status == "404") {
        return false;
    } else {
        return true;
    }
}

Calling :

if (doesFileExist(filePath)) {
            // yay, file exists!
        } else {
   // oops, file not exist!
}

Wednesday, 3 June 2015

Error - "Sorry, apps are turned off. If you know who runs the server, tell them to enable apps."

you will see this error when you try to add SharePoint Hosted app :

Sorry, apps are turned off. If you know who runs the server, tell them to enable apps.

Solution:

In order to install an App from the App Store you must setup an isolated App Domain, this is because Apps from the store deploy to their own app domain and run under a separate process from your SharePoint sites.

If your SharePoint site uses the DNS alias http://sharepoint.contoso.com you could have *.apps.contoso.com as your app domain.

http://www.sharepointalex.co.uk/index.php/2012/11/enabling-sharepoint-2013-apps/

How to: Set up an on-premises development environment for apps for SharePoint

http://msdn.microsoft.com/en-us/library/fp179923(v=office.15).aspx

The Subscription Settings service and corresponding application and proxy needs to be running in order to make changes to these settings.

I was working on hosted app when I encountered below error:

The Subscription Settings service and corresponding application and proxy needs to be running in order to make changes to these settings.


Solution:

Copy and paste below script in SharePoint Management Shell.

$acc = Get-SPManagedAccount <AccountName>
$appPool = New-SPServiceApplicationPool -Name "<Application pool name>" -Account $acc
$app = New-SPSubscriptionSettingsServiceApplication –ApplicationPool $appPool –Name "Subscription Settings Service Application" –DatabaseName <Database name>
$proxy = New-SPSubscriptionSettingsServiceApplicationProxy –ServiceApplication $app

Where
   Replace your <AccountName> with managed account
   Replace your <Application pool name> with Subscription Settings Service Apppool

   Replace your <Database name> with SPMT_Settings_Service_DB  

Reference:
https://technet.microsoft.com/en-us/library/fp161236(v=office.15).aspx

Monday, 25 May 2015

Service error - "Memory gates checking failed because the free memory (xxxxx bytes) is less than 5% of total memory."

I was testing few service scripts when I encounter with this error -

"Memory gates checking failed because the free memory (xxxxxxxxx bytes) is less than 5% of total memory."

Resolution:

Adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element or your project config file.

The easiest way just add this into your web.config

<system.serviceModel>
<serviceHostingEnvironment minFreeMemoryPercentageToActivateService="0" />

</system.serviceModel>

Reference:
1) http://support.ge-ip.com/support/index?page=kbchannel&id=23301025e79bf210148caf0ad63007ec5
2) http://stevemannspath.blogspot.in/2012/07/sharepoint-2013-opening-memory-gates.html

Friday, 22 May 2015

SharePoint 2010/2013: Updating Master Pages and Page layouts

Recently I have a task to replace masterpage manually(Programmatically). I tried to do it creating a module and putting masterpage inside it. But IgnoreIfAlreadyExists attribute within Module element can be tricky because sometimes it doesn’t work properly to update the MasterPages and PageLayouts.

Here is my solution for the update masterpage and Page layouts:

Feature Activation Code sample:

public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            if (properties != null)
            {
                using (SPSite currentSite = (SPSite)properties.Feature.Parent)
                {
                    using (var web = currentSite.OpenWeb())
                    {
                        var ElementDefinitions = properties.Definition.GetElementDefinitions(CultureInfo.CurrentCulture);

                        foreach (SPElementDefinition ElementDefinition in ElementDefinitions)
                        {
                            if (ElementDefinition.ElementType == "Module")
                            {
                                Helper.UpdateFilesInModule(ElementDefinition, web);

                            }
                        }
                    }
                }
            }

        }

You need to add a new class in your solution named "Helper" and add below code in it.

Namespaces:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;
using System.Xml.Linq;
using System.IO;
using Microsoft.SharePoint;
using System.Xml;

using System.Collections;

Class Code:

internal static class Helper
    {
        internal static void UpdateFilesInModule(SPElementDefinition elementDefinition, SPWeb web)
        {
            XElement xml = elementDefinition.XmlDefinition.ToXElement();
            XNamespace xmlns = "http://schemas.microsoft.com/sharepoint/";
            string featureDir = elementDefinition.FeatureDefinition.RootDirectory;
            Module module = (from m in xml.DescendantsAndSelf()
                             select new Module
                             {
                                 ProvisioningUrl = m.Attribute("Url").Value,
                                 //PhysicalPath = Path.Combine(featureDir, m.Attribute("Path").Value),
                                 Files = (from f in m.Elements(xmlns.GetName("File"))
                                          select new Module.File
                                          {
                                              Name = f.Attribute("Url").Value,
                                              PhysicalPath = Path.Combine(featureDir, f.Attribute("Path").Value),
                                              Properties = (from p in f.Elements(xmlns.GetName("Property"))
                                                            select p).ToDictionary(
                                                              n => n.Attribute("Name").Value,
                                                              v => v.Attribute("Value").Value)
                                          }).ToArray()
                             }).First();

            if (module == null)
            {
                return;
            }

            foreach (Module.File file in module.Files)
            {
                string physicalPath = file.PhysicalPath;
                string virtualPath = string.Concat(web.Url, "/", module.ProvisioningUrl, "/", file.Name);

                if (File.Exists(physicalPath))
                {
                    using (StreamReader sreader = new StreamReader(physicalPath))
                    {
                        if (!CheckOutStatus(web.GetFile(virtualPath)))
                        {
                            web.GetFile(virtualPath).CheckOut();
                        }
                        SPFile spFile = web.Files.Add(virtualPath, sreader.BaseStream, new Hashtable(file.Properties), true);
                        spFile.CheckIn("Updated", SPCheckinType.MajorCheckIn);
                        if (CheckContentApproval(spFile.Item))
                        {
                            spFile.Approve("Updated");
                        }

                        spFile.Update();
                    }
                }
            }

        }

        private static bool CheckOutStatus(SPFile file)
        {
            if (file.CheckOutStatus != SPFile.SPCheckOutStatus.None)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private static bool CheckContentApproval(SPListItem listitem)
        {
            bool isContentApprovalEnabled = listitem.ParentList.EnableModeration;

            return isContentApprovalEnabled;
        }

        public static XElement ToXElement(this XmlNode node)
        {
            XDocument xDoc = new XDocument();

            using (XmlWriter xmlWriter = xDoc.CreateWriter())

                node.WriteTo(xmlWriter);

            return xDoc.Root;

        }
    }

    public class Module
    {
        public string ProvisioningUrl { get; set; }
        //public string PhysicalPath { get; set; }
        public Module.File[] Files { get; set; }

        public class File
        {
            public string Name { get; set; }
            public string PhysicalPath { get; set; }
            public Dictionary<string, string> Properties { get; set; }
        }

    }

Reference: http://falakmahmood.blogspot.in/2011/09/sharepoint-2010-updating-masterpages.html

You can now check useful post links on "useful links" Right hand side top.



Wednesday, 6 May 2015

How to find the Microsoft.SharePoint.Identitymodel.dll location in SharePoint-2013 development environment?

I was searching on "session timeout and setup sliding sessions on an FBA enabled site". Where i need to add a reference namespace "Microsoft.SharePoint.IdentityModel". I have spend lot of time searching it and trying to add it in solution.

Please follow below steps to get the dll.

1. Open the Windows Explorer

2. Navigate to C:\Windows\Microsoft.NET\assembly\GAC_MSIL\ Microsoft.SharePoint.IdentityModel

3. And you can find the dll here C:\Windows\Microsoft.NET\assembly\GAC_MSIL\ Microsoft.SharePoint.IdentityModel\v4.0_15.0.0.0__71e9bce111e9429c


But it's not so simple some time as GAC_MSIL folder is not visible (Missing) in the assembly folder.

Here are few ways you can get it :

A)

  1. start > run > cmd
  2. type : "cd\windows\assembly"
  3. type: "attrib -r -h -s desktop.ini"
  4. type: "ren desktop.ini desktop.bak"

now open the GAC folder normally in your explorer. 
B)
  1. Run regsvr32 /u C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\shfusion.dll
  2. shfusion.dll is an explorer extension DLL that gives a distinct look to the GAC folder. Unregistering this file will remove the assembly cache viewer and the GAC folder will be then visible as any normal folder in explorer.
  3. Open “%windir%\assembly\GAC_MSIL”.
Hope it helps you too.

Dependency feature 'PPSSiteCollectionMaster' for feature 'PPSSiteMaster' is not activated at this scope.

I was trying to create a new sub site under my site collection while working with SharePoint 2010 and I got the below error message.

Dependency feature 'PPSSiteCollectionMaster' (id: a1cb5b7f-e5e9-421b-915f-bf519b0760ef) for feature 'PPSSiteMaster' (id:0b07a7f4-8bb8-4ec0-a31b-115732b9584d) is not activated at this scope.

Resolution:


1. Go Site Actions -> Site Settings ->Site Collection Administration ->Site collection features -> Performance Point Services Site Collection Features -> Activate

2. Go Site Actions -> Site Settings ->Site Actions ->Manage site features -> Performance Point Services Site Features -> Activate

SharePoint Classic Site Retirement: Your Plan to Avoid Last-Minute Chaos

Classic SharePoint has been on borrowed time for years. Microsoft has now put dates on the remaining pieces. Microsoft will disable creation...