Saturday, July 20, 2013

Installing Sharepoint 2013

This post will be a guide on installing sharepoint 2013.
This will be a process which has several steps.
First we'll have to run the Sharepoint Prerequisite installer which will check for some software in your server and install them if they are not available enable the required roles in the server.

Step 1 - Prerequisite installer

The Prerequisite installer is very simple and you just have to click the next buttons to continue with the setup.
As this enables some some server roles this will require you to restart the server.







Step 2 - The Sharepoint setup
first open the setup.exe

It'll require you the key , you can provide the key that you purchased from Microsoft.
Then the license agreement, well accept that and click continue.
Then you'll have to select the installation type, here I'm installing for a farm so its a full installation, you can do a stand alone installation for development environments.
this step will require you to select the file locations as well.


 Then it will install Sharepoint 2013 in your server.
when the installation is done you can start the configuration wizard.





Step 3 - Sharepoint Product configuration wizard

This will help you to do the required configuration for Sharepoint.


when you click it'll ask whether to start some required services, click yes to continue.




In the next step you can choose to connect to an existing sharepoint farm or to create a new farm.
in this post we are going to create a new farm.



Then you'll have to select the database server for farm, it can even be the same machine if you are setting up a single machine.
then you'll have to give the farm password.
The next step will be selecting the port for Central Administration and the security type
The next page will be a summary of the information you have just provided,
you can click next if everything is ok.
Now the configuration wizard will run and do the required configuration.
After the wizard complete it'll show a summary again saying that the configuration is successful.




Now that the installation and configuration is done, you can open the Central Administration using Internet Explorer.

Step 4 - Central Administration
The first window will ask you whether you want to be enrolled in the customer experience improvement program, select your preference.
Then the CA will show you a page to do the required configuration. you can choose to do it later.
this is basically starting the services.
if you choose to start the wizard you'll be shown a list of service applications that are to be started.
you can choose the ones you want to run in your farm. you can provide an account for the service applications.
When you click next, it will show the Working on it window, after that you can create web applications.




Thats it your Sharepoint 2013 farm is ready :)




Wednesday, July 10, 2013

Federating Sharepoint Services between Farms

Hi Readers,

In this post i'll explain how to federate and access a Sharepoint 2013 service application from Sharepoint 2010.

The concept is simple both farms will need to have a trust relationship,
this relationship is established by exchanging certificate between farms.

All the Commands given in this post will have to be run on the machine which the Central Administration is running.

First you'll need to get the certificate from the Consumer Farm, here the 2010 Farm.
Here you'll need to get the Root Certificate and the Security Token Service Certificate.

$rootCert = (Get-SPCertificateAuthority).RootCertificate 
$rootCert.Export("Cert") | Set-Content "C:\ConsumerFarmRoot.cer" -Encoding byte 

$stsCert = (Get-SPSecurityTokenServiceConfig).LocalLoginProvider.SigningCertificate 
$stsCert.Export("Cert") | Set-Content "C:\ConsumerFarmSTS.cer" -Encoding byte


Then we'll need to get the Root Certificate from the Publisher Farm

$rootCert = (Get-SPCertificateAuthority).RootCertificate 
$rootCert.Export("Cert") | Set-Content "C:\PublisherFarmRoot.cer" -Encoding byte

Then we'll have to exchange (Copy) the certificates between the farms.

After exchanging the certificates between the farms we'll have to establish the trust between farms.

Creating trust in Publisher Farm
Create trusted Authority
$trustCert = Get-PfxCertificate "C:\ConsumerFarmRoot.cer" 
New-SPTrustedRootAuthority "ConsumerFarm" -Certificate $trustCert

Create trusted token issuer
$stsCert = Get-PfxCertificate "c:\ConsumerFarmSTS.cer" 
New-SPTrustedServiceTokenIssuer "ConsumerFarm" -Certificate $stsCert

Now you'll have to do some security configuration
First Get the GUID of the Consumer Farm

(Get-SPFarm).Id

Then give access to Publisher farm (Run in Publisher farm)
$security = Get-SPTopologyServiceApplication | Get-SPServiceApplicationSecurity
$claimProvider = (Get-SPClaimProvider System).ClaimProvider
$principal = New-SPClaimsPrincipal -ClaimType "http://schemas.microsoft.com/sharepoint/2009/08/claims/farmid" –ClaimProvider  $claimProvider -ClaimValue  ConsumerFarmID
Grant-SPObjectSecurity -Identity $security -Principal $principal -Rights "Full Control"
Get-SPTopologyServiceApplication | Set-SPServiceApplicationSecurity -ObjectSecurity $security

Now we'll have to get the information from the service application of 2013 and create a service proxy in sharepoint 2010 central admin.

First go to the Shapoint 2013 central Admin and Go to Application Management and the select the Manage Service Applications.
Then select the Service application that you want to federate and click publish on the ribbon

from the menu check the "Publish this Service Application to other farms"
and copy the Service URL.

Then Click permissions from the ribbon and give full control to the Farm Admin of the Consumer farm.

Now we have the service URL so we can create a proxy at the Consumer End and start using the service.

In the Central admin of the consumer farm go to Application Management->Manage Service Applications and the from the ribbon click connect and select the service type which you are going to access.



Then give the URL of the service address we copied from Publisher service click ok.



Now sharepoint will show you the available service at the location, select it and click OK, then you'll have to give a name for the proxy, when its done you can use the service of 2013 from 2010 applications.

Please leave a comment :) 

Saturday, June 22, 2013

Access WCF Rest Services from JQuery Part 2

This is the Part 2 of the Post.
You can find Part 1 Here

In this post we'll see how to access the service we created using JQuery.

First we'll see the insert Employee part.
here we are posting the Employee object from  JQuery to WCF, As I'm using IIS Express its localhost you can give your service url correctly.

$.ajax({
 url: "http://localhost:53840/SampleService.svc/insertemployee",
 type: "POST",
 processData: true,
 contentType: "application/json",
 data: '{"Id":1, "Name":"Guru"}',
 dataType: "json",
 crossDomain : true,
 success: function(data) { alert(data) },
 error : function(data){alert('error')}
 
});

In this method we are getting all the employees as a json object array to the client side.
You do more by changing the Uri template and send information to the server side when using GET.

$.ajax({
 url: "http://localhost:53840/SampleService.svc/GetEmployees",
 type: "GET",
 processData: true,
 contentType: "application/json",
 dataType: "json",
 crossDomain : true,
 success: function(data) { alert(data) },
 error : function(data){alert('error')}
 
}); 

Thats it now you can access you service from JQuery.

Download Sample

Please Leave a Comment.

Access WCF Rest Services from JQuery Part 1

Hi Readers, this post is about creating the wcf service that is going to be accessed from jquery,

This service is very simple it allows you to add an employee via POST and retrieve all the employees via GET.
You can learn how to create a GET request and POST request.

As the first step you’ll have to create a WCF service project in Visual Studio (I’m using 2012). Here I’m creating the project as “WCF Rest Sample”.
You can use the Service1 which comes as default but I’ve created a new service called “SampleService” so that it’s easy to understand.

Then create the required classes, the given image shows the project structure.






Lets see the code for each class

The data provider class is used to contain the employee objects, in real world you can use a database as the data source.

public static class DataProvider
{
    private static List<Employee> Employees = new List<Employee>();

    public static List<Employee> GetEmployees()
    {
        return Employees;
    }

    public static void AddEmployee(Employee employee)
    {
        Employees.Add(employee);
    }
}

The next class is our Entity Employee this will be transferred as Json

[DataContract]
public class Employee
{
    [DataMember]
    public int Id { get; set; }

    [DataMember]
    public string Name { get; set; }
}

Then our service contract here the methods are declared and appropriate settings are made to change the request and response to json.

[ServiceContract]
public interface ISampleService
{
    [OperationContract]
    [WebInvoke(ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
    int InsertEmployee(Employee employee);

    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json)]
    List<Employee> GetEmployees();
}

This is the implementation for the service.

public class SampleService : ISampleService
{
    public int InsertEmployee(Employee employee)
    {
        DataProvider.AddEmployee(employee);
        return 1;
    }

    public List<Employee> GetEmployees()
    {
        return DataProvider.GetEmployees();
    }
}

In the global.asax file only the Begin request method is modified so that the service can be accessed from Firefox and Chrome.

protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    {
        HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, x-requested-with");
        HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
        HttpContext.Current.Response.End();
    } 
}

Now you'll have to do the appropriate changes the the web.config to turn the service into REST.

Now you can run the service and see the methods that are available using the help page (Enabled in the Web.config file).


Now our service is ready to be called from JQuery.
The jquery part will be explained in Part 2.

Tuesday, June 4, 2013

Syncing tables using Merge in SQL Server

Hi Readers,

In this post I'll explain how to use the 'Merge' statement in sql server to Sync two tables.
For this we'll need two tables, one will act as the source and the other one will act as the destination.

First create the required tables

CREATE TABLE SourceTable
(
 ID INT IDENTITY PRIMARY KEY,
 Name VARCHAR(100)
);

CREATE TABLE DestinationTable
(
 ID INT PRIMARY KEY,
 Name VARCHAR(100)
);


Then insert some data to the source table
INSERT INTO SourceTable VALUES('George');
INSERT INTO SourceTable VALUES('Saman');
INSERT INTO SourceTable VALUES('Kamal');
INSERT INTO SourceTable VALUES('Nimal');
INSERT INTO SourceTable VALUES('Sunil');
INSERT INTO SourceTable VALUES('Mark');
INSERT INTO SourceTable VALUES('Bill');
INSERT INTO SourceTable VALUES('Paul');
INSERT INTO SourceTable VALUES('Sean');
INSERT INTO SourceTable VALUES('Shane');
INSERT INTO SourceTable VALUES('Elvis');
Now we'll come to the Merge Statement

MERGE DestinationTable D
USING SourceTable S
ON D.ID=S.ID 
WHEN MATCHED AND D.Name!=S.Name THEN UPDATE SET D.Name=S.Name
WHEN NOT MATCHED BY SOURCE THEN DELETE
WHEN NOT MATCHED BY TARGET THEN INSERT(ID,Name) VALUES(S.ID,S.Name);

As this is the first time , all the rows will be inserted
So we'll do some changes to the table (insert, update , delete)
DELETE FROM SourceTable WHERE Name='Bill';
UPDATE SourceTable SET Name='Mark2' WHERE Name= 'Mark';
INSERT INTO SourceTable VALUES('Alex');
Now if we run the merge statement again we can see that both the tables are synced.
You can schedule it to a job so that the tables will be in sync.

Thursday, May 30, 2013

Using a WSDL file in C#

Hi Readers

This Article is about using the WSDL file from a non .NET based service with C#.
Say that you got a WSDL file from Java based service and you want to access it using C# , You may think its hard but its really easy.
All you have to do is to use the WSDL utility.

Lets go Step By Step

Step 1 : Save your WSDL with the Extension .wsdl because .XML wont work
I'm using this file as the sample.

Step 2: Open the Visual Studio Command Prompt


Step3: Locate the WSDL file (Hello.wsdl) and Use the command WSDL Hello.wsdl

Now you have the CS file Hello_Service.cs

Step 4 : Insert the Hello_Service.cs in your project and
Create an object from the class and simply call the methods.
Happy Coding :)
-Guruparan-

Thursday, April 4, 2013

Some Simple C Language String Functions

Here are some C Language functions that I created to use in one of my University Assignments This was a C language assignment and i needed some String functions that i use in java and C#. Ther first one is the IndexOf Function which return the index of a given Character in a string
//Method to find the index of a given char in a string
int IndexOf(char *string,char find)
{
 char *i=strchr(string,find);
 int index=(int)(i-string);
 if(index>=0)
 {
  return index;
 }
 else
 {
  return -1;
 }
}
The second one is the Substring which returns the subsequence of a string
//Method to get the SubString from a given string
char* SubString(int startIndex, int length, char *ch) {
 char *output=malloc(length);
 strncpy(output,&ch[startIndex],length);
 return output;
}
The third one is a function to validate a string using regular expressions You'll need to include the regex.h file to use this
int CheckMatch(char *input,char *format)
{
 regex_t regex;
 regcomp(&regex,format,0);
 int match=regexec(&regex,input,0,NULL,0);
 if( !match ){
                return 1;
        }
        else
        {
         return 0;
        }
}
Please leave a comment

Wednesday, March 27, 2013

Connecting Windows 8 Store Application with SQL Server using WCF - Part 2

This post is all about creating the application


First we need to add the service reference

Give the Namespace as DataProvider


Now we'll go to the coding Here i have added the coding for the buttons Both button click events will have to be async.


   private async void btnGetStudent_Click(object sender, RoutedEventArgs e)
    {
        //Create a client object to access the service
        DataProvider.DataProviderClient serviceClient = new DataProvider.DataProviderClient();

        //Get the student id and convert it to integer
        int ID = Convert.ToInt32(txtStudentID.Text);

        //Get the student via the service
        DataProvider.Student student = await serviceClient.getStudentAsync(ID);

        //The service will return null if the student is not available
        //If student is not found show a message
        if (student==null)
        {
            Windows.UI.Popups.MessageDialog message = new Windows.UI.Popups.MessageDialog("Student not found");
            message.ShowAsync();
            return;
        }

        //Set the values to the appropriate labels
        lblFirstName.Text = student.FirstName;
        lblLastName.Text = student.LastName;
    }

    private async void btnGetAllStudents_Click(object sender, RoutedEventArgs e)
    {
        //Create a client object to access the service
        DataProvider.DataProviderClient serviceClient = new DataProvider.DataProviderClient();

        //Get the student objects from the service
        ObservableCollection students = await serviceClient.getStudentsAsync();

        //Add the objects to the list view
        foreach (DataProvider.Student student in students)
        {
            lstStudents.Items.Add(student.FirstName+" "+student.LastName);
        }
    }

Download Code

Please Leave a comment about the post.

Connecting Windows 8 Store Application with SQL Server using WCF - Part 1

Hi Readers This post is about connecting Windows 8 Store application and SQL server using WCF. The Part 1 is about creating the WCF service. First lets create the Database.
CREATE DATABASE LearnerDB;

USE LearnerDB;

CREATE TABLE Students
(
 ID INT IDENTITY PRIMARY KEY,
 FirstName VARCHAR(100),
 LastName VARCHAR(100)
);

INSERT INTO Students VALUES('John','Doe');
INSERT INTO Students VALUES('Mark','Moe');
INSERT INTO Students VALUES('Grace','Goe');
INSERT INTO Students VALUES('Paula','Poe');
INSERT INTO Students VALUES('John','Rambo');
INSERT INTO Students VALUES('Jane','Joe');
 
in Visual Studio 2012 create a WCF service project

Then create a new service called "DataProvider"  (You can use the IService which comes as default as well)



 Let go the coding Part
   [ServiceContract]
    public interface IDataProvider
    {
        [OperationContract]
        Student getStudent(int ID);

        [OperationContract]
        List getStudents();
    }

    [DataContract]
    public class Student
    {
        [DataMember]
        public int ID { get; set; }

        [DataMember]
        public string FirstName { get; set; }

        [DataMember]
        public string LastName { get; set; }
    }
The student class is going to be used as the entity class to represent the table. The actual coding for the Service will be in the DataProvider Class
    public class DataProvider : IDataProvider
    {
        //Get the information of a single student
        public Student getStudent(int ID)
        {
            DataAccess dataAccess = new DataAccess();
            return dataAccess.getStudent(ID);
        }

        //Get information of all students
        public List getStudents()
        {
            DataAccess dataAccess = new DataAccess();
            return dataAccess.getStudents();
        }
    }
The data provider uses the dataaccess class to communicate with the database
public class DataAccess
{
    //Connection to the Database
    SqlConnection DBconnection;

    public DataAccess()
    {
        //Get the connection from the Web config
        string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ToString();
        DBconnection = new SqlConnection(connectionString);
    }

    /// Get the information based on Student ID
    public Student getStudent(int ID)
    {
        if (DBconnection.State==ConnectionState.Closed)
        {
            DBconnection.Open();
        }

        Student student = null;

        SqlCommand command = new SqlCommand("select * from students where ID ="+ID,DBconnection);
        SqlDataReader reader = command.ExecuteReader();
        if (reader.Read())
        {
            student = new Student()
            {
                ID = ID,
                FirstName = reader["FirstName"].ToString(),
                LastName = reader["LastName"].ToString()
            };
        }
        return student;
    }

    /// Get a list of all students
    public List getStudents()
    {
        if (DBconnection.State == ConnectionState.Closed)
        {
            DBconnection.Open();
        }

        List students = new List();

        SqlCommand command = new SqlCommand("select * from students", DBconnection);
        SqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            students.Add(new Student()
            {
                ID = Convert.ToInt32(reader["ID"].ToString()),
                FirstName = reader["FirstName"].ToString(),
                LastName = reader["LastName"].ToString()
            });
        }
        return students;
    }
}
After creating the service you can test it using WCF Test Client.

Tuesday, February 5, 2013

Download files from Sharepoint Library Recursively

Hi
This is a small program that will download the contents of a Sharepoint documnt library.

This will download all the files in the subfolders as well

class Program
{
 static void Main(string[] args)
 {
  Console.WriteLine("This Application will download the documents in a library");
  Console.Write("Enter Site URL : ");
  string SiteURL = Console.ReadLine();

  Console.Write("Library Name : ");
  string LibraryName = Console.ReadLine();

  //Open the site using the given url
  using (SPSite site = new SPSite(SiteURL))
  {
   //Open the web application
   using (SPWeb web = site.OpenWeb())
   {
    try
    {
     //Get the library folder
     SPFolder folder = web.GetFolder(LibraryName);

     //Download files
     downloadFilesrecursively(folder);
    }
    catch (Exception ex)
    {
     //Print the details of the exception
     Console.WriteLine("An Error Occured while processing " + ex.Message);
    }
   }
  }

  Console.ReadLine();
 }

 //The method that downloads the files from a given SPFolder
 public static void downloadFiles(SPFolder folder)
 {
  foreach (SPFile item in folder.Files)
  {
   //Download the file
   byte[] fileData = item.OpenBinary();
   System.IO.FileStream fstream = System.IO.File.Create(item.Name);
   fstream.Write(fileData, 0, fileData.Length);
   Console.WriteLine(item.Name + " " + fileData.Length);
  }
 }

 //Method that is used to call the download method recursively
 public static void downloadFilesrecursively(SPFolder folder)
 {
  //If the folder have subfolders call the download
  //Methods for the subfolders
  if (folder.SubFolders.Count != 0)
  {
   //Download the files in the current folder
   downloadFiles(folder);
   foreach (SPFolder item in folder.SubFolders)
   {
    downloadFilesrecursively(item);
   }
  }
  else
  {
   //If the folder has no subfolders
   //then download the file in the folder
     downloadFiles(folder);   
  }
 }
}

Monday, February 4, 2013

SQLite Database in Windows 8 RT application Part-2

Hi Devs
This is the Part 2 of the post
You can find Part 1 Here

This post will have all the Coding required
Here I'll show you how to make a simple Employee Management system.

Hope you have the Project created in Part 1,
First goto the Project Properties->Build and Make the Platform target to x86 or x64 because Any CPU is not supported yet.

This is the UI of the sample application.

This will be the structure of the solution,


 Here I'm having two classes to manage the database
First the Employee Class
The concept is just like SQL CE you have to create a class to represent a table and the use LINQ to work with the database.
This class will be representation of the Employee table, the explanation is given as the comment in the code.

public class Employee
{
    /// <summary>
    /// The ID of the Employee
    /// Used as the primary key
    /// Automatically incremented
    /// </summary>
    [PrimaryKey, AutoIncrement]
    public int ID { get; set; }

    /// <summary>
    /// Name of the Employee
    /// </summary>
    [MaxLength(30)]
    public string Name { get; set; }

    /// <summary>
    /// Address of the Employee
    /// </summary>
    [MaxLength(30)]
    public string Address { get; set; }
}
 
Now the Employee Manager class which handles the interaction with the database

public class EmployeeManager
{
    /// <summary>
    /// The Connection to SQLite database file
    /// </summary>
    private SQLiteConnection connection;

    /// <summary>
    /// The constructor
    /// Creates the connection to the database and creates the table
    /// </summary>
    public EmployeeManager()
    {
        //Windows.Storage.ApplicationData.Current.LocalFolder.Path is used to get the location of the Application
        connection = new SQLiteConnection(Windows.Storage.ApplicationData.Current.LocalFolder.Path+"\\EmployeeDB");
        connection.CreateTable<Employee>();
    }

    /// <summary>
    /// Insert a new employee to the database
    /// </summary>
    /// <param name="employee">The Employee to be inserted</param>
    /// <returns>ID of the inserted employee</returns>
    public int insertEmployee(Employee employee)
    {
        return connection.Insert(employee);
    }

    /// <summary>
    /// Delete and employee from the database
    /// </summary>
    /// <param name="ID">ID of the employee to be deleted</param>
    public int deleteEmployee(int ID)
    {
        return connection.Delete<Employee>(ID);
    }

    /// <summary>
    /// Update the details of an employee
    /// </summary>
    /// <param name="employee">New Employee object</param>
    public int updateEmployees(Employee employee)
    {
        return connection.Update(employee);
    }

    /// <summary>
    /// Get a employee object
    /// </summary>
    /// <param name="ID">ID of the employee</param>
    /// <returns>Employee with the given ID</returns>
    public Employee findEmployee(int ID)
    {
        List<Employee> employees = connection.Table<Employee>().Where(X=>X.ID==ID).ToList();

        if (employees.Count()==1)
        {
            return employees.First();
        }
        else
        {
            return null;
        }
    }

    /// <summary>
    /// Get a list of all the employees in a database
    /// </summary>
    /// <returns></returns>
    public List<Employee> getAllEmployees()
    {
        return connection.Table<Employee>().ToList();
    }

}
 
Thats it you can just call these methods from the Button click events to use the database.
You can find the UI calls in the sample application

Sample Application

Happy Coding
Please Leave a comment
Guruparan G

SQLite Database in Windows 8 RT application Part-1

Hi Devs
This post is all about using a SQLIte database in Windows 8 application
In this post i'll explain how to setup Visual Studio 2012 in order to work with SQLite.
In Part 2 I'll explain how to do the basic operations such as Add delete and update.
Lets get started
First you'll have to install the SQLite runtime for windows.
Goto Tools->Extension and Updates

Then search for SQLite and install it

Create a project based on your requirement (Blank\Grid Application)
And now add the reference to your project


Here you'll have to add the reference to both C++ runtime and SQLite runtime because SQLite runtime requires C++ runtime.


Now we can move to the NuGet Packages
Here we'll be installing the Wrapper Class Library for SQlite.

Goto Tools->Library Package Manager->Manage NuGet Packages for Solution


And select the "Online" packages and search for Sqlite-net and install it


Now we are good to start coding
All the coding part will be covered in Part 2.

Please Leave a comment
Guruparan G

Tuesday, January 8, 2013

Creating Sharepoint Security Groups and Adding People to it via Code

Hi Readers

In this post I'll explain how to Create security groups using C# code and add users to the group.

//Get the specific site
using (SPSite site = new SPSite("http://mytestsite"))
{
    using (SPWeb web = site.OpenWeb())
    {
        //Create the user group with the name test group
        //The default user and the description will have to be given
        web.SiteGroups.Add("Test Group", web.Users["abc\\user"], null, "This is a test group");
        //Add a user to the group
        //The other parameters are given emplty strings because they are not required
        web.SiteGroups["Test Group"].AddUser("abc\\user2", "", "", "");
    }
}

This is really simple.

Leave a comment if you have any queries

-Guruparan-