Quantcast
Channel: SharePoint 2010 - Development and Programming forum
Viewing all articles
Browse latest Browse all 11571

Access Denied. Exception: System.UnauthorizedAccessException:

$
0
0

Deal all

In last weekend we moved the databases of Sharepoint to another server and changed sharepoint services accounts to meet best practices. Now we have a problem with a page.

This page generate a vCard and is published to internet.

Now, we have this error:

Access Denied. Exception: System.UnauthorizedAccessException: Attempted to perform an unauthorized operation..


Here´s the code:

using System;
using System.Web.UI;
using System.ComponentModel;
using Microsoft.SharePoint;
using Microsoft.Office.Server.UserProfiles;
using Thought.vCards;
using System.Drawing;
using System.Drawing.Imaging;
using System.Net;
using System.Security.Principal;
using System.IO;
using System.Net.Mail;
using System.Net.Mime;

namespace Demarest.SP2010.Internet
{
    [ToolboxItemAttribute(false)]
    public class exportarVCard : Page
    {
        string userId;
        string userName = "";
        string fileName;
        Guid site;

        Image FixedSize(Image imgPhoto, int width, int height)
        {

            int sourceWidth = imgPhoto.Width;
            int sourceHeight = imgPhoto.Height;

            if (sourceHeight == sourceWidth)
                return imgPhoto;

            int sourceX = 0;
            int sourceY = 0;
            int destX = 0;
            int destY = 0;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = ((float)width / (float)sourceWidth);
            nPercentH = ((float)height / (float)sourceHeight);
            if (nPercentH < nPercentW)
            {
                nPercent = nPercentH;
                destX = System.Convert.ToInt16((width -
                              (sourceWidth * nPercent)) / 2);
            }
            else
            {
                nPercent = nPercentW;
                destY = System.Convert.ToInt16((height -
                              (sourceHeight * nPercent)) / 2);
            }

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap bmPhoto = new Bitmap(width, height,
                              PixelFormat.Format24bppRgb);
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
                             imgPhoto.VerticalResolution);

            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.Clear(Color.White);
            grPhoto.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

            grPhoto.DrawImage(imgPhoto,
                new Rectangle(destX, destY, destWidth, destHeight),
                new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                GraphicsUnit.Pixel);

            grPhoto.Dispose();
            return bmPhoto;
        }

        protected override void OnLoad(EventArgs e)
        {
            if (Request.QueryString["login"] != null)
            {
                userId = Request.QueryString["login"].ToString();
                site = SPContext.Current.Site.ID;

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite admsite = new SPSite(site))
                    {
                        using (SPWeb web = admsite.OpenWeb())
                        {
                            web.AllowUnsafeUpdates = true;
                            SPUser user = web.EnsureUser(userId);
                            userName = user.Name;
                            web.AllowUnsafeUpdates = false;
                        }
                    }
                });

                fileName = userName;

                //bool iphone = Request.UserAgent != null && Request.UserAgent.ToLower().Contains("iphone");
                //string email = Request.QueryString["email"];
                //if (iphone)
                //{
                //    if (!string.IsNullOrEmpty(email) && IsValidEmail(email)) 
                //        SendVCardByEmail(email);                         
                //}
                //else {
                        DownloadVCard();
                //}
            }
        }

        public bool IsValidEmail(string emailaddress)
        {
            try
            {
                MailAddress m = new MailAddress(emailaddress);
                return true;
            }
            catch (FormatException)
            {
                return false;
            }
        }

        //public void SendVCardByEmail(string email)
        //{
        //    if (IsValidEmail(email))
        //    {
        //        //try
        //        //{
        //        MailMessage mail = new MailMessage();
        //        SmtpClient SmtpServer = new SmtpClient("relay.demarest.com.br");
        //        mail.From = new MailAddress("noreply@demarest.com.br");
        //        mail.To.Add(email);
        //        mail.Subject = "Demarest Advogados - Download de Contato";
        //        mail.Body = "Por favor, abra o contato anexo";

        //        string vcfText;
        //        using (StringWriter stringWrite = new StringWriter())
        //        {
        //            WriteVCard(GenerateVCard(), stringWrite);
        //            vcfText = stringWrite.ToString();
        //        }
        //        //byte[] vcfBinary = System.Text.UTF8Encoding.UTF8.GetBytes(vcfText);
        //        //MemoryStream stream = new MemoryStream(vcfBinary);

        //        System.Net.Mail.Attachment attachment = System.Net.Mail.Attachment.CreateAttachmentFromString(vcfText, new System.Net.Mime.ContentType("text/vcard"));
        //        ContentDisposition disposition = attachment.ContentDisposition;
        //        disposition.CreationDate = DateTime.Now;
        //        disposition.ModificationDate = DateTime.Now;
        //        disposition.ReadDate = DateTime.Now;
        //        disposition.DispositionType = DispositionTypeNames.Attachment;
        //        attachment.Name = fileName + ".vcf";

        //        mail.Attachments.Add(attachment);

        //        SmtpServer.Send(mail);

        //        //Response.Clear();
        //        Response.Write("Verifique seu e-mail");
        //        Response.End();
        //        //}
        //        //catch ()
        //        //{
        //        //    Response.Clear();
        //        //    Response.Write("Erro ao enviar e-mail");
        //        //}
        //    }
        //    else
        //    {
        //        Response.Write("Email invalido");
        //    }
        //}


        public void DownloadVCard()
        {
            Response.Clear();
            Response.Charset = "UTF-8";
            Response.ContentType = "text/x-vcard";
            Response.AppendHeader("content-disposition", "attachment;filename=" + fileName + ".vcf");
            WriteVCard(GenerateVCard(), Response.Output);
            Response.Flush();
            Response.End();
        }

        protected vCard GenerateVCard()
        {
                vCard toReturn = new vCard();
                
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite admSite = new SPSite(site))
                    {
                        using (SPWeb web = admSite.OpenWeb())
                        {
                            UserProfileManager oProfile = new UserProfileManager(SPServiceContext.GetContext(admSite), false);
                            UserProfile prof = oProfile.GetUserProfile(userId.ToLower(), false);
                            string fullName = prof["PreferredName"].ToString().Replace(" | Demarest Advogados", "");
                            var names = fullName.Split(' ');
                            string firstName = names[0];
                            string lastName = fullName.Replace(firstName + " ", "");

                            toReturn.GivenName = firstName;
                            toReturn.FamilyName = lastName;
                            toReturn.FormattedName = fullName;
                            toReturn.DisplayName = fullName;
                            toReturn.Organization = prof["RazaoSocial"].ToString();
                            toReturn.EmailAddresses.Add(new vCardEmailAddress(prof["WorkEmail"].ToString()));
                            toReturn.DeliveryAddresses.Add(new vCardDeliveryAddress()
                            {
                                City = prof["Municipio"].ToString(),
                                AddressType = vCardDeliveryAddressTypes.Work,
                                Country = "Brasil",
                                Street = prof["EnderecoEmpresa"].ToString(),
                                PostalCode = prof["CEP"].ToString(),
                                Region = prof["Estado"].ToString()
                            });
                            toReturn.Phones.Add(new vCardPhone(prof["WorkPhone"].ToString(), vCardPhoneTypes.WorkVoice));
                            toReturn.Websites.Add(new vCardWebsite("http://www.demarest.com.br", vCardWebsiteTypes.Work));

                            try
                            {
                                HttpWebRequest imgRequest = WebRequest.Create(prof["PictureURL"].ToString()) as HttpWebRequest;
                                imgRequest.Credentials = CredentialCache.DefaultCredentials;
                                imgRequest.ImpersonationLevel = TokenImpersonationLevel.Delegation;
                                Bitmap imgBitmap;
                                using (HttpWebResponse imgResponse = imgRequest.GetResponse() as HttpWebResponse)
                                {
                                    imgBitmap = new Bitmap(imgResponse.GetResponseStream());
                                }

                                ImageConverter converter = new ImageConverter();
                                var finalPhoto = new Bitmap(FixedSize(imgBitmap, 96, 96));

                                byte[] finalBytes = (byte[])converter.ConvertTo(finalPhoto, typeof(byte[]));
                                toReturn.Photos.Add(new vCardPhoto(finalBytes));
                            }
                            catch
                            {

                            }
                        }
                    }
                });

                return toReturn;
            }

        public void WriteVCard(vCard card, TextWriter destination) {
            vCardStandardWriter writer = new vCardStandardWriter();
            writer.EmbedInternetImages = true;
            writer.EmbedLocalImages = true;
            writer.Options = vCardStandardWriterOptions.IgnoreCommas;
            writer.Write(card, destination);
        }
               
    }
}

        //static string ChunksUpto(string str, int maxChunkSize)
        //{
        //    string toReturn = string.Empty;
        //    for (int i = 0; i < str.Length; i += maxChunkSize)
        //        toReturn += string.Format(" {0}\r\n", str.Substring(i, Math.Min(maxChunkSize, str.Length - i)));
        //    return toReturn;
        //}

Before the changes of databases and users, this page works perfect!

Any suggestion?

Best regards

Keny Schmeling



Viewing all articles
Browse latest Browse all 11571

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>