Thursday 27 March 2014

Find the assembly path in command line.


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


SharePoint Rating Enable and Disable programmatically

The following code snippet can be used to SharePoint rating enable and disable programmatically.
 private static void EnableRatingSetting(SPList list)
        {
            SPFieldCollection allfields = list.Fields;
            SPFieldCollection availFields = list.ParentWeb.AvailableFields;
            if (!allfields.Contains(FieldId.AverageRatings))
            {
                SPField field = availFields[FieldId.AverageRatings];
                list.Fields.AddFieldAsXml(field.SchemaXmlWithResourceTokens, true, SPAddFieldOptions.AddFieldToDefaultView | SPAddFieldOptions.AddFieldInternalNameHint | SPAddFieldOptions.AddToAllContentTypes);
            }
            if (!allfields.Contains(FieldId.RatingsCount) && availFields.Contains(FieldId.RatingsCount))
            {
                SPField field2 = availFields[FieldId.RatingsCount];
                list.Fields.AddFieldAsXml(field2.SchemaXmlWithResourceTokens, false, SPAddFieldOptions.AddFieldInternalNameHint | SPAddFieldOptions.AddToAllContentTypes);
            }
            list.Update();
        }

   private static void DisableRatingSetting(SPList list)
        {
            SPField field1 = GetField(FieldId.AverageRatings, list.Fields);
            if (field1 != null)
            {
                list.Fields.Delete(field1.InternalName);
            }
            SPField field2 = GetField(FieldId.RatingsCount, list.Fields);
            if (field2 != null)
            {
                list.Fields.Delete(field2.InternalName);
            }
            list.Update();
        }
        private static SPField GetField(Guid id, SPFieldCollection fieldColl)
        {
            return fieldColl[id];
        }


Monday 24 March 2014

Programmatically Column validations in SharePoint 2013

The following code snippet can be used to programmatically column validations.

using System;
using Microsoft.SharePoint;

namespace ValidationSettings
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            const string siteUrl = "SiteUrl";
            const string listName = "Custom List";
            FieldValidation(siteUrl, listName, "CID", "=AND([CID]<=50,[CID]>0)", "Please enter a value between 1-50.");
            FieldValidation(siteUrl, listName, "EmpId", "=EmpId=INT(EmpId)", "decimals are not allowed.");
            FieldValidation(siteUrl, listName, "EmpId", "=EmpId>10", "only EmpId greater than 10");
            FieldValidation(siteUrl, listName, "Phone", "=IF(LEN(Phone)>9,TRUE,FALSE)","length greater than 10 digits only");
            FieldValidation(siteUrl, listName, "CID", "=[CID]<> 00", "Restricts users not to give CID as 00");
            Console.ReadKey();
        }

        private static void FieldValidation(string siteUrl, string listName, string fieldName, string validationFormula,string validationMessage)
        {
            using (var spSite = new SPSite(siteUrl))
            {
                using (SPWeb spWeb = spSite.RootWeb)
                {
                    SPList customList = spWeb.Lists.TryGetList(listName);
                    if (customList != null)
                    {
                        var getListField = customList.Fields.GetField(fieldName) as SPFieldNumber;
                        if (getListField != null)
                        {
                            getListField.ValidationFormula = validationFormula;
                            getListField.ValidationMessage = validationMessage;
                            getListField.Update();
                            Console.WriteLine("Validation created in " + fieldName + "");

                        }
                        else
                        {
                            Console.WriteLine("Invalid Field Name");                          
                        }
                    }
                    else
                    {
                        Console.WriteLine("Invalid List Name");                    
                    }
                }
            }
        }
    }
}

Reference:
http://chakkaradeep.com/index.php/sharepoint-2010-list-improvements-column-validation-and-list-validation-settings/
http://adicodes.com/column-validations-and-list-validations-in-sharepoint-2010/

Saturday 22 March 2014

Programmatically Backup and Restore in SiteCollection

The following code snippet can be used to programmatically backup the site collection.

     static void Main(string[] args)
        {
            var backupSiteUrl = "SiteUrl";
            var backupfilename = @"D:\\Backup\\SharePointSiteBackup_.bak";
            SiteBackup(backupSiteUrl, backupfilename);

        }
 public static void SiteBackup(string siteUrl, string fileName)
        {
            try
            {
                SPWebApplication webApplication = null;
                webApplication = SPWebApplication.Lookup(new Uri(siteUrl));
                SPSiteCollection sitecols = webApplication.Sites;
                string backupName = fileName;
                sitecols.Backup(siteUrl, backupName, true);             
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        } 



The following code snippet can be used to programmatically restore the site collection.

   static void Main(string[] args)
        {
            var restoreSiteUrl = "SiteUrl";
            var restoreBackupFile = "D:\\Backup\\SharePointSiteBackup_24-02-2014.bak";
            RestoreSite(restoreSiteUrl, restoreBackupFile);
        }

  private static void RestoreSite(string siteUrl, string fileName)
        {
            try
            {
                SPWebApplication webApplication = null;
                webApplication = SPWebApplication.Lookup(new Uri(siteUrl));
                SPSiteCollection sitecols = webApplication.Sites;
                sitecols.Restore("Teamsite", fileName, true);// overwrite sitecollection if already exists
                Console.WriteLine("Site collection restored successfully");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

Enable Target Audience Field Programmatically

The following code snippet can be used to enable target audience field programmatically.

 using (SPSite site = new SPSite("SiteUrl"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists["Documents"];

                    XmlElement fldElement = new XmlDocument().CreateElement("Field");
                    fldElement.SetAttribute("ID", "61cbb965-1e04-4273-b658-eedaa662f48d");
                    fldElement.SetAttribute("Type", "TargetTo");
                    fldElement.SetAttribute("Name", "TargetTo");
                    fldElement.SetAttribute("DisplayName", "Target Audiences");
                    fldElement.SetAttribute("Required", "FALSE");

                    list.Fields.AddFieldAsXml(fldElement.OuterXml);
                    list.Update();
                }
            }

Friday 21 March 2014

Retrieve ListItem data Using CAML in SharePoint 2013

The following code snippet can be used to programmatically retrieve list item data Using CAML

 SPWeb web = SPContext.Current.Web;
            SPList list = web.Lists["Documents"];
            SPQuery query = new SPQuery();
            query.ViewFields = "<FieldRef Name='ID'/>" +"<FieldRef Name='Title'/>" + "<FieldRef Name='LastName'/>" +"<FieldRef Name='Age'/>";
            SPListItemCollection item = list.GetItems(query);
            GridView1.DataSource = item.GetDataTable();
            GridView1.DataBind();


Tuesday 18 March 2014

Programmatically Sending Email in SharePoint

The following code snippet can be used to Programmatically Sending Email in SharePoint
 SPWebApplication webApp = SPWebApplication.Lookup(new Uri("http://ServerName:7777/"));
            var mail = new MailMessage();
            mail.From = new MailAddress("Test@Example.com");
            mail.To.Add("Test@Example.com");
            mail.Subject = "Subject of the email";
            mail.Body = "Body of the email";
            SmtpClient smtp = new SmtpClient(webApp.OutboundMailServiceInstance.Server.Address);
            smtp.UseDefaultCredentials = true;
            smtp.Send(mail);


Programmatically Sending Email in SMTP
The following code snippet can be used to Programmatically Sending Email in SMTP
var message = new MailMessage("Test@Example.com", "Test@Example.com", "Subject of the email", "Body of the email");
            message.IsBodyHtml = true;
            var smtp = new SmtpClient("172.XX.XX.XX");
            smtp.Send(message);
            Console.WriteLine("Mail Sent Successfull");

Programmatically Sending Email in C#
The following code snippet can be used to Programmatically Sending Email in C#
 var mailSend = new MailMessage("Test@gmail.com", "Test@gmail.com");
            mailSend.Subject = "Subject of the email";
            mailSend.Body = "Body of the email";
            mailSend.Priority = MailPriority.High;
            var objSmtp = new SmtpClient();
            objSmtp.Host = "smtp.gmail.com";
            objSmtp.Credentials = new NetworkCredential("Test@gmail.com", "Password");
            objSmtp.EnableSsl = true;
            objSmtp.Send(mailSend);

Saturday 15 March 2014

Programmatically Modify List View Web Part

The following code snippet can be used to modify list view web part.

 private static void Main(string[] args)
        {
            var site = new SPSite("http://Servername/sites/cbteamsite");
            SPWeb web = site.OpenWeb();

            SPFile file = web.GetFile(pageUrl);
            SPLimitedWebPartManager mgr =
                file.GetLimitedWebPartManager(
                    (PersonalizationScope)Microsoft.SharePoint.Client.WebParts.PersonalizationScope.Shared);

            SPList list = web.Lists["Sales Announcements"];
            foreach (System.Web.UI.WebControls.WebParts.WebPart wp in mgr.WebParts)
            {
                if (wp.Title == "Sales Announcements")
                {
                    var listWp = (ListViewWebPart)wp;
                    var viewId = new Guid(listWp.ViewGuid);
                    SPView view = list.Views[viewId];
                    view.ViewFields.Delete("Value");
                    view.ViewFields.Delete("Report_x0020_Path");
                    //hide check box
                    view.ViewFields.View.TabularView = false;
                    view.Update();
                }
          } 

Convert Image To Byte Array in C#

The following code snippet can be used to convert image to byte array.

  protected void btnUpload_Click(object sender, EventArgs e)
        {
            try
            {
                if (FileUpload1.HasFile)
                {
                    Image imag = Image.FromStream(FileUpload1.PostedFile.InputStream);
                    var connection = new SqlConnection(ConnectionString);
                    connection.Open();
                    var sqlCom = new SqlCommand("Insert into SP_ProductsImage (ProductsName, ProductsDescription,ProductsImage) Values (@ProductsName, @ProductsDescription,@ProductsImage)", connection);
                    sqlCom.Parameters.Add("@ProductsName", txtProductName.Text);
                    sqlCom.Parameters.Add("@ProductsDescription", txtDescription.Text);
                    sqlCom.Parameters.Add("@ProductsImage", SqlDbType.Image, 0).Value = ConvertImageToByteArray(imag, ImageFormat.Jpeg);
                    sqlCom.ExecuteNonQuery();
                }
                else
                {
                    Response.Write("<script>alert('Please file upload')</script>");
                }

            }
            catch (Exception ex)
            {
                Response.Write("<script>alert('" + ex.Message + "')</script>");
            }
        }



  private byte[] ConvertImageToByteArray(Image imageToConvert, ImageFormat formatOfImage)
        {
            byte[] bytes;
            try
            {
                using (var ms = new MemoryStream())
                {
                    imageToConvert.Save(ms, formatOfImage);
                    bytes = ms.ToArray();
                }
            }
            catch (Exception)
            {
                throw;
            }

            return bytes;
        }


OR

        public static byte[] GetBytesFromFile(string fullFilePath)
        {
            try
            {
                FileStream fs = null;
                fs = File.OpenRead(fullFilePath);
                byte[] bytes = new byte[fs.Length];
                fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
                return bytes;
            }
            catch (Exception exception)
            {
                throw;
            }
        }

Convert Byte Array To Image.


 protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                var connection = new SqlConnection(ConnectionString);
                connection.Open();
                var command = new SqlCommand("select * from [AdventureWorks2012].[Production].[ProductRevenue]", connection);
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    byte[] imageData = ((Byte[])reader["Image"]);
                    Image1.ImageUrl = "data:image/jpg;base64," + Convert.ToBase64String(imageData);
                }
            }
            catch (Exception ex)
            {

                Response.Write("<script>alert('" + ex.Message + "')</script>");
            }

        }


Web Part Custom Properties

The following code snippet can be used to web part custom properties

using System;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls.WebParts;

namespace WebPartProperties.VisualWebPart1
{
    [ToolboxItemAttribute(false)]
    public partial class VisualWebPart1 : WebPart
    {        
        public VisualWebPart1()
        {
            _titles = "";
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            Label1.Text = _titles + "</br>" + _eProperties + "</br>" + _list + "</br>" + _property;
        }

        //TextBox custom properties
        private string _titles;
        [WebBrowsable(true),
         WebDisplayName("Title"),
         WebDescription("Title Display"),
         Personalizable(PersonalizationScope.Shared),
         Category("TextBox Properties")]
        public string MyTitleString
        {
            get { return _titles; }
            set { _titles = value; }
        }


        //DropDownList custom properties
        public enum EnumProperties
        {
            Property1,
            Property2,
            Property3
        }
        private EnumProperties _eProperties;
        [Personalizable(),
         WebBrowsable(true),
         WebDisplayName("DropDown Property"),
         Category("DropDownList Properties"),
         WebDescription("Property description")]
        public EnumProperties eProperties
        {
            get { return _eProperties; }
            set { _eProperties = value; }
        }



        //ListItems custom properties
        public enum siteLists
        {
            List1,
            List2,
            List3
        };
        protected siteLists _list;
        [WebBrowsable(true),
         WebDisplayName("Select the List"),
         WebDescription(""),
         Personalizable(PersonalizationScope.Shared),
         Category("List Properties"),
         DefaultValue("")]
        public siteLists List
        {
            get { return _list; }
            set { _list = value; }
        }


        //CheckBox custom properties
        public Boolean _property;
        [WebBrowsable(true),
         WebDisplayName("Check box property"),
         WebDescription(""),
         Personalizable(
         PersonalizationScope.Shared),
         Category("Checkbox Properties"),
         DefaultValue("")]

        public Boolean _Property
        {
            get { return _property; }
            set { _property = value; }
        }

        //Adding multiple controls in single category
        public Boolean _property1;
        [WebBrowsable(true),
         WebDisplayName("Check box property1"),
         WebDescription(""),
         Personalizable(
         PersonalizationScope.Shared),
         Category("Checkbox Properties"),
         DefaultValue("")]
        public Boolean _Property1
        {
            get { return _property; }
            set { _property = value; }
        }
    }

}

Configure Content deployment in sharepoint 2013

Configuration the following content deployment steps:
  1. Create a source site.
  2. Create a destination site collection.
  3. Enable incoming content deployment jobs.
  4. Create a content deployment path.
  5. Create a content deployment job.
  6. Deploy the source site.
  7. Update the source site.
  8. Deploy changes.
  9. Check the destination site for changes.

Step 1: Central administration- General application setting Click Content Deployment Settings select Accept incoming content deployment jobs and do not require encryption click ok

Step 2 : Specify the web application and site collection on the source server. The specified site collection must have the “Content Deployment Source” feature activated.

Step 3: Central administration- General application setting Click Manage Content Deployment Paths and Jobs Click New Path.
         Name and Description - Content Deployment Path.
         Destination Central Administration Web Application - http://ServerName:7777

Step 4: Central administration- General application setting Click Manage Content Deployment Paths and Jobs Click New Job

Sometime following error occurred in the  Content deployment Configuration:
Error Message:
Either the URL for the destination Web application is not valid, or you do not have permissions to the Central Administration site on the destination server farm.
Error details: The remote Web service request failed with this message: 'the request failed with HTTP status 401: Unauthorized.'. 
You have specified a URL that begins with http://. Communication to this URL will not be secure and can be intercepted by malicious users.
Solution:
Select Use Integrated Windows authentication Reenter Username and password 

Error Message:
One or more issues preventing successful Content Deployment export were detected on this site collection http://ServerName:26108/sites/sourcesite. For more information, go to Content Deployment Source Status page
Solution:
 Log in into your source site collection.

2. Go to Site Settings--> Content Deployment Source Status.

3. Here you will find the list of feature to be deactivated.

4. Deactivate these features and then that’s it you are now ready to proceed further.
Following the Deactivate Power Shell Command:
Disable-SPFeature –Identity "Metadata Navigation" –URL http://ServerName/sites/sourcesite





Programmatically move items from one document library to another

The following code snippet can be used to move items in one document library to another.
 
  public static void Movefiles(string url, string sourceListName, string destinationListName)
        {
            try
            {
                var site = new SPSite(url);
                SPWeb web = site.OpenWeb();
                SPList itemCollection = web.Lists[sourceListName];
                SPListItem spItem = itemCollection.Items[0];
                SPFile srcFile = web.GetFile(spItem.Url);
                SPList destDocLib = web.Lists[destinationListName];
                srcFile.MoveTo(destDocLib + "/" + srcFile.Name, true);
                Console.WriteLine("Document Move Successfull.");
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }


PROGRAMMATICALLY CONFIGURE SEND TO CONNECTIONS

The following code snippet can be used to Create a ‘Send To’ Connection to Send Documents to The Records Center in SharePoint 2013.

 public static void ConfigureSendToConnections(string url)
        {
            try
            {          
                using (var site = new SPSite(url))
                {
                    SPWebApplication webapp = site.WebApplication;
                    var newhost = new SPOfficialFileHost(true);
                    newhost.OfficialFileUrl = new Uri(site.Url + "/records/_vti_bin/officialfile.asmx");
                    newhost.OfficialFileName = "Records Center";
                    newhost.ShowOnSendToMenu = true;
                    newhost.Action = SPOfficialFileAction.Move;
                    webapp.OfficialFileHosts.Add(newhost);
                    webapp.Update();                
                }
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }


SharePoint 2013 - IIS Server Errors

The following are some of the IIS Server errors that provide the general solution.
Error Message:
HTTP 500 Internal Server Error
Solution:
Start the SharePoint Web Services web application in IIS.

Error Message in SharePoint Designer 2013:
the server could not complete your request, for more specfic infomation click the details button
Solution:
Select the Anonymous Authentication in IIS. In Actions pane, click on "Enable" link. Now we can open SharePoint site in designer without any issues.

Error Message:
404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.
Solution:
Application path share in every one on read and write Permission
or
Visual studio-> click aspx page properties --> dont copy

Error Message:
To enable the details of this specific error message to be viewable on remote machines, please create a <customErrors> tag within a "web.config" configuration file located in the root directory of the current web application. This <customErrors> tag should then have its "mode" attribute set to "Off".
Solution:
1) Go to Run screen and type services.msc
2) Look for SQL Server (MSSQLSERVER) service, right click on it and click Start

Error Message:
HTTP Error 404.3 - Not Found The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.
Solution:
-Open IIS Manager and navigate to the level you want to manage.
-In Features View, double-click MIME Types.
-In the Actions pane, click Add.
-In the Add MIME Type dialog box, type a file name extension in the File name extension text box.  Type a MIME type
-In the MIME type text box.

-Click OK.

Error Message:
HTTP Error 500.19 - Internal Server Error The requested page cannot be accessed because the related configuration data for the page is invalid.
Solution:
Install the .NET Core Windows Server Hosting bundle on the hosting system.

Friday 14 March 2014

SharePoint 2013 - Web Part Errors

The following are some of the web part errors that provide the general solution.
Error Message:
 A Web Part or Web Form Control on this Page cannot be displayed or imported
Solution:

Error Message:
Error occurred in deployment step 'Activate Features': Unable to locate the workflow's association data. To restore the association data to the workflow, restart the workflow settings wizard by selecting the workflow node in Solution Explorer and then clicking the ellipsis button (…) on one of the properties in the Properties window that has an ellipsis button" 
Solution:
Go to Visual Studio 2012 > Right Click on Workflow file > Property Window  >  Click on any one of (History List/ Target List / Task List ) ... 
Then, one popup window will open and fill required details.

Error Message:
Failed to extract the cab file in the solution
Solution:

Error Message:
Unhandled exception was thrown by the sandboxed code wrapper's Execute method in the partial trust app domain
Solution:
Sandbox solution changed the  true  to false.

Error Message:
The request could not be completed because the specified solution was not found
Solution:
Just edit the page, delete the web part, then re-add the web part to the page.  This fixes the error.

Error Message:
Error validating assembly
Solution:
Set Include Assembly In Package Is false

Installing and configuring workflow for SharePoint Server 2013

Step 1: Configure the Workflow on following link steps.
http://letrasandnumeros.com/2013/01/17/installing-and-configuring-workflow-for-sharepoint-server-2013-step-by-step/
http://sharepoint-community.net/profiles/blogs/configuring-sharepoint-2013-to-support-workflow-management

Sometime following error occurred in the  Workflow Configuration:
Error 1:
Register-SPWorkflowService : The root of the certificate chain is not a
Trusted root authority
Solution:
Change the port no 12290 to 12291 and HTTPS to HTTP

Error 2:
Register-SPWorkflowService : The underlying connection was closed: An
unexpected error occurred on a send. Client ActivityId :
Solution:
http://sharepoint1on1.blogspot.in/2012/10/sp2013-register-spworkflowservice-error.html

Error 3:
Register-SPWorkflowService : The remote server returned an error: (401)
Unauthorized.
Solution:
Turn on "Anonymous Authentication" from workflow server IIS site settings.