Friday, August 16, 2013

How to read list items using REST in Sharepoint 2010


Here I am giving on simple example that will read data from a list using REST.
Earlier we need to use SPAPI for this task but we can do very easily with REST.

var queryUrl ="http://YourSitename/_vti_bin/ListData.svc/ListName";

$.ajax({
    url: queryUrl,
    accepts: {
        json: "application/json;odata=verbose"
    },
 dataType: "json",              //By Default it returns in xml formate
    method: "GET",
    success: onQuerySuccess,
    error: onQueryError
});

function onQuerySuccess(data) {
var i =parseInt(0);
    if (data) {
        $.each(data.d.results, function () {
            alert(data.d.results[i].Title);    // give your internal column name of list
i=parseInt(i)+parseInt(1);
        });
    }
}
function onQueryError(error) {
   alert("ee");
}


We can get any column’s value.
data.d.results[i].Title

Here “Title” is the name of column so you can change the column name and get your data.

Thanks



Wednesday, August 7, 2013

How to get attached file url in sharepoint

Hi Friends,
I was searching one solution that how can i have url of Attached item, but mostly i got hard coding
:(

mostly searched solution is like this
"/you Stie/List/Your list name/Attachments/" + item("ID").ToString() + "/" + obj.ToString
and this is really bad to use.
But now i have explored Sharepoint and get solution, and its very simpl.

Here is the solution.
 dim _url as string= item.Attachments.UrlPrefix.ToString + item.Attachments.Item(0).ToString

Explations:
1)
item.item.Attachments.UrlPrefix
it will return till id value in the form of url
2)
 item.Attachments.Item(0).ToString

This will return the item name that we need
by this solution we will have our url of Attached item


I hope this will helpful for you, If u are facing any problem regarding of this plz let me know through ur post

How to detect escape key press with javascript


Hi Frnds ...

I was using some code for escape key handle but it was working fine only in IE,  Not in Chrome. So i have stared doing some R&D and finally got solution :-)
And really it is working fine in all

<script type="text/javascript">
 document.onkeydown = function(evt) {
    evt = evt || window.event;
    if (evt.keyCode == 27) {
        alert("Escape");
    }
};
</scrip>

Dynamically Create CAML QUERY

 By using this code we can create a CAML Query at run time .
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
 Public Function topic_Wise_Collection(ByVal strin As ListItemCollection) As String
        Dim str As String = "<Where>"
        Dim firstLine As String = ""
        Dim starting As String = ""
        Dim midll As String = ""
        Dim i As Integer = 0
        For Each _item As ListItem In strin
            Dim _topic01 As String = _item.ToString
            If i = 0 Then
                firstLine += "<Or>"
                firstLine += "<Contains>"
                firstLine += "<FieldRef Name=" + "Topic0" + " />"
                firstLine += "<Value Type=" + "Text" + ">" + _topic01 + "</Value>"
                firstLine += "</Contains><Contains>"
                firstLine += "<FieldRef Name=" + "Topic0" + " />"
                firstLine += "<Value Type=" + "Text" + ">" + _topic01 + "</Value>"
                firstLine += "</Contains>"
                firstLine += "</Or>"
            Else
                Dim befor As String
                befor = "<Or><Contains><FieldRef Name=" + "Topic0" + " />"
                befor += "<Value Type=" + "Text" + ">" + _topic01 + "</Value>"
                befor += "</Contains>"
                midll = befor + midll
                firstLine += "</Or>"
            End If
            i = i + 1
        Next
        str += midll + firstLine + "</Where>"
        Return str
    End Function

Hot to get Current user name using SPAPI

 This is so simple just need to follow step in correct way
<-----Start------------------->
<script src="/SPAPI_Core.js"></script>
<script src="/SPAPI_Lists.js"></script>
<script src="/jquery-1.4.1.js"></script>
<script type="text/javascript">
$(function (){
 var nameOnly = getCurrentUserName();
 alert(nameOnly);
});
function getCurrentUserName(){
// put path of user information list
var lists = new SPAPI_Lists('path for User information list is');
// put the id of user information list
var items = lists.getListItems('888216C4-B998-4889-91C2-16D68127010A','','<Query><Where><Eq><FieldRef Name="ID"/><Value Type="Counter">'+ _spUserId +'</Value></Eq></Where></Query>','','');
 if (items.status == 200)
 {
 var rows = items.responseXML.getElementsByTagName('z:row');
  for (var i=0; i<rows.length; i++)
  {
    return rows[0].getAttribute('ows_Title');
   break;
  }
 }
 else
 {
  alert("Error in getting user");
 }
}
</script>
<-----End------------------->

If you are getting any error then check ur linked file path.

Thanks

How to work with SPGridView using Object Data Source.

To work with SPGridview you need to register
 <%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

Now we can start working with SPGridView. First will add SPGridView control on our aspx page.

<SharePoint:SPGridView runat="server" ID="SPGridView1"
 AutoGenerateColums="false"  PageSize="300" AllowPaging="true" AllowFiltering="true"
 AllowSorting="true"   AutoGenerateColumns="false"> </SharePoint:SPGridView>

<SharePoint:SPGridViewPager ID="SPGridViewPager1" runat="server" GridViewId="SPGridView1"></SharePoint:SPGridViewPager>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" />

You can see that I have added three control SPgridView, SPGridViewPager, and ObjectDatasource.
Mostly ppl don’t use objectdatasource in context of SPGridview but there may be a scenario that you need to use custom data source. Let me explain some part for you , suppose u need to get all items from Sharepoint list and then u alter some field and then need to show in spridview in this situation filtering and sorting will not work automatic and u will suffer lots, so in that situation we need to use this ObjectDataSource.
Now you need to write code on your vb file.
First we need to write code either on page load or CreateChildControls event. I am going to write on CreateChildControls so no need to handle postback.

Protected Overrides Sub CreateChildControls()
        Dim obj As New Foobar()
        ObjectDataSource1.TypeName = obj.GetType().AssemblyQualifiedName
        BuildGridColumns()
        ObjectDataSource1.SelectMethod = "getall"
        Me.SPGridView1.DataSourceID = "ObjectDataSource1"
        Me.SPGridView1.DataBind()
End Sub

In this i have create one object of Foobar class so we can give ObjectDataSource TypeName.
Next line for assigning TypeName of object. That means which type of data this ObjectDataSource going to store, since we are going to store Foobar type so I am assigning foobar assembly Qualified name.
Now next line is for creating columns in SPGRidview. So I have created one function that will create columns in SPGRidview.

Private Sub BuildGridColumns()
        Me.SPGridView1.Columns.Clear()
        Dim gridColumn3 As New SPBoundField With { _
           .DataField = "SNo", _
                           .HeaderText = "S/No", _
                           .SortExpression = "SNo" _
                       }
        Me.SPGridView1.Columns.Add(gridColumn3)
        Dim gridColumn4a As New SPBoundField With { _
                           .DataField = "Title", _
                           .HeaderText = "File Ref No", _
                           .SortExpression = "Title" _
                       }
        Me.SPGridView1.Columns.Add(gridColumn4a)
        Me.SPGridView1.FilterDataFields = "SNo,Title"
        Me.SPGridView1.FilteredDataSourcePropertyName = "FilterExpression"
        Me.SPGridView1.FilteredDataSourcePropertyFormat = "{1} Like'{0}'"
    End Sub

Now this function is creating two columns, and then adding to SPGridView.
 After that assigning Filter Data Fields so that filtering can be done. For that simply assigning 3 properties FilterDataFields, FilteredDataSourcePropertyName, .FilteredDataSourcePropertyFormat.
Note:-Here no need to change anything in your code for filtering just need to give same value and it will work(Last 2 line).
Come back to CreateChildControls sub. Next line is SelectMethod=”getalll”. Fon now i am skiping this , will explain after explaing few more things
.
Next line is assigning DatasourceId of SPGirdview. For this putting objcetDatasource id as string.
After that we bind SPGridview to data source.
Now come to the “getall” this is a function of foobar class. Function will return datasource as Datatable. Now check our class Foobar.

Public Class Foobar
    Private _SNo As String
    Public Property SNo() As String
        Get
            Return _SNo
        End Get
        Set(ByVal value As String)
            _SNo = value
        End Set
    End Property
    Private _Title As String
    Public Property Title() As String
        Get
            Return _Title
        End Get
        Set(ByVal value As String)
            _Title = value
        End Set
    End Property
    Public Function getall() As DataTable
        Dim _site As SPSite = SPContext.Current.Site
        Dim result As New System.Collections.Generic.List(Of Foobar)
        Using _web As SPWeb = _site.OpenWeb("")
            Dim _list As SPList = _web.Lists("")
            Dim spList As SPListItemCollection = _list.Items
            For Each _it In spList
                Dim _new As New Foobar
                _new.SNo = _it("ID")
                _new.Title = _it("Title")
                result.Add(_new)
            Next
        End Using
        Dim datatable As DataTable = BuildDataTable(Of Foobar)(result)
        Dim ListAsDataView As DataView = datatable.DefaultView
        Return datatable
    End Function
 Public Function BuildDataTable(Of T)(ByVal lst As System.Collections.Generic.List(Of T)) As DataTable
        'create DataTable Structure
        Dim tbl As DataTable = CreateTable(Of T)()
        Dim entType As Type = GetType(T)
        Dim properties As PropertyDescriptorCollection = TypeDescriptor.GetProperties(entType)
        'get the list item and add into the list
        For Each item As T In lst
            Dim row As DataRow = tbl.NewRow()
            For Each prop As PropertyDescriptor In properties
                row(prop.Name) = prop.GetValue(item)
            Next
            tbl.Rows.Add(row)
        Next
        Return tbl
    End Function
    Private Function CreateTable(Of T)() As DataTable
        'T –> ClassName
        Dim entType As Type = GetType(T)
        'set the datatable name as class name
        Dim tbl As New DataTable(entType.Name)
        'get the property list
        Dim properties As PropertyDescriptorCollection = TypeDescriptor.GetProperties(entType)
        For Each prop As PropertyDescriptor In properties
            'add property as column
            tbl.Columns.Add(prop.Name, prop.PropertyType)
        Next
        Return tbl
    End Function

If you will go through this class you will find there are 3 functions and two properties you can add as much as property you want. “getall” function is responsible for fetching data from SharePoint list and assigning to Foobar class.

After that inside “getall” we are calling BuildDataTable() function. In this function we are passing list collection(result) of Foobar and Type of list that is Foobar (Dim datatable As DataTable = BuildDataTable(Of Foobar)(result))
In this function you can see that we are calling one other function(CreateTable) that create columns for Table. Once table and columns has created we can assign value to each columns.
After that will have one table that will keep information of one list.
Why we are using table and why we are sending all data inform of table?
If you are not able to find this answer post here I will try to solve once again

Thanks and Regards,
Shailendra Kumar Singh

How to start with SPAPI in Sharepoint


How to use SPAPI in Sharepoint

Really this is a great api of Javascript for Sharepoint
Lets start ..............

First we need two SPAPI file and one Jquery file
 1) SPAPI_Core.js
 2) SPAPI_Lists.js
 3) jquery-1.5.1.js

and also Jquery file that you can get very easily. These three file you need to add in your file after that you can work. I m just giving one example how to get data from list and display through alert box.

<------Start----------------->
<html>
<head>
 <script src="jquery-1.5.1.js"></script>
<script src="SPAPI_Lists.js"></script>
<script src="SPAPI_Core.js"></script>
<script type="text/javascript">
$(function (){
var lists = new SPAPI_Lists('ListLocation');
var items = lists.getListItems('ListName');
if (items.status == 200)
 {
   var rows = items.responseXML.getElementsByTagName('z:row'); // Get only list rows
    for (var i=0; i<rows.length; i++)
    {
         var newid =rows[i].getAttribute('ows_ID');
            alert(newid);
      //List's field names are prefixed with 'ows_' when converted
   }
 }
 else
 {
           alert('There was an error: ' + items.statusText);
 }
});

</script>
</head>
<body>
   <div>
       <p>
             Change path, list name, fields name and then it will work else give u error.......!
       </p>
   </div>
</body>
</html>

<-------------End------------>

Working with CollapsiblePanelExtender

I hope it would be use full for beginner. It is very simple and effective control of ajax.
Let Start with Collapsible Panel Extender.
First register ajax assembly in your page like I have added below.
 
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit"
TagPrefix="ajaxToolkit" %>

Second step is we need to add one “ScriptManager” in our page.
 It would be only one, means if it has been added in master page then we don’t need to add in our page or user control.

 <asp:ScriptManager
       runat="server" ID="script1" >
</asp:ScriptManager> 

Now from here we are adding our Collapsible panel extender, like below i have added in my page.

    <ajaxToolkit:CollapsiblePanelExtender ID="CollapsiblePanelExtender1"
       runat="server"
       TargetControlID="PannelFieldsList"
       ExpandControlID="PanelHiddenFieldsList"
       Collapsed="true"
       CollapseControlID="PanelHiddenFieldsList">
    </ajaxToolkit:CollapsiblePanelExtender> 

Now here we need some explanations , so I am giving one by one
ID: - This is the id of collapsible panel extender by which we can identify our control.
TargetControlID:-  We give id of that panel which we want to collapsible . 
                                      like I have given “
PannelFieldsList”.
ExpandControlID:- We give id of control by which clicking we can see target. Like I have given id “PanelHiddenFieldsList” so clicking on this id I can see target.
Collapsed:-  we can choose one option collapsed or not . If we give value as true then it will be hidden at load time
 CollapseControlID:-  we give the id of that control by which clicking target control collapse . Because I want to collapse target control on click on same control so both having same control id.
Now bellow I have code for showing magic of collapsible panel
<table >   
   <tr>
      <td align="left" valign="top" colspan="1">
            <asp:Panel ID="PanelHiddenFieldsList" runat="server">
                <div>
                    Click here
                </div>
            </asp:Panel>
        </td>
        <td align="left" valign="top" >
           <asp:Panel ID="PannelFieldsList" runat="server" Visible="true">
              <asp:CheckBoxList
                     ID="CheckBoxListFields"
                     runat="server"                
                     BorderStyle="Solid" 
                     BorderColor="Blue" 
                     BorderWidth="1px">
               <asp:ListItem >Solid</asp:ListItem>
                    <asp:ListItem >Dotted</asp:ListItem>
                    <asp:ListItem >Double</asp:ListItem>

                </asp:CheckBoxList>
                <asp:Button ID="ButtonSaveSetting" runat="server"
                  Text="SaveSetting" Width="96px" />
            </asp:Panel>
        </td>  
</tr>
</table>

How to hide ContentPlaceHolder by any user control

Hi,
Sometime we need to work with ContentPlaceHolder that is present in our master page, and we have to edit that ContentPlaceHolder by one user control .
So problem is that "how i can access master page content in my usercontrol ? " :-( .
When i had this situation i was full tension but finally i got solution and it was easy.
But there is some points which i should share with you. Always find parent content place holder then go to child like hierarchy. So you will not get error "Null reffrence".
Suppose you have a one ContenPlaceHolder that has ID "footerPrintHide" . So you can find that ContentPlaceHolder like this
 \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Dim xx As ContentPlaceHolder =
                               CType(Me.Page.Master.FindControl("footerPrintHide"),  ContentPlaceHolder)
                xx.Visible = False
 But this should be parent ContentPlaceholder mean there is no other contetplaceholder holding this one
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Some time we do required to find control inside the ContentPlaceHolder. So for this first we will find ContentPlaceHolder then using that reference we can find child control .
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Dim xx As ContentPlaceHolder =
                               CType(Me.Page.Master.FindControl("footerPrintHide"),  ContentPlaceHolder)
               xx.FindControl("printHideDiv").Visible = False
And this will not give you "null reference" error.

Thanks and regards
Shailendra singh

How to Hide Ribbon in Sharepoint 2010


It may be your Boss ask to hide sharepoint Ribbon and you dont have any idea about that :(
So you are in big trouble. But no need to worry here is the solution.
First what is Ribbon in sharepoint?
The place where we find option to Site Setting is Called Ribbon and that is enclosed  in one Div called Ribbon.







This is the Ribbon in SharePoint.
Now we need to hide this, it comes under one div so if we hide that div it will be hidden automatically.
Then question is how to find that div.
Answer is that in every Sharepoint master page it comes at same div that is "s4-ribbonrow".

So you need to hide this div only, here is solutions.

 <div id=”s4-ribbonrow” class=”s4-pr s4-ribbonrowhidetitle”>
    <!--- this is the div where ribbone content is present...-->
 </div>
  <style type="text/css">
     <!-- this is style which we use for hide the content it will go to master page or ur css file --->
     #s4-ribbonrow{ display:none; }
   </style>
If you face any problem regarding of this post let me know i will try to solve that

Tuesday, August 6, 2013

How to read file(iCal) from Document Library list in Sharepoint 2010

Here i am trying to give an example to read iCal file which had uploaded in one document library.

  Dim _listFile As SPList = web.Lists("Your Document Library")
  Dim _listItemFiles As SPListItemCollection = _listFile.Items


    For Each _item In _listItemFiles
Dim _spFile As SPFile = _item.File

Dim sr As New StreamReader(_spFile.OpenBinaryStream())

Dim ical As String = sr.ReadToEnd()
            Dim delim As Char() = {ControlChars.Lf}
            Dim lines As String() = ical.Split(delim)

   For i As Integer = 0 To lines.Length - 1
              If lines(i).Contains("BEGIN:VEVENT") Then
Dim eventData As String() = New String(11) {}
                   For j As Integer = 0 To 10
                     Dim splt As String() = lines(i + j + 1).Split(":")
                        If splt.Length > 1 Then
                          eventData(j) = splt(1).ToString()
                        End If
                   Next
  Dim strDate As String = eventData(0).ToString().Trim() 'start Date
                Dim endDate As String = eventData(1).ToString().Trim() 'end Date
                Dim title As String = eventData(10).ToString() 'Title
                strDate = strDate.Replace(vbCr, "")
                Dim format As String
                Dim result As DateTime
                Dim lastDate As DateTime
                Dim provider As CultureInfo = CultureInfo.InvariantCulture
                format = "yyyyMMdd"
                result = DateTime.ParseExact(strDate, format, provider)
                lastDate = DateTime.ParseExact(endDate, format, provider)
              End If
   Next
    Next
          

Friday, August 2, 2013

How to insert listitem in a folder in sharepoint 2010




  Using websp As SPWeb = Commonn.getWeb
                Dim List As SPList
                List = websp.Lists("yourListName")
                Dim _folder As SPFolder = List.RootFolder.SubFolders("YourFolderName")
                Dim _item as SPListItem=List.Items.Add(_folder.ServerRelativeUrl, SPFileSystemObjectType.File)
 _item("Title") = "your data as string"
  -------------------------------------------------
_item.Update()
  End Using  

Thursday, August 1, 2013

How to upload image in Sharepoint Document using vb.net

Hi Frnds,
Some time we need to upload one image in document library.
So i am uploading one -one image for each page and giving name for image is page name so it would be unique.
This is being stored in one document library.

  Dim spSite As SPSite = New SPSite("yoursite url")
            Dim _web As SPWeb = spSite.OpenWeb()
            Dim slist As SPList = _web.Lists("Content Images")
            Dim sPath As String = System.Web.HttpContext.Current.Request.Url.AbsolutePath
            Dim oInfo As System.IO.FileInfo = New System.IO.FileInfo(sPath)
            Dim sRet As String = HttpUtility.UrlDecode(oInfo.Name)
            Dim imageName As String = sRet.Substring(0, sRet.LastIndexOf("."))
            If FileUploadAttach.HasFile Then
                Dim fileExtension As String = FileUploadAttach.FileName.ToString.Substring(FileUploadAttach.FileName.ToString.LastIndexOf("."))

                imageName = imageName + fileExtension

                Dim destfile As SPFile = slist.RootFolder.Files.Add(slist.RootFolder.Url + "/" + imageName, FileUploadAttach.FileBytes, True)

                Dim item As SPListItem = destfile.Item
                item("Title") = FileUploadAttach.FileName.ToString
                item.Update()
            End If

How to get attached file url in sharepoint

Hi Friends,

I was searching one solution like "how can i have url of Attached item ?", but mostly i got hard coding
:(

mostly searched solution is like this

"/you Stie/List/Your list name/Attachments/" + item("ID").ToString() + "/" + obj.ToString

and this is really bad to use.
But now i have explored Sharepoint and get solution, and its very simpl.


Here is the solution.
 dim _url as string= item.Attachments.UrlPrefix.ToString + item.Attachments.Item(0).ToString

1) item.item.Attachments.UrlPrefix
it will return till id value in the form of url

2) item.Attachments.Item(0).ToString


This will return the item name that we need by this solution we will have our url of Attached item

I hope this will helpful for you, If u are facing any problem regarding of this plz let me know through ur post

How to Check query String is exist or not


Imports System.Collections.Specialized

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim n As NameValueCollection = Request.QueryString
' See if any query string exists
 If n.HasKeys() Then
            Dim k As String = n.GetKey(0)
            Dim v As String = n.[Get](0)
            Response.Write(v)
            Response.Write(k)
 End If
End Sub

How to identify Browser using Javascript

navigator.userAgent 

it will give the client browser information and accornding to that we can identify the browser.
Let see an example, like if we want to know is this browser Chrome or not then we can
use this conditions..

 if(navigator.userAgent.toLowerCase().indexOf('chrome')>-1)
{
alert("it is chrome");
}
else
{
alert("it is not Chrome");
}


Thanks

How to Call Javascript function inside any event of servre control like button click

It is simple just need to use some property of page, like i am using in my example. With this example i am also trying to show u how can we write Button click on ASPX page that called inline code.


<html>
<head runat="server">
    <title></title>
    <script type="text/javascript" >

        function hello() {
            alert("hello");
             }

    </script>
</head>
<body>

<script language="c#" runat="server" >

    protected void Button1_Click(object sender, EventArgs e)
    {
        TextBox1.Text = "Jatin Don";
        Page.ClientScript.RegisterStartupScript(this.GetType(), "javascript", "hello()", true);
        
    }
 </script>

    <form id="form1" runat="server">
    <div>

    </div>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button"/>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </form>
</body>
</html>

How to send email using Javascript....


Simple and very usefull

function sendMail() {
     var link  = 'mailto:?subject=You can insert subject here&body=';
     var curntLoc=window.location.href;
     link +=escape(curntLoc);
  window.location.href = link;
   // window.location.href = link;
}