All About SharePoint

Liedong(Ken) Zheng,SharePoint Leader at SIMPLOT

Archive for November, 2010

Pass Proxy Server URL rto HTTPWebRequest

Posted by ken zheng on November 30, 2010

Below is the example code that you can pass proxy server url

            HttpWebRequest webRequest = null;
            string strResult = null;
            try
            {
                // Create a new web request
                webRequest = WebRequest.Create(url) as HttpWebRequest;
                // Check if ProxyServerUrl in the appSettings is not empty
                if (!string.IsNullOrEmpty(WebConfigurationManager.AppSettings["ProxyServerUrl"].ToString()))
                {
                    // instantiate a new WebProxy class and send the ProxyServerUrl to the contructor parameter
                    System.Net.WebProxy proxy = new System.Net.WebProxy(WebConfigurationManager.AppSettings["ProxyServerUrl"].ToString(), 
true);
                    // Set the proxy credentials
                    proxy.Credentials = new NetworkCredential(WebConfigurationManager.AppSettings["PassThroughUser"].ToString(),
 WebConfigurationManager.AppSettings["PassThroughPwd"].ToString());
                    // Set the WebRequest proxy property by the WebProxy class already configured
                    webRequest.Proxy = proxy;
                }
                // Read the response
                using (StreamReader sr = new StreamReader(webRequest.GetResponse().GetResponseStream()))
                {
                    // Set strResult to the response
                    strResult = sr.ReadToEnd();
                }
            }
            catch
            {
            }

Posted in vs2010 | Tagged: | 1 Comment »

Using SPSecurity.RunWithElevatedPrivileges with SPContext.Current

Posted by ken zheng on November 23, 2010

You may get exception if you using RunWithElevatedPrivileges like below

    SPSecurity.RunWithElevatedPrivileges(delegate() {

        SPSite siteColl =    SPContext.Current.Site;
        SPWeb site = SPContext.Current.Web;
     //Code to execute

    });

That’s because SPSite object permissions are determined when they are created, so SPContext.Current.Site will already have the permissions of the current user even if you get the reference within RWEP.

The code should look like below:

SPSite siteColl = SPContext.Current.Site;
SPWeb site = SPContext.Current.Web;
SPSecurity.RunWithElevatedPrivileges(delegate() {
  using (SPSite ElevatedsiteColl = new SPSite(siteColl.ID)) {
    using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb(site.ID)) {
        //Code to execute
    }
  }
});

Posted in Sharepoint | Tagged: , | Leave a Comment »

AnythingSlider to Multiple Announcement Lists in SharePoint 2010

Posted by ken zheng on November 19, 2010

From Dave’s blog, I changed a little bit. First, I upload all the anythingslider into a slider library that can be easily managed.

image
Below is the XSLT I used.
<Xsl>
<xsl:stylesheet xmlns:x="http://www.w3.org/2001/XMLSchema&quot; xmlns:d="http://schemas.microsoft.com/sharepoint/dsp&quot; version="1.0" exclude-result-prefixes="xsl msxsl ddwrt" xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime&quot; xmlns:asp="http://schemas.microsoft.com/ASPNET/20&quot; xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer&quot; xmlns:xsl="http://www.w3.org/1999/XSL/Transform&quot; xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:SharePoint="Microsoft.SharePoint.WebControls" xmlns:ddwrt2="urn:frontpage:internal">
<xsl:output method="html" indent="no"/>
<xsl:decimal-format NaN=""/>
<xsl:param name="dvt_apos">&apos;</xsl:param>
<xsl:variable name="dvt_1_automode">0</xsl:variable>
<xsl:template match="/" xmlns:x="http://www.w3.org/2001/XMLSchema&quot; xmlns:d="http://schemas.microsoft.com/sharepoint/dsp&quot; xmlns:asp="http://schemas.microsoft.com/ASPNET/20&quot; xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer&quot; xmlns:SharePoint="Microsoft.SharePoint.WebControls">
<xsl:call-template name="dvt_1"/>
</xsl:template>
<xsl:template name="dvt_1">
<xsl:variable name="Rows" select="/dsQueryResponse/Rows/Row" />
<link rel="stylesheet" href="/slider/page.css" type="text/css" media="screen" />
<link rel="stylesheet" href="/slider/anythingslider.css" type="text/css" media="screen" />
<script type="text/javascript" src="/slider/jquery.easing.1.2.js"></script> <script src="/slider/jquery.anythingslider.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript">
function formatText(index, panel) {
return index + &quot;&quot;;
}
$(function () {
$(&apos;.anythingSlider&apos;).anythingSlider({
easing: &quot;easeInOutExpo&quot;,
autoPlay: true,
delay: 3000,
startStopped: false,
animationTime: 600,
hashTags: true,
buildNavigation: true,
pauseOnHover: true,
startText: &quot;Go&quot;,
stopText: &quot;Stop&quot;,
navigationFormatter: formatText
});
$(&quot;#slide-jump&quot;).click(function(){
$(&apos;.anythingSlider&apos;).anythingSlider(6);
});
});
</script>
<div class="anythingSlider">
<div class="wrapper">
<ul>
<xsl:call-template name="dvt_1.body">
<xsl:with-param name="Rows" select="$Rows" />
</xsl:call-template>
</ul>
</div>
</div>
</xsl:template>
<xsl:template name="dvt_1.body">
<xsl:param name="Rows" />
<xsl:for-each select="$Rows">
<xsl:call-template name="dvt_1.rowview" />
</xsl:for-each>
</xsl:template>
<xsl:template name="dvt_1.rowview">
<li>
<div class="textSlide">
<!– display the item title and a link to the item –>
<h3><a href="/{@FileDirRef}/DispForm.aspx?ID={@ID}" title="{@Title}"><xsl:value-of select="@Title" /></a></h3>
<!– display the body of the item –>
<xsl:value-of select="@Body" disable-output-escaping="yes" />
</div>
</li></xsl:template>
</xsl:stylesheet>
</Xsl>

To have data view across multiple lists (same fields). Just click Configure Data Source, add lists you want.

In the Data Source Details task pane, in the Details Panel, select the fields you want and Click Insert Selected Fields as, and then click Multiple Item View to insert the selected data into the Data View.

You can see more details on this tutorial.

Posted in Sharepoint | Tagged: , , | 3 Comments »

Create an AdditionalPageHead control packed into a Feature in Visual Studio 2010

Posted by ken zheng on November 18, 2010

It did take me a while to understand how could I package a solution by VS 2010.

I use JQuery UserControl as an example and assume you have JQuery Library installed already

1. First, create an empty SharePoint project

image

Choose deploy as farm solution

2. Add new feature by right click the Feature Folder, we will create a Site Collection Feature

image

3. Create 2 Mapped Folders

image

4. In JQueyTest.JS just have a simplt JQuery Script

$(document).ready(function () {
    $("a").click(function (event) {
        alert("Thanks for visiting!");
    });
});

5. the code in your ascx

<%@ Control Language="C#" ClassName="Ken.Test.JQuery" %>
<script type="text/javascript" src="/_layouts/Ken.Test.JQuery/JQueryTest.js"></script>

 

6. Create an empty element file that can reference our user control

image

7. In the Elements.xml file should look like

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

<Elements xmlns="

http://schemas.microsoft.com/sharepoint/"
>

  <Control

Id="AdditionalPageHead"

ControlSrc="~/_controltemplates/Ken.Test.JQuery/Ken.Test.JQuery.ascx"

Sequence="12"/>

</Elements>

8. Now in your feature you should see like

image

9. Your Solution List should look like

image

10. Now if we click the Package button, then go to Bin\Debug folder, there is a WSP has been created. Rename the extension to .CAB file, then you can double click to see all files in the package

 image

11. If we deploy now, it will deploy the dll to the GAC which is not required. To remove the GAC deployment we have to modify the Package file

12. Now we need to double click the Package.package, then click the Manifest button and Click the “Overwrite …” to manually remove the Assemblies part

image

image

13. All ready to go! Click the deploy button and then go to your test page. If you click any link you will get an alert box

image

14. If you found it not working, here is some tips to find what is wrong

A. Check your site collection feature to see if the feature has been actived

B. Right click the page and view source to see if your user control is there

C. Check the 14 folder to make sure your feature, user control and script is there

D. Make sure the element file point to the right path or name

Posted in Sharepoint, vs2010 | Tagged: , , , | 2 Comments »

Change Ribbon Head Background in SharePoint 2010

Posted by ken zheng on November 17, 2010

To update the background of the Ribbon row from

image

to

image

First, create a css file under “\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\template\layouts\1033\STYLES\” and put your background image to “Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\template\layouts\1033\IMAGES”

then in the master page, add below to the head tag

<SharePoint:CssRegistration name=”customfolder/samplecustom.css” After=”corev4.css” runat=”server”/> 

Note: Alternate CSS on Server and comes after corev4.css.

Output Order:

  1. <link rel="stylesheet" type="text/css" href="/_layouts/1033/styles/Themable/corev4.css"/>
  2. <link rel="stylesheet" type="text/css" href="/_layouts/1033/styles/customfolder/samplecustom.css"/>

 

So in your samplecustom.css file you add

body, body.v4master{background:#fff;}

Body #s4-ribbonrow{
	background:url(/_layouts/1033/IMAGES/SimplotBanner2.jpg)
}

 

Checked in and publish the master page. you are done.

Posted in Sharepoint | Tagged: , , | 6 Comments »

PowerShell Replace Script

Posted by ken zheng on November 17, 2010

Below is the script that loop folder to replace the string in all XML files.

The string I need to place is the href link in InfoPath form. So it look like

href="http://ppp/ppp/template.xsn"

 

So I use the way to replace string in between the characters

'bleeeh' -replace '(bl).+(h)','$1cc$2' 

 

This will print out: blcch

The whole script is look like:

Param($Path = "D:\Temp",[switch]$verbose)

Write-Host

$fc = new-object -com scripting.filesystemobject
$folder = $fc.getfolder($path)
$strFinder = '(href="http://).+(template.xsn)'

function ProcessFiles([string]$folderpath) {

Write-host " + Processing all Forms from: $folderpath"
$Forms = dir $folderpath "*.xml"

Write-host "  + $($Forms.count) Forms found"
Write-host " + Processing all $($Forms.count) Forms located at: $folderpath" -fore White

	foreach($Form in $Forms)
	{
		$strReplace ="$1XXX$2"
		Write-Host "  + +	Processing Form: $($Form.Name)" -fore White
		if($Form.Name.Contains("IPP")){$strReplace ='$1IPP$2'}
		elseif($Form.Name.Contains("EDP")){$strReplace ='$1EDP$2'}
		Replace-String  $strFinder $strReplace $Form.FullName
	}	
}

function Replace-String($find, $replace, $path)
{
	echo "Replacing string `"$find`" with string `"$replace`" in file contents and file names of path: $path"
	ls $path | select-string $find -list |% { echo "Processing contents of $($_.Path)"; (get-content $_.Path) |% { $_ -replace $find, $replace } | set-content $_.Path -Force }
}

Write-Host "$($folder.ShortName) "
Write-Host "  + Total Folders: $($folder.SubFolders.Count)"
foreach ($i in $folder.SubFolders) {
	Write-Host "  + Folder Name: $($i.ShortName)"
	ProcessFiles($i.Path)
}

 

Love PowerShell

Posted in PowerShell | Tagged: | Leave a Comment »

Show a Favicon in SharePoint 2010

Posted by ken zheng on November 15, 2010

In SharePoint 2010 there is a special control for adding favicons:

<SharePoint:SPShortcutIcon runat="server" IconUrl="/Style%20Library/favicon.ico"/>

But I found for IE 7 you need add

	<link rel="shortcut icon" href="/Style%20Library/favicon.ico">
	<link rel="icon" href="/Style%20Library/favicon.ico">

in your head tag of the master page too.

image

Be careful because IE sometimes caches the heck out of the favicon state. Make sure you make a new bookmark and clear the cache and close and open IE. Firefox sometimes is easier. So you may see the effect after a while

Also you can replace the icon permanently by

\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\IMAGES\

Posted in Sharepoint | Tagged: , | 2 Comments »

Programmatically creating Sites from a Custom Web Template

Posted by ken zheng on November 15, 2010

In SharePoint 2010, you still can use

SPWeb newSite = web.Webs.Add(url, title, desc, LCID, templateName, true, false);

but the templateName is a string like ‘{Template-GUID}#TemplateName’.

I use below power shell script to get all templates

[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

$url = "http://chidev51/sites/subsite"

$site= new-Object Microsoft.SharePoint.SPSite($url )
$loc= [System.Int32]::Parse(1033)
$templates= $site.GetWebTemplates($loc)

foreach ($child in $templates)
{
    write-host $child.Name "  " $child.Title
}
$site.Dispose()

 

Or in the code:

 // Get Web Template
    SPWebTemplateCollection webTemplates = site.RootWeb.GetAvailableWebTemplates(1033);
    SPWebTemplate webTemplate = (from SPWebTemplate t
                                 in webTemplates
                                 where t.Title == "test"
                                 select t).FirstOrDefault();
 webTemplate.Name

 

Here is a example that you can create site collection based on Custom Web Template


http://blog.mastykarz.nl/programmatically-creating-sites-site-collections-custom-web-template/

Posted in PowerShell, Sharepoint | Tagged: , | 32 Comments »

SharePoint 2010 development target framework

Posted by ken zheng on November 15, 2010

When you converting exisitng projects to 2010, make sure the target framework set to 3.5 not 2.0 (that new SharePoiint dll cannot be referenced) or 4.0

Posted in .Net, Sharepoint, vs2010 | Leave a Comment »

An exception occurred while enqueueing a message in the target queue. Error: 15404, State: 19. Could not obtain information about Windows NT group/user ‘DOMAIN\ppsservice’, error code 0×5.

Posted by ken zheng on November 15, 2010

The problem I found was the SQL Server Service was running on a invalid admin account.

image

Once I changed the account, no errors anymore

Posted in Sharepoint, SQL | Tagged: , | 4 Comments »

 
Follow

Get every new post delivered to your Inbox.

Join 28 other followers