JavaScript

Custom Web Services SharePoint Part I – (LOB)

Posted on Updated on

  1. CUSTOM REST WEBSERVICES SHAREPOINT PART I – (LOB)
  2. Writing….

Write custom WCF REST Web Services in SharePoint why?

  1. You have your data outside SharePoint
  2. You don’t want or can’t override  the default throttling limit
  3. You want to build a BCS Model for Search inside SharePoint
  4. You want to integrate a REST System independent of the Technology

Principles

Every system uses resources. These resources can be pictures, video files, Web pages, business information, or anything that can be represented in a computer-based system. The purpose of a service is to provide a window to its clients so that they can access these resources. Service architects and developers want this service to be easy to implement, maintainable, extensible, and scalable. A Restful design promises that and more. In general, Restful services should have following properties and features.

REST’s client–server separation of concerns simplifies component implementation, reduces the complexity of connector semantics, improves the effectiveness of performance tuning, and increases the scalability of pure server components. Layered system constraints allow intermediaries—proxies, gateways, and firewalls—to be introduced at various points in the communication without changing the interfaces between components, thus allowing them to assist in communication translation or improve performance via large-scale, shared caching. REST enables intermediate processing by constraining messages to be self-descriptive: interaction is stateless between requests, standard methods and media types are used to indicate semantics and exchange information, and responses explicitly indicate cacheability.

I Prefer to use Linq 2 SQL in order to provide my Models, it’s faster than Entity Framework.

MODELS

Microsoft: LINQ to SQL [LINQ to SQL]

JSON DATA CLASSES SAMPLE

[DataContract()]
[Serializable()]
public class RetServices
{
    [DataMember()]
    public double? ServiceId { get; set; }
    [DataMember()]
    public double? ServiceParentId { get; set; } 
    [DataMember()]
    public string ServiceTitle { get; set; }

    [DataMember()]
    public string ServiceRelated { get; set; }
} 
 
INTERFACE SAMPLE
 
[OperationContract]
[WebGet(UriTemplate = "GetServicesTree", BodyStyle = WebMessageBodyStyle.Bare,
ResponseFormat = WebMessageFormat.Json)]
List<RetServices> GetSevicesTree();
 
IMPLEMENTATION SAMPLE
 
public List<RetServices> GetServicesTree()
{
    var db = new YourContext(Cs);
    var ret = from s in db.YourTable
              select new RetServices
              {
                  ServiceId = s.SER_ID,
                  ServiceParentId = s.SER_PARENT_ID,
                  ServiceTitle = s.NOME_SHORT,
                  ServiceRelated = s.SER_DIRECTOR.ToString()
              };
    return ret.ToList();
} 
 
SVC FILE SAMPLE
 

You can put you SVC file wherever you want, since the DLL for the project with the DATA, INTERFACES and IMPLEMENTATIONS reside in the GAC or the Web Application BIN Folder

<@ ServiceHost Language="C#" Debug="true" Service="YourDLL.YourNamespace.YourClass" %>
 
PUT IN SHAREPOINT
 
I prefer to create a Mapped Folder and put it in the ISAPI (On Premises Only), but you can put it whatever, since you secure it
 
Point from Client Side:
 
function get_ServicesTree()
{
    jQuery.ajax({
    cache: false,
type: "GET",
url: "/_vti_bin/YourFolder/YourService.svc/GetServicesTree",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$.each(data, function(key, value) {
            });
        },
error: function(jqXhr, status) { 
        }
    });
} 
 
WEB.CONFIG CONFIGURATION
 
<connectionStrings>
  <add name="LobConnectionString" connectionString="Data Source=SERVER;Initial Catalog=DATABASE;user=sa; pwd=xxxxx" />
</connectionStrings>
<system.serviceModel>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  <services>
    <service name="YOURDLL.YOURNAMESPACE.YOURCLASS" behaviorConfiguration="">
      <endpoint address="" binding="webHttpBinding" behaviorConfiguration="restfulBehavior" contract="YOURDLL.YOURNAMESPACE.IYourInterface">
        <identity>
          <dns value="localhost" />
        </identity>
      </endpoint>
      <host>
        <baseAddresses>
          <add baseAddress="http://localhost/" />
        </baseAddresses>
      </host>
    </service>
  </services>
  <behaviors>
    <endpointBehaviors>
      <behavior name="restfulBehavior">
        <webHttp helpEnabled="true" automaticFormatSelectionEnabled="true" />
      </behavior>
    </endpointBehaviors>
  </behaviors>
</system.serviceModel>
<system.webServer> 
 
REFERENCES
Advertisements

ECMA Script SP.ClientContext to Json

Posted on Updated on

Want to convert to Json a list.getItems collection? this is the way using ECMA Javascript

Declare SP.js

<SharePoint:ScriptLink runat="server" Name="SP.js" Localizable="false" OnDemand="False" LoadAfterUI="True"></SharePoint:ScriptLink> 

 

JavaScript Function

function getJson() {
    var context = new SP.ClientContext("/");
    var list = context.get_web().get_lists().getByTitle("YourList"); 
    var viewXml = "<View><RowLimit>1000</RowLimit></View>";
    var query = new SP.CamlQuery();
    query.set_viewXml(viewXml);
    var items = list.getItems(query);
    context.load(items, "Include(Column1,Column2,Column3)");

    function onLoaded() {
        var myItems = [];
        var itemsCount = items.get_count();
        for (var i = 0; i < itemsCount; i++) {
            var item = items.itemAt(i);
            var myItem = JSON.stringify(item.get_fieldValues());
            myItems.push(myItem);
        }
        alert(myItems);
    }

    context.add_requestSucceeded(onLoaded);

    function onFailure() {

    }

    context.add_requestFailed(onFailure);
    context.executeQueryAsync();
} 
 
UPDATE
 
In order to use JSON.parse() you must change the [Object<Array>] like this
 
var dt = "[" + MyItems + "]";
var ret = JSON.parse(MyItems); 

It will give you a [Object],[Object],[Object]

Unable to get property ‘showModalDialog’ of undefined or null reference

Posted on Updated on

the “Unable to get property ‘showModalDialog’ of undefined or null reference” error display because you are not calling the sp.ui.dialog.js

Wrong Way:

SP.UI.ModalDialog.showModalDialog(options);
 

Good Way:

SP.SOD.execute('sp.ui.dialog.js', 'SP.UI.ModalDialog.showModalDialog', options); 
 

Sample

function openYourDialog(tUrl, tTitle) {
	 var options = {
		 url: tUrl,
		 title: tTitle
	 };
	 SP.SOD.execute('sp.ui.dialog.js', 'SP.UI.ModalDialog.showModalDialog', options); 
 }

Calling:

<a href="#" onclick="openYourDialog('MyPage.aspx','Basic;">Show Dialog</a>