Search This Blog

Wednesday, January 9, 2013

WebClient TimerJob -Sharepoint 2010( Read Image Uri)

  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 System.Net.Security.RemoteCertificateValidationCallback(delegate { return true; });

                    client.Credentials = CredentialCache.DefaultCredentials;//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;
            }
        }

No comments:

Post a Comment