Wednesday, January 3, 2018

Query XML with SQL

I've just learned how to query an xml structure with SQL.
I'm presenting you a simple example. Assuming your XML column looks like this:

<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.xyz.de/activerepository/fileprops">
  <props>
    <prop ns="ARM:" elem="_NoFilter">
      <value xsi:type="xsd:boolean">true</value>
    </prop>
    <prop ns="DAV:" elem="displayname">
      <value xsi:type="xsd:string">Some text in it</value>
    </prop>
    <prop ns="DAV:" elem="getcontenttype">
      <value xsi:type="xsd:string">message/rfc822</value>
    </prop>
    <prop ns="DAV:" elem="creationdate">
      <value xsi:type="xsd:dateTime">2017-01-02T09:38:28.1278078</value>
    </prop>
  </props>
</root>
...you can write this query to get single values from the XML. In my example, I want to query the displayname prop.

SELECT 
  CAST(properties as xml).value('(/root/props/prop[@elem="displayname"]/value)[1]','nvarchar(max)') as [displayname],
  *
FROM   

  tm_cas_files (nolock)

The result will be:

displayname

Some text in it

See also this Stackoverflow link to get more details:
https://stackoverflow.com/questions/48075328/sql-xml-how-to-query-specific-node

Thursday, November 23, 2017

Apache - Enable gzip compression with .htaccess

Today I found a simple method to enable gzip compression on your homepage, when you are using Apache webserver. You just have to create a .htaccess file with this code, assuming you have mod_deflate enabled in your Apache config.


<IfModule mod_deflate.c>
<FilesMatch "\\.(js|css|html|xml|jpg|png)$">
SetOutputFilter DEFLATE
</FilesMatch>
</IfModule>

This code snippet provides gzip compression for all js, css, html, xml, jpg and png files.
Ok. Images are most time already compressed, but I added them as well.
Very simple and very useful. :-)

Thursday, November 16, 2017

SQL - Use PARSENAME function to extract individual parts from a string

Today I discovered a very cool feature in T-SQL from Microsoft SQL Server.
It happens (unfortunately) again and again that several records are written in a single column and one is forced to extract individual parts from it. So far, I have always written a SQL function of my own, but this is will be history from now on with the help of the PARSENAME function. :-)

See this examples. I think, this explains it very well:

DECLARE @exampleString nvarchar(max) = 'Test;Test1;Test2' 
SELECT PARSENAME(REPLACE(@exampleString,';','.'),1)

--Result: Test2

SELECT PARSENAME(REPLACE(@exampleString,';','.'),2)

--Result: Test1

SELECT PARSENAME(REPLACE(@exampleString,';','.'),3)

--Result: Test

Tuesday, October 10, 2017

SharePoint 2010 - How to check if group exists without exception

The SharePoint Server handles some things differently than you might know from standard C # programs.
I recently stumbled upon that I've tried to determine if a user group exists in SharePoint. I thought no problem and tried it with this code:

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

I assumed that the variable group is null if the group is not present, but SharePoint throws an exception instead.
This does not happen with the following code snippet:

using System.Linq;
...
string nameOfGroupToCheck = "Test Group";
if (spWeb.Groups.OfType<SPGroup>().Where(g => g.Name == nameOfGroupToCheck).Count() > 0)
{
  ...
}

To get this code work correctly, you need to add the System.Linq namespace into your code.

By the way, this check also works with lists in SharePoint. You would only have to query the lists instead of the groups.


Friday, July 22, 2016

jQuery - Searching a multi-dimensional array

Last days ago, I had an issue to search multi-dimensional arrays in JavaScript / jQuery.
This post will give you a quick example how it works.

First we create an multi-dimensional array.
In my example we create an array for each employee...

var hansi = { firstName: "Hansi", lastName: "Hansen", wage: "2000" };
var paul = { firstName: "Paul", lastName: "Paulsen", wage: "1900" };
var otto = { firstName: "Otto", lastName: "Ottensen", wage: "1500" };
var thomas = { firstName: "Thomas", lastName: "Tomate", wage: "2500" };

...and then push them all together in another array. And here is our multi-dimensional array:

var employees = [hansi, paul, otto, thomas];

Now we want to search for an employee with the first name "Thomas", so we define a variable with the search term:

var searchValue = "Thomas";

Then we use the grep function from jQuery to search for the term "Thomas" in our multi-dimensional array:

var result = $.grep(employees, function (e) {
   return e.firstName == searchValue;
});

Now we just need to check our results variable:

if (result.length == 0) {
   alert('Error: ' + searchValue + ' not found');
} else if (result.length == 1) {
   employee = result[0];
} else {
   alert('Error: Multiple items found');
}

See the results:

Employee Details: First Name: Thomas / Last Name: Tomate / Wage: 2500

Here is the complete code again:

<!DOCTYPE html>
<head>
<script   src="https://code.jquery.com/jquery-3.1.0.min.js"   integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s="   crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function() {

var hansi = { firstName: "Hansi", lastName: "Hansen", wage: "2000" };
var paul = { firstName: "Paul", lastName: "Paulsen", wage: "1900" };
var otto = { firstName: "Otto", lastName: "Ottensen", wage: "1500" };
var thomas = { firstName: "Thomas", lastName: "Tomate", wage: "2500" };

var employees = [hansi, paul, otto, thomas];

var searchValue = "Thomas";
var result = $.grep(employees, function (e) {
return e.firstName == searchValue;
});

if (result.length == 0) {
alert('Error: ' + searchValue + ' not found');
} else if (result.length == 1) {
employee = result[0];
} else {
alert('Error: Multiple items found');
}

document.write("Employee Details: ");
document.write("First Name: " + employee.firstName + " / ");
document.write("Last Name: " + employee.lastName + " / ");
document.write("Wage: " + employee.wage + " ");
});
</script>
</head>
<body>
</body>
</html>


Tuesday, July 19, 2016

SQL - Fehler - ARITHABORT

Heute mal in Deutsch, da ich den genauen Wortlaut der englischen Fehlermeldung nicht kenne. :-)

Das Thema ist mal wieder SQL.



Ich hatte vor kurzem bei einem SQL Statement folgenden Fehler:

"Fehler bei SELECT, da die folgenden SET-Optionen falsche Einstellungen aufweisen: 'ARITHABORT'. Überprüfen Sie, ob die SET-Optionen für die Verwendung mit indizierten Sichten und/oder Indizes für berechnete Spalten und/oder gefilterte Indizes und/oder Abfragebenachrichtigungen und/oder XML-Datentypmethoden und/oder Vorgänge für räumliche Indizes richtig sind."

Dieser Fehler ist in der Regel recht einfach zu beheben. Es muss lediglich der Wert für ARITHABORT auf ON festgelegt werden und schon funktioniert die Abfrage (zumindest in meinem Fall :-) ).

SET ARITHABORT ON
...

Ich hoffe, ich euch damit viel Sucherei ersparen...

Friday, July 15, 2016

SQL Query - Get multiple row results in one column with XML and STUFF()



Today I want to show you, how you can put the results of an SQL query into one column.

First I create a temporarily table for our data and fill some data in it:

CREATE TABLE #table (product nvarchar(255)) 

INSERT INTO #table
SELECT 'product-1' as product
UNION 
SELECT 'product-2' as product
UNION 
SELECT 'product-3' as product
UNION 
SELECT 'product-4' as product


Now we have our base table for our query. Here are the results of this table

Query:
select * from #table

Results:
product
product-1
product-2
product-3
product-4

Now we can see, we have 4 rows with our example products. Maybe we have a requirement to put all products in one row. This can be done by using the STUFF function and XML.
Here is the code:

select STUFF((SELECT distinct ',' + t.product
                    from #table t (nolock)
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'') as allProducts

Now the result of this query is this:

allProducts
product-1,product-2,product-3,product-4


Hope you enjoyed this lesson.

Tuesday, July 5, 2016

SharePoint 2010 - New Feature in already deployed solution does not appear




Yesterday, I have created a new feature in an existing SharePoint 2010 solution.
I wrote my code and added the parts to the feature. When I finished my work, I update the solution as usual with this code:

Update-SPSolution -Identity mysolution.wsp -LiteralPath "C:\C#\_DN\MySolution\MySolution\bin\Debug\mysolution.wsp" -GACDeployment

Next, I went to the site collection features and wanted to activate it, but the feature was not appearing in the site collection feature list. What the ...!?!?

After a short Google search I found a solution for this problem.  We need to execute some commands in the PowerShell (SharePoint 2010 Management Shell):

Install-SPFeature -ScanForFeatures

This command will list all not installed features.
You will find your new feature in this list. Now you can install it with the following command:

Install-SPFeature -AllExistingFeatures

After successful execution of this command your feature will appear.

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));