Search This Blog

Monday, April 15, 2013

WebConfig-TimerJob


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;
using Microsoft.Office.Server.UserProfiles;
using System.Configuration;
using System.Collections;
using System.Data;
using System.Net;
using System.IO;
using System.Net.Security;
using System.Web.Configuration;

namespace .CustomerPortal.Core
{
    class CPTimerJobUserProfileUpdate : SPJobDefinition
    {
        public CPTimerJobUserProfileUpdate()

            : base()
        {

        }

        public CPTimerJobUserProfileUpdate(string jobName, SPService service, SPServer server, SPJobLockType targetType)

            : base(jobName, service, server, targetType)
        {

        }

        public CPTimerJobUserProfileUpdate(string jobName, SPWebApplication webApplication)

            : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
        {

            this.Title = " UserProfile Timer Job";

        }

        #region Get All Sites
        public DataTable GetSiteColletion(string siteurl)
        {
            SPSite spSite; DataTable result = new DataTable();
            SPList list = null;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (spSite = new SPSite(siteurl))
                {
                    spSite.AllowUnsafeUpdates = true;

                    result.Columns.Add("SiteName");

                    foreach (SPSite sc in spSite.WebApplication.Sites)
                    {
                        foreach (SPWeb item in sc.AllWebs)
                        {
                            list = item.Lists.TryGetList("My Contacts");
                            if (list != null)
                            {
                                DataRow dr = result.NewRow();
                                dr["SiteName"] = item.ServerRelativeUrl;
                                result.Rows.Add(dr);
                            }
                        }
                    }


                }
            }); return result;
        }
        #endregion

        public override void Execute(Guid contentDbId)
        {
            SPWebApplication webApplication = this.Parent as SPWebApplication;

            SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];
          
            SPSite site = new SPSite(contentDb.Sites[0].RootWeb.Url);
            SPServiceContext serviceContext = SPServiceContext.GetContext(site);
            DataTable result = GetSiteColletion(contentDb.Sites[0].RootWeb.Url);
            if (result != null && result.Rows.Count > 0)
            {
                foreach (DataRow item in result.Rows)
                {
                    string siteurl = Convert.ToString(item["SiteName"]).TrimStart('/');

                    UserProfileManager userProfileManager = new UserProfileManager(serviceContext);
                    UserProfile profile = null; SPGroupCollection groupCollection = null;
                    SPList spList = null;

                    SPWeb spwb = null; SPGroup ownerGroup = null;
                    if (siteurl.Contains("/"))
                    {

                        spwb = contentDb.Sites[siteurl.Split('/').GetValue(0).ToString()].OpenWeb(siteurl.Split('/').GetValue(1).ToString());
                        spList = spwb.Lists.TryGetList("My Contacts");
                        if (spList != null)
                        {
                            groupCollection = spwb.SiteGroups;
                            foreach (SPGroup group in groupCollection)
                            {

                                if (group.Name.Contains("Owners"))
                                {
                                    ownerGroup = group;
                                    spwb.Site.WebApplication.FormDigestSettings.Enabled = false;
                                    foreach (SPUser ownerUser in ownerGroup.Users)
                                    {

                                        if (!chekUserNameAlreadyExit(spwb, ownerUser.LoginName))
                                        {
                                            profile = userProfileManager.GetUserProfile(ownerUser.LoginName);
                                            SPListItem newList = spList.Items.Add();
                                            spwb.AllowUnsafeUpdates = true;
                                          
                                            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["Email"] = Convert.ToString(profile[PropertyConstants.WorkEmail].Value);
                                            newList["AccountName"] = ownerUser.LoginName;
                                            newList["Title"] = Convert.ToString(profile[PropertyConstants.PictureUrl].Value);
                                            newList.Update();
                                            GetImageFromUriAndUpdate(spwb, newList.ID, spList, ownerUser.LoginName);
                                          
                                        }
                                        else
                                        {
                                            //update
                                            profile = userProfileManager.GetUserProfile(ownerUser.LoginName);
                                            SPListItem newList = spList.GetItemById(GetID(spwb, ownerUser.LoginName));
                                            spwb.AllowUnsafeUpdates = true;
                                         
                                            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["Email"] = Convert.ToString(profile[PropertyConstants.WorkEmail].Value);
                                            newList["AccountName"] = ownerUser.LoginName;
                                            newList["Title"] = Convert.ToString(profile[PropertyConstants.PictureUrl].Value);
                                            newList.Update();
                                            //update Image
                                            GetImageFromUriAndUpdate(spwb, newList.ID, spList, ownerUser.LoginName);
                                         
                                        }

                                    }
                                }
                            }
                        }

                    }
                    else
                    {
                        spwb = contentDb.Sites[siteurl].RootWeb;
                        spList = spwb.Lists.TryGetList("My Contacts");
                        if (spList != null)
                        {
                            groupCollection = spwb.SiteGroups;
                            foreach (SPGroup group in groupCollection)
                            {
                                if (group.Name.Contains("Owners"))
                                {
                                    ownerGroup = group;
                                    spwb.Site.WebApplication.FormDigestSettings.Enabled = false;
                                    foreach (SPUser ownerUser in ownerGroup.Users)
                                    {

                                        if (!chekUserNameAlreadyExit(spwb, ownerUser.LoginName))
                                        {
                                            profile = userProfileManager.GetUserProfile(ownerUser.LoginName);
                                            SPListItem newList = spList.Items.Add();
                                            spwb.AllowUnsafeUpdates = true;
                                          
                                            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["Email"] = Convert.ToString(profile[PropertyConstants.WorkEmail].Value);
                                            newList["AccountName"] = ownerUser.LoginName;
                                            newList["Title"] = Convert.ToString(profile[PropertyConstants.PictureUrl].Value);
                                            newList.Update();
                                            GetImageFromUriAndUpdate(spwb, newList.ID, spList, ownerUser.LoginName);
                                          
                                        }
                                        else
                                        {
                                            //update
                                            profile = userProfileManager.GetUserProfile(ownerUser.LoginName);
                                            SPListItem newList = spList.GetItemById(GetID(spwb, ownerUser.LoginName));
                                            spwb.AllowUnsafeUpdates = true;
                                         
                                            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["Email"] = Convert.ToString(profile[PropertyConstants.WorkEmail].Value);
                                            newList["AccountName"] = ownerUser.LoginName;
                                            newList["Title"] = Convert.ToString(profile[PropertyConstants.PictureUrl].Value);
                                            newList.Update();
                                            //update Image
                                            GetImageFromUriAndUpdate(spwb, newList.ID, spList, ownerUser.LoginName);
                                         
                                        }

                                    }
                                }
                            }
                        }

                    }

                }
            }

        }

        #region Custom Methods
        private bool GetImageFromUriAndUpdate(SPWeb spwb, int ID, SPList spList, string accountname)
        {
            try
            {
                SPWebApplication webApplication = this.Parent as SPWebApplication;
                Configuration config = WebConfigurationManager.OpenWebConfiguration("/", webApplication.Name);

                string strPicUrl = config.AppSettings.Settings["ImageUrl"].Value + "_" + Convert.ToString(accountname).Split('|').GetValue(1).ToString().Split('\\').GetValue(1).ToString() + "_MThumb.jpg";

                Uri uriPic;

                uriPic = new Uri(strPicUrl);
                using (WebClient client = new WebClient())
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
                    // web service calling here
                    // com..community.UserProfileService svc = new com..community.UserProfileService();
                    // svc.GetUserProfileByName(accountname);
                    string usrname = config.AppSettings.Settings["UserName"].Value;
                    string Pwd = config.AppSettings.Settings["Password"].Value;
                    string domain = config.AppSettings.Settings["Domain"].Value;
                    if (!string.IsNullOrEmpty(usrname) && !string.IsNullOrEmpty(Pwd) && !string.IsNullOrEmpty(domain))
                    {
                        client.Credentials = new System.Net.NetworkCredential(usrname, Pwd, domain);

                        using (Stream stream = client.OpenRead(strPicUrl))
                        {
                            System.Drawing.Image webImage = System.Drawing.Image.FromStream(stream);

                            SPSecurity.RunWithElevatedPrivileges(delegate()
                            {
                                spwb.AllowUnsafeUpdates = true;
                                var streasms = new System.IO.MemoryStream();
                                MemoryStream mss = new MemoryStream();
                                webImage.Save(mss, System.Drawing.Imaging.ImageFormat.Jpeg);
                                byte[] ImageBytes = mss.ToArray();
                                if (spList != null)
                                {
                                    SPListItem spattch = spList.GetItemById(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("MySiteUser.jpeg", ImageBytes);
                                    spattch.Update();
                                }

                            });

                        }
                    }
                } return true;
            }
            catch
            {
                return false;
            }
        }
     
        private bool chekUserNameAlreadyExit(SPWeb spWeb, string LoginName)
        {

            spWeb.AllowUnsafeUpdates = true; bool istrue = false;
            SPList spList = spWeb.Lists.TryGetList("My Contacts");

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

            spWeb.AllowUnsafeUpdates = true;
            spList = spWeb.Lists.TryGetList("My Contacts");

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

            return id;
        }
        #endregion
    }
}



No comments:

Post a Comment