Sunday, December 27, 2015

Step by Step Procedure to Migrate sites from MOSS 2007 to SharePoint 2013

Hi,

To migrate sites from MOSS 2007 to SharePoint 2013, we need to first perform two tasks.

a. Migration from MOSS 2007 to SharePoint 2010
b. Migration from SharePoint 2010 to SharePoint 2013

Please follow the above links to perform migration and let me know in case of any issues.

Thanks !

Sunday, October 18, 2015

Developing SharePoint 2007 Webparts using Visual Studio 2010

So for the purposes of this article I am going create a basic visual web part, something that was difficult to do in SharePoint 2007 development. This process should work for most project types available…
  1. Start New Project, select Visual Web Part
    image
  2. Select – Deploy as a farm solution
    image
  3. Write your custom web part. I have just created a simple web part that contains some text and a button. When the user clicks the button the button text will change.
    image
  4. I now press F5 on the keyboard and Visual Studio will automatically build & deploy my web part to SharePoint 2010.
  5. I confirm it all works by adding the web part to the page. Great! But there is nothing special so far.
    image
  6. Now to get it into SharePoint 2007! First lets try deploying the current wsp as it is…
  7. So we need to package up the solution.
    image
  8. Grab the wsp from the bin folder
  9. Copy to SharePoint 2007 server.
  10. Deploy to 2007 env and we get an error. The error tells us that it found a version number in the manifest that it doesnt understand.
    image “Solution manifest for solution ’48cae4c9-68ba-cccf5a89304′ failed validation, file manifest.xml, line 2, character 110: The ‘SharePointProductVersion’ attribute is not declared.

Solution

After the steps above:
  1. Go back into Visual Studio 2010.
  2. Double click the “Package.package” file
  3. Select “Manifest” down the bottom. Notice where is reads SharePointProductVersion=”14.0” in the xml file.
    image
  4. In the properties panel, clear out 14.0 in the SharePointProductVersion field. This removes the property all together from the manifest file.
    image
  5. We also need to change the assembly reference in the project from Microsoft.SharePoint.dll 14.0 to 12.0.
    To do this you will need to click the show all files icon in the solution explorer panel.  image  -Next, delete out Microsoft.SharePoint & delete out Microsoft.SharePoint.Security as these wont be on the SP 2007 environment.-Then you want to add a reference to Microsoft.SharePoint.dll but make sure its the 12.0 version found in C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI\Microsoft.SharePoint.dll
  6. Because we have built a ‘Visual Web Part’, Visual Studio 2010 automattically adds some imports into the ascx user control file which wont exists in SP 2007. Therefore you need to comment these references out. Obviously if we were doing a coded web part or a event receiver we would not need to do this step.Mine currently looks like this.
    image
  7. Package up your solution again and deploy on SP 2007 environment.
    image
  8. Active, test and your good to go.
    SharePoint 2007 webpart
Notes:
  • You will need Asp.Net 3.5 installed on your SharePoint 2007 environment.
  • This may not always be the right solution for you (depending on your project) but it certainly saves me a lot of time for those basic web parts.

Thursday, September 17, 2015

Update vs Systemupdate vs UpdateOverwriteVersion

When creating event receivers or workflows it might be interesting to look at the differences between the following SPListItem methods. The differences might be subtle but it can make a huge difference when you have extra event receivers or workflows attached to your SharePoint list or items.

Update()

  • Updates the item in the database.
  • Updates the “Modified” and “Modified by” values.
  • Creates a new version

Systemupdate()

  • Updates the item in the database.
  • No changes in the “Modified” and “Modified By” fields.
  • No new version.
  • Triggers the item events.

Systemupdate(true)

  • Same as Systemupdate() and increments the item version.
  • Using SystemUpdate(false) is exactly the same as SystemUpdate()

UpdateOverwriteVersion()

  • Updates the item but does not create a new version.
  • Updates the “Modified” and “Modified by” values.
Note that :
You can also disable the triggering of events by using “this.EventFiringEnabled = false;”. Do your update and enable the events again with “this.EventFiringEnabled = true;”

Monday, July 13, 2015

SharePoint 2010 Top Navigation Menu


Create Your List First

Before you install the Web Part you should create a custom list on your primary site collection, note the list will need to reside in the default lists location in the site collection: http://<your url>/lists/<your list>. You can name the list anything you want, you will be passing the list name to the Web Part in your master page, which will be described below. Here is a list of columns that you will need in your list.

ListColumns.png

The following List Columns are used by the Web Part:

List Column Name Description Field Name Type Additional Info
Title This field is already included in any list by default. LinkTitle Single line of text
Link URL The navigation link. Link_x0020_URL Single line of text
Link Order The order the link will appear in the menu. Link_x0020_Order Number
Show Menu Item Show or hide the menu item. Show_x0020_Menu_x0020_Item Choice Add 2 values: Yes No
Parent Menu The parent menu item. Parent_x0020_Menu Lookup Get Information From: choose <your list name> In this column: choose Title
OpenNewWindow Open link in a new window OpenNewWindow Yes/No


The name of the columns in the list are important because the column names are hard coded in the Web Part. The field name is what really matters here. The Web Part uses CAML queries to reference the fields in the list.

You should add a couple of items to your list so you can see some results once the Web Part is installed and configured in the Master Page. So how do you accomplish security trimming, simple.... You can apply permissions to each list item, slick.

Install The Web Part

After you have created your list, you can now install the Web Part, this is the easy part. Using another excellent tool SharePoint Solution Installer, it was simple to create an installation for the feature:
  • Download the zip file from the download section
  • From a Web Frontend, unzip the zip file you just downloaded
  • Run the setup.exe
  • Keep choosing next until you reach the Web Applications/Site Collections page, click on the desired webapp(s)/site collection(s) where the feature will be installed, then choose next
  • Choose Next, then Close to close out the setup
  • Your feature should be activated but if not, activate your feature from Site Collection Features (Site Actions->Site Settings->Site collection featues, under Site Collection Administration)

You will see a reference to SharePoint 2007 when running the setup, this is because the SharePoint Installer does not fully support SharePoint 2010, but it will install just fine.

Configure The Master Page

So now we have to add the Web Part to the Master Page. Using SharePoint Designer, open up your Master Page. I find the split view in SPD the easiest, so you can see the code and the design on one page. After opening your master page, you will need to register the assembly. At the top of the master page you will see several assembly declarations, we need to register the assembly so we can use it in the Master Page. Head to the end of the declaration section just before the first HTML tag and add this line:

<%@ Register TagPrefix="spNav" Namespace="spNavMenu2010" Assembly="spNavMenu2010, Version=1.0.0.0, Culture=neutral, PublicKeyToken=e7d947ded56689ec" %>

MasterPageRegister.png

Next we can add the Web Part to the Master Page. We are going to replace the top menu, but the Web Part can be configured as a side menu/vertical navigation as well. Find the the ContentPlaceHolder control for your top menu, should look something like this:

<asp:ContentPlaceHolder id="PlaceHolderHorizontalNav" runat="server">.

You will want to comment out everything between the beginning and closing ContentPlaceHolder tags.

<asp:ContentPlaceHolder id="PlaceHolderHorizontalNav" runat="server">
<!-- <SharePoint:AspMenu ID="TopNavigationMenu" .....> .... </SharePoint:AspMenu> <SharePoint:DelegateControl ...>...</SharePoint:DelegateControl> -->
</asp:ContentPlaceHolder>

Now add the new Web Part, make sure to put it between the beginning and ending ContentPlaceHolder tags:

<asp:ContentPlaceHolder id="PlaceHolderHorizontalNav" runat="server">
<spNav:spNavMenu2010 runat="server" id="TopNavigationMenu" Set_MenuList="<name of your list>" Set_ServerURL="<url of your SharePoint site>" />
<!-- <SharePoint:AspMenu ID="TopNavigationMenu" .....> .... </SharePoint:AspMenu> <SharePoint:DelegateControl ...>...</SharePoint:DelegateControl> -->
</asp:ContentPlaceHolder>

Just for clarity, you will notice that the original/commented out AspMenu is below the spNav Web Part we just added and is between the ContentPlaceHolder tags. There are a couple of parameters that are necessary for the Web Part to work, one is the name of the list you just created and the other is the URL of your primary site collection, where your list resides.... If you named your list MyList and your primary site collection url was http://myspsite then your Web Part would look like this:

<spNav:spNavMenu2010 runat="server" id="TopNavigationMenu" Set_MenuOrientation="horizontal" Set_TopNavigationMenu="yes" Set_MenuList="MyList" Set_ServerURL="http://myspsite"/>

NOTE: If this is a top menu, you will need to give it a special id - "TopNavigationMenu" or the menu items will display behind the webparts on the page. There is an additional parameter to force the id, but setting the id directly will suffice.

Once you add the menu, you should see it render from the SPD designer view, if it doesnt, try clicking on a different control in the Master Page, that will usually trigger an update. Save your work and publish/approve your master page.

After you confirmed the Web Part is working you should remove the original ASP Menu, while we have commented out the menu, it appears that SPD (and SharePoint as well) still reads/processes the control. After subsequent edits to the master page from SPD, I noticed that SPD was adding some garbage to the commented menu and causing the master page to produce errors. Problem resolved by removing the commented out ASP menu.

Register the navigation css file

Find this tag in your master page:
<SharePoint:ScriptLink language="javascript" name="core.js" OnDemand="true" runat="server"/>

Add this tag right after the tag referenced above:
<SharePoint:CssRegistration name="spNavigation/spNavigation.css" After="corev4.css" runat="server"/>

This will register the css file that is installed with the web part. You can customize the css file to meet your look and feel needs, see next section.

Change The Look And Feel

So now you want to customize the look and feel, we can do that... This is where things are much easier than the 2007 counterpart. There is a custom style sheet built right into the solution. SharePoint 2010 also makes this much easier as the rendering of the menu is much cleaner. The style sheet can be found here C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\template\LAYOUTS\1033\STYLES\spNavigation\spNavigation.css. The AspMenu has been preconfigured to look like the out of the box menu, feel free to customize for your needs.


Reference:
http://spnavigationmenu2010.codeplex.com/documentation













                                                          

Friday, June 19, 2015

How to download all deployed wsp solution files in SharePoint using powershell

$pathName = "<PATH to Save files>"
foreach ($solution in Get-SPSolution)  
{
     $solid = $Solution.SolutionID
     $title = $Solution.Name
     $filename = $Solution.SolutionFile.Name
     $solution.SolutionFile.SaveAs("$pathName\$filename")
}

Friday, June 5, 2015

Move Folder and Document permissions from once document library to other

Call MainMethod with necessary parameters.
It will copy the folder level/file level broken permissions.


public void MainMethod(string siteCollURL, string sourceRelativeURL, string destinationRelativeURL, string sourceLibName, string destinationLibName)
        {
            try
            {
                using (SPSite site = new SPSite(siteCollURL))
                {
                    using (SPWeb sourceWeb = site.AllWebs[sourceRelativeURL])
                    {
                        using (SPWeb targetWeb = site.AllWebs[destinationRelativeURL])
                        {
                            SPList sourceList = sourceWeb.Lists.TryGetList(sourceLibName);
                            SPList targetList = targetWeb.Lists.TryGetList(destinationLibName);
 
                            if (sourceList != null && targetList != null)
                            {
                                CopySecurity(sourceList, targetList, targetWeb, truefalse);
                                
                            }
  
                        }
                    }
                }
            }
            catch (Exception ex)
            { 
            
            }
        }
 
 
 public static void CopySecurity(SPList sourceList, SPList targetList, SPWeb targetWeb, bool includeItemSecurity, bool quiet)
        {
            if (!quiet)
            {
                LogEntry(string.Format("Start Time: {0}."DateTime.Now.ToString()));
            }
                
 
            try
            {
                if (sourceList.WriteSecurity != targetList.WriteSecurity)
                    targetList.WriteSecurity = sourceList.WriteSecurity;
 
                if (sourceList.ReadSecurity != targetList.ReadSecurity)
                    targetList.ReadSecurity = sourceList.ReadSecurity;
 
                
                SetFolderSecurity(targetWeb, sourceList, targetList, quiet);
                
            }
            catch (Exception ex)
            {
                
            }
            finally
            {
                if (!quiet)
                    LogEntry(string.Format("Finish Time: {0}.\r\n"DateTime.Now.ToString()));
            }
        }
 
 public static void SetFolderSecurity(SPWeb targetWeb, SPList sourceList, SPList targetList, bool quiet)
        {
            foreach (SPListItem sourceFolder in sourceList.Folders)
            {
                SPListItem targetFolder = null;
                foreach (SPListItem f in targetList.Folders)
                {
 
                    if (f.Folder.ServerRelativeUrl.Substring(targetList.RootFolder.ServerRelativeUrl.Length) ==
                        sourceFolder.Folder.ServerRelativeUrl.Substring(sourceList.RootFolder.ServerRelativeUrl.Length))
                    {
                        targetFolder = f;
                        break;
                    }
                }
                if (targetFolder == null)
                    continue;
                CopyRoles(sourceFolder, targetFolder);
                
            }
        }
 
 
private static void CopyRoles(SPListItem source, SPListItem taget)
        {
            if (source.HasUniqueRoleAssignments)
            {
                if (!taget.HasUniqueRoleAssignments)
                    taget.BreakRoleInheritance(false);
 
                for (int i = taget.RoleAssignments.Count - 1; i >= 0; i--)
                    taget.RoleAssignments.Remove(i);
 
                foreach (SPRoleAssignment role in source.RoleAssignments)
                {
                    //if role contains only "Restricted access" permission level
                    if (role.RoleDefinitionBindings.Count == 1 &&
                        role.RoleDefinitionBindings[0].Type == SPRoleType.Guest)
                    {
                        taget.RoleAssignments.Add(role.Member);
                    }
                    else
                        taget.RoleAssignments.Add(role);
                }
 
                taget.SystemUpdate(false);
            }
 
            // check items in the folder
            foreach (SPFile sourceFile in source.Folder.Files)
            {
                if (sourceFile.Item.HasUniqueRoleAssignments)
                {
                    foreach (SPFile destFile in taget.Folder.Files)
                    {
                        if (sourceFile.Name == destFile.Name)
                        {
                            // do copy permissions
                            CopyRoles2(sourceFile.Item, destFile.Item);
                            break;
                        }
                    }
                }
                
            }
        } 

private static void CopyRoles2(SPListItem source, SPListItem taget)
        {
            if (source.HasUniqueRoleAssignments)
            {
                if (!taget.HasUniqueRoleAssignments)
                    taget.BreakRoleInheritance(false);
 
                for (int i = taget.RoleAssignments.Count - 1; i >= 0; i--)
                    taget.RoleAssignments.Remove(i);
 
                foreach (SPRoleAssignment role in source.RoleAssignments)
                {
                    //if role contains only "Restricted access" permission level
                    if (role.RoleDefinitionBindings.Count == 1 &&
                        role.RoleDefinitionBindings[0].Type == SPRoleType.Guest)
                    {
                        taget.RoleAssignments.Add(role.Member);
                    }
                    else
                        taget.RoleAssignments.Add(role);
                }
 
                taget.SystemUpdate(false);
            }
        }

 
 

Thursday, April 16, 2015

Show alert in add new list item and show confirm in cacel button click

Create a JS file and place the below code

function CancelEvent()
{
if (confirm(confMessage)) {
    return true;
}
else
{
    e.preventDefault();
}
}

function SaveEvent()
{
   alert(saveMessage);
}

function addHandler()
{
$("input[id$=SaveItem]").attr("onclick","SaveEvent();" + $("input[id$=SaveItem]").attr("onclick"));
$("input[id$=diidIOGoBack]").attr("onclick","CancelEvent();" + $("input[id$=diidIOGoBack]").attr("onclick"));
}
_spBodyOnLoadFunctionNames.push('addHandler');

Put this in content editor webpart
<script src="/....../js/NewFormScript.js"></script>
<script>
var confMessage="Confirm 'Ok' to Cancel or 'Cancel' to retain";
var saveMessage = "After saving the record, please start the workflow";
</script>


custom-redirect-after-creating-a-new-sharepoint-item
$(document).ready(function() {
 
    var button = $("input[id$=SaveItem]");
    // change redirection behavior
        button.removeAttr("onclick");
        button.click(function() {
            var elementName = $(this).attr("name");
            var aspForm = $("form[name=aspnetForm]");
            var oldPostbackUrl = aspForm.get(0).action;
            var currentSourceValue = GetUrlKeyValue("Source", true, oldPostbackUrl);
            var newPostbackUrl = oldPostbackUrl.replace(currentSourceValue, "MyRedirectionDestination.aspx");
 
            if (!PreSaveItem()) return false;
            WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(elementName, "", true, "", newPostbackUrl, false, true));
        });
     
});

 

Tuesday, February 10, 2015

Hide the Actions Menu in SharePoint

Introduction

The article shows you have to hide or show the "Actions Menu" depending on the permissions of the current user; i.e., how to security trim your SharePoint pages. You do this by using the Sharepoint:SPSecurityTrimmedControl.

Background

I had to give my read-only users the site-level permission "Edit Personal User Information". However, giving them this permission turned on the "Site Actions" menu displaying the "View all site content" menu item. To resolve thism I wrapped the PublishingSiteAction:SiteActionMenu control in a Sharepoint:SPSecurityTrimmedControl.

Using the Code

SharePoint comes with a control for security trimming your pages, called Sharepoint:SPSecurityTrimmedControl. You can use this to hide certain elements and show certain elements depending on the permissions of the current user.
You use the control by:
  1. wrapping the control to be security trimmed with the Sharepoint:SPSecurityTrimmedControl.
  2. specifying what permissions a user can have in the Permissions property of the Sharepoint:SPSecurityTrimmedControl.
<Sharepoint:SPSecurityTrimmedControl runat="server" 
      Permissions="ManagePermissions,ViewPages,BrowseUserInfo,Open,EditMyUserInfo">
 <PublishingSiteAction:SiteActionMenu runat="server"/>
</SharePoint:SPSecurityTrimmedControl>
You can see the possible values that can be assigned to the Permissions property here: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spbasepermissions.aspx. For more info on the SPSecurityTrimmedControl class, visit this page: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.webcontrols.spsecuritytrimmedcontrol.aspx.

Thursday, February 5, 2015

Expanding and collapsing the left navigation in SharePoint 2010


Mehtod 1
 
/* File Created: January 27, 2015 */ $(document).ready(function () {     $('.s4-ql li ul').hide();     //Set the Images up        var Collapse = "/_layouts/images/collapse.gif";     var Expand = "/_layouts/images/expand.gif";     //alert($('.s4-ql ul li').find('ul').length);     $('.s4-ql ul li').find('ul').each(function (index) {         var $this = $(this);         $this.parent().find('>a:first .menu-item-text').parent().parent().parent().prepend(['<a class=\'min\' style=\'float:right; margin-left:5px;margin-top:6px;margin-right:5px;\'><img src=\'/_layouts/images/expand.gif\'/></a>'].join(''));         $this.parent().find('>span:first .menu-item-text').parent().parent().parent().prepend(['<a class=\'min\' style=\'float:right; margin-left:5px;margin-top:6px;margin-right:5px;\'><img src=\'/_layouts/images/expand.gif\'/></a>'].join(''));     });     $('.min').click(function () {         //Get Reference to img            var img = $(this).children();         //Traverse the DOM to find the child UL node            var subList = $(this).siblings('ul');         //Check the visibility of the item and set the image            var Visibility = subList.is(":visible") ? img.attr('src', Expand) : img.attr('src', Collapse); ;         //Toggle the UL            subList.slideToggle();     });     var status = 0;     var currentURL = $(location).attr('href');     if ($(".s4-ql ul li ul li a").length > 0) {         $(".s4-ql ul li ul li a").each(function () {             var eachUrl = $(this).attr('href');             if (currentURL.toLowerCase().indexOf(eachUrl.toLowerCase()) > 0) {                 $(this).parent().parent().parent().find('a:first').click();                 status = 1;             }         });     }     if (status == 0) {         if ($(".s4-ql ul li a").length > 0) {             $(".s4-ql ul li a.menu-item").each(function () {                 var eachUrl = $(this).attr('href');                 //if(eachUrl != undefined)                 {                     if (currentURL.toLowerCase().indexOf(eachUrl.toLowerCase()) > 0) {                         $(this).parent().find('a:first').click();                         status = 1;                     }                 }             });         }     }     if (status == 0) {         //$('.min').click();     } });

 

 
 
Method2
//Mark as hidden
    $('.s4-ql ul.root > li > a.menu-item').attr('data-hide', '1');
    $('.s4-ql ul.root > li > span.menu-item').attr('data-hide', '1');
    //Hide the children
    $('.s4-ql ul.root ul').hide();
    var url = window.location.toString().toLowerCase();
    $('.s4-ql ul.root > li > a.menu-item, .s4-ql ul.root > li > span.menu-item').each(function (index) {
        var $this = $(this);
        var thisURL = $this.attr('href');
        if (thisURL)
            thisURL = thisURL.toLowerCase();
        var menuExpanded = 0;
        if (url.indexOf(thisURL) != -1) {
            showChildren($this);
            menuExpanded = 1;
        }
        if (menuExpanded == 0) {
            $this.next().find('li > a').each(function (j) {
                var childURL = $(this).attr('href');
                if (childURL)
                    childURL = childURL.toLowerCase();
                if (url.indexOf(childURL) != -1) {
                    //alert("menuExpanded false");
                    showChildren($this);
                    menuExpanded = 1;
                    $(this).addClass("selected");
                }
            });
        }
        else {
            //alert();
            //$this.attr('style', "background-image: url('/_LAYOUTS/IHiS.Intranet.DevCentre/Images/arrow_state_blue_down.png');background-repeat: no-repeat");
        }
    });
    function showChildren($this) {
        $this.next().show();
        $this.attr('data-hide', '0');
        $this.attr('style', "background-image: url('/_LAYOUTS/IHiS.Intranet.DevCentre/Images/arrow_state_blue_down.png');background-repeat: no-repeat");
    }
    //Show/Hide when the heading is clicked.
    $('.s4-ql ul.root > li > a.menu-item').bind('click', function (e) {
        var $this = $(this);
        toggleChildrenElems($this);
        e.preventDefault();
    });
    function toggleChildrenElems($this) {
        if ($this.attr('data-hide') == '1') {
            $this.next().show("fast");
            $this.attr('data-hide', '0');
            //window.location.href = $this.attr('href');
            $this.attr('style', "background-image: url('/_LAYOUTS/IHiS.Intranet.DevCentre/Images/arrow_state_blue_down.png');background-repeat: no-repeat");
        }
        else {
            $this.next().hide("fast");
            $this.attr('data-hide', '1');
            $this.attr('style', "background-image: url('/_LAYOUTS/IHiS.Intranet.DevCentre/Images/arrow_state_blue_right.png');background-repeat: no-repeat");
        }
    }
    //Disable the webpart header link
    $('.ms-WPHeaderTd .ms-standardheader a').bind('click', function (e) {
        e.preventDefault();
    });
    if ($.browser && $.browser.msie) {
        var version = parseInt($.browser.version);
        if (version == 7) {
            $('ul#custom-top-nav > li.first_level').bind('mouseover', function (e) {
                var $this = $(this);
                var width = $this.width() + 5;
                var marginStyle = 'margin-left: -' + width + 'px;';
                var $thisDiv = $(this).find("div#top-nav-children");
                $thisDiv.attr("style", marginStyle);
            });
        }
    }
 


Wednesday, February 4, 2015

Sending Email Sharepoint 2010

Calling Method: 
emailFrom you can give any emailID
 
SendEmail(subject, body, true, champions, string.Empty, string.Empty, SPContext.Current.Site.RootWeb, emailFrom);
 
Method:
public static void SendEmail(string subject, string body, bool isBodyHtml, string receiverEmail,
                                    string cc, string bcc, SPWeb web,string from)
        {
            StringDictionary headers = new StringDictionary();
 
            headers.Add("to", receiverEmail);
            headers.Add("cc", cc);
            headers.Add("bcc", bcc);
            headers.Add("from", from);
            headers.Add("subject", subject);
            headers.Add("content-type""text/html");
            headers.Add("fAppendHtmlTag""true");
            headers.Add("fHtmlEncode""true");
            SPUtility.SendEmail(web, headers, body.ToString());

Open in separate window when clicking on "My Site" - sharepoint 2010


1116 is mysite port number, you can check with specific name

$(function(){
// store a reference to the STSNavigate2 function
window.oldSTSNavigate2 = window.STSNavigate2;
window.STSNavigate2 = function (evt, Url){
if (Url.indexOf(":1116/") != -1) {
// if you want to open in separate window
window.open(Url,'_blank');

// if the url contains mysite - open it in showModalDialog
/* SP.UI.ModalDialog.showModalDialog({
url: Url + "#",
title: "My Site",
autoSize: true
}); */

return;
}
// otherwise call the old version of STSNavigate2
window.oldSTSNavigate2(evt, Url);
};
});

 

Monday, February 2, 2015

Create a zip file download it

Need to have "ICSharpCode.SharpZipLib.dll" to make it

Here MatchCollection is document paths.

private void DownloadZipToBrowser(MatchCollection matches,SPWeb web)
        {
 
            Response.ContentType = "application/zip";
            // If the browser is receiving a mangled zipfile, IIS Compression may cause this problem. Some members have found that
            //    Response.ContentType = "application/octet-stream"     has solved this. May be specific to Internet Explorer.
 
            Response.AppendHeader("content-disposition""attachment; filename=\"Memo.zip\"");
            Response.CacheControl = "Private";
            Response.Cache.SetExpires(DateTime.Now.AddMinutes(3)); // or put a timestamp in the filename in the content-disposition
 
            byte[] buffer = new byte[4096];
 
            ZipOutputStream zipOutputStream = new ZipOutputStream(Response.OutputStream);
            zipOutputStream.SetLevel(3); //0-9, 9 being the highest level of compression
            foreach (Match m in matches)
            {
                SPFile oFile = web.GetFile(m.Result("${url}"));
                Stream fs = oFile.OpenBinaryStream();
                //Stream fs = File.OpenRead(fileName);    // or any suitable inputstream
 
                ZipEntry entry = new ZipEntry(ZipEntry.CleanName(oFile.Name));
                entry.Size = fs.Length;
                // Setting the Size provides WinXP built-in extractor compatibility,
                //  but if not available, you can set zipOutputStream.UseZip64 = UseZip64.Off instead.
 
                zipOutputStream.PutNextEntry(entry);
                buffer = new byte[fs.Length];
                int count = fs.Read(buffer, 0, buffer.Length);
                while (count > 0)
                {
                    zipOutputStream.Write(buffer, 0, count);
                    count = fs.Read(buffer, 0, buffer.Length);
                    if (!Response.IsClientConnected)
                    {
                        break;
                    }
                    Response.Flush();
                }
                fs.Close();
            }
            zipOutputStream.Close();
 
            Response.Flush();
            Response.End();
        }

Tuesday, January 20, 2015

How to host wcf service in IIS 7 or 7.5

This article will give you brief description about required steps to host your wcf service in IIS and test it using console application.

For creating and hosting WCF service in IIS follow below steps.

  1. Create WCF service

    Create a new service using Create new WCF service library and test using WCFTestClient
  2. Add Service Host

    Add service host for hosting Product Service by right clicking on Project from solution explorer. Name the service host as ProductServiceHost.svc
    WCF Service host for Product Service
  3. ServiceHost tag

    Add below service host tag to ProductServiceHost.svc. Give fully qualified name of service to ServiceHost attribute.
                <%@ ServiceHost Service="NorthwindServices.ProductService" %>
                

  4. Create Web Site in IIS

    Open IIS manager by clicking Windows start -> Run -> enter inetmgr -> click ok If IIS is not installed on your machine click here to install.
    Go to IIS manager and right click on sites and select Add Web site.
    Add new web site to IIS

    Enter details as shown in below picture
    • Enter site name as NorthwindServices
    • Change the application pool to ASP.net V4.0
    • Select the physical path of folder containing ProductServiceHost.svc
    • Enter port number on you wish to host service.
    Add new web site to IIS
  5. Publish Services

    Go to your service application and right click on service project and select publish.
    Publish WCF service to IIS
    Enter target location as http://localhost:7741/
  6. Test the WSDL

    Open your browser and enter http://localhost:7741/ProductServiceHost.svc. You will see the link for WSDL.
    WCF service to IIS
  7. Add Client Application

    Now add console application to solution. Name it as NorthwindApp. WCF Client Application
  8. Add Service Reference

    Add service reference to NorthwindApp by right click on NorthwindApp project and click on Add Service Reference. Below window should appear. Enter the address of service endpoint which you have added in service app.config. WCF Client Application

    Enter ProductServiceRef for Namespace and click on OK. Service reference is added to your client application.

    WCF Client Application

    Check Client application's App.config, it should have service endpoint and client details.
  9. Client Implementation

    Service reference is now available for Northwind. We can call service operations. Add the below code to NorthwindApp -> Program.cs file.
    class Program
    {
        static void Main(string[] args)
        {
            ShowOperations();
        }
    
        private static  void ShowOperations()
        {
            ConsoleKeyInfo cki;
    
            do
            {
                Console.WriteLine(); 
                Console.WriteLine("Enter Product ID or press Esc to quit : ");
                cki = Console.ReadKey();
                if (!char.IsNumber(cki.KeyChar))
                {
                    Console.WriteLine("  Invalid number");
                }
                else
                {
                    Int32 number;
                    if (Int32.TryParse(cki.KeyChar.ToString(), out number))
                    {
                        Console.WriteLine(); 
                        GetProductName(number);
                        GetProductQty(number);
                        GetCategoryName(number);  
                    }
                    else
                    {
                        Console.WriteLine("Unable to parse input");
                    }
                }
            } while (cki.Key != ConsoleKey.Escape);
    
            Console.Read(); 
        }
    
        private static void GetProductName(int ProductID)
        {   
            ProductsClient client = new ProductsClient();
            string ProductName = client.GetProductName(ProductID);
            Console.WriteLine(string.Format("Product name {0} for Product ID {1}",
                    ProductName, ProductID));
        }
    
        private static void GetProductQty(int ProductID)
        {   
            ProductsClient client = new ProductsClient();
            int ProductQty = client.GetProductQty(ProductID);
            Console.WriteLine(string.Format("Product qty {0} for Product ID {1}",
                    ProductQty, ProductID));
        }
    
        private static void GetCategoryName(int ProductID)
        {   
            ProductsClient client = new ProductsClient();
            string CategoryName = client.GetCategoryName(ProductID);
            Console.WriteLine(string.Format("Category name {0} for Product ID {1}",
                        CategoryName, ProductID));
        }
    }
                

See more details about Hosting WCF service in IIS with SSL and Transport Security

Download source code with Service Library, Service Host and client application.

Image noise comparison methods

 1. using reference image technique     - peak_signal_noise_ratio (PSNR)     - SSI 2. non-reference image technique     - BRISQUE python pac...