Monday, November 18, 2013

CAML (Collaborative Application Markup Language) for SharePoint query

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?
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> 

Creating a Custom Filter Dropdown for a SharePoint List Using InfoPath

Almost all of the SharePoint power users and developers are undoubtedly familiar with the web part connectivity feature of SharePoint. This has been an out-of-the-box feature that was available in SharePoint 2007, SharePoint 2010 and is still available in SharePoint 2013. Although, we all find this feature very useful, quick and easy to implement, this might not fulfill our requirements all the time, especially, if the filter dropdown that we need must be in a customized fashion. Let’s take for instance a requirement where user needs to select a Region (E.g. Europe) and then its respective Country should be cascaded in another list. After selecting a Country (E.g. Italy), its respective cities should then be cascaded in another list. And then, upon selecting City (E.g. Rome), the items related to that city is then filtered in another list, for example Hotel names as used scenario in this article.
In this article, I will be drawing attention to 2 solutions that will be beneficial for SharePoint power users or non-developers who have requirements on cascading dropdown list and custom filter dropdown. I am able to achieve this solution with the use of InfoPath Form Designer 2010 with SharePoint 2010. Although this solution is also achievable also using InfoPath Form Designer 2007, however, the steps provided below might not be the same as interface are a bit different.
Below is the summary of the procedures to implement this solution.
a. Create a custom list where the regions, countries and cities will be looked up.
b. Create a custom list where cascading list items will be applied using InfoPath form.
c. Customize a list through InfoPath Form Designer to implement the cascading dropdown list.
d. Create a new list where custom filter will be applied using InfoPath Form Designer.
e. Insert InfoPath form on a page and apply web part connection between the form and the list web part to apply filter.
After complementing the steps, you should be able to achieve the 2 features shown on the screenshots below.
Cascading Dropdown list on a New Form
 Cascading Dropdown.png
Custom Filter Dropdown
Custom Filter Dropdown.png 
a. Create a custom list where the regions, countries and cities will be looked up.
1. Create a custom list with the list name, Hotel-Country-City.
2. Create the columns listed in the table below.
Column
Type
Region
Single line of text
Country
Single line of text
City (Title)
Single line of text
 
3. Enter sample items in the Hotel-Country-City list with the items shown in the screenshot below. Two items per Region will also do.
Sample Items.png 
b. Create a custom list where cascading list items will be applied using InfoPath form.
1. Create a custom list with the list name, Hotels.
2. Create the columns listed in the table below.
ColumnType
Hotel Name (Title)Single line of text
RegionSingle line of text
CountrySingle line of text
CitySingle line of text
 
c. Customize a list through InfoPath Form Designer to implement the cascading dropdown list.
1. On the Hotels list, under the List Tools, click List tab > Customize Form.
2. InfoPath Form Designer is then launched with the Hotels form controls displayed on the page.
3. On the InfoPath Form Designer window, click Data tab > Data Connections > click Add
4. On the Data Connection Wizard > Create a new connection to: > select Receive Data > click Next.
5. On the Select the source of your data > From where you want to receive your data? > select SharePoint library or list.
6. On the SharePoint site details > Enter the location of the SharePoint site: > the URL of the list location is already populated. (E.g. [WebURL]/[List]) > click Next
7. On the Select a list or library: > select “Region-Country-City” list > click Next
8. On the Select fields: > tick Region, Country and City fields > click Next
9. Verify if the list name is displayed on Enter a name for this data connection and click Finish
10. Verify if the Region-Country-City is already added as one of the Data Connections and then Close.
11. Right click Region form control > Change Control > Dropdown list box.
12. Right click again on the Region form control > Dropdown list box properties > on the List box choices section > select Get choices from an external data source.
13. On the Data Source field, select Region-Country-City list.
14. Verify if the Value and Display Name are both Region.
15. Put checkmark on the “Show only entries with unique display names”.
Checkmark.png 
16. Click Apply and OK.
17. Do steps 11-13 for the Country form control.
18. On the Entries section click Select XPath button.
19. Expand the “SharePointListItem_RW” and then select Country.
Select Country.png 
20. While Country is selected click Filter Data… button. On the Filter Data window, click Add button.
21. On Specify Filter Conditions window > on the drop down on the left side, select Region.
22. Verify if the dropdown menu in the middle is set to “is equal to”.
23. On the right dropdown menu, click “Select a field or a group…” option.
24. On the Data Source section, click the dropdown menu and select Main.
25. Expand “dataFields” and then expand “SharePointListItem_RW”, select Region
26. On the Fields section select Region. Click OK
Select Region.png 
27. In the Filter Data win​dow, click OK.
Filter Data Window.png 
28. Click OK twice.
29. Do steps 11-28 for City form control. Note that for the City control, the filter is Country = Country
City Form Control.png 
30. Click Region form control > Properties tab > Field Properties > Default Value > type in the value “Select…”
31. Do step 30 for Country and City controls.
32. Click Region form control again> Properties tab > Rules section > Manage Rules
33. Click New dropdown > select Validation.
34. Enter “Select” on the Details for: section.
35. On the Condition section, click None link and then set the condition, Region is not equal to “Select…” (Type text…). Click OK.
36. On the Rule type: > select Action
37. On the Run these actions: click Add button > Set a field’s value > Select the Country field and type “Select…” on the Value: section > click OK.
Action.png 
38. Do step 37 to set value “Select…” for City control.
Select.png 
39. Click Country form control > Properties tab > Rules section > Manage Rules
40. Click New dropdown > select Validation.
41. Enter “Select” on the Details for: section.
42. On the Condition section, then click None link and then set the condition, Country is not equal to “Select…” (Type text…)
43. On the Rule type: > select Action
44. On the Run these actions: click Add button > Set a field’s value > Select the City field and type “Select…” on the Value: section > click OK.
45. Click Save and Publish
46. Test the list new form by adding new item in the list.
d. Create a new list where custom filter will be applied using InfoPath Form Designer.
1. Create a custom list with the list name, Filter.
2. Create the columns listed in the table below.
Column
Type
Region
Single line of text
Country
Single line of text
City (Title)
Single line of text
 
3. Follow the steps in section c, steps 1-46. Note that on step 7, you should select Hotels list.
4. Still on InfoPath Form Designer, select City field > click Properties tab > Manage Rules > click New dropdown > click Action.
5. On the Details for: section, type in “Send data”. Leave the condition to None.
6. Click Add button and then select Send data to Web Part.
Rules.png 
7. On the Rule Details pop window, click OK.
8. Save and Publish the form.
e. Insert InfoPath form on a page and apply web part connection between the form and the list web part to apply filter.
1. Create a new page and give it a name (E.g. Hotels Filter).
2. Edit the page and click Add a Web Part button.
3. On the Categories column, select List and Libraries
4. On the Web Parts column, select Hotels
5. While page is still in edit mode, click Add a Web Part button.
6. On the Categories column, select Forms.
7. On the Web Parts column, select InfoPath Form Web Part.
8. On the InfoPath Form Web Part inserted on the page, click the link, “Click here to open the tool pane”
9. On the InfoPath Form Web Part properties, on the List or Library section, select Filter.
10. Uncheck the “Show InfoPath Ribbon or toolbar”.
11. Leave the rest of the properties to default and then click OK.
12. On the Hotels list web part menu, click Connections > Get Filter Values From > Filter
13. On the Connection Settings > On the Provided and Consumer Field Name select, “City” for both. Click Finish.
14. Save and Close and Check In the page. Publish the page if applicable.
15. Test the solution by selecting Region and then Country, and then City, and the list should be filtered accordingly.
The above solution doesn’t really entail much of an effort to implement as InfoPath Form Designer is very intuitive software to use. It’s just a matter of getting yourself familiar with the interface on where to find what property or feature and how to use it in SharePoint environment. If this is your first time to use InfoPath, this could be a good start for you discover the power of InfoPath Form Designer with SharePoint. For those who already have experience using InfoPath Form Designer in SharePoint, I hope my solution helps you achieve your requirements as much as how I was able to accomplish mine.

Monday, November 11, 2013

catch script errors in event log


$error.Clear()
 # ... script does work 
foreach ($errorRecord in $error) { Write-EventLog -LogName psLogs -Source scripts -Message "$($errorRecord | Out-String)" -EventId 0 -EntryType Error }
try-catch
Try { SomeFunction }
Catch {Write-EventLog -LogName psLogs -Source scripts -message $_.Exception.message}
trap [System.Exception] {Write-EventLog -LogName psLogs -Source scripts -Message "$($errorRecord | Out-String)" -EventId 0 -EntryType Error}  source

Use PowerShell to create my own event log

One of the cool things to do with Windows PowerShell is to create my own event logs. Here, I am talking about an event log that is like one of the traditional event logs (traditional event logs are System, Security, and Application). By using Windows PowerShell, these traditional types of event logs are easy to read, easy to write to, easy to back up, and easy to clear.

Use PowerShell to create an event log    source

I use the New-EventLog cmdlet to create a new event log. To use this cmdlet, I need three things:
  1. Open the Windows PowerShell console with admin rights—an error occurs when attempting to create a new event log without elevated rights.
  2. I need the name for the log.
  3. I need to specify a source for the events that write to the log.
The following command creates a new traditional event log named ScriptingGuys with a source named scripts. 
New-EventLog -LogName ScriptingGuys -Source scripts
When the command runs, no output appears to the Windows PowerShell console. To ensure the command actually created a new event log, I use the Get-EventLog cmdlet with the –List parameter. Here is the command and the associated output.
10:06 C:\> Get-EventLog -List
  Max(K) Retain OverflowAction        Entries Log
  ------ ------ --------------        ------- ---
  20,480      0 OverwriteAsNeeded      18,504 Application
  20,480      0 OverwriteAsNeeded           0 HardwareEvents
     512      7 OverwriteOlder              0 Internet Explorer
  20,480      0 OverwriteAsNeeded           0 Key Management Service
  10,240      0 OverwriteAsNeeded           4 Lenovo-Customer Feedback
     512      7 OverwriteOlder              2 Lenovo-Lenovo Patch Utility/Admin
     128      0 OverwriteAsNeeded          30 OAlerts
     512      7 OverwriteOlder              0 ScriptingGuys
                                              Security
  20,480      0 OverwriteAsNeeded      21,437 System
  15,360      0 OverwriteAsNeeded      10,059 Windows PowerShell

Configuring my event log

One of the things I notice when I check the ScriptingGuys event log is that it is set to 512 KB, and it will retain entries for 7 days when it will begin deleting older events. This is not the behavior I want. What I want is for the log to be 64 KB in size and to overwrite as needed. To do this, I would think that I use the Set-EventLog cmdlet—but no, there is not such a thing. The cmdlet is named Limit-EventLog. Looking at the Help, it appears there is only one parameter set. Well, I want toOverWriteAsNeeded, so I guess I also need to set a retention days of 0. I craft the following command, but as you can see, it fails.
10:19 C:\> Limit-EventLog -OverflowAction OverWriteAsNeeded -RetentionDays 0 -Maximum
Size 64KB
Limit-EventLog : Cannot validate argument on parameter 'RetentionDays'. The 0 argument is less than the minimum allowed range of 1. Supply an argument that is greater than or equal to 1 and then try the command again.
At line:1 char:65
+ Limit-EventLog -OverflowAction OverWriteAsNeeded -RetentionDays 0 -MaximumSize
+                                                                 ~
    + CategoryInfo          : InvalidData: (:) [Limit-EventLog], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell
   .Commands.LimitEventLogCommand
Major bummer. Ok, so I try it without the RetentionDays parameter … and it works.
Limit-EventLog -OverflowAction OverWriteAsNeeded -MaximumSize 64KB -LogName scriptingguys
I now use Get-EventLog to confirm my changes took place … the output below confirms that the command worked properly.
10:23 C:\> Get-EventLog -list | ? log -eq scriptingguys
  Max(K) Retain OverflowAction        Entries Log
  ------ ------ --------------        ------- ---
      64      0 OverwriteAsNeeded           0 ScriptingGuys

I can’t get an event log without entries

Interestingly enough, I cannot get an event log that has no entries in it … at least not yet. Because if I use the Get-EventLogcmdlet to attempt to retrieve the ScriptingGuys event log, an error appears. The command and error are here.
10:23 C:\> Get-EventLog -LogName scriptingguys
Get-EventLog : No matches found
At line:1 char:1
+ Get-EventLog -LogName scriptingguys
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (:) [Get-EventLog], ArgumentException
    + FullyQualifiedErrorId : GetEventLogNoEntriesFound,Microsoft.PowerShell.Comman
   ds.GetEventLogCommand

Writing to the event log

To write to my new event log, I need to specify the following information:
  1. The log name (scriptingguys in my example)
  2. The source (scripting in my case)
  3. EventID (I generally start with 1)
  4. EntryType (Information, Warning, Error)
  5. Message (this is what I want to log)
In this example, I add a new entry to the ScriptingGuys event log.
Write-EventLog -LogName ScriptingGuys -Source scripts -Message "Dude, it works ... COOL!" -EventId 0 -EntryType information
I can now use the Get-EventLog cmdlet to retrieve the event. This is shown here.
10:27 C:\> Get-EventLog -LogName scriptingguys
   Index Time          EntryType   Source                 InstanceID Message
   ----- ----          ---------   ------                 ---------- -------
       1 Jan 29 10:27  Information scripts                         0 Dude, it wor...
That is all there is to using Windows PowerShell to create and to manage event logs. Join me tomorrow when I will talk about more cool stuff.

Script in windows scheduler

1.

Open Task Scheduler

Open Task Scheduler and Create a new task. Name it and set your security options.
36cad5283fcfcf840b353680676936550349eb4d68470f275925743e337c0c6c_createtask_big
2.

Set Triggers

Click on the Triggers tab and set your schedule or event that will trigger the running of your Powershell script.
758c72854bd646378e604516076a136ca73e18b08236afb681a5ccc46e62f41f_settrigger_big
3.

Create your Action

Click on the Actions tab and click on New.
Action: Start a program
Program/script: Powershell.exe
You don't need to put a path as it should already be on your system.
8519a2f519b07af55c2de43af78056169599e68ae99fa824792803483bf79d8d_newaction_big
4.

Set Argument

First you need to set the ExecutionPolicy. You have two options here, you can set the ExecutionPolicy on the machine or you can do it on a per-script basis. Read the PowerShell ExecutionPolicy link below as it talks about or you can issue the command:
Get-Help About_execution_policies
To set the execution policy globally, you can issue this command from within PowerShell:
Set-ExecutionPolicy Unrestricted
Or use one of the other settings available depending on your environment. In the context of this how-to, however, we want to set the execution policy on a per script basis and open up security for us to run the script. This security policy will only be in effect for the script we are running and not compromise security otherwise.
That means we use the following Argument:
-ExecutionPolicy Bypass
D9a7403f0e632b5c85e040aef0e2a1612c6ef9c6f0ec67c601c738218e3b0ffa_executionpolicy_big
5.

Set the next argument

Next comes the path and name of your script. This can be either a drive letter path, or a full UNC. I've run into problems using the -FILE parameter so I don't use it.
c:\scripts\myscript.ps1
Bf8c65c134cd5b4a63a973530d14b32246a6dae40e72b0b0eb49d1e3a84b1acd_script_big
6.

Add parameters

If your script has any parameters, you want to add them now:
-RunType $true -Path c:\mydatafiles
Please keep in mind these arguments/parameters are purely as an example, many scripts won't have any arguments at all.
7.

Full Argument

That makes your full argument line look like so:
-ExecutionPolicy Bypass c:\scripts\myscript.ps1 -RunType $true -Path c:\mydatafiles
8.

Save the scheduled task

Save your scheduled task and run it.
I've found it helpful to run the task with the "Run only when user is logged on" security option turned on (on the General tab). This will run your script interactively and will allow you to observe it and see if there are any errors.
Once you have a clean run you can change the security option back to "Run whether user is logged on or not".

Friday, November 8, 2013

cut string by symbol

$pos = $name.IndexOf(";") 
$leftPart = $name.Substring(0, $pos) 
$rightPart = $name.Substring($pos+1)

Thursday, November 7, 2013

SharePoint 2010 number field display without ","



A common request is to display number fields in SharePoint 2010 lists without commas. For example, if you had a list of books that included PublicationYear column, it would format the values as:
2,001
1,998
2,011

This is confusing to the viewer, as values no longer look like years.

The most frequent suggestion is to create an additional field that calculates a value based on the Number field and ignores all non-numeric parts. This is relatively straightforward, and can be accomplished entirely within the browser:

=TEXT([MyNumericData], "0")

Or, in a case where you’d like to retain two digits after the decimal:
=TEXT([MyNumericData], "0.00")

SharePoint appears to store the data in its numeric format in a another column, hidden to the browser but visible in SharePoint Designer. It’s [column name] followed by a period. For example, I created a field called MyNumericData, so the hidden field is MyNumericData. Again:
MyNumericData
MyNumericData.

Adding this to a view via SharePoint Designer is non-obvious. Here are the steps I used:
Click on a data item in Design mode until you see a tab labeled xsl:value-of:



SharePoint Designer 2010 Design Mode
Right-click the item and select Edit Formula
Remove the current XPath expression
Add the MyNumericData. row from the fields pane
Add the format-number function from the Math / Number functions
Add the appropriate format pattern (e.g. ‘#’)

The appropriate format pattern depends on how you wish to display the data:
Display integer value:
format-number($thisNode/@MyNumericData.,'#')
Always display two digits after the decimal:
format-number($thisNode/@MyNumericData.,'0.00')
Display up to 2 digits after the decimal:
format-number($thisNode/@MyNumericData.,'#.##')

If you look at the code view after making these changes, you will see that SharePoint Designer added a hefty chunk of XSL to the XsltListViewWebPart.

Is there any advantage to this method over adding a calculated field? Not as far as I can tell–but it’s interesting to note that there is more than one overly-complicated solution to what seems like a trivial problem.

- See more at: http://osric.com/chris/accidental-developer/2011/11/displaying-numeric-fields-in-sharepoint-2010-without-commas/#sthash.Rr8NzTgL.dpuf