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.

Wednesday, December 17, 2014

Column Validation in SharePoint 2010

The ability to easily validate the column values entered into list items is a welcome addition to SharePoint 2010.I’d like to walk thru 2 simple example s of how to use column validation, at the column level, then at the list level.I’ll then point out some specific notes about this feature.
Simple Example #1 – Column Level
  1. Create a new column on a list, and click "Column Validation":
  1. Add a validation Formula, and a message that will display if validation fails:
  1. Create a new item, and enter a value that will not validate.Click OK.You will see your failure message:
Simple Example #2 – List Level
  1. In the List Settings, click on "Validation Settings"
  1. Enter a validation formula to apply to this list.Click Save.
  1. Create a new list item, entering in values that will not validate.Click OK.The item does not save, but the User Message doesn’t appear either.I assume this is a bug, and it ought to be fixed before RTM.
Field Types
In this simple example we used a "Single Line of Text" field type.The following field types can be validated with the "Column Validation" feature:
  • Single Line of Text
  • Choice (single only)
  • Number
  • Currency
  • Date & Time
Formulas
  1. You can only compare column values to one another in a list level validation.
  2. A validation formula at the column level cannot include any other columns besides itself.For example, [Column1]>[Column2] is an invalid formula and SharePoint will not allow it to be used at the column level.In this case, you want to use list-level validation.
  3. There is only one formula available at the list level.
  4. The formula syntax is similar to that used in Calculated Columns
There are a few dozen functions available – I have not tried every one.One interesting thing to note is that SharePoint 2010 would not allow me to use the TODAY function, even when validating a Date field.[DateColumn]>TODAY is not a valid validation formula.
Conflicts
  1. What if you have both column level validation and list level validation?
    1. The column level formulas will be evaluated first, then the list formulas
  1. What if the column and list level validations are in conflict?
    1. Example – at the list level, you require that [Text1] = [Text2], but each column has it’s own validation; [Text1]="AAA", and [Text2]="BBB".In this case, it will be impossible to actually submit a list item.The column validations are evaluated first, but if the values validate here, they will of course fail the list validation.
  1. What if the list level validation includes columns not included in a particular content type?
    1. If a column used in the list formula isn’t available in the current content type, validation will always fail.This means that if you have multiple content types in your list,you should not validate at the list level for a column that is not included in all content types on the list.These columns can only be validated at the column level.
Site Columns
  1. You can set validation on custom columns of the field types listed above
  2. You can override the validation of a site column at the list level
Items To Investigate
  1. How does validation behave with page fields in a Pages library on a publishing site?
  2. How does validation behave in Office client applications?
  3. Is validation available in the Site Directory?Does it work at site creation time?
  4. Can we use regular expressions in a validation formula?

Reference:
http://blogs.perficient.com/microsoft/2009/09/column-validation-in-sharepoint-2010/
 

Wednesday, December 10, 2014

Adding Target audience to sharepoint left navigation programatically

SPNavigationNodeCollection nodeColl = newSite.Navigation.QuickLaunch;
 
                                            SPGroupCollection groups = newSite.Groups;
                                            string groupnamesString = ";;;;";
                                            foreach (SPGroup group in groups)
                                            {
                                                if (group.Name.Contains("Owner") || group.Name.Contains("Member"))
                                                    groupnamesString += group.Name + ",";
                                            }
 
                                            //groupnamesString = groupnamesString.Substring(0, groupnamesString.Length - 1);
                                            //node.Properties.Add("Audience",  ";;;;" + Group1+","+ Group2 +","+ Group3+","+etc... "" );
                                            Console.WriteLine(groupnamesString);
 
                                            if (!string.IsNullOrEmpty(groupnamesString))
                                            {
                                                foreach (SPNavigationNode node in nodeColl)
                                                {
                                                    if (node.IsExternal == true && node.Title != "General")
                                                    {
                                                        if (node.Properties.ContainsKey("Audience"))
                                                        {
                                                            node.Properties["Audience"] = groupnamesString;
                                                        }
                                                        else
                                                        {
                                                            node.Properties.Add("Audience", groupnamesString);
                                                        }
                                                        node.Update();
                                                    }
                                                }
                                                newSite.Update();
                                            }

Assign broken permissions to publishing pages through programtically

PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(newSite);
                                            PublishingPageCollection allPages = publishingWeb.GetPublishingPages();
 
                                            foreach (PublishingPage page in allPages)
                                            {
                                                Console.WriteLine(page.Name);
 
                                                if (page.Name.ToLower() == "about us.aspx" || page.Name.ToLower() == "people.aspx" || page.Name.ToLower() == "services.aspx")
                                                {
                                                    #region checkout and assign the permissions to intranet_readers
 
                                                    // checkout the page
                                                    if (page.ListItem.File.CheckOutType == SPFile.SPCheckOutType.None)
                                                    {
                                                        page.CheckOut();
                                                    }
                                                    else
                                                    {
                                                        page.ListItem.File.UndoCheckOut();
                                                        page.CheckOut();
                                                    }
 
                                                    // Break the permissions
                                                    page.ListItem.BreakRoleInheritance(true);
 
                                                    // Rename the page
                                                    //page.ListItem["Name"] = "About us";
 
                                                    // Assign the permissions to intranet_readers
                                                    SPRoleAssignment roleAssignment = new SPRoleAssignment(newSite.SiteGroups["readersgroup"]);
                                                    if (roleAssignment != null)
                                                    {
                                                        roleAssignment.RoleDefinitionBindings.Add(newSite.RoleDefinitions["Read"]);
                                                        page.ListItem.RoleAssignments.Add(roleAssignment);
                                                        page.ListItem.Update();
                                                    }
                                                    // CheckIn the page
                                                    page.CheckIn("Broken permissions added");
                                                    // publish the page
                                                    SPModerationInformation moderationInformation = page.ListItem.ModerationInformation;
 
                                                    if (moderationInformation != null && moderationInformation.Status != SPModerationStatusType.Approved)
                                                    {
                                                        SPFile pageFile = page.ListItem.File;
                                                        pageFile.Publish("publish comments");
                                                        pageFile.Approve("approve comments");
                                                    }
 
                                                    #endregion
                                                }
 
                                            }

Image noise comparison methods

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