Wednesday, 28 November 2012

SharePoint designer 2010, send and receive Data using Query string

SharePoint Designer is Great tool to Create Web parts , and you can easily understand its code behind and very easily you can change it according to your need/requirement.

i have created 2 web parts and they are placed on different pages, I have define the Students in one web part and in Other i need Filter its courses.

  1. Create 2 Lists (Students, Courses), In courses i have used Student as lookup column.
  2. Open SharePoint designer and open specific site .
Create First Web Part (Sender)


Step 1:
Create Page in Site Pages Library. Click on Design mode ,                                                                
From Menu Choose Insert - > Data  View  -> Empty Data View -> Select Data source (Student)   
  
Step 2:
 From right Side choose ->Insert Selected Fields -> Multiple item View .


Insert Item to Empty Data Source

Select Columns




Step 3:
 Select the Design mode of Web Part and From menu select Options -> Add/Remove Columns -> and choose items that you want to display.

Step 4: 
Also Add Created Date Column -> we can modify it into Hyperlink in next.

Step 5: 
Now Select Created Column from Design view -> and Check its Code Behind. and Replace             "<xsl:valueof >" with Hyper Link <a href="courses.aspx?SID={@ID}"> View Course</a>  In this Link SID is Query string value.







Second Web Part (Query string Receiver page)

Step 1:
Now Repeat these Steps for second Web part , you don't need step 5 in it.

Step 2:
Select Web part from design Mode -> Go to options -> Filter -> Create Parameter ( select the item from drop down which you have set as lookup).  and suppose i have set Student:ID as Lookup. and then comparison (Select According) , In Value Select Create new Parameter, -> It will open new Dialoug Box, from where you have to give same paramerter Name that you have set in hyperlink in First webpart and 
select type as Query string from Parameter Source and Press OK.



Every thing is Done you can test these page , Browse Page 1 - click at View Courses link. 

Tuesday, 27 November 2012

Enable Developer Dashboard in SharePoint 2010

In SharePoint 2007, its very difficult to understand the performance or page delay, SharePoint 2010 offer new feature with the name of developer Dash Board, its very use-full to understand whats exactly going on.

using developer Dash Board you can view information such as

  • Thread execution time
  • Number, duration, call stack information and query text of each SQL Server query generated by the page
  • Number, duration, and call stack information of each WCF call
  • URL or timer job name
  • Current user
  • Execution start time
  • Any of the preceding statistics for code enclosed by SPMonitoredScope

How to Enable Developer Dash Board using PowerShell.
Developer Dash Board have 2 modes

  1. On (it Display on every page)
  2. OnDemand (it display information on demand , you can use icon along login user name.)
open sharepoint 2010 powershell and write below script in it. you can change the value of On and OnDemand from 3 line.



$contentService =[Microsoft.SharePoint.Administration.SPWebService]::ContentService
$dashboardSetting = $contentService.DeveloperDashboardSettings
$dashboardSetting.DisplayLevel =[Microsoft.SharePoint.Administration.SPDeveloperDashboardLevel]::On
$dashboardSetting.Update()

You can user icon to open Dash board:















Developer Dash board Will display at bottom of the page, which looks like as


Error in Excel service SharePoint The workbook cannot be opened.


I have start working on it,
Configure Excel services properly, Created library for Excel document, Documents are uploaded properly, but  i was unable to open the Excel file in Browser , also unable to chart control with excel sheet,

After Checking the log file i got following error in Log.

Result=Microsoft.Office.Excel.Server.CalculationServer.Proxy.ServerSessionException: The workbook cannot be opened.    
 at Microsoft.Office.Excel.Server.CalculationServer.Proxy.ServerSession.ExecuteWebMethodCore(WebMethodType webMethodType, WebMethodBehaviorAttribute webMethodBehavior, CommandParameter parameter, CoreWebMethod coreWebMethod)    
 at Microsoft.Office.Excel.Server.CalculationServer.Proxy.ServerSession.ExecuteWebMethod(WebMethodType webMethodType, WebMethodBehaviorAttribute webMethodBehavior, CommandParameter parameter, CoreWebMethod coreWebMethod)


I have tired many solutions that are given on different blogs but nothing is working for me.


Solution.
i delete my current Excel service and configured it again.  its start working.

Friday, 23 November 2012

How to use LINQ, SPMetal in Sharepoint 2010


What is LINQ and why it’s useful in LINQ
LINQ is Language integrated Query Language. It’s part of .Net framework, you can easily integrate this with SharePoint 2010. It’s used to Query on Data sources such as Object, Datasets, SQL, XML and other entities. LINQ provide access to sharepoint in TYPED Manner, you can easily access List columns name as property. As syntax is same as it is for .net development.
var items = from s in DataContext.Students
           select s;


SPMetal
SPMetal is tool provided by sharepoint , used to created entity model for sharepoint site objects. You can write these classes manually as well, but its very time consuming task. It will create partial class at specified location, you can simply add these classes in your project.
Simple CRUD operation using LINQ for SharePoint List
Step 1: Create List
Create a simple list in sharepoint site .i have created Custom List with the name of students(Title, firstname,lastname, Country).
Step 2:  Generate Entity model.
Open command line -> start -> type cmd in search box -> open Command Line.
Type CD C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN
This is path for SPMetal.exe
Now in command line type   SPMetal.exe /web: http://sp2010-sana /code: C:/MyEntities.cs
Note : just put your web url instead of  http://sp2010-sana
It will create entities classes for you. Go to given path in command to verify.
Step 3: Create Visual WebPart.
Open Visual studio 2010 and Create new sharepoint 2010 visual webpart project,
File -> New -> Project -> Sharepoint - >2010  -> Visual web part . Give its appropriate name and location and press OK.
 Visual webpart work as form solution so next you have to verify your site url and press ok.
 Visual studio load its project structure.
Now you have to add reference for LINQ.
Right Click on Project (Solution Explorer)  -> Add Reference -> Select Microsoft.Sharepoint.LINQ
In code Behind of Webpart, add following Namespaces
using System.Linq;
using Microsoft.SharePoint.Linq;
using Microsoft.SharePoint;


In visual web part  you can simple trag and drop control to perform your operation.
After creating form design you have to move in code behind . (.CS file of webpart)
I have  written these four methods to perform CRUD Operation

        #region CRUD Operation using LINQ
        /// <summary>
        /// Delete the student
        /// </summary>
        /// <param name="objTitle"></param>
        public void DeleteStudent(string objTitle)
        {
            try
            {
                using (MyEntitiesDataContext dc = new MyEntitiesDataContext(SPContext.Current.Site.Url))
                {
                    EntityList<StudentsItem> listItems = dc.GetList<StudentsItem>("Students");
                    var updateobj = (from c in listItems
                                     where c.Firstname == objTitle
                                     select c).First();
                        dc.Students.DeleteOnSubmit(updateobj);
                    //Submit the changes
                    dc.SubmitChanges();

                }

            }
            catch (Exception ex)
            {

                Response.Write(ex.Message);
            }
        }

        /// <summary>
        /// Insert Student
        /// </summary>
        public void InsertStudent()
        {
            try
            {

                using (MyEntitiesDataContext dc = new MyEntitiesDataContext("http://sp2010-sana/"))
                {
                    EntityList<StudentsItem> listItems = dc.GetList<StudentsItem>("Students");
                    StudentsItem objnew = new StudentsItem()
                    {
                        Firstname = txtFname.Text.Trim(),
                        Lastname = txtLname.Text.Trim(),

                        Country = Country.USA,
                        Title = txtTitle.Text.Trim()
                    };// Insert the new list item to the list
      dc.Students.InsertOnSubmit(objnew);
                    dc.SubmitChanges();
                }
            }
           
            catch (Exception ex)
            {
               
                throw;
            }
        }
        /// <summary>
        /// Update items
        /// </summary>
        /// <param name="objTitle"> title for the Item</param>
        public void UpdateStudent(string objTitle)
        {
            try
            {

                using (MyEntitiesDataContext dc = new MyEntitiesDataContext("http://sp2010-sana/"))
                {
                    EntityList<StudentsItem> listItems = dc.GetList<StudentsItem>("Students");
                    StudentsItem updateobj = (from c in listItems
                                    where c.Id == 4
                                    select c).First();
                                  updateobj.Lastname = "Item2";
                    updateobj.Firstname = "Item2";
                    txtLname.Text = updateobj.Id.ToString();
                
                    dc.Students.InsertOnSubmit(updateobj);
                    dc.SubmitChanges();
}

            }
            catch (Exception ex)
            {
                Response.Write(ex.Message + "</br>");
            }
        }


        #endregion


I have Created one Grid View to Show all the students. So in in Page Load I have just added data source to Gridview.  You can see one more method name as Register Events() , I have used it to register all events (such as I am using 2 buttons (btnsave and btndelete))
  protected void Page_Load(object sender, EventArgs e)
        {
            using (MyEntitiesDataContext dc = new MyEntitiesDataContext(SPContext.Current.Site.Url))
            {

                var items = from s in dc.Students
                            select s;

                GridView1.DataSource = items;
                GridView1.DataBind();
               
            }

            RegisterEvents();
        }

        
        public void RegisterEvents()
        {
            btnSave.Click += new EventHandler(btnSave_Click);
            btnDelete.Click += new EventHandler(btnDelete_Click);
        }

     
Visual Web part Designer Code,
<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="StudentdropDownUserControl.ascx.cs" Inherits="LINQ_Visual_Web_Part.StudentdropDown.StudentdropDownUserControl" %>

<table class="style1">
    <tr>
        <td>
            Title</td>
        <td>
            <asp:TextBox ID="txtTitle" runat="server"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            first Name</td>
        <td>
            <asp:TextBox ID="txtFname" runat="server" ></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            Last Name</td>
        <td>
            <asp:TextBox ID="txtLname" runat="server"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            Country</td>
        <td>
            <asp:DropDownList ID="DropDownList1" runat="server">
            </asp:DropDownList>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;</td>
        <td>
            <asp:Button ID="btnSave" runat="server" Text="Save" Width="123px" />
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;</td>
        <td>
            <asp:Button ID="btnDelete" runat="server" Text="Delete" />
        </td>
    </tr>
</table>


<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
    BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px"
    CellPadding="3" EnableModelValidation="True" ForeColor="Black"
    GridLines="Vertical" >
    <AlternatingRowStyle BackColor="#CCCCCC"  CssClass=”alternateItemStyle”/>
    <Columns>
        <asp:BoundField DataField="Title" HeaderText="Title" />
        <asp:BoundField DataField="firstname" HeaderText="First name" />
        <asp:BoundField DataField="Lastname" HeaderText="Last name" />
    </Columns>
    <FooterStyle BackColor="#CCCCCC" />
    <HeaderStyle BackColor="Black" CssClass=”headerStyle” Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
    <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
</asp:GridView>





Deploy to sharepoint.
Build the project to verify that you don’t have any syntax error.
If you have sharepoint on your Visual studio machine then you can simply
Right Click on Project -> Deploy. Otherwise select package option it will create .wsp solution file ,

Adding webpart in sharepoint
Go to any page (must have webpart zone option) -> Add Webpart -> Choose Custom Category -> your newly born webpart will be there, select this webpart. Now you can test functionality.y


You can Download Complete Here

Your comments are really appreciated and more helpful for me to writing more and in best way.

Thursday, 22 November 2012

Simple and Dynamic JQuery Slider For Sharepoint


Step 1
         Create One Picture Library to save image .(No extra columns are required)
         Create page in SharePoint designer.

Step 2

Apply master page from Menu for current page




Add Jquery reference as given below (these are online reference )
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://malsup.github.com/chili-1.7.pack.js"></script>
<script type="text/javascript" src="http://cloud.github.com/downloads/malsup/cycle/jquery.cycle.all.2.72.js"></script>

Or you can download these libraries, and add local SharePoint server path instead of online path


Step 3:
Add div to show images (Place this code in Content area)
<div id="ImageSlider" style="height:300px; width:500px">  </div>





Now Place the Below Code in below the References of Jquery.


<script>

function GetData(Picture)
{
//change 1    full path pointing to your picture library
var imageURL = "http://site url /pictures/";
//change 2   
var itemURL = "http://sp2010-sana/Banners/Forms/DispForm.aspx?ID";


$(Picture.responseXML).find("z\\:row").each(function() {
  var title = $(this).attr("ows_Title");
  var imageLink = imageURL+$(this).attr("ows_FileLeafRef").substring($(this).attr("ows_FileLeafRef").indexOf('#')+1);
  var itemLink = itemURL+$(this).attr("ows_ID");
  var Html ="<img width='500' height='300'  src='"+ imageLink +"'/>";

        $("#BannerSlider").append(Html);
    });

$('#BannerSlider').cycle({
    fx:    'scrollLeft',
    sync:  true,
    delay: -10000
 });
}
 function PlaySlideshow()
{
 var srvCAML = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'><soapenv:Body><GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'>";
//Change 3 ---  put you picture library name in Listname tag
 srvCAML+= "<listName>Your Picture Library name </listName><query></query><viewFields> <ViewFields><FieldRef Name='Title'/><FieldRef Name='ows_FileLeafRef'/></ViewFields> </viewFields></GetListItems></soapenv:Body></soapenv:Envelope>";

//Change 4  ---change site url
var srvlists ="http://site url/_vti_bin/lists.asmx";

    $.ajax({ url: srvlists,type: "POST", dataType: "xml",data: srvCAML,complete: GetData,contentType: "text/xml; charset=utf-8",       
   
    });
}
PlaySlideshow();
</script>


Now make 4 changes according to your SharePoint site.
I have comment in code 4 four changes.
After this save change and preview this in browser.
This is simplest way to run Slider in SharePoint.



Friday, 13 July 2012

Specified method is not supported. sharepoint 2010 (SP1)delete site


Specified method is not supported. SharePoint delete site
My SharePoint Server was working fine, I have install SharePoint 2010 SP1 on It, After that I am getting the Above error while I am deleting the site from Site Action - >  Site Settings -> Site Action -> Delete this Site. I am using Farm admin user, and ran Browser with Administrative privileges, 

This is Error come due Pre-Configure Site with Sp1, Site data Base is Create before Sp1 Installation on SharePoint server.
Solution:
You can use Following PowerShell Commands to Upgrade its Configuration Database.
Get Configuration databases for all Sites.

Upgrade Site Database Providing id in Above Result. Run the Upgrade-SpcontentDatabase 
To Confirm Type Y, It will Start Upgrade process and will Show progress in Percentage.

After that Delete the Site from Site Action - >  Site Settings -> Site Action -> Delete this Site


Thursday, 12 July 2012

Sharepoint designer 2010 , Create Custom List Forms With Asp.net Controls and Fields Validation


As SharePoint designer is no code solution for SharePoint, you can see there are list of all asp.net controls available in SharePoint designer,
I am looking to create new item Form using Custom asp.net controls
Step 1: Create List Named as “Contacts” (You can Use any Name) with following columns.
Title Single line of text
Address Multiple lines of text
E-Mail Single line of text
Step 2: Open SharePoint Site in SharePoint Designer
            Navigate to List and libraries; Select the List named as contacts.
            Select the List settings for Ribbon and then select List Form or you will find same option at
Right              
side in second group/panel Click New. And Give some appropriate name to page.
You can see below screen shot as well to follow the Steps
               
               
Step 3 : Edit page in advance mode

Now Delete the Email Address Field from Form ->

Now go to insert and select Asp.net Controls and Select Text Box Control.


Note its Id will be display and control is selected; now associate this control with SharePoint List Column.

After that Add asp.net regular Expression validation Control to validate the Email Address field.
Follow the same steps as Insert -> Asp.net -> Regular Expression Control.
Open its Properties Window or you can edit its properties in Source View. Properties to be set such as Control to Validate, Error Message, Set Focus, Regular expression etc. like I have select its email Address  Validation you can write you own by selecting Custom Option,
“{} “ these braces did not work in SharePoint , so you cannot use them in regular expression.

Now save it and Open it in browser.
Type invalid email address it will Show error message




Automatic Sharepoint 2010 Site Collection BackUP Script


You can Take Site collection backup Using SharePoint 2010 Central Administration.
Central Administration -> Backup And Restore -> Specify  Site Collection and path to save backup.
But Most simple way to Use Power Shell Command 

Backup-Spsite -identity  “SiteURL”  -Path “File Name With Path”.

this is Manual Process,  You can automate this Process using PowerShell and Windows Task Scheduler , This will automate your Back process.

Step 1: 
Open Note pad and Paste Below written Script in it , Also modify Function call According to your  Environment (SiteCollection Url, path and Initial/prefix of you FileName).

Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue
Function BackupSite([string]$SiteURL,[string]$path,[string]$BackUpInitial)
{
$today=(Get-Date  -Format dd-MMMM-yyyy-"'Time'"-hh-mm)
backup-Spsite -identity $SiteURL -Path $path\$BackUpInitial-$today.bak
}
#Function Call – Replace Parameter according to you requirements.
BackupSite "http://sp2010/" "C:\Backups" "SP2010"

Step2 : Save this File as ps1 Extension  (MyScript.ps1)

Step 3: Add this Script you Windows Task Scheduler.
            Start -> Administrative Tools -> Task Scheduler - > Create Task.
            Specify Task Name, Specify User to Run this Task in General Tab,
            Specify Trigger Time (to Automatic Trigger this Task)
Specify Action in Action Tab. select Action to Start Program from Dropdown, Write     
Program/Script “powershell.exe” Or you can select path from Browse Button.
            Add Argument s Write the PS1 File Name with path. 
You can read More details about windows task scheduler at technet Article  
You can Run this this Task Manually To test it, Select the Task, right Click and Click RUN.

Wednesday, 11 July 2012

SharePoint 2010 PowerShell Commands List

SharePoint 2010 PowerShell is very powerful Feature for SharePoint. It’s very easy and some time required for SharePoint administrator to work in PowerShell.
It’s very hard to remember all PowerShell command SharePoint.

Here is simplest way to get list of all command related to SharePoint .

That will show results in table format. 
get-command -PSSnapin "Microsoft.SharePoint.Powershell" | select name, definition | format-table 
That will show results in List format.  
get-command -PSSnapin "Microsoft.SharePoint.Powershell" | select name, definition | format-List 
you can save all Commands in Text File by adding -wrap > [path to save file] at end of above command
get-command -PSSnapin "Microsoft.SharePoint.Powershell" | select name, definition | format-List  > C:\Sharepointcmd.txt

Wednesday, 13 June 2012

How can I get Right Plan, Office 365?


As office 365 is enough flexible for Clients, Means you can use plan according to you needs?
It can be simple but you can choose Office 365 advisor tool to get most appropriate/recommended plan for your organization.  
Simple save your money by choosing right plan for your organization/your needs

Where and how you can use this tool
Simple Click Below
Advisortool (Get your Right Plan)
You will find link at Right bottom of the page, just Click on it’s, another popup screen will Open there,