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...