Search This Blog

Wednesday, April 24, 2013

Code Helper

// -----------------------------------------------------------------------
// <copyright file="MyContactHelper.cs" company="Microsoft">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace Inter.CustomerPortal.Branding
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.SharePoint;
    using System.Data;
    using Microsoft.Office.Server.Search.Administration;
    using Microsoft.Office.Server.Search.Query;
    using System.Net;
    using System.Net.Security;
    using System.IO;
    using Microsoft.Office.Server.UserProfiles;    
    using System.Drawing;
    using System.Drawing.Drawing2D;
    using System.Drawing.Imaging;
    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public class ContactHelper
    {
        //const -listname      
        const string listname = "My Contacts";
        const string Pubhublistname = "Pubhub_ProfilePics";
        /// <summary>
        /// Show Contact in Summary page &Display contact left panel
        /// </summary>
        /// <returns></returns>
        public static DataTable GetShowContacts(string ContactInfo)
        {
            DataTable dtTemp = new DataTable();
            DataTable dtContct = new DataTable();
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite spSite = new SPSite(SPContext.Current.Web.Url))
                {
                    spSite.AllowUnsafeUpdates = true;
                    using (SPWeb spWeb = spSite.OpenWeb())
                    {
                        spWeb.AllowUnsafeUpdates = true;
                        SPList spList = spWeb.Lists.TryGetList(listname);
                        if (spList != null)
                        {
                            SPQuery oQuery = new SPQuery();
                            //Generating custom CAML query                                                          
                            oQuery.Query = "<OrderBy><FieldRef Name='Display_x0020_Contact_x0020_Orde' Ascending='TRUE' /></OrderBy>";
                            dtTemp = spList.GetItems(oQuery).GetDataTable();
                            if (dtTemp != null)
                            {
                                if (dtTemp.Rows.Count > 0)
                                {
                                    dtContct = dtTemp.Clone();
                                    if (ContactInfo == "1")
                                    {
                                        foreach (DataRow item in dtTemp.Rows)
                                        {
                                            if (Convert.ToString(item["Show_x0020_Contact"]).Equals("1"))
                                            {
                                                dtContct.ImportRow(item);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        foreach (DataRow item in dtTemp.Rows)
                                        {
                                            if (Convert.ToString(item["Display_x0020_Contact"]).Equals("1"))
                                            {
                                                dtContct.ImportRow(item);
                                            }
                                        }
                                    }
                                }
                            }
                            spList.Update();
                        } spWeb.AllowUnsafeUpdates = false;
                    } spSite.AllowUnsafeUpdates = false;
                }
            });

            return dtContct;
        }
     
        /// <summary>
        /// get image from custom list
        /// </summary>
        /// <param name="site"></param>
        /// <param name="listName"></param>
        public static string GetListAttachments(string ShortName)
        {
            string sAttNames = "/_Layouts/Inter.CustomerPortal.Branding/img/empty.png";
            using (SPSite spSite = new SPSite(SPContext.Current.Web.Site.WebApplication.Sites[0].Url))
            {
                using (SPWeb oWeb = spSite.OpenWeb())
                {
                    SPList oList = oWeb.Lists[Pubhublistname];

                    SPListItemCollection oListItems = oList.Items;
                  //  int ID = GetID(CPUtility.GetUserProfileAccountName(ShortName));
                    int ID = GetID(ShortName);
                    if (ID != 0)
                    {
                        SPListItem spListItem = oListItems.GetItemById(ID);
                        SPAttachmentCollection collAttachments = spListItem.Attachments;
                        if (collAttachments.Count > 0)
                        {
                            foreach (var attachment in collAttachments)
                            {
                               sAttNames = collAttachments.UrlPrefix + attachment.ToString();
                            }
                        }
                    }
                }
              
            }
            return sAttNames.ToString();
        }       
        /// <summary>
        /// import profile pic from pubhub to root site
        /// </summary>
        /// <param name="searchQuery"></param>
        /// <returns></returns>
        public static bool ImportContacts(string searchQuery)
        {
            var searchDt = new DataTable(); bool isImport = false;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SearchServiceApplicationProxy proxy =
                    SearchServiceApplicationProxy.GetProxy(
                        SPServiceContext.GetContext(SPContext.Current.Site)) as SearchServiceApplicationProxy;
                if (proxy == null) throw new ArgumentNullException("SearchServiceApplicationProxy is null");
                var keywordQuery = new KeywordQuery(proxy)
                {
                    ResultsProvider = SearchProvider.Default,
                    ResultTypes = ResultType.RelevantResults,
                    TrimDuplicates = false,
                    HiddenConstraints = "scope:\"MyContacts\"",
                    RowLimit = 500
                };
              
                keywordQuery.SelectProperties.Add("Title");
                keywordQuery.SelectProperties.Add("Path");
                keywordQuery.SelectProperties.Add("PictureThumbnailURL");
                keywordQuery.SelectProperties.Add("PicOwner");
                keywordQuery.SelectProperties.Add("PicOwnerEmail");
                ResultTableCollection fullTextSearchResults = keywordQuery.Execute();
                if (fullTextSearchResults.Exists(ResultType.RelevantResults))
                {
                    ResultTable searchResult = fullTextSearchResults[ResultType.RelevantResults];
                    searchDt.Load(searchResult, LoadOption.OverwriteChanges);
                    if (searchDt.Rows.Count > 0)
                    {
                        //insert data to list
                        insertToRootList(searchDt);
                        isImport = true;
                    }
                }

            }); return isImport;
        
        }
        /// <summary>
        /// insert data fr-m root sites
        /// </summary>
        /// <param name="data"></param>
        private static void insertToRootList(DataTable data)
        {
            string ShortName = string.Empty; string strPicUrl = string.Empty;
            Uri uriPic; string UrlRoot = SPContext.Current.Site.RootWeb.Url;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite spSite = new SPSite(SPContext.Current.Web.Site.WebApplication.Sites[0].Url))
                {
                    spSite.AllowUnsafeUpdates = true;
                    using (SPWeb spWeb = spSite.OpenWeb())
                    {
                        spWeb.AllowUnsafeUpdates = true;
                        SPList spList = spWeb.Lists.TryGetList(Pubhublistname);
                        if (spList != null)
                        {
                            SPListItem spListitem = spList.Items.Add();
                            foreach (DataRow item in data.Rows)
                            {
                                ShortName= Convert.ToString(item["PicOwner"]);
                                if (!string.IsNullOrEmpty(ShortName))
                                {
                                    if (!CheckUserAlreadyExitorNot(ShortName))
                                    {
                                        //insert
                                        spListitem["PicOwner"] = Convert.ToString(item["PicOwner"]);
                                        spListitem["PicOwnerEmail"] = Convert.ToString(item["PicOwnerEmail"]);
                                        spListitem.Update();
                                        #region Update Image
                                         strPicUrl = Convert.ToString(item["PictureThumbnailURL"]);
                                         if (!string.IsNullOrEmpty(strPicUrl))
                                         {
                                             uriPic = new Uri(strPicUrl);
                                             using (WebClient client = new WebClient())
                                             {
                                                 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
                                                 client.Credentials = CredentialCache.DefaultCredentials;
                                                 using (Stream stream = client.OpenRead(strPicUrl))
                                                 {
                                                     System.Drawing.Image webImage = System.Drawing.Image.FromStream(stream);
                                                     var streasms = new System.IO.MemoryStream();
                                                     MemoryStream mss = new MemoryStream();
                                                     webImage.Save(mss, System.Drawing.Imaging.ImageFormat.Jpeg);
                                                     byte[] ImageBytes = mss.ToArray();
                                                     SPListItem spattch = spList.GetItemById(spListitem.ID);
                                                     SPAttachmentCollection attachmentsHeader = spattch.Attachments;
                                                     if (spattch.Attachments.Count > 0)
                                                     {
                                                         for (int i = spattch.Attachments.Count - 1; i >= 0; i--)
                                                         {
                                                             spattch.Attachments.Delete(Convert.ToString(spattch.Attachments[i]));
                                                         }
                                                     }
                                                     SPAttachmentCollection attach = spattch.Attachments;
                                                     attach.Add("Picture.jpeg", ImageBytes);
                                                     spattch.Update();
                                                 }
                                             }
                                         }
                                        #endregion
                                    }
                                    else
                                    {
                                        //update
                                        spListitem = spList.GetItemById(GetID(Convert.ToString(item["PicOwner"])));
                                        spListitem["PicOwner"] = Convert.ToString(item["PicOwner"]);
                                        spListitem["PicOwnerEmail"] = Convert.ToString(item["PicOwnerEmail"]);
                                        spListitem.Update();
                                        #region Update Image
                                        strPicUrl = Convert.ToString(item["PictureThumbnailURL"]);
                                        if (!string.IsNullOrEmpty(strPicUrl))
                                        {
                                            uriPic = new Uri(strPicUrl);
                                            using (WebClient client = new WebClient())
                                            {
                                                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
                                                client.Credentials = CredentialCache.DefaultCredentials;
                                                using (Stream stream = client.OpenRead(strPicUrl))
                                                {
                                                    System.Drawing.Image webImage = System.Drawing.Image.FromStream(stream);
                                                    var streasms = new System.IO.MemoryStream();
                                                    MemoryStream mss = new MemoryStream();
                                                    webImage.Save(mss, System.Drawing.Imaging.ImageFormat.Jpeg);
                                                    byte[] ImageBytes = mss.ToArray();
                                                    SPListItem spattch = spList.GetItemById(spListitem.ID);
                                                    SPAttachmentCollection attachmentsHeader = spattch.Attachments;
                                                    if (spattch.Attachments.Count > 0)
                                                    {
                                                        for (int i = spattch.Attachments.Count - 1; i >= 0; i--)
                                                        {
                                                            spattch.Attachments.Delete(Convert.ToString(spattch.Attachments[i]));
                                                        }
                                                    }
                                                    SPAttachmentCollection attach = spattch.Attachments;
                                                    attach.Add("Picture.jpeg", ImageBytes);
                                                    spattch.Update();
                                                }
                                            }
                                        }
                                        #endregion
                                    }
                                }
                            }

                        } spWeb.AllowUnsafeUpdates = false;
                    }
                    spSite.AllowUnsafeUpdates = false;
                }
            });
        }
        /// <summary>
        /// Chekc user exit or not
        /// </summary>
        /// <param name="UserName"></param>
        /// <returns></returns>
        private static bool CheckUserAlreadyExitorNot(string UserName)
        {
            bool isExit = false;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite spSite = new SPSite(SPContext.Current.Web.Site.WebApplication.Sites[0].Url))
                {
                    spSite.AllowUnsafeUpdates = true;
                    using (SPWeb spWeb = spSite.OpenWeb())
                    {
                        spWeb.AllowUnsafeUpdates = true;
                        SPList spList = spWeb.Lists.TryGetList(Pubhublistname);
                        if (spList != null)
                        {
                            spWeb.AllowUnsafeUpdates = false;
                            foreach (SPListItem item in spList.Items)
                            {
                                string Shortname = (Convert.ToString(item["PicOwner"]));
                                if (Shortname.ToLower().Equals(UserName.ToLower()))
                                {
                                    isExit = true; break;
                                }
                            }
                        }
                    }
                    spSite.AllowUnsafeUpdates = false;
                }
            }); return isExit;
        }
        /// <summary>
        /// get id -update
        /// </summary>
        /// <param name="UserName"></param>
        /// <returns></returns>
        private static int GetID(string UserName)
        {
            int id = 0;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite spSite = new SPSite(SPContext.Current.Web.Site.WebApplication.Sites[0].Url))
                {
                    spSite.AllowUnsafeUpdates = true;
                    using (SPWeb spWeb = spSite.OpenWeb())
                    {
                        spWeb.AllowUnsafeUpdates = true;
                        SPList spList = spWeb.Lists.TryGetList(Pubhublistname);
                        if (spList != null)
                        {
                            spWeb.AllowUnsafeUpdates = false;
                            foreach (SPListItem item in spList.Items)
                            {
                                string Shortname = (Convert.ToString(item["PicOwner"]));
                                if (Shortname.ToLower().Equals(UserName.ToLower()))
                                {
                                    id = item.ID; break;
                                }
                            }
                        }
                    }
                    spSite.AllowUnsafeUpdates = false;
                }
            }); return id;
        }


        private static bool chekUserNameAlreadyExit(SPWeb spWeb, string LoginName)
        {

            spWeb.AllowUnsafeUpdates = true; bool istrue = false;
            SPList spList = spWeb.Lists.TryGetList(listname);

            if (spList != null)
            {
                spWeb.AllowUnsafeUpdates = false;
                foreach (SPListItem item in spList.Items)
                {
                    string lgnname = (Convert.ToString(item["Title"]));
                    if (lgnname.ToLower() == LoginName.ToLower())
                    {
                        istrue = true; break;
                    }
                }
            }
            return istrue;
        }
        private static int GetListID(SPWeb spWeb, string LoginName)
        {
            SPList spList; int id = 0;

            spWeb.AllowUnsafeUpdates = true;
            spList = spWeb.Lists.TryGetList(listname);

            if (spList != null)
            {
                spWeb.AllowUnsafeUpdates = false;
                foreach (SPListItem item in spList.Items)
                {
                    string Loginname = (Convert.ToString(item["Title"]));
                    if (Loginname.ToLower() == LoginName.ToLower())
                    {
                        id = item.ID; break;
                    }
                }
            }

            return id;
        }
        internal static bool ImportSitesOwnersToList()
        {
            SPServiceContext serviceContext = SPServiceContext.GetContext(SPContext.Current.Site);
            SPGroupCollection groupCollection = null; SPGroup ownerGroup = null;
            UserProfileManager userProfileManager = new UserProfileManager(serviceContext);
            UserProfile profile = null; bool isUpdate = false; string loginname = string.Empty;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite spSite = new SPSite(SPContext.Current.Web.Url))
                {
                    spSite.AllowUnsafeUpdates = true;
                    using (SPWeb spWeb = spSite.OpenWeb())
                    {
                        spWeb.AllowUnsafeUpdates = true;
                        SPList spList = spWeb.Lists.TryGetList(listname);
                        if (spList != null)
                        {
                            groupCollection = spWeb.SiteGroups;
                            foreach (SPGroup group in groupCollection)
                            {
                                string KeyAccount = SPContext.Current.Web.Url.Split('/').Last();
                                if (group.Name.Contains(KeyAccount + " Owners") || group.Name.Contains(KeyAccount + " Managers"))
                                {
                                    ownerGroup = group;                                  
                                    foreach (SPUser ownerUser in ownerGroup.Users)
                                    {
                                        loginname = CPUtility.GetUserProfileAccountName(ownerUser.LoginName);
                                        if (!chekUserNameAlreadyExit(spWeb, loginname))
                                        {
                                            spWeb.AllowUnsafeUpdates = true;
                                            profile = userProfileManager.GetUserProfile(loginname);
                                            SPListItem newList = spList.Items.Add();
                                            newList["First Name"] = Convert.ToString(profile[PropertyConstants.FirstName].Value);
                                            newList["Last Name"] = Convert.ToString(profile[PropertyConstants.LastName].Value);
                                            newList["Job Title"] = Convert.ToString(profile[PropertyConstants.JobTitle].Value);
                                            newList["Work Phone"] = Convert.ToString(profile[PropertyConstants.WorkPhone].Value);
                                            newList["Cell Phone"] = Convert.ToString(profile[PropertyConstants.CellPhone].Value);
                                            newList["Email"] = Convert.ToString(profile[PropertyConstants.WorkEmail].Value);
                                            newList["Title"] = loginname;                                       
                                            newList.Update();
                                            isUpdate = true;
                                        }
                                        else
                                        {
                                            //update
                                            loginname = CPUtility.GetUserProfileAccountName(ownerUser.LoginName);
                                            profile = userProfileManager.GetUserProfile(loginname);
                                            int id = GetListID(spWeb, loginname);
                                            if (id != 0)
                                            {
                                                spWeb.AllowUnsafeUpdates = true;
                                                SPListItem newList = spList.GetItemById(id);
                                                newList["First Name"] = Convert.ToString(profile[PropertyConstants.FirstName].Value);
                                                newList["Last Name"] = Convert.ToString(profile[PropertyConstants.LastName].Value);
                                                newList["Job Title"] = Convert.ToString(profile[PropertyConstants.JobTitle].Value);
                                                newList["Work Phone"] = Convert.ToString(profile[PropertyConstants.WorkPhone].Value);
                                                newList["Cell Phone"] = Convert.ToString(profile[PropertyConstants.CellPhone].Value);
                                                newList["Email"] = Convert.ToString(profile[PropertyConstants.WorkEmail].Value);
                                                newList["Title"] = loginname;
                                                newList.Update();
                                                isUpdate = true;
                                            }

                                        }

                                    }
                                }
                            }
                        }
                        spWeb.AllowUnsafeUpdates = false;
                    }
                    spSite.AllowUnsafeUpdates = false;
                }
            }); return isUpdate;
        }
    }


}



No comments:

Post a Comment