Public Function MoveListItemsSiteToSite(sourceSiteURL As String,sourceList As String, destinationSiteURL As String, destinationList As String, retainMeta As Boolean) As Boolean Using sourceSite As New SPSite(sourceSiteURL) Using sourceWeb As SPWeb = sourceSite.OpenWeb() sourceWeb.AllowUnsafeUpdates = True ' Get your source library Dim source As SPList = sourceWeb.Lists(sourceList) ' Get the collection of items to move, use source.GetItems(SPQuery) if you want a subset Dim items As SPListItemCollection = source.Items Dim fileCount As Integer = 0 Using destSite = New SPSite(destinationSiteURL) Using destinationWeb = destSite.OpenWeb() destinationWeb.AllowUnsafeUpdates = True ' get destination library Dim destination As SPList = destinationWeb.Lists(destinationList) ' Get the root folder of the destination we'll use this to add the files Dim destinationFolder As SPFolder = destinationWeb.GetFolder(destination.RootFolder.Url) ' Now to move the files and the metadata For Each item As SPListItem In items 'Get the file associated with the item Dim file As SPFile = item.File ' Create a new file in the destination library with the same properties Dim newFile As SPFile = destinationFolder.Files.Add(destinationFolder.Url + "/" + file.Name, file.OpenBinary(), file.Properties, True) If retainMeta Then Dim newItem As SPListItem = newFile.Item WriteFileMetaDataFiletoFile(item, newItem) End If file.Delete() fileCount += 1 Next destinationWeb.AllowUnsafeUpdates = False End Using End Using sourceWeb.AllowUnsafeUpdates = False Return True End Using End Using End Function Public Shared Sub WriteFileMetaDataFiletoFile(sourceItem As SPListItem, destinationItem As SPListItem) destinationItem("Editor") = sourceItem("Editor") destinationItem("Modified") = sourceItem("Modified") destinationItem("Modified By") = sourceItem("Modified By") destinationItem("Author") = sourceItem("Author") destinationItem("Created") = sourceItem("Created") destinationItem("Created By") = sourceItem("Created By") destinationItem.UpdateOverwriteVersion() End Sub
Thursday, 8 November 2012
How to copy files between two SiteCollection
Friday, 26 October 2012
find checked radio button throug jQuery
$("#_chkbox").change(function () {
var items = $(".childCheckBox").find("input");
if ($('#_chkbox').is(':checked') == false) {
for (i = 0; i < items.length; i++) {
if (items[i].type == "checkbox") {
items[i].checked = false;
}
}
}
if ($('#_chkbox').is(':checked') == true) {
for (i = 0; i < items.length; i++) {
if (items[i].type == "checkbox") {
items[i].checked = true;
}
}
}
});
var items = $(".childCheckBox").find("input");
if ($('#_chkbox').is(':checked') == false) {
for (i = 0; i < items.length; i++) {
if (items[i].type == "checkbox") {
items[i].checked = false;
}
}
}
if ($('#_chkbox').is(':checked') == true) {
for (i = 0; i < items.length; i++) {
if (items[i].type == "checkbox") {
items[i].checked = true;
}
}
}
});
Wednesday, 3 October 2012
Generate CSV File in ASP.Net
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Response.Clear()
Response.ContentType = "text/csv"
Response.AppendHeader("Content-Disposition", String.Format("attachment; filename={0}.csv", DateTime.Now))
Dim _web As SPWeb = New SPSite(SPContext.Current.Site.Url).OpenWeb()
Dim _list As SPList = _web.Lists("List Name")
Dim _items As SPListItemCollection = _list.Items
For Each _item As SPListItem In _items
Response.Write(_item("Title") + "," + CStr(_item("ID")) + "," + System.Environment.NewLine)
Next
Context.Response.End()
End Sub
Wednesday, 26 September 2012
How to check id of clicked button
Hi Frnds,
Today i m trying to share with you one interesting things... like how can we find "who is responsible for postback ?"
very easily w to catch target controls who fired postback event.
Take a look of this code.
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
MyBase.OnLoad(e)
If Page.Request.Params("__EVENTTARGET") = btnClikOk.UniqueID Then
txtResult.Text = "Ok Button has clicked"
End If
If Page.Request.Params("__EVENTTARGET") = Button1.UniqueID Then
txtResult.Text = "Cancel button has clicked"
End If
End Sub
Page.Request.Params("__EVENTTARGET") this one will return target control ID and by condition checking you can catch Control.
Don't you think this is very simple ?
Today i m trying to share with you one interesting things... like how can we find "who is responsible for postback ?"
very easily w to catch target controls who fired postback event.
Take a look of this code.
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
MyBase.OnLoad(e)
If Page.Request.Params("__EVENTTARGET") = btnClikOk.UniqueID Then
txtResult.Text = "Ok Button has clicked"
End If
If Page.Request.Params("__EVENTTARGET") = Button1.UniqueID Then
txtResult.Text = "Cancel button has clicked"
End If
End Sub
Page.Request.Params("__EVENTTARGET") this one will return target control ID and by condition checking you can catch Control.
Don't you think this is very simple ?
Friday, 21 September 2012
Modal Dailog Box In SharePoint
Modal dialog play very important role to improve the user experience by reducing the number of postbacks. So, SharePoint 2010 comes up with in-build API to show modal dialog to improve the user experience. Here, I will explain you How to integrate SharePoint 2010 modal dialog with the application and some real time problems and their solutions. Before I go on and provide you with the details, Let us see some of the features that this new Modal Dialog provides.
Functionality provided by Modal Dialog: -
- Display HTML content in Modal Dialog
- Display external url (e.g. http://www.google.com) or any application page of SharePoint in the form of an iframe
- Show/Hide Close button
- Show/Hide Maximize button
Mentioned below are the steps to integrate a modal dialog in the SharePoint 2010:
Examples:
a. Sample code to show HTML content in the SharePoint 2010 modal dialog:
HTML code
b. Sample code to open a web page or application page in the modal dialog:
JavaScript code
Mentioned below are real time scenarios, you may encounter while using out of box modal dialog of SharePoint 2010 :-
1. Scenario: If page is too long and with the movement of vertical scrollbar, modal popup also move with the scrollbar. Ideally position of modal dialog should be fix.
Solution: Put mentioned below CSS class in you page:
Solution: Use following code- ExecuteOrDelayUntilScriptLoaded(<showModelMethodName>, "sp.js");
This method be make sure that js method showModalDialog is not called till sp.js is fully loaded.
3. Scenario: Sometime we need to close popup from server side and also parent window refresh is required after saving modal dialog data in the SharePoint.
Solution: Mentioned below is the sample code to implement above requirement-
4. Scenario: After closing modal dialog, all controls disappear from the page.
Solution: If you assign HTML element id like we have done in our first example, you might encounter this issue, we should set copy of modal data instead of assigning ID. See sample code below:
Functionality provided by Modal Dialog: -
- Display HTML content in Modal Dialog
- Display external url (e.g. http://www.google.com) or any application page of SharePoint in the form of an iframe
- Show/Hide Close button
- Show/Hide Maximize button
Mentioned below are the steps to integrate a modal dialog in the SharePoint 2010:
- The JavaScript files for the ECMAScript Object Model (SP.js, SP.Core.js, SP.Ribbon.js, and SP.Runtime.js ) are installed in the %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\LAYOUTS directory. We need to add these JavaScript files in the page.
- To open a dialog we need to use the 'SP.UI.ModalDialog.showModalDialog' method from the ECMAScript Client Object model and we can pass following parameters as per requirement:
- width: Set the width of the modal dialog
- height: Set the height of the modal dialog
- html: the ID HTML control or HTML content to be displayed in modal dialog
- url: Page url or relative path
- dialogReturnValueCallback: In case we want some code to run after the dialog is closed, set JavaScript method name
- allowMaximize: Set to true or false to show hide this option.
- showClose: Set to true or false to show or hide the close button
Examples:
a. Sample code to show HTML content in the SharePoint 2010 modal dialog:
HTML code
// Modal Dialog HTML content
<div id="divModalDialogContent">
Hello World!
<input type="button" value="OK"onclick="SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, 'Ok clicked'); return false;"
class="ms-ButtonHeightWidth" />
<input type="button" value="Cancel"onclick="SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, 'Cancel clicked'); return false;"
class="ms-ButtonHeightWidth" />
</div>
|
JavaScript Code
<script type="text/javascript">
// Call openDialog method on button click or on page load
function openDialog() {
var options = {
html: divModalDialogContent, // ID of the HTML tag
// or HTML content to be displayed in modal dialog
width: 600,
height: 300,
title: "My First Modal Dialog",
dialogReturnValueCallback: dialogCallbackMethod, // custom callback function
allowMaximize: true,
showClose: true
};
SP.UI.ModalDialog.showModalDialog(options);
}
//Results displayed if 'OK' or 'Cancel' button is clicked if the html content has 'OK' and 'Cancel' buttons
function onDialogClose(dialogResult, returnValue) {
if (dialogResult == SP.UI.DialogResult.OK) {
alert('Ok!');
}
if (dialogResult == SP.UI.DialogResult.cancel) {
alert('Cancel');
}
}
// Custom callback function after the dialog is closed
function dialogCallbackMethod() {
alert('Callback method of modal dialog!');
}
</script>
|
JavaScript code
<script type="text/javascript">
function openDialog() {
var options = {
url: "<Page Url>",
width: 600,
height: 300,
title: "My First Modal Dialog",
};
SP.UI.ModalDialog.showModalDialog(options);
}
</script>
|
Mentioned below are real time scenarios, you may encounter while using out of box modal dialog of SharePoint 2010 :-
1. Scenario: If page is too long and with the movement of vertical scrollbar, modal popup also move with the scrollbar. Ideally position of modal dialog should be fix.
Solution: Put mentioned below CSS class in you page:
.ms-dlgContent
{
position: fixed!important;
}
2. Scenario: Display modal popup on page load depending. Sometimes the page don't show modal dialog and a JavaScript error message comes (error: showModalDialog does not exist in SP.UI.ModalDialog).Solution: Use following code- ExecuteOrDelayUntilScriptLoaded(<showModelMethodName>, "sp.js");
This method be make sure that js method showModalDialog is not called till sp.js is fully loaded.
3. Scenario: Sometime we need to close popup from server side and also parent window refresh is required after saving modal dialog data in the SharePoint.
Solution: Mentioned below is the sample code to implement above requirement-
a. Check current page is popup page or not
{
// Code
}
OR
//Layout pages you can ensure byquery string
if(Request.QueryString["IsDlg"]=="1")
{
//code
}
|
b. To close popup use mentioned below JavaScript code:
<script type="text/javascript">
//Close popup on cancel button click
function CloseForm() {
window.frameElement.cancelPopUp();
return false;
}
//Commit/Refresh parent window on save button click
function SaveForm() {
window.frameElement.commitPopup();
return false;
}
</script>
|
c. use following server side code to close or save modal dialog:
//Put following code in the button click event, if update panel is not present in the page
ClientScript.RegisterClientScriptBlock(this.GetType(), Guid.NewGuid().ToString(),"CloseForm()", true);
OR
// Put following code in the button click event, if update panel is present in the page
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), Guid.NewGuid().ToString(),"CloseForm()", true);
|
4. Scenario: After closing modal dialog, all controls disappear from the page.
Solution: If you assign HTML element id like we have done in our first example, you might encounter this issue, we should set copy of modal data instead of assigning ID. See sample code below:
<script type="text/javascript">
//Pass copy of HTML content instead of content control ID
function openDialog() {
var cloneModalContent = document.createElement('div');
cloneModalContent.innerHTML = document.getElementById('divModalDialogContent').innerHTML;
var options = {
html: cloneModalContent, //html content to be displayed in modal dialog
width: 600,
height: 300,
title: "My First Modal Dialog",
dialogReturnValueCallback: customOnDialogClose, //custom callback function
allowMaximize: true,
showClose: true
};
SP.UI.ModalDialog.showModalDialog(options);
}
</script>
|
Thursday, 20 September 2012
Find the list item attachment url using SPAPI
Webmasters Earn Money Here!
Find the url of the attachments
-------------------------------------------------
function getattachment(id)
{
var lists = new SPAPI_Lists('http://yoursite/Announcements');
var items = lists.getAttachmentCollection("Announcements",id);
if (items.status == 200){
var rows = items.responseXML.getElementsByTagName('Attachment');
if (rows.length>0){
var str="";
for (var i=0; i<rows.length; i++){
alert($(rows[i]).text());
}
}
else
{
return "/Announcements/Lists/Announcements/DispForm.aspx?ID="+id;
}
}
}
//Here my site is 'http://yoursite/Announcements' and my list name is "Announcements" and id=ID of the item
know wheather the item has any attachment or not
-------------------------------------------------------------------------
function list_itms(itemid)
{
var lists = new SPAPI_Lists('http://yoursite/Announcements');
var items = lists.getListItems('Announcements');
if (items.status == 200)
{
var rows = items.responseXML.getElementsByTagName('z:row'); // Get only list rows
for (var i=0; i<rows.length; i++)
{
if (itemid == ows_ID){
var newid =rows[i].getAttribute('ows_Attachments');
alert(newid);
}
}
}
}
//The above code is to know wheather the item has any attachment or not
//Here my site is 'http://yoursite/Announcements' and my list name is "Announcements" and id=ID of the item
-------------------------------------------------
function getattachment(id)
{
var lists = new SPAPI_Lists('http://yoursite/Announcements');
var items = lists.getAttachmentCollection("Announcements",id);
if (items.status == 200){
var rows = items.responseXML.getElementsByTagName('Attachment');
if (rows.length>0){
var str="";
for (var i=0; i<rows.length; i++){
alert($(rows[i]).text());
}
}
else
{
return "/Announcements/Lists/Announcements/DispForm.aspx?ID="+id;
}
}
}
//Here my site is 'http://yoursite/Announcements' and my list name is "Announcements" and id=ID of the item
know wheather the item has any attachment or not
-------------------------------------------------------------------------
function list_itms(itemid)
{
var lists = new SPAPI_Lists('http://yoursite/Announcements');
var items = lists.getListItems('Announcements');
if (items.status == 200)
{
var rows = items.responseXML.getElementsByTagName('z:row'); // Get only list rows
for (var i=0; i<rows.length; i++)
{
if (itemid == ows_ID){
var newid =rows[i].getAttribute('ows_Attachments');
alert(newid);
}
}
}
}
//The above code is to know wheather the item has any attachment or not
//Here my site is 'http://yoursite/Announcements' and my list name is "Announcements" and id=ID of the item
Thursday, 13 September 2012
How to create list Programmatically/VB.NET
This time i have created one list using VB.Net code
For this one i have created on function and passing one Foobar list that containg information that i need to upload in list .
In this function i m checking that if list is there then delete it and create new one .
Public Function GetSplist(ByVal ds As Generic.List(Of Foobar)) As SPList
Dim web As SPWeb = SPContext.Current.Web
web.AllowUnsafeUpdates = True
'creating one object of splist with nothing value bcz this has no constractur
Dim newList As SPList = Nothing
Try
If Not IsNothing(web.Lists("TempNewList")) Then
Dim mylist As SPList = web.Lists("TempNewList")
mylist.Delete()
web.Update()
End If
Catch ex As Exception
End Try
'Here i am creating one list guid
Dim newListGuid As Guid = web.Lists.Add("TempNewList", "This is my temp list, it will be removed when used", SPListTemplateType.GenericList)
newList = web.Lists(newListGuid)
If Not IsNothing(newList) Then
newList.Fields.Add("SNo", SPFieldType.Text, False)
newList.Fields.Add("FileRefNo", SPFieldType.Text, False)
newList.Fields.Add("NavUrl", SPFieldType.Text, False)
End If
newList.Update()
Dim newItem As SPListItem = Nothing
For Each _item As Foobar In ds
newItem = newList.Items.Add()
newItem("SNo") = _item.SNo
newItem("FileRefNo") = _item.FileRefNo
newItem("NavUrl") = _item.NavUrl
newItem.Update()
Next
web.AllowUnsafeUpdates = False
Dim _mylist As SPList = newList
Return _mylist
End Function
Thanks And Regards,
Shailendra Kumar Singh
For this one i have created on function and passing one Foobar list that containg information that i need to upload in list .
In this function i m checking that if list is there then delete it and create new one .
Public Function GetSplist(ByVal ds As Generic.List(Of Foobar)) As SPList
Dim web As SPWeb = SPContext.Current.Web
web.AllowUnsafeUpdates = True
'creating one object of splist with nothing value bcz this has no constractur
Dim newList As SPList = Nothing
Try
If Not IsNothing(web.Lists("TempNewList")) Then
Dim mylist As SPList = web.Lists("TempNewList")
mylist.Delete()
web.Update()
End If
Catch ex As Exception
End Try
'Here i am creating one list guid
Dim newListGuid As Guid = web.Lists.Add("TempNewList", "This is my temp list, it will be removed when used", SPListTemplateType.GenericList)
newList = web.Lists(newListGuid)
If Not IsNothing(newList) Then
newList.Fields.Add("SNo", SPFieldType.Text, False)
newList.Fields.Add("FileRefNo", SPFieldType.Text, False)
newList.Fields.Add("NavUrl", SPFieldType.Text, False)
End If
newList.Update()
Dim newItem As SPListItem = Nothing
For Each _item As Foobar In ds
newItem = newList.Items.Add()
newItem("SNo") = _item.SNo
newItem("FileRefNo") = _item.FileRefNo
newItem("NavUrl") = _item.NavUrl
newItem.Update()
Next
web.AllowUnsafeUpdates = False
Dim _mylist As SPList = newList
Return _mylist
End Function
Thanks And Regards,
Shailendra Kumar Singh
Tuesday, 11 September 2012
How to find web parts through vb.net
Hi Friedns,
Few days ago i was asked to hide Advaced search web part through one user control's button click.
i was socked how could i find that web parts, and really i wasted too much time to doing this simple task,
bcz i didnt know how to do :(
But we should not give up till get solution :D
and i finaly get solution.
There was a webpart zone in that i added advanced search web part and my Usercontrol through smartPartwithajax features.
so both are in same webpart zone.
Now this is simpl code that we use to find advanceSearchBox
Public Sub setTab()
Dim _controls As ControlCollection = Me.Parent.Parent.Controls
For Each _cde As Control In _controls
If _cde.GetType().ToString = "Microsoft.Office.Server.Search.WebControls.AdvancedSearchBox" Then
Dim _webpart As WebPart = CType(_cde, WebPart)
_webpart.Hidden = False
Exit For
End If
Next
End Sub
Call this function on ur button click on user control u will get solution .
Friday, 31 August 2012
How to work with SPGridView using Object Data Source.
This post has been moved to this
http://unique2026.blogspot.in/2013/08/how-to-work-with-spgridview-using.html
Thursday, 23 August 2012
How to activate SharePoint Taxonomy Fearture
In this article we will be seeing how to resolve "The Taxonomy feature (Feature ID "73EF14B1-13A9-416b-A9B5-ECECA2B0604C") has not been activated" error.
Sometimes when you try to use the Managed Metadata column type in SharePoint 2010 you may get an error saying "The Taxonomy feature (Feature ID "73EF14B1-13A9-416b-A9B5-ECECA2B0604C") has not been activated".
Activating the Taxonomy Feature using Power Shell:
GO to Start menu.
Go to SharePoint 2010 Management Shell and select Run as Administrator.
In the command prompt, type each of the following commands.
Enable-SPFeature -id 73EF14B1-13A9-416b-A9B5-ECECA2B0604C -URL http://<Server>
<Server>- is the SharePoint server name.
Now you have activated the Taxonomy Feature.
Activating the Taxonomy Feature using STSADM command:
GO to Start menu.
Go to SharePoint 2010 Management Shell and select Run as Administrator.
In the command prompt, type each of the following commands.
STSADM -o activatefeature -id 73EF14B1-13A9-416b-A9B5-ECECA2B0604C -url http://< Server > -force
<Server>- is the SharePoint server name.
Now you have activated the Taxonomy Feature.
Sometimes when you try to use the Managed Metadata column type in SharePoint 2010 you may get an error saying "The Taxonomy feature (Feature ID "73EF14B1-13A9-416b-A9B5-ECECA2B0604C") has not been activated".
Activating the Taxonomy Feature using Power Shell:
GO to Start menu.
Go to SharePoint 2010 Management Shell and select Run as Administrator.
In the command prompt, type each of the following commands.
Enable-SPFeature -id 73EF14B1-13A9-416b-A9B5-ECECA2B0604C -URL http://<Server>
<Server>- is the SharePoint server name.
Now you have activated the Taxonomy Feature.
Activating the Taxonomy Feature using STSADM command:
GO to Start menu.
Go to SharePoint 2010 Management Shell and select Run as Administrator.
In the command prompt, type each of the following commands.
STSADM -o activatefeature -id 73EF14B1-13A9-416b-A9B5-ECECA2B0604C -url http://< Server > -force
<Server>- is the SharePoint server name.
Now you have activated the Taxonomy Feature.
Monday, 2 July 2012
How to prevent default button event
There are some situation when we need to fire only one event on Enter key and block others default event like a button.
Suppose we have a search box and that is available on all page through master page, In this condition where ever other button would be there we can face default event problem. So preventing this situation we can use preventDefault(); ...
This is one code that can help u to understand this situation and u can get solution.
Here I bind a keypress event to one text box that id is txtUserName.
$('#txtUserName').bind('keypress', function(e)
{
if(e.keyCode==13){
if($("#txtUserName").attr("value")=="")
{
alert("please enter value to search");
}
else
{
e.preventDefault();
location.href=getSPUrl() +"Search/Pages/results.aspx?k=" + $("#txtUserName").attr("value");
}
}
});
I think your looking for this only;...
Thanks and Regards,
Shailendra Kumar Singh
Tuesday, 26 June 2012
How to fetch all user of SharePoint using Webserivec
$(function () {
getLoggedInUser();
function getLoggedInUser() {
var soapEnv = '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body><GetUserCollectionFromSite xmlns="http://schemas.microsoft.com/sharepoint/soap/directory/"/></soap:Body></soap:Envelope>';
$.ajax({
url: "/_vti_bin/UserGroup.asmx",
type: "POST",
dataType: "xml",
data: soapEnv,
complete: processResult,
contentType: "text/xml; charset=\"utf-8\""
});
}
function processResult(xData, status) {
$(xData.responseXML).find("User").each(function () {
if ($(this).attr("ID") == _spUserId) {
var uname = $(this).attr("Name");
alert(uname);
}
});
}
});
Just need to copy paste on script of Browser and u can get all user of SharPoint and based on current login u can find the name of current user name ...............
So simple just try this.....:
Thanks And Regards,
Shailendra Kumar Singh
Monday, 18 June 2012
Hide Ribon in Sharepoint
This post has been moved to this link
http://unique2026.blogspot.in/2013/08/how-to-hide-ribbon-in-sharepoint-2010.html
http://unique2026.blogspot.in/2013/08/how-to-hide-ribbon-in-sharepoint-2010.html
Sunday, 10 June 2012
CAML
As Small syntax error or order of tag in
spquery can result any web part (or any thing in which spquery is used) doesn’t
work, I’m explaining SPQuery with example, hope which may help you.
CAML (Collaborative Application Markup Language)
SPQuery is the SharePoint object which is used to perform a query operation against SharePoint data.SPList.getItems(SPQuery) is the step, will return SPListItemCollection which satisfies the query.SPQuery has one data member ‘Query’, which need to set before passing SPQuery object to SPList.
CAML (Collaborative Application Markup Language)
SPQuery is the SharePoint object which is used to perform a query operation against SharePoint data.SPList.getItems(SPQuery) is the step, will return SPListItemCollection which satisfies the query.SPQuery has one data member ‘Query’, which need to set before passing SPQuery object to SPList.
Some Properties
Properties
|
Description
|
RowLimit
|
Gets or sets a
limit for the number of items returned in the query per page.
<RowLimit>10</RowLimit>
---
Can be used as: query.rowLimit = 10;
|
ViewFields
|
Gets or sets the
fields that are displayed in the query.
<ViewFields>
<FieldRef Name='Title'/>
<FieldRef Name='Name'/>
</ViewFields>
---
Can be used as:
SPQuery
query = new SPQuery();
query.ViewFields
= "<FieldRef Name='Field1'/>" +
"<FieldRef
Name='Field2'/>";
|
How to Implement
SPQuery?
using (SPWeb web =
SPContext.Current.Site.RootWeb)
{
SPList mylist = web.Lists["Tasks"];
SPQuery query = new
SPQuery();
query.Query
= "<Where><Eq><FieldRef
Name='Status'/>" +
"<Value
Type='Text'>Completed</Value></Eq></Where>";
SPListItemCollection items =
mylist.GetItems(query);
foreach
(SPListItem item in items)
{
Response.Write(SPEncode.HtmlEncode(item["Title"].ToString())
+ "<BR>");
}
}
Operators:
Comparison Operators,
Logical Joins and Order/ Group Operators, plays an important role to make this
syntax.
Comparison
Operators
Comparison Operators
|
General Meaning
|
Eq
|
=
|
Gt
|
>
|
Lt
|
<
|
Geq
|
>=
|
Leq
|
<=
|
Neq
|
<>
|
Contains
|
Like
|
IsNull
|
Null
|
IsNotNull
|
NotNull
|
BeginsWith
|
Beginning with word
|
DateRangesOverlap
|
compare the dates in a
recurring event with a specified DateTime value, to determine whether they
overlap
|
Now, to use Or between
Geq and Leq conditions, we put it inside <Or> tag.
I.e. condition: where
(Field1 >= 1500) or
(field2 <= 500) can be written like this:
<Where>
<Or>
<Geq>
<FieldRef Name='Field1'/>
<Value
Type='Number'>1500</Value>
</Geq>
<Leq>
<FieldRef
Name='Field2'/><Value Type='Number'>500</Value>
</Leq>
</Or>
</Where>
The full Code snippets
will look like:
<View>
<Query>
<OrderBy>
<FieldRef Name='ID'/>
</OrderBy>
<Where>
<Or>
<Geq>
<FieldRef Name='Field1'/>
<Value
Type='Number'>1500</Value>
</Geq>
<Leq>
<FieldRef
Name='Field2'/><Value Type='Number'>500</Value>
</Leq>
</Or>
</Where>
</Query>
<ViewFields>
<FieldRef Name='Title'/>
<FieldRef Name='Name'/>
</ViewFields>
<RowLimit>10</RowLimit>
</View>
Example: Contains, And,
BeginsWith
The following example uses the Contains element that is assigned to the Query property to return the titles of items
where the Conference column value begins with "Morning" and contains
"discussion session".
<Where>
<And>
<BeginsWith>
<FieldRef
Name="Conference"/>
<Value
Type="Note">Morning</Value>
</BeginsWith>
<Contains>
<FieldRef Name="Conference" />
<Value
Type="Note">discussion session</Value>
</Contains>
</And>
</Where>
Example:
DateRangesOverlap
<Where>
<DateRangesOverlap>
<FieldRef
Name="EventDate"></FieldRef>
<FieldRef
Name="EndDate"></FieldRef>
<FieldRef
Name="RecurrenceID"></FieldRef>
<Value
Type="DateTime">
<Now/>
</Value>
</DateRangesOverlap>
</Where>
Logical
Joins:
Logical Joins
|
Comments
|
And
|
Used within the
‘Where’ element to
group filters in a query for a view
|
Or
|
Used within the
‘Where’ element
to group filters in a query for a view
|
Example: And
<Where>
<And>
<Neq>
<FieldRef
Name="Status"></FieldRef>
<Value
Type="Text">Completed</Value>
</Neq>
<IsNull>
<FieldRef
Name="Sent"></FieldRef>
</IsNull>
</And>
</Where>
Order/Group
Operators:
Order/Group Operators
|
Comments
|
OrderBy
|
Determines the sort
order for a query.
The OrderBy element
contains a group
of FieldRef elements
I.e.
<OrderBy>
<FieldRef
Name="Title" Ascending="TRUE">
</FieldRef>
</OrderBy>
|
GroupBy
|
Contains a Group By
section for grouping the data returned through a query in a list view
|
Example: OrderBy
<OrderBy>
<FieldRef Name="Modified"
Ascending="FALSE"></FieldRef>
</OrderBy>
<Where>
<Or>
<Neq>
<FieldRef Name="Status"></FieldRef>
<Value Type="Text">Completed</Value>
</Neq>
<IsNull>
<FieldRef Name="Status"></FieldRef>
</IsNull>
</Or>
</Where>
Example: GroupBy
<GroupBy>
<FieldRef Name="Modified"/>
</GroupBy>
<Where>
<Or>
<Neq>
<FieldRef
Name="Status"></FieldRef>
<Value
Type="Text">Completed</Value>
</Neq>
<IsNull>
<FieldRef
Name="Status"></FieldRef>
</IsNull>
</Or>
</Where>
Important:
This is very important
thing to keep in mind, because SPQuery will be assigned as a string so it wont
show compile time error though it may have tag syntax error, not in order,
escape sequence error, etc.
Escape sequence:
The
ScriptEncode method escapes characters that would otherwise conflict with
script.
Original
|
Replacement
|
"
|
\"
|
\
|
\\
|
+
|
\u002b
|
>
|
\u003e
|
<
|
\u003c
|
'
|
\u0027
|
Example:
<FieldRef
Name=\"Checkbox\"></FieldRef> <Value
Type=\"bit\">1</Value>
Thanks
Subscribe to:
Posts (Atom)