Monday, May 20, 2013

Read Blog Feeds in SharePoint using object model

BlogFeeds.ascx:-
<asp:Label ID="lblHeaderImage" runat="server"></asp:Label>
BlogFeeds.ascx.cs:-
using Microsoft.SharePoint;
using System;
using System.Net;
using System.ComponentModel;
using System.Text;
using System.Web.UI.WebControls.WebParts;
using System.Xml;
namespace BlogFeeds.BlogFeeds
{
    [ToolboxItemAttribute(false)]
    public partial class BlogFeeds : WebPart
    {
        public BlogFeeds()
        {
        }
        private string rssUrl;
        [Personalizable(true)]
        [WebBrowsable()]
        public virtual string RssUrl
        {
            get { return "http://ankushbhatia.wordpress.com/feed/"; }
            set { rssUrl = value; }
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }
        private StringBuilder AddContainer(StringBuilder sbContent)
        {
            sbContent.Append("<div class='box2'>");
            sbContent Append("<div class='head-icon'><img runat='server' width='60' height='60' src='/_layouts/15/BlogFeeds/blog-feed-icon.png' /></div>");
            sbContent.Append("<div class='head-text'>");
            sbContent.Append("Blog Feeds");
            sbContent.Append("</div><div class='clear'></div>");
            return sbContent;
        }
        private StringBuilder AddItemToContainer(XmlReader itemReader, StringBuilder sbContent)
        {
            string link = string.Empty; ;
            string title = string.Empty;
            string description = string.Empty;
            while (itemReader.Read())
            {
                if (itemReader.NodeType == XmlNodeType.Element)
                {
                    if (itemReader.Name == "link")
                        link = itemReader.ReadElementContentAsString();
                    else if (itemReader.Name == "title")
                        title = itemReader.ReadElementContentAsString();
                    else if (itemReader.Name == "description")
                        description = itemReader.ReadElementContentAsString();
                }
            }
            sbContent.Append("<div class='icon'>");
            sbContent.Append("<img src='/_layouts/15/BlogFeed/post-blog-icon.png' width='26' height='26' />");
            sbContent.Append("</div>");
            sbContent.Append("<div class='blog-text'>");
            sbContent.Append("<span>");
            sbContent.Append(title == null ? string.Empty : title);
            sbContent.Append("</span><br />");
            sbContent.Append(description == null ? string.Empty : description);
            sbContent.Append("<div class='tol'>TOI</div>");
            sbContent.Append("</div>");
            sbContent.Append("<div class='clear'></div>");
            return sbContent;
        }
        private void loadBlogFeeds()
        {
            StringBuilder sbContent= new StringBuilder();
            int topFour = 0;
            sbContent= AddContainer(sbContent);
            sbContent Append("<div id='blogFeeds' class='blog-comment-box' style='width:675px; height:290px; overflow:scroll;'>");
            try
            {
                using (XmlReader reader = XmlReader.Create(RssUrl))
                {
                    reader.MoveToContent();
                    reader.ReadToDescendant("channel");
                    reader.ReadToDescendant("item");
                    do
                    {
                        using (XmlReader itemReader = reader.ReadSubtree())
                        {
                            sbContent= AddItemToContainer(itemReader, sbContent);
                            topFour++;
                        }
                    } while (reader.ReadToNextSibling("item") && topFour < 4);
                    sbContent.Append("<div class='clear'></div>");
                    sbContent.Append("</div>");
                    sbContent.Append("<a href='" + RssUrl + "' class='view-all-btn'>View All</a>");
                    sbContent.Append("<div class='clear'></div>");
                    sbContent.Append("</div>");
                }
                lblHeaderImage.Text = sbContent.ToString();
            }
            catch (Exception ex)
            {
                sbContent.Append("Exception " + ex.Message + " while reading rss at " + RssUrl);
                sbContent.Append("</div><div class='clear'></div></div>");
                lblHeaderImage.Text = sbContent.ToString();
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            loadBlogFeeds();
        }
    }
}



Thank You.

Tuesday, May 14, 2013

CreateChildControls() and Render()


private TextBox _textBox = new TextBox();
        private Label _label = new Label();
----------------------------------------------------------------------------------------------
protected override void CreateChildControls()
        {
            Controls.Clear();
            _textBox.ID = "txtBox1";
            _label.ID = "label1";
            Controls.Add(_textBox);
            Controls.Add(_label);
            base.CreateChildControls();
        }
        protected override void Render(HtmlTextWriter writer)
        {
            EnsureChildControls();
            AddAttributesToRender(writer);
            writer.RenderBeginTag(HtmlTextWriterTag.Div);
            writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "1", false);
            writer.RenderBeginTag(HtmlTextWriterTag.Table);
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            _label.RenderControl(writer);
            writer.RenderEndTag(); //</td>
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            _textBox.RenderControl(writer);
            writer.RenderEndTag(); //</td>
            writer.RenderEndTag(); //</tr>
            writer.RenderEndTag(); //</table>
            writer.RenderEndTag();
        }
----------------------------------------------------------------------------------------------------
protected override void CreateChildControls()
        {
            Controls.Clear();
            _textBox.ID = "txtBox1";
            _label.ID = "label1";

            Controls.Add(new LiteralControl("<table cellpadding='1'><tr>"));
            Controls.Add(new LiteralControl("<td>"));
            Controls.Add(_label);
            Controls.Add(new LiteralControl("</td>"));
            Controls.Add(new LiteralControl("<td>"));
            Controls.Add(_textBox);
            Controls.Add(new LiteralControl("</td>"));
            Controls.Add(new LiteralControl("</tr></table>"));
            base.CreateChildControls();
        }
--------------------------------------------------------------------------------------------------
protected override void CreateChildControls()
        {
            Controls.Clear();
            _textBox.ID = "txtBox1";
            _label.ID = "label1";
           
            Table table = new Table();
            table.CellPadding = 1;
            TableRow row1 = new TableRow();
            TableCell cell1 = new TableCell();
            cell1.Controls.Add(_label);
            TableCell cell2 = new TableCell();
            cell2.Controls.Add(_textBox);
            row1.Cells.Add(cell1);
            row1.Cells.Add(cell2);
            table.Rows.Add(row1);

            Controls.Add(table);
            base.CreateChildControls();
        }
---------------------------------------------------------------------------------------------

Wednesday, April 24, 2013

Working with People Search, KeywordQuery, SearchExecutor, ResultTableCollection in SharePoint 2013

using Microsoft.Office.Server.Search.Query;
using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            SPSite sp = new SPSite("http://server:portno/sites/esc/");
            DataTable dt = GetPeople(sp, "EmployeeID:" + "101");
            dataGridView1.DataSource = dt;
        }
        private DataTable GetPeople(SPSite spSite, string queryText)
        {
            var keywordQuery = new KeywordQuery(spSite)
            {
                QueryText = queryText,
                KeywordInclusion = KeywordInclusion.AllKeywords,
                SourceId = new Guid("B09A7990-05EA-4AF9-81EF-EDFAB16C4E31")
            };
            keywordQuery.RowLimit = 7;
            keywordQuery.SelectProperties.Add("AccountName");
            keywordQuery.SelectProperties.Add("EmployeeID");
            SearchExecutor e = new SearchExecutor();
            ResultTableCollection rt = e.ExecuteQuery(keywordQuery);
            var tab = rt.Filter("TableType", KnownTableTypes.RelevantResults);
            var result = tab.FirstOrDefault();
            DataTable DT = result.Table;
            return DT;
        }
    }
}

Saturday, April 13, 2013

Working with UserProfileChangeQuery, UserProfileChangeToken, UserProfilePropertyName


using System;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.Office.Server;
using Microsoft.Office.Server.CustomerProfiles;

namespace CustomerTimerJob
{
    class CustomerTimerJob : SPJobDefinition
    {
        public const string CustomerRPFOILELIST_TIMERJOB_NAME = "Customerr Timer Job";

        public CustomerTimerJob()
            : base()
        {
        }

        public CustomerTimerJob(SPWebApplication web)
            : base(CustomerRPFOILELIST_TIMERJOB_NAME, web, null, SPJobLockType.Job)
        {
            this.Title = "Customerr Timer Job";
        }

        public override void Execute(Guid targetInstanceId)
        {
            SPWebApplication webApp = this.Parent as SPWebApplication;
            SPList Customerr = webApp.Sites[0].RootWeb.Lists["Customerr"];

            SPServiceContext spServiceContext = SPServiceContext.GetContext(webApp.Sites[0]);
            CustomerrProfileManager CustomerrProfileManager = new CustomerrProfileManager(spServiceContext);
            DateTime fromDate = DateTime.UtcNow.Subtract(TimeSpan.FromDays(1));

            CustomerrProfileChangeQuery CustomerrProfileChangeQuery = new CustomerrProfileChangeQuery(false, true);
            CustomerrProfileChangeToken CustomerrProfileChangeToken = new CustomerrProfileChangeToken(fromDate);

            CustomerrProfileChangeQuery.ChangeTokenStart = CustomerrProfileChangeToken;
            CustomerrProfileChangeQuery.SingleValueProperty = true;
            CustomerrProfileChangeQuery.CustomerrProfile = true;

            CustomerrProfilePropertyName CustomerrProfilePropertyName = new CustomerrProfilePropertyName();

            if (Customerr != null)
            {
                SPCustomerr spCustomerr;
                foreach (SPListItem item in Customerr.Items)
                {
                    if (item["Login_x0020_Name"] != null)
                    {
                        string fieldValue = item["Login_x0020_Name"].ToString();
                        SPFieldCustomerrValue CustomerrValue = new SPFieldCustomerrValue(webApp.Sites[0].RootWeb, fieldValue);
                        spCustomerr = CustomerrValue.Customerr;
                        string[] spCustomerrAccountName = spCustomerr.LoginName.Split(new string[] { "i:0#.w|" }, StringSplitOptions.RemoveEmptyEntries);
                        for (int lenght = 0; lenght < spCustomerrAccountName.Length; lenght++)
                        {
                            if (spCustomerrAccountName[lenght].ToString() != "")
                            {
                                getChangePropertyValue(CustomerrProfileManager, spCustomerrAccountName[lenght], CustomerrProfileChangeQuery, CustomerrProfilePropertyName);
                                updateCustomerr(webApp.Sites[0].RootWeb, CustomerrProfilePropertyName, item, false);
                            }
                        }
                    }
                    else if (item["Employee_x0020_ID"].ToString() != null)
                    {
                        string accountName = GetLoginName(item["Employee_x0020_ID"].ToString(), CustomerrProfileManager, CustomerrProfilePropertyName);
                        getChangePropertyValue(CustomerrProfileManager, accountName, CustomerrProfileChangeQuery, CustomerrProfilePropertyName);
                        updateCustomerr(webApp.Sites[0].RootWeb, CustomerrProfilePropertyName, item, true);
                    }
                }
            }
        }
     
        private void updateCustomerr(SPWeb sPWeb, CustomerrProfilePropertyName CustomerrProfilePropertyName, SPListItem item, bool isLogInNameEmpty)
        {
            try
            {
                if (isLogInNameEmpty)
                {
                    if (CustomerrProfilePropertyName.logInName != null)
                    {
                        item["Login_x0020_Name"] = CustomerrProfilePropertyName.logInName.ToString();
                    }
                }
                if (CustomerrProfilePropertyName.employeeNumberValue != null)
                {
                    item["Employee_x0020_ID"] = CustomerrProfilePropertyName.employeeNumberValue.ToString();
                }
                if (CustomerrProfilePropertyName.preferredNameValue != null)
                {
                    item["Display_x0020_Name"] = CustomerrProfilePropertyName.preferredNameValue.ToString();
                }
                if (CustomerrProfilePropertyName.designaitonValue != null)
                {
                    item["Designation"] = CustomerrProfilePropertyName.designaitonValue.ToString();
                }
                if (CustomerrProfilePropertyName.locationValue != null)
                {
                    item["Location"] = CustomerrProfilePropertyName.locationValue.ToString();
                }
                if (CustomerrProfilePropertyName.departmentValue != null)
                {
                    item["Department"] = CustomerrProfilePropertyName.departmentValue.ToString();
                }
                if (CustomerrProfilePropertyName.mobileValue != null)
                {
                    item["Mobile"] = CustomerrProfilePropertyName.mobileValue.ToString();
                }
                if (CustomerrProfilePropertyName.deskNumberValue != null)
                {
                    item["Desk_x0020_Number"] = CustomerrProfilePropertyName.deskNumberValue.ToString();
                }
                sPWeb.AllowUnsafeUpdates = true;
                item.Update();
                sPWeb.AllowUnsafeUpdates = false;
            }
            catch (Exception ex)
            {
            }
        }

        private string GetLoginName(string strEmpID, CustomerrProfileManager CustomerrProfileManager, CustomerrProfilePropertyName CustomerrProfilePropertyName)
        {
            string strLoginName = "";
            try
            {
                foreach (CustomerrProfile Customerr in CustomerrProfileManager)
                {
                    if (Customerr["employeeNumber"].Value != null)
                    {
                        if (Customerr["employeeNumber"].Value.ToString() == strEmpID)
                        {
                            strLoginName = Customerr["AccountName"].Value.ToString();
                            CustomerrProfilePropertyName.logInName = Customerr["AccountName"].Value.ToString();
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return strLoginName;
        }

        private void getChangePropertyValue(CustomerrProfileManager CustomerrProfileManager, string logInName, CustomerrProfileChangeQuery CustomerrProfileChangeQuery, CustomerrProfilePropertyName CustomerrProfilePropertyName)
        {
            try
            {
                CustomerrProfileChangeCollection CustomerrProfileChangeColl = CustomerrProfileManager.GetCustomerrProfile(logInName).GetChanges(CustomerrProfileChangeQuery);
                foreach (CustomerrProfileChange CustomerrProfileChange in CustomerrProfileChangeColl)
                {
                    if (CustomerrProfileChange is CustomerrProfileSingleValueChange)
                    {
                        CustomerrProfileSingleValueChange singleValueChange = (CustomerrProfileSingleValueChange)CustomerrProfileChange;

                        if (singleValueChange.ProfileProperty.Name.Equals(CustomerrProfilePropertyName.employeeNumber, StringComparison.OrdinalIgnoreCase))
                        {
                            if (singleValueChange.NewValue.ToString() != "")
                            {
                                CustomerrProfilePropertyName.employeeNumberValue = singleValueChange.NewValue.ToString();
                            }
                        }
                        if (singleValueChange.ProfileProperty.Name.Equals(CustomerrProfilePropertyName.preferredName, StringComparison.OrdinalIgnoreCase))
                        {
                            if (singleValueChange.NewValue.ToString() != "")
                            {
                                CustomerrProfilePropertyName.preferredNameValue = singleValueChange.NewValue.ToString();
                            }
                        }
                        if (singleValueChange.ProfileProperty.Name.Equals(CustomerrProfilePropertyName.designaiton, StringComparison.OrdinalIgnoreCase))
                        {
                            if (singleValueChange.NewValue.ToString() != "")
                            {
                                CustomerrProfilePropertyName.designaitonValue = singleValueChange.NewValue.ToString();
                            }
                        }
                        if (singleValueChange.ProfileProperty.Name.Equals(CustomerrProfilePropertyName.location, StringComparison.OrdinalIgnoreCase))
                        {
                            if (singleValueChange.NewValue.ToString() != "")
                            {
                                CustomerrProfilePropertyName.locationValue = singleValueChange.NewValue.ToString();
                            }
                        }
                        if (singleValueChange.ProfileProperty.Name.Equals(CustomerrProfilePropertyName.department, StringComparison.OrdinalIgnoreCase))
                        {
                            if (singleValueChange.NewValue.ToString() != "")
                            {
                                CustomerrProfilePropertyName.mobileValue = singleValueChange.NewValue.ToString();
                            }
                        }
                        if (singleValueChange.ProfileProperty.Name.Equals(CustomerrProfilePropertyName.deskNumber, StringComparison.OrdinalIgnoreCase))
                        {
                            if (singleValueChange.NewValue.ToString() != "")
                            {
                                CustomerrProfilePropertyName.deskNumberValue = singleValueChange.NewValue.ToString();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
    }
}
--------------------------------------------------------------------------------------------
using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace CustomerTimerJob.Features.Feature1
{
    [Guid("344b4b58-f515-4903-8a51-a232bb2a7b8a")]
    public class Feature1EventReceiver : SPFeatureReceiver
    {    
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
            DeleteJob(webApp.JobDefinitions);

            CustomerTimerJob CustomerTimerJob = new CustomerTimerJob(webApp);
            SPDailySchedule spDailySchedule = new SPDailySchedule();
            spDailySchedule.BeginHour = 0;
            spDailySchedule.BeginMinute = 0;
            spDailySchedule.BeginSecond = 0;
            spDailySchedule.EndHour = 23;
            CustomerTimerJob.Schedule = spDailySchedule;
            CustomerTimerJob.Update();
        }
     
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
            DeleteJob(webApp.JobDefinitions);
        }

        private void DeleteJob(SPJobDefinitionCollection sPJobDefinitionCollection)
        {
            foreach (SPJobDefinition job in sPJobDefinitionCollection)
            {
                if (job.Name.Equals(CustomerTimerJob.CUSTOMERPFOILELIST_TIMERJOB_NAME, StringComparison.OrdinalIgnoreCase))
                {
                    job.Delete();
                }
            }
        }  
    }
}
---------------------------------------------------------------------------------------------

Sunday, March 17, 2013

programmatically Mapping between Managed Properties and Crawled Properties in SharePoint 2013



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Office.Server.Search.Administration;
using Microsoft.SharePoint;

namespace ManagedAndCrawledPropertyMappingSample
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Guid cPropGUID = new Guid("00110329-0000-0110-c000-000000111146");  // // This GUID is for 'MyBookName'. we can get this GUID through programmatically
                string cPropName = "urn:schemas-microsoft-com:sharepoint:portal:profile: ‘MyBookName’";
                int vType = Convert.ToInt32(0); // //We can variant type through programmatically;              
  string mPropName = "MyBookName";
                string strCategoryName = "People";
                string strCraledPropName = string.Empty;

                string strURL = "http://<myServer>:14341";
                SearchContext context;
                using (SPSite site = new SPSite(strURL))
                {
                    context = SearchContext.GetContext(site);
                }
                Schema sspSchema = new Schema(context);

                // Get Crawled Properties
                CategoryCollection categories = sspSchema.AllCategories;
                foreach (Category category in categories)
                {
                    // Console.WriteLine(category.Name);
                    if (category.Name == strCategoryName)
                    {
                        foreach (CrawledProperty property in category.GetAllCrawledProperties())
                        {
                            strCraledPropName = property.Name;
                            Console.WriteLine("Propset: " + property.Propset);
                            Console.WriteLine("Name: " + property.Name);
                            Console.WriteLine("VariantType: " + property.VariantType);
                        }
                        Console.Read();
                    }
                }
                Console.Read();


                ManagedPropertyCollection properties = sspSchema.AllManagedProperties;

                bool isMngdPropertyExists = false;
                foreach (ManagedProperty mProperty in properties)
                {
                    if (mProperty.Name == mPropName)
                    {
                        isMngdPropertyExists = true;
                    }
                }

                if (!isMngdPropertyExists)
                {
                    ManagedProperty _mpNewProperty = properties.Create(mPropName, ManagedDataType.Text);
                    _mpNewProperty.Refinable = true;
                    _mpNewProperty.Sortable = true;
                    _mpNewProperty.SafeForAnonymous = true;
                    _mpNewProperty.Queryable = true;
                    _mpNewProperty.Update();
                }


                ManagedPropertyCollection props = sspSchema.AllManagedProperties;
                ManagedProperty mProp1 = properties["MyBookName"];
                foreach (CrawledProperty cProp in mProp1.GetMappedCrawledProperties(mProp1.GetMappings().Count))
                {
                    Console.WriteLine(cProp.Name);
                    Console.WriteLine(cProp.Propset);
                }
                Console.Read();


                //if (properties[mPropName] != null)
                //{
                //    ManagedProperty _mpNewProperty = properties.Create(mPropName, ManagedDataType.Text);
                //    _mpNewProperty.Update();
                //}
                //foreach(ManagedProperty mProp1 in properties)
                //{
                //    Console.WriteLine(mProp1.Name);
                //}
                //Console.Read();
                ManagedProperty mProp = properties[mPropName];
                //Mapping newMapping = new Mapping(cPropGUID, cPropName, vType, mProp.PID);//          
                MappingCollection mappings = mProp.GetMappings();
                foreach (Mapping mpg in mappings)
                {
                    Console.WriteLine("CrawledPropertyName: " + mpg.CrawledPropertyName);
                    Console.WriteLine("CrawledPropertyVariantType: " + mpg.CrawledPropertyVariantType);
                    Console.WriteLine("ManagedPid: " + mpg.ManagedPid);

                }
                Console.Read();

                if (mProp.DeleteDisallowed)
                {
                    mProp.DeleteAllMappings();
                    Console.WriteLine(mPropName + " Delete All Mappings.");
                    Console.Read();
                }

                //Mapping newMapping = new Mapping(cPropGUID, strCraledPropName, vType, mProp.PID);
                Mapping newMapping = new Mapping(cPropGUID, cPropName, vType, mProp.PID);
                if (mappings.Contains(newMapping))
                {
                    Console.WriteLine("Mapping failed: requested mapping already exists.");
                    Console.Read();
                    return;
                }
                mappings.Add(newMapping);
                mProp.SetMappings(mappings);
                Console.WriteLine(cPropName + " crawled property mapped to " + mProp.Name + " managed property.");
                Console.Read();
            }
            catch (Exception ex1)
            {
                Console.WriteLine(ex1.ToString());
                Console.Read();
            }
        }
    }
}

Thanks...

Featured Post

Reassign a Copilot Studio Agent Owner Using PowerShell and the Dataverse Web API

Reassign a Copilot Studio Agent Owner Using PowerShell and the Dataverse Web API Every Copilot Studio agent is a row in the Dataverse bot t...

Popular posts