Friday, June 24, 2016

SharePoint - JavaScript - Get parameter from current URL

Today, just one short code snippet to read out an URL parameter with the SharePoint JavaScript libraries:

GetUrlKeyValue(parameter, noDecode, url) is a JavasSript function which we can use to get a query string parameter either from url in the browser or a url we specify.

parameter (string): Query string parameter from the url. 
noDecode (bool)(optional): Specifies whether the value has to be encoded or not. If false value is decoded, else returned as it is. 
url (string)(optional): the url from which Query string values are to be retrieved.(Optional)

Example:

alert(GetUrlKeyValue('a', false, 'www.abc.com?a=te%20sting'));
The above statement will return the value ‘te sting’ from the url paramter a. Here we are specifying our own url.


alert(GetUrlKeyValue('a', false));
The above statement will look for a query string variable a in the browser url, and returns the decoded value.


alert(GetUrlKeyValue('a'));
The above statement will look for a query string variable a in the browser url.

Thursday, June 23, 2016

Code Snippet - SQL - Replacing line breaks with SQL query

If you have line breaks in an SQL string field and you want to replace or remove them, you can use the following code (bold marked):

UPDATE details SET user_text = REPLACE(REPLACE(user_text, char(10), char(32)), char(13), char(32));

Friday, February 26, 2016

SQL Server - Finding values in different columns with CROSS APPLY

I've found a nice way to check values in different columns in an SQL Server table and return only the columns where the search value is in.

In my example, we have a table with several columns (No1 - No7). We want to find out which columns have the value 8 in it and only return these ones.

Check the code:

First we create a table to check.

DECLARE @t TABLE (AdrNr INT, Nr1 INT, Nr2 INT, Nr3 INT, Nr4 INT, Nr5 INT, Nr6 INT, Nr7 INT)

Then we enter some values in it:

INSERT INTO @t
VALUES (500, 3, 4, 8, 42, 5, 76, 91)

This is the SQL code to return only the columns where the value "8" can be found:

SELECT AdrNr, a, b
FROM @t
CROSS APPLY (
    VALUES
        ('Nr1', Nr1),
        ('Nr2', Nr2),
        ('Nr3', Nr3),
        ('Nr4', Nr4),
        ('Nr5', Nr5),
        ('Nr6', Nr6),
        ('Nr7', Nr7)
) t(a, b)
WHERE b = 8

Friday, January 15, 2016

IIS 7+ - Force redirect to HTTPS version of website

If you have a website with a SSL certificate, you may want to redirect all visitors to the HTTPS version of your website by default.
This you can realize with the web.config file of your root directory, if your using IIS 7 or higher.
Just add the bold code part to your web.config file.

<?xml version="1.0" encoding="UTF-8"?> 
<configuration> 
  <system.webServer> 
    <rewrite> 
     <rules> 
      <rule name="HTTP to HTTPS redirect" stopProcessing="true"> 
       <match url="(.*)" /> 
       <conditions> 
        <add input="{HTTPS}" pattern="off" ignoreCase="true" /> 
       </conditions> 
       <action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}/{R:1}" /> 
      </rule> 
     </rules> 
    </rewrite> 
  </system.webServer> 
</configuration>

Monday, January 11, 2016

Tutorial - SQL Server 2014 Express - Job automation

Hi guys,

as you know, in Express Editions of Microsoft SQL Server the agent is not available. So it is difficult to create jobs, which run automated.
I've found a nice way via the command line to create automated SQL jobs without the SQL Server Agent.

First create your SQL statement and save it in an extra file. Name it i.e. "sqlCommand.sql".
Maybe you want to make a daily backup of your database, you create a statement like this, but it can be any valid SQL statement. This is just an example.

BACKUP DATABASE [db_myDatabase] TO  DISK = N'C:\Backup\SQL Server\db_myDatabase.bak' WITH NOFORMAT, INIT,  NAME = N'db_myDatabase-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10, CHECKSUM
GO
declare @backupSetId as int
select @backupSetId = position from msdb..backupset where database_name=N'db_myDatabase' and backup_set_id=(select max(backup_set_id) from msdb..backupset where database_name=N'db_myDatabase' )
if @backupSetId is null begin raiserror(N'Verify failed. Backup information for database ''db_myDatabase'' not found.', 16, 1) end
RESTORE VERIFYONLY FROM  DISK = N'C:\Backup\SQL Server\db_myDatabase.bak' WITH  FILE = @backupSetId,  NOUNLOAD,  NOREWIND
GO


I you have Microsoft SQL Server 2014 Express installed, you can navigate via command line to the following directory:

"C:\Program Files\Microsoft SQL Server\110\Tools\Binn"

In this directory you find a executable named "sqlcmd.exe".


This executable you can use to execute your SQL Statement saved in your file "SqlCommand.sql".
Replace <server> with your server / machine name and <sqlInstance> with your instance of your SQL Server. The parameter -i tells the executable what SQL script should run. Replace it where your SQL script is saved.

sqlcmd -S <server>\<sqlInstance> -E -i "C:\Jobs\SQL Server\SqlCommand.sql"

When you press enter, the command(s) in your SQL script will be executed.
Now you just have  to create a simple command line script, which can be executed in a task scheduler job.

Command-line script:
c:
cd\
cd "C:\Program Files\Microsoft SQL Server\110\Tools\Binn"
sqlcmd -S <server>\<sqlInstance> -E -i "C:\Jobs\SQL Server\SqlCommand.sql"


That's it. :-)

Wednesday, January 6, 2016

SharePoint 2010 - How to check if SPGroup exists

I've tried to check, if a SPGroup exists this way:

string nameOfGroupToCheck = "My SPGroup";
if(spWeb.Groups[nameOfGroupToCheck] != null)
{
...
}

...but this causes an exception, when the SPGroup is not existing.
Try this one:

string nameOfGroupToCheck = "My SPGroup";
if (spWeb.Groups.OfType<SPGroup>().Where(g => g.Name == nameOfGroupToCheck).Count() > 0)
{
...
}

Tuesday, November 24, 2015

SharePoint 2010 - Tutorial - Hiding Ribbon Items

Today I want to show you, how you can hide items from the ribbon bar.
We start as usual with an empty SharePoint project.
Add a new item to the project: User Control and give it a name (i.e. "RibbonControl.ascx").


Add the "Microsoft.Web.CommandUI.dll" reference from "c:\program files\common files\microsoft shared\web server extensions\14\isapi"-folder to your project.



Then open the code-behind file. In my case it is "RibbonControl.ascx.cs".


Add the following namespaces to your code:

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.Web.CommandUI;

Use the ribbon.TrimById() method to hide items in the ribbon bar.
Here are some examples. See a full list of all ribbon items here:

https://msdn.microsoft.com/en-us/library/office/ee537543(v=office.14).aspx

protected void Page_Load(object sender, EventArgs e)
{
            try
            {
                SPRibbon ribbon = SPRibbon.GetCurrent(this.Page);
                using (SPSite site = SPContext.Current.Site)
                {
                    //"Documents"-tab
                    ribbon.TrimById("Ribbon.Documents.Copies");
                    ribbon.TrimById("Ribbon.Documents.Workflow");
                    ribbon.TrimById("Ribbon.Documents.Share");
                    ribbon.TrimById("Ribbon.Documents.Manage.ManagePermissions");
                    ribbon.TrimById("Ribbon.Documents.TagsAndNotes");

                    //"Library"-tab
                    ribbon.TrimById("Ribbon.Library.ViewFormat");
                    ribbon.TrimById("Ribbon.Library.Share");
                    ribbon.TrimById("Ribbon.Library.Datasheet");
                    ribbon.TrimById("Ribbon.Library.Actions");
                    ribbon.TrimById("Ribbon.Library.CustomizeLibrary");
                }
            }
            catch (Exception exp)
            {
                throw exp;
            }
}

Then your user control is ready now.
The next step is to add your user control whereever you need it, i.e. to your master page, page, web parts etc..
To deploy a custom master page, see my blog post http://me-and-my-sharepoint.blogspot.de/2015/11/sharepoint-2010-tutorial-deploying.html
You can also use SharePoint Designer to modify a page.

I deployed a custom master page to hide ribbon items in all document libraries in a site collection.
Register the user control at the top of the page:

<%@ Register TagPrefix="custom" TagName="RibbonBarControl" src="~/_controltemplates/TestRibbonsHideProject/RibbonControl.ascx" %>




We've created user control for SharePoint 2010, registered it on the page. Now, the final step is to  include the user control in the page itself:


<custom:RibbonControl id="RibbonControl1" runat="server"></custom:RibbonControl>



Then we are ready to deploy the solution.

See the ribbon bar before activating our user control:



Then afterwards:



Hope you enjoyed it. Feel free to leave a comment, if you like (or not) ;-)

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]