Monday, November 3, 2014

C# - Null-coalescing Operator



The "??" operator is called the null-coalescing operator and is used to define a default value for a nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand.


Example:

int? a = 123;
int? b = 5;
int? x = a ?? b;

/*Output:x = 123*/



int? a = null;
int? b = 5;
int? x = a ?? b;

/*Output:x = 5*/

Thursday, September 11, 2014

Transact SQL - Creating Temp Tables

This simple example shows you how to create and use temp tables in Microsoft SQL Server 2008.

First we have to create the temp table. The difference between regular tables and temp tables is to use the # before the table name. The syntax is the same:

create table #tempTable(keyword nvarchar(max), productNo nvarchar(30), anotherValue nvarchar(max))

After the temp table is created, we can put some data into it:

insert into #tempTable (keyword, productNo, anotherValue) 
 values ('test', 1234, 'somewhat')

After the data is in the temp table, we can use regular select statements:

select * from #tempTable

The result is:

keyword productNo anotherValue

test 1234 somewhat

Tuesday, July 22, 2014

SharePoint 2010 - JavaScript Client - Updating items with visual feedback to user

I had created a custom action for a document library in SharePoint 2010.
When the user presses the custom action button in the ribbon bar, the selected documents should be updated in a special field ("Document Status").
I noticed, that the procedure to update the selected documents takes long time. During the update process the user cannot see what is happening, because of the asynchronous update request via JavaScript.
I thought, this is not very user-friendly, so I created a screen, where the user can see what the system is doing in this moment.
Here is my code with some screenshots.

function ApproveDocuments() {
    var ApprovalProcess = this;
    ApprovalProcess.SiteCollectionUrl = '';
    var counter = 0;
    var fileItems = [], item, docsSentToApproval = [];

    var ClientContext = SP.ClientContext.get_current();
    var LibraryID = SP.ListOperation.Selection.getSelectedList();
    var Library = ClientContext.get_web().get_lists().getById(LibraryID); //Gets the current Library
    var SelectedDocuments = SP.ListOperation.Selection.getSelectedItems(ClientContext);
    var SiteCollection = ClientContext.get_site();
    ClientContext.load(SiteCollection);
    ClientContext.executeQueryAsync(function (s, a) {
        jQuery('#myCloseInfoDivButton').click(function () {
            window.location.href = SiteCollection.get_url() + '/Lists/Document Center';
            ApprovalProcess.SiteCollectionUrl = SiteCollection.get_url();
        });
    });

    var newDiv = '<div id="myCoverAll" style="background-color:#182738;width:100%;height:100%;position:fixed;top:0px;left:0px;display:block;z-index:1000;filter:alpha(opacity=70);-ms-filter:alpha(opacity=70);opacity:0.7;"></div>';
    newDiv += '<DIV id="myInfoDivContainer" class="ms-dlgBorder" style="background-color:#ffffff;HEIGHT: 345px; WIDTH: 609px; position:absolute; left:50%; margin-left:-304px; top:50%; margin-top:-172px;z-index:1001;">';
    newDiv += ' <DIV class="ms-dlgTitle" style="CURSOR: default; WIDTH: 609px">';
    newDiv += ' <SPAN class="ms-dlgTitleText" id="dialogTitleSpan" style="WIDTH: 545px">Approve Documents</SPAN>';
    newDiv += '</DIV>';
    newDiv += '<DIV id="myInfoDivData" class="ms-dlgFrameContainer" style="background-color:#ffffff;padding-top:20px;"></DIV>';
    newDiv += '<div id="myButtonCloseDiv" style="position:relative;width:100px;left:50%;margin-left:-50px;background-color:#ffffff;padding-top:20px;"><input class="ms-toolbar" type="button" name="myCloseInfoDivButton" id="myCloseInfoDivButton" value=" Close " /></DIV>';
    newDiv += '</DIV>';
    jQuery("#aspnetForm").after(newDiv);
    if (SelectedDocuments.length > 0) {
        jQuery('#myCloseInfoDivButton').attr('disabled', 'disabled');
    }

    for (var currentItem in SelectedDocuments) {
        item = Library.getItemById(SelectedDocuments[currentItem].id);
        fileItems.push(item);
        ClientContext.load(item, 'FileLeafRef','Id','DocumentStatus');
    }

    var newElementHtmlHeader;
    newElementHtmlHeader = '<div style="position:relative;width:100px;left:50%;margin-left:-50px;display:block;vertical-align:middle; text-align:center;" id="myLoadingBar"><img src="' + ApprovalProcess.SiteCollectionUrl + '_layouts/images/mySPProject/busy.gif" /><br />Loading...</div>';
    newElementHtmlHeader += '<div style="font-weight:bold;float:left;padding:3px;width:50px;display:table-cell; vertical-align:middle; text-align:center;">Approval Status</div>';
    newElementHtmlHeader += '<div style="font-weight:bold;float:left;padding:3px;">Document</div>';
    newElementHtmlHeader += '<div style="font-weight:bold;float:left;padding:3px;"></div>';
    newElementHtmlHeader += '<div style="clear:both;"></div>';
    jQuery("#myInfoDivData").append(newElementHtmlHeader);

    ClientContext.executeQueryAsync(Function.createDelegate(this, function () {
        var newElementHtml;
        for (var i = 0; i < fileItems.length; i++) {
            newElementHtml = '<div style="float:left;padding:3px;width:50px;display:table-cell; vertical-align:middle; text-align:right;" id="item' + fileItems[i].get_id() + '">';
            if (fileItems[i].get_item('DocumentStatus') != 'Waiting for Approval') {
                newElementHtml += '<img src="' + ApprovalProcess.SiteCollectionUrl + '_layouts/images/mySPProject/docError.png" style="border:0px;width:15px;height:12px;" alt="Document approval error"></img>';
            }
            newElementHtml += '</div>';
            newElementHtml += '<div style="float:left;padding:3px;">' + fileItems[i].get_item('FileLeafRef') + '</div>';

            if (fileItems[i].get_item('DocumentStatus') == 'Waiting for Approval') {
                newElementHtml += '<div style="float:left;padding:3px;" id="approvalStatus' + fileItems[i].get_id() + '">';
                newElementHtml += '</div>';
            }
            else {
                newElementHtml += '<div style="float:left;padding:3px;color:#F60000;" id="approvalStatus' + fileItems[i].get_id() + '">';
                newElementHtml += 'Error: Document not in "Waiting for Approval"-State';
                newElementHtml += '</div>';
            }
            newElementHtml += '<div style="clear:both;"></div>';
            jQuery("#myInfoDivData").append(newElementHtml);
            if (fileItems[i].get_item('DocumentStatus') == 'Waiting for Approval') {
                fileItems[i].set_item('DocumentStatus', 'Approved');
                fileItems[i].update();
                docsSentToApproval[counter] = fileItems[i];
                counter++;
            }
        }
        ClientContext.executeQueryAsync(Function.createDelegate(this, function () {
            for (var i = 0; i < docsSentToApproval.length; i++) {
                jQuery('#item' + docsSentToApproval[i].get_id()).html('<img src="' + ApprovalProcess.SiteCollectionUrl + '_layouts/images/mySPProject/docApproved2.png" style="border:0px;width:15px;height:12px;" alt="Document approved"></img>');
                jQuery('#approvalStatus' + docsSentToApproval[i].get_id()).css('color', '#368131');
                jQuery('#approvalStatus' + docsSentToApproval[i].get_id()).html('Success');
                if(i == (docsSentToApproval.length - 1))
                {
                 jQuery('#myCloseInfoDivButton').removeAttr("disabled");
                 jQuery('#myLoadingBar').css('display','none');
                }
            }
        }), Function.createDelegate(this, function (sender, args) {
            // handle error somehow
        }));
    }), Function.createDelegate(this, this.onLoadItemFailure));
}

and here how it looks like:

Full Screen Layer with "PopUp"


After updating the properties of the selected documents

Maybe this is useful for someone.

LUA - native.newWebView - Showing a loading status during request

Hi guys,

here a small, but very useful code if you are programming apps in LUA with Corona SDK.
If you are using a simple native.newWebView and you want to display a status / loading bar during the request, you can use the following code:

-- show activity indicator
native.setActivityIndicator( true )
-- create the native.newWebView object
webView = native.newWebView( display.contentWidth * 0.5, 200 , display.contentWidth  * 0.5, 400 )
-- request the URL
webView:request( theURL )
-- add an event listener to the native.newWebView object
webView:addEventListener( "urlRequest", webViewListener )

-- this function will be called during the request
function webViewListener( event )
      print "Entering: webViewListener"      
      if (event.type == "loaded") then
        print("URL: "..event.url)
        native.setActivityIndicator( false )
      else
        native.setActivityIndicator( true )
      end
end

Friday, June 13, 2014

SharePoint 2010 - Building Custom Actions in Visual Studio

Today I will show how you can add custom actions to the ribbon bar and the edit control block in SharePoint.

We have to start with creating an empty element in the project. Then replace the text in the xml file with this:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction
  Description="Approve Documents"
  Title="Approve Documents"
  Id="RibbonDocumentsManageApproveDocuments"
  Location="CommandUI.Ribbon"
  RegistrationId="10000"
  RegistrationType="List"
  Sequence="0"
  xmlns="http://schemas.microsoft.com/sharepoint/">
    <CommandUIExtension xmlns="http://schemas.microsoft.com/sharepoint/">
      <!-- Define the (UI) button to be used for this custom action -->
      <CommandUIDefinitions>
        <CommandUIDefinition Location="Ribbon.Documents.Manage.Controls._children">
          <Button Id="Ribbon.Documents.Manage.ApproveDocuments"
          Command="{4E2F5DC0-FE2C-4466-BB2D-3ED0D1917763}"
          Image32by32="~site/_layouts/Images/SharePoint-Z-Drive-Project/approve_document_32x32.png"
          Image16by16="~site/_layouts/Images/SharePoint-Z-Drive-Project/approve_document_16x16.png"
          Sequence="0"
          LabelText="Approve Documents"
          Description="Approve Documents"
          TemplateAlias="o1" />
        </CommandUIDefinition>
      </CommandUIDefinitions>
      <CommandUIHandlers>
        <!-- Define the action expected on the button click -->
        <CommandUIHandler Command="{4E2F5DC0-FE2C-4466-BB2D-3ED0D1917763}" CommandAction="javascript:window.open('http://www.bing.com/search?q='.concat(escape(document.title)))" />
      </CommandUIHandlers>
    </CommandUIExtension>
  </CustomAction>

  <CustomAction
  Description="Approve Document"
  Title="Approve Document"
  Id="EditControlBlockApproveDocument"
  Location="EditControlBlock"
  RegistrationId="10000"
  RegistrationType="List"
  ImageUrl="~site/_layouts/Images/SharePoint-Z-Drive-Project/approve_document_16x16.png"
  Sequence="1101"
  xmlns="http://schemas.microsoft.com/sharepoint/">
    <CommandUIExtension xmlns="http://schemas.microsoft.com/sharepoint/">
      <!-- Define the (UI) button to be used for this custom action -->
      <CommandUIDefinitions>
        <CommandUIDefinition Location="EditControlBlock">
          <Button Id="EditControlBlock.ApproveDocument"
          Command="{F8C45D3A-A00D-4412-91BB-C49D75A36F3A}"
          Sequence="1101"
          LabelText="Approve Document"
          Description="Approve Document"
          TemplateAlias="o2" />
        </CommandUIDefinition>
      </CommandUIDefinitions>
      <CommandUIHandlers>
        <!-- Define the action expected on the button click -->
        <CommandUIHandler Command="{F8C45D3A-A00D-4412-91BB-C49D75A36F3A}" CommandAction="javascript:window.open('http://www.bing.com/')" />
      </CommandUIHandlers>
    </CommandUIExtension>
  </CustomAction>
</Elements>

The first custom action is to add the button to ribbon bar in the document library. 
The second custom action will add the button to the edit control block of an item.

Wednesday, June 11, 2014

SharePoint 2010 - Tutorial - Create an event receiver with custom error message on redirect url while item updating

Today I would like to show you, how you can use event receivers to check documents / items in a list and give the user immediately a feeback about an error, while he is still in the edit form of the item / document.
That can be useful for users, because they don't leave the edit form and can correct the error immediately without opening the edit mask again.
We start with an empty SharePoint Project in Visual Studio 2010.


Set a project name ("SPProject"), then provide the url and set the trust level ("Farm solution").


The first step is to add the list definition with list instance to our project. That will be our list, where the event receiver will be listen on. Right-click the project name in the project explorer and choose "Add" -> "New Item".


From the list select "List Defintion" and set a name for it ("ListDefinition"), then press "Add".


On the next screen you have to enter a name for the list definition ("SPProject - ListDefinition"). Also you have to choose, which type the list should be. In my case it was a document library, but you can use other types as well. Ensure that the box "Add a list instance for the list definition" is ticked.


After we have added the list defintion, we can add our event receiver. The event receiver will check our doucment and return an error to the edit form, when the item / document is not ok. So we right-click again on the project name in the project explorer and choose "Add" -> "New Item" again.


Now we choose "Event Receiver" from the list and set again a name ("EventReceiver").


On the next screen, we have to decide, which type of event receiver we would like to have. We want the event receiver to check the items of a list - so our choice is "List Item Events".
Then we have to tell SharePoint on which list the event receiver should listen. That is our created list instance from our list definition ("SPProject - ListDefinition").
The last point we have to decide, when the event receiver should start its work. We select "An item is being added".


In the file "EventReceiver.cs" we can add now our code, our logic to check the item / document.
I keep it simple for this example. I will only check if the title property starts with the word "SharePoint", otherwise I want to give an error message to the user. You can put in there more complex logic according to your needs.
Open the "EventReceiver.cs" and search for the method "ItemUpdating". Overwrite the method with your code:

/// <summary>
/// An item is being updated.
/// </summary>
public override void ItemUpdating(SPItemEventProperties properties)
{
  try
  {
    base.ItemUpdating(properties);
    // ensure that the code will be executed only once
    if ((properties.AfterProperties["vti_sourcecontrolcheckedoutby"] == null && properties.BeforeProperties["vti_sourcecontrolcheckedoutby"] != null) || (properties.AfterProperties["vti_sourcecontrolcheckedoutby"] == null && properties.BeforeProperties["vti_sourcecontrolcheckedoutby"] == null))
    {
      // check title property
      if (properties.AfterProperties["vti_title"].ToString().StartsWith("SharePoint") == false)
      {
        // redirect
        properties.RedirectUrl = @"EditForm.aspx?"
                                 + "Mode=Upload"
                                 + "&CheckInComment="
                                 + "&ID=" + properties.ListItem.ID
                                 + "&RootFolder=%2Fsites%2FIT%2FLists%2FSPProject-ListInstance1"
                                 + "&IsDlg=1"
                                 + "&ContentTypeId=" + properties.ListItem.ContentType.Id
                                 + "&IsDlg=1";
        properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
       }
      }
     }
     catch (Exception exp)
     {
       throw exp;
     }
 
}
I use the property "vti_sourcecontrolcheckedoutby" to ensure that the code is executed once and nor multiple times. If you have enabled versioning in your list, the event will be fired muliple.
Then I use the AfterProperties to check the title. If the check fails, SharePoint should redirect the user to a specific url. We set the url to our editform.aspx of the list. 
Note: You have to check the bold marked area in the code (RootFolder parameter). You have to change this to your list url!

Now we can start the solution. Navigate to the list, add an item and edit the properties afterwards. You will see that the title have to start with the word "SharePoint", otherwise the popup comes up again when saving.


But we still have no error displayed to the user. The user would be confused now, because he don't knows what is wrong and why he cannot save the properties.

To display an error on the editform.aspx of the list, we create a simple visual webpart.
We add another item to our project via right-click on the project name in the project explorer.


Select "Visual WebPart" from the list and set a name ("VisualWebPart").


To the visual webpart we add just a label ("Label1") from the toolbox ("VisualWebPartUserControl.ascx").


In my solution I did some small changes to the label, like red color, another font, cleared the text property of the label etc, but this is up to you, how you design the label.

Now we open the code-behind file "VisualWebPartUserControl.ascx.cs" and modify the Page_Load method.

protected void Page_Load(object sender, EventArgs e)
{
  string ErrorMessage = System.Web.HttpUtility.ParseQueryString(System.Web.HttpContext.Current.Request.Url.Query).Get("error");
  this.Label1.Text = ErrorMessage;
}

Explanation:
We use the HttpUtility class to get the parameter "error" from the current url. The paramter "error" we will use later for our custom error message.
The content of the error parameter we put in our label text property.

Now we have our webpart for displaying the error message, but we still have to put in the editform.aspx of our list.
Therefore we open the file "schema.xml" of our list definition and search for the "<Forms>" section in it.
It should similar look like this:


Now we create our custom editform.aspx by creating a new <Form> from type "EditForm". Give a own name ("MyEditForm.aspx") and set default = true:


Code:
      <Form Type="EditForm"
            SetupPath="pages\form.aspx"
            WebPartZoneID="Main"
            Url="Forms/MyEditForm.aspx"
            Default="TRUE">
        <WebParts>
          <AllUsersWebPart WebPartZoneID="Main" WebPartOrder="0">
            <![CDATA[
            ]]>
          </AllUsersWebPart>
        </WebParts>
      </Form>

Now we have a custom editform.aspx, but we still have to put our webpart in it. Actually we have the same editform as the standard one. Open the file "VisualWebPart.webpart" from the project explorer.


Copy the complete code except the first line ("<?xml version....>) and paste it in the CDATA area in the schema.xml.
Your form code in your schema.xml should look like this now:


Code:
 <Form Type="EditForm"
            SetupPath="pages\form.aspx"
            WebPartZoneID="Main"
            Url="Forms/MyEditForm.aspx"
            Default="TRUE">
        <WebParts>
          <AllUsersWebPart WebPartZoneID="Main" WebPartOrder="0">
            <![CDATA[
            <webParts>
            <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
              <metaData>
                <type name="SPProject.VisualWebPart.VisualWebPart, $SharePoint.Project.AssemblyFullName$" />
                <importErrorMessage>$Resources:core,ImportErrorMessage;</importErrorMessage>
              </metaData>
              <data>
                <properties>
                  <property name="Title" type="string">VisualWebPart</property>
                  <property name="Description" type="string">My Visual WebPart</property>
                </properties>
              </data>
            </webPart>
          </webParts>
            ]]>
          </AllUsersWebPart>
        </WebParts>
      </Form>

Now we have embedded the webpart in our custom editform.aspx.
We have to tell the event receiver, that it should redirect to our new custom editform.aspx ("MyEditForm.aspx") and we have to add the error parameter to our url.
Navigate back to the event receiver code file ("EventReceiver.cs") and modify the redirect url:

properties.RedirectUrl = @"MyEditForm.aspx?"
                         + "Mode=Upload"
                         + "&CheckInComment="
                         + "&ID=" + properties.ListItem.ID
                         + "&RootFolder=%2Fsites%2FIT%2FLists%2FSPProject-ListInstance1"
                         + "&IsDlg=1"
                         + "&ContentTypeId=" + properties.ListItem.ContentType.Id
                         + "&IsDlg=1"
                         + "&error=Error in Title - Must start with SharePoint";

Changes in code are marked in bold.
We changed the aspx file from "EditForm.aspx" to "MyEditForm.aspx" and added the parameter "error" with a custom error message.


Let's start the solution now. Navigate to the list, add an item and edit the properties afterwards. Click "Save" with an empty title. Now you should get the error message:


If you enter a text beginning with the word "SharePoint" in the title property the popup will disappear.
Hope you enjoyed this lesson. :-)

Sunday, June 8, 2014

SharePoint 2010 - Adding your created visual web part to the schema.xml of a list definition

Hi guys,

Today I tried to add a visual webpart to a list definition, especially to an indidividual edit form of the list definition.
I created a visual webpart in visual studio and a list definition with a list instance.
For the list defintion, I wanted to add a custom editform.aspx in the <forms> area of the schema.xml.
That can be done this way:

Find the <forms> area in the schema.xml:

    <Forms>
      <Form Type="DisplayForm" SetupPath="pages\form.aspx" Url="Forms/DispForm.aspx" WebPartZoneID="Main" />
      <Form Type="EditForm" SetupPath="pages\form.aspx" Url="Forms/EditForm.aspx" WebPartZoneID="Main" />
      <Form Type="NewForm" Url="Forms/Upload.aspx" WebPartZoneID="Main" />
...

We see the 3 standard forms (display, edit and new). Now we can add a custom editform.aspx by defining a new form with the type "editform":

      <Form Type="EditForm"
            SetupPath="pages\form.aspx"
            WebPartZoneID="Main"
            Url="Forms/MyEditForm.aspx"
            Default="TRUE"></Form>

Important are the "type", "url" and the "default" property. The type as the name says, defines the type of the form. The url property can be defined free. You can enter there any name. And the last property "default", if this form will be the standard / default for the specific type.

If we start our solution now, we would have the same result as the standard editform.aspx. There would be no difference for the user. We, of course, can see that the url is different than the standard editform.aspx.

Now we want to add another webpart to our new editform.aspx (in my case myeditform.aspx):
First we have to add a container for all webparts, we want to add to the myeditform.aspx. This code has to placed between the <form> tags:

<Form Type="EditForm"
            SetupPath="pages\form.aspx"
            WebPartZoneID="Main"
            Url="Forms/MyEditForm.aspx"
            Default="TRUE">
        <WebParts>

        </WebParts>
</Form>

Then we need to add the webpart itself:

<Form Type="EditForm"
            SetupPath="pages\form.aspx"
            WebPartZoneID="Main"
            Url="Forms/MyEditForm.aspx"
            Default="TRUE">
        <WebParts>
          <AllUsersWebPart WebPartZoneID="Main" WebPartOrder="1">
            <![CDATA[

            ]]>
          </AllUsersWebPart>
        </WebParts>
</Form>

In the cdata area we can copy the complete code of our visual webpart file (*.webpart) except the first line:

<?xml version="1.0" encoding="utf-8"?>

So we get this result in the end:

<Form Type="EditForm"
            SetupPath="pages\form.aspx"
            WebPartZoneID="Main"
            Url="Forms/MyEditForm.aspx"
            Default="TRUE">
        <WebParts>
          <AllUsersWebPart WebPartZoneID="Main" WebPartOrder="1">
            <![CDATA[
<webParts>
  <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
    <metaData>
      <type name="SharePoint_Z_Drive_Project.WP_ErrorField.WP_ErrorField, $SharePoint.Project.AssemblyFullName$" />
      <importErrorMessage>$Resources:core,ImportErrorMessage;</importErrorMessage>
    </metaData>
    <data>
      <properties>
        <property name="Title" type="string">Error</property>
        <property name="Description" type="string">Error Field WebPart</property>
      </properties>
    </data>
  </webPart>
</webParts>
            ]]>
          </AllUsersWebPart>
        </WebParts>
</Form>

If we start the solution now and edit an item in our list instance, we see the properties of our item and our visual webpart.

Wednesday, April 30, 2014

SQL Server 2008 - Query XML data

Just recognized, that it is easy to query xml data stored in a SQL Server 2008 table (field):

declare @data xml

select @data = <datafield> from <table> (nolock) where <condition>

select @dataselect @data.query('<node>') as result

Here an example with sample xml:

declare @data xml
select @data = '<root><datas><data><add name="a" value="x1" /><add name="b" value="y2" /> <add name="c" value="z3" /></data><data><add name="a" value="e4" /> <add name="b" value="f5" /><add name="c" value="g6" /> </data></datas></root>' 
select @data
select @data.query('(/root/datas/data/add[@name="c"])[1]') as result 

The result is:

<add name="c" value="z3" /> 

Now I need to find out, how to get the value and not the complete node.

SharePoint 2010 - Using REST in client application

Hi guys,

today I want to show you, how you to get data from a SharePoint 2010 Server by using a REST client. 

Imagine we have a document library "How To" in a site collection "IT" on a SharePoint 2010 Server like this one:


We write a small console application to request all documents from this document library. The user can enter a search string and the results will be displayed after the input.

Ok, let's create a new solution in Visual Studio 2010:

I called the solution "REST-Solution".
Press "Ok" to create it.

After Visual Studio has created the solution, we have to add a service reference.

We have to enter the address to the service. In SharePoint 2010 we always find this service for each site in the "_vti_bin" folder. It's name is listdata.svc.
You can enter a different namespace in the text line. I called it ServiceReference1.


After adding the service reference to the project, we need to add 2 rows in the "using"-section:


Code Section: 
using REST_Solution.ServiceReference1;
using System.Net;
Note: In the first line, you have to use your solution name with the name of your service reference.

Then we can add our code.

Note:
The class name of the data context ("ctx" object) depends of the name of your Sharepoint site. In my case it is "IT", so the class name is "ITDataContext".
I think, the code is self-explanatory.

Code Section:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using REST_Solution.ServiceReference1;
using System.Net;
namespace REST_Solution
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create Uri
            Uri myUri = new Uri("http://testportal.grolman.de/sites/IT/_vti_bin/listdata.svc");
            // Create DataContext with Uri
            ITDataContext ctx = new ITDataContext(myUri);
            // Set Credentials
            ctx.Credentials = CredentialCache.DefaultCredentials;
            Console.WriteLine("Please enter search string:");
            // Get user input:
            string searchString = Console.ReadLine();
            // Create Query
            var linqQuery =
                from document in ctx.HowTo
                where document.Name.Contains(searchString)
                select document;
            // Results
            Console.WriteLine("Results:");
            foreach (HowToItem howtoItem in linqQuery)
            {
                Console.WriteLine("Document: " + howtoItem.Name + " / Version: " + howtoItem.Version);
            }
            // Stop here, wait for user input
            Console.ReadLine();
        }
    }
}
That's all. Start the program and you see it works fine:

All without using the client object model of SharePoint.

Wednesday, April 23, 2014

SharePoint 2010 - Document Templates

Here is a list for all available document templates of SharePoint 2010:

Template IDDescription
100No Template
101 Word 2003 document
103 Excel 2003 document
104 PowerPoint 2003 document
121 Word document
122 Excel document
123 PowerPoint document
111 OneNote Notebook
102 SharePoint Designer HTML document
105 ASPX Web Page
106 ASPX Web Part Page
1000 InfoPath document

SharePoint 2010 - Deleting a content type - Error message "The content type is in use"

I got mad with an issue. I have programmatically created content types and added them to new document libraries. I figured out some errors and I wanted to delete all and start from the scratch. So I deleted all document libraries and afterwards I tried to delete the content types - with the result: Error - "The content type is in use". :-(

Server Error in '/' Application.
The content type is in use.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.  
Exception Details: Microsoft.SharePoint.SPException: The content type is in use. 
Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. 
Stack Trace:
[SPException: The content type is in use.]   Microsoft.SharePoint.SPContentTypeCollection.DeleteFromWeb(SPContentTypeId id,    String strName) +648   Microsoft.SharePoint.SPContentTypeCollection.Delete(SPContentTypeId id) +26928500   Microsoft.SharePoint.SPContentType.Delete() +85   Microsoft.SharePoint.ApplicationPages.ManageContentTypePage.DeleteContentType() +145   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl,    String eventArgument) +29   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint,    Boolean includeStagesAfterAsyncPoint) +2981
Version Information: Microsoft .NET Framework Version:2.0.50727.5477; ASP.NET Version:2.0.50727.5479 

I got mad with this issue, because I deleted everything, even I cleaned the recycle bin, which is visible on the pages. Nothing helped. Still got that error, but the solution is so simple:

Navigate to "Site Settings". A subpoint of "Site Collection Administration" is "Recycle bin".
You have 2 views:


Mark all items in both views and delete all.
Then it worked for me. Hope it solves your issue, too.


Friday, March 14, 2014

C# - Resizing Arrays - Add String to String Array

Guys,
here's a simple way to add a string to a string array (C#):

String[] Sorting;
foreach (String StringObj in StringObjCollection)
{
     Array.Resize(ref Sorting, Sorting.Length + 1);
     Sorting[Sorting.Length - 1] = StringObj;
}

C# - CollectionBase - Sorting a collection

Based on my blog post about creating a collection using the CollectionBase class yesterday, I figured out, how to sort a collection based on the class CollectionBase.

public List<MyClass> SortByColumnSortColumn()
{
     List<MyClass> SortedList = this.List.Cast<MyClass>().ToList();
     SortedList = SortedList.OrderBy(x => x.SortColumn).ToList();
     return SortedList;
}

Thursday, March 13, 2014

C# - Creating a Collection class


Creating a simple Collection class is very easy.
Assuming we have a class like this and want to create a collection class from it...

public class MyClass
{
     public string Name;

     public MyClass()
     {
     }
}

We can easily create a collection of it by using the CollectionBase class in the .NET Framework.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace My_Project.Classes
{
    public class MyClassCollection : System.Collections.CollectionBase
    {
        #region Variables
        #endregion

        #region Properties
        #endregion

        #region Constructors
        #endregion

        #region Methods

        public void Add(My_Project.Classes.MyClass NewMyClassObject)
        {
            List.Add(NewMyClassObject);
        }

        public void Remove(int index)
        {
            // Check to see if there is a MyClass at the supplied index.
            if (index > Count - 1 || index < 0)
            // If no MyClass exists, a messagebox is shown and the operation 
            // is cancelled.
            {
                throw new Exception();
            }
            else
            {
                List.RemoveAt(index);
            }
        }

        public My_Project.Classes.MyClass Item(int Index)
        {
            // The appropriate item is retrieved from the List object and
            // explicitly cast to the MyClass type, then returned to the 
            // caller.
            return (My_Project.Classes.MyClass)List[Index];
        }
        #endregion
    }
}

Now we can use the Collection class:

// create MyClass Object 1:
MyClass MyClassObject1 = new MyClass();

//create MyClass Object 2:
MyClass MyClassObject2 = new MyClass();

//creating the collection object:
MyClassCollection Col = new MyClassCollection();

//adding both objects to the collection
Col.Add(MyClassObject1);
Col.Add(MyClassObject2);

//removing an object from the collection:
Col.Remove(1);

//getting the item object from a collection
MyClass NewObject = Col.Item(0);


Here is a good walkthrough from Microsoft:

http://msdn.microsoft.com/en-us/library/xth2y6ft(v=vs.71).aspx