Friday, November 20, 2015

SharePoint 2010 - Tutorial - Deploying a custom master page

Please feel free to comment my new tutorial "Deploying a custom master page" in a SharePoint 2010 enviroment. Enjoy.

The first step is to add feature to your project, if you have not already one. 
I created an empty SharePoint project for this tutorial.


Ensure, that the feature scope is set to "Site" to apply the master page to all webs in this site collection.


Then add a "Module" to the project. You can give any name:


After the module is created it contains an "elements.xml" and "sample.txt" file. The "sample.txt" file can be renamed to "sample.master".

Your project then should cotain these elements:


Best practice: Open the SharePoint Designer, navigate to the current master file and edit it.
Note: In SharePoint 2010 the default master page is "v4.master" and NOT "default.master"



Copy the contents of "v4.master" in your "sample.master" and do your changes on the code.

Then make sure, that your "elements.xml" of the module looks like this:



<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="Module1" List="116" Url="_catalogs/masterpage">
  <File Path="Module1\sample.master" Url="sample.master" Type="GhostableInLibrary" IgnoreIfAlreadyExists="FALSE" />
</Module>
</Elements>
You could stop here and this solution will deploy your "sample.master" master page to the master page gallery of your site collection. 
This will not apply the master page to the site collection when the feature gets activated though. It will only make it available for selection.

If you want to apply your "sample.master" file, when the feature gets activated, add an event receiver to your feature via right-click on the feature and selection "Add Event Receiver".


Open "Feature1.EventReceiver.cs" and comment in "FeatureActivated" and "FeatureDeactivating" methods. Then paste the following code in it:

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
            try
            {
                using (SPSite site = (SPSite)properties.Feature.Parent)
                {
                    using (SPWeb web = site.RootWeb)
                    {
                        // Create full master url
                        Uri masterUri = new Uri(web.Url + "/_catalogs/masterpage/sample.master");

                        // Master page used by all forms and pages on the site that are NOT publishing pages
                        web.MasterUrl = masterUri.AbsolutePath;

                        // Master page used by all publishing pages on the site
                        web.CustomMasterUrl = masterUri.AbsolutePath;
                        web.Update();
                    }
                }
            }
            catch (Exception exp)
            {
                throw exp;
            }
}

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
            try
            {
                using (SPSite site = (SPSite)properties.Feature.Parent)
                {
                    using (SPWeb web = site.RootWeb)
                    {
                        // Create full master url
                        Uri masterUri = new Uri(web.Url + "/_catalogs/masterpage/v4.master");

                        // Master page used by all forms and pages on the site that are NOT publishing pages
                        web.MasterUrl = masterUri.AbsolutePath;

                        // Master page used by all publishing pages on the site
                        web.CustomMasterUrl = masterUri.AbsolutePath;
                        web.Update();
                    }
                }
            }
            catch (Exception exp)
            {
                throw exp;
            }
}



If you activate the feature, the code in the feature receiver will be executed and will apply "sample.master" to the site collection. As you can see we change both the MasterUrl and the CustomMasterUrl. The MasterUrl is used on all pages that are not publishing pages. This means it is used on the pages in the sitepages library and on the pages in the _layouts directory like the settings page for instance. The CustomMasterUrl is only used on pages that are stored in the Pages library. This library is created when the SharePoint Server Publishing Infrastructure features is activated on the site collection and the SharePoint Server Publishing feature is activated on the site.

Friday, November 6, 2015

PHP - Debugging PHP in Visual Studio

Hi there,

I've found a very, very nice tool for developing PHP applications / websites in Visual Studio.
You can even debug your code line for line as usual in Visual Studio.
Here is the link to the tool:

https://visualstudiogallery.msdn.microsoft.com/6eb51f05-ef01-4513-ac83-4c5f50c95fb5

SQL Server 2008 - Creating an empty GUID

You can create a empty guid with this SQL code:

select CAST(0x0 AS UNIQUEIDENTIFIER) as [emptyGuid]

Tuesday, April 28, 2015

C# - using "params" in method parameter


You can define a method with "params":

void Method(string s, params object[] param)

That means, you can use this code to add parameters to the method 

Customer customer;
Method("bla", customer.CustomerID, customer.CustomerSearchName);

instead of defining this:

void MethodKacke(string s, object[] param)

Then the method parameters had to  be like this:


MethodKacke("bla", new object[] { customer.CustomerID, customer.CustomerSearchName });

So using params is the more easy way. :-)

Wednesday, March 25, 2015

SQL Server 2008 - Get primary key in INSERT SQL statement

This tutorial is about to receive the primary key of a new inserted dataset.

declare @CreatedID bigint
exec sp_MyStoredProcedure parameter1, parameter2, @CreatedID OUTPUT
select @CreatedID

The stored procedure looks like this:
ALTER PROCEDURE [dbo].[sp_MyStoredProcedure]
@parameter1 int,
@parameter2 int,
@CreatedID BIGINT OUTPUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

insert into 
tbl_MyTable
(
field1,
field2
)
values
(
@parameter1,
@parameter2
);
SELECT @CreatedID = CAST(SCOPE_IDENTITY() as bigint)
END

Wednesday, March 4, 2015

C# - How to implement the IList Interface into a collection class

Yesterday I learned how to implement interfaces into my classes. 
I will show you, how to implement the IList interface into my custom collection class.
It's very simple. :-)

First we have to add 2 references to your class:

using System.Collections.Generic;
using System.Collections;
Then you have to add the interface behind your class name:

namespace MyProject.Classes
{
    class CollectionBase<T> : Connection, IList<T>
...

My example code is a universal collection class. Therefore, there is the type not defined of the IList not defined. You could write instead IList<MyClass>.

After added the interface name to the class, we can use the Visual Studio feature "Implement Interface":






The following code will be added automatically:

public int IndexOf(T item)
{
throw new NotImplementedException();
}

public void Insert(int index, T item)
{
throw new NotImplementedException();
}

public void RemoveAt(int index)
{
throw new NotImplementedException();
}

public T this[int index]
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}

public void Add(T item)
{
throw new NotImplementedException();
}

public void Clear()
{
throw new NotImplementedException();
}

public bool Contains(T item)
{
throw new NotImplementedException();
}

public void CopyTo(T[] array, int arrayIndex)
{
throw new NotImplementedException();
}

public int Count
{
get { throw new NotImplementedException(); }
}

public bool IsReadOnly
{
get { throw new NotImplementedException(); }
}

public bool Remove(T item)
{
throw new NotImplementedException();
}

public IEnumerator<T> GetEnumerator()
{
throw new NotImplementedException();
}

IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}

Now we have all methods declared, but not defined yet.
We add now a list of our class to store to code:

#region Variables
private List<T> _InternalList = new List<T>();
#endregion

This list we can use to store all objects from the given class.

Now we have to modify the methods:

public int IndexOf(T item)
{
return _InternalList.IndexOf(item);
}

public void Insert(int index, T item)
{
_InternalList.Insert(index, item);
}

public void RemoveAt(int index)
{
_InternalList.RemoveAt(index);
}

public T this[int index]
{
get
{
        return _InternalList[index];
}
set
{
_InternalList[index] = value;
}
}

public void Add(T item)
{
_InternalList.Add(item);
}

public void Clear()
{
_InternalList.Clear();
}

public bool Contains(T item)
{
return _InternalList.Contains(item);
}

public void CopyTo(T[] array, int arrayIndex)
{
_InternalList.CopyTo(array, arrayIndex);
}

public int Count
{
get 
{
return _InternalList.Count;
}
}

public bool IsReadOnly
{
get 
{
return false;
}
}

public bool Remove(T item)
{
return _InternalList.Remove(item);
}

public IEnumerator<T> GetEnumerator()
{
return _InternalList.GetEnumerator();
}

System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return (IEnumerator)this;
}

Now we have the interface implemented and are able to use the collection.

Here is the complete code:

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

namespace MyProject.Classes
{
    class CollectionBase<T> : Connection, IList<T>
    {
        #region Variables
        private List<T> _InternalList = new List<T>();
        #endregion

        #region Properties
        #endregion

        #region Constructors
        public CollectionBase()
        {
        }
        #endregion

        #region Methods
        #endregion

        #region IList Interface
        public int IndexOf(T item)
        {
            return _InternalList.IndexOf(item);
        }

        public void Insert(int index, T item)
        {
            _InternalList.Insert(index, item);
        }

        public void RemoveAt(int index)
        {
            _InternalList.RemoveAt(index);
        }

        public T this[int index]
        {
            get
            {
                return _InternalList[index];
            }
            set
            {
                _InternalList[index] = value;
            }
        }

        public void Add(T item)
        {
            _InternalList.Add(item);
        }

        public void Clear()
        {
            _InternalList.Clear();
        }

        public bool Contains(T item)
        {
            return _InternalList.Contains(item);
        }

        public void CopyTo(T[] array, int arrayIndex)
        {
            _InternalList.CopyTo(array, arrayIndex);
        }

        public int Count
        {
            get 
            {
                return _InternalList.Count;
            }
        }

        public bool IsReadOnly
        {
            get 
            {
                return false;
            }
        }

        public bool Remove(T item)
        {
            return _InternalList.Remove(item);
        }

        public IEnumerator<T> GetEnumerator()
        {
            return _InternalList.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return (IEnumerator)this;
        }
        #endregion
    }
}

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