Monday 13 June 2016

Get User Details Based on NTID from AD

//Get User Details Based on NTID from AD


 /// <summary>
        /// Logged in USER NTID
        /// </summary>
        public string LogOnName
        {
            get
            {
                return SPContext.Current.Site.RootWeb.CurrentUser.LoginName;
            }

        }

/// <summary>
        /// Get User Details Based on NTID
        /// </summary>
        /// <param name="ntid"></param>
        /// <returns></returns>
        public Requestor GetRequestorDetails(string ntid)
        {
            try
            {
                Requestor objRequestorDetails = new Requestor();
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    if (string.IsNullOrEmpty(ntid))
                    {
                        ntid = LogOnName;
                    }


                    //string connection = "LDAP://DC=bp1,DC=com";
                    using (System.Web.Hosting.HostingEnvironment.Impersonate())
                    {

                        string connection = Convert.ToString(Constants.Configuration.RequestorLdapConnection);
                        string userid = Convert.ToString(Constants.Configuration.ServiceAccountId);
                        string pwd= Convert.ToString(Constants.GmdmConfiguration.ServiceAccountPassword);
                       
                        using (var domainContext = new PrincipalContext(ContextType.Domain, connection, Convert.ToString(userid), Convert.ToString(pwd)))
                        {
                            using (var foundUser = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, ntid))
                            {
                                if (foundUser != null)
                                {
                                    try
                                    {

                                        DirectoryEntry directoryEntry = foundUser.GetUnderlyingObject() as DirectoryEntry;
                                        objRequestorDetails.Ntid = ntid;
                                        if (directoryEntry != null)
                                        {
                                            objRequestorDetails.RequestorName = directoryEntry.Properties[Constants.DictionaryVals.displayName][0].ToString();
                                            objRequestorDetails.Email = directoryEntry.Properties[Constants.DictionaryVals.mail][0].ToString();
                                        }
                                        //objRequestorDetails.Country = directoryEntry.Properties["co"][0].ToString();
                                        //objRequestorDetails.PhoneNumber = directoryEntry.Properties["mobile"][0].ToString();


                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(ex.Message);
                                    }
                                }
                            }
                        }

                    }
                });
                return objRequestorDetails;

            }
            catch (Exception ex) { GMDMLogger.ErrorloggerUls(Constants.UlsLogs.EntityClassNames.Gmdmservercontext, Constants.UlsLogs.EntityMethodNames.Getrequestordetails, ex); return null; }
        }


//User Details Class

 public class Requestor
    {
        /// <summary>
        /// Requestor Details Properties
        /// </summary>
       
        public string Ntid { get; set; }
        public string RequestorName { get; set; }
        public string Email { get; set; }
        public string PhoneNumber { get; set; }
        public string Country { get; set; }
        public string Department { get; set; }
    }

is Login User In Group

/// <summary>
        /// isLoginUserInGroup
        /// </summary>
        /// <param name="group"></param>
        /// <returns></returns>
        public bool IsLogOnUserInGroup(string group)
        {
            var bUserIsInGroup = false;
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate
                {

                    using (var objSite = new SPSite(SPContext.Current.Site.Url))
                    {
                        using (var objWeb = objSite.OpenWeb())
                        {
                            SPGroup objGroup = SearchGroup(objWeb, group.Trim());
                            if (objGroup != null)
                            {
                                String sUserLoginName = LogOnName;
                                SPUser x = objGroup.Users[sUserLoginName];
                                if (x != null)
                                    bUserIsInGroup = true;
                            }
                        }
                    }
                });
            }
            catch
            {
                bUserIsInGroup = false;
            }

            return bUserIsInGroup;
        }

Copy and Update Excel sheet with Dynamic values using cell ID

//Copy and Update Excel sheet with Dynamic values using cell ID

public string TemplateCreation()
{
string destinationFilePath = string.Format(Convert.ToString(ConfigurationManager.AppSettings[Constants.Configuration.DestinationFilePath]) + @"\{0}.xlsx", DateTime.Now.ToString(CultureInfo.InvariantCulture).Replace(":", string.empty).Replace("/", "_").Replace(" ", "_"));

            string sourceFilePath = Convert.ToString(ConfigurationManager.AppSettings[Constants.Configuration.SourceFilePath]);

            File.Copy(sourceFilePath, destinationFilePath);


            using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(destinationFilePath, true))
            {
                WorksheetPart worksheetPart = GetWorksheetPartByName(spreadSheet, Constants.VendorFormConstants.Sheet1);
                if (worksheetPart != null)
                {
UpdateCellData(worksheetPart, Constants.CddSections.GCell, 2, "Value");


                    // Save the worksheet.
                    worksheetPart.Worksheet.Save();
                }
         }
 return destinationFilePath;
        }
 /// <summary>
        /// Update Cell Data
        /// </summary>
        /// <param name="worksheetPart"></param>
        /// <param name="cellColumn"></param>
        /// <param name="cellRow"></param>
        /// <param name="cellValue"></param>
        public void UpdateCellData(WorksheetPart worksheetPart, string cellColumn, uint cellRow, string cellValue)
        {
            Cell cddEntitiesValue = GetCell(worksheetPart.Worksheet, cellColumn, cellRow);
            cddEntitiesValue.CellValue = new CellValue(cellValue);
            cddEntitiesValue.DataType = new EnumValue<CellValues>(CellValues.String);
        }

        /// <summary>
        /// Get Celll Based WorkSheet, Column and Row Index
        /// </summary>
        /// <param name="worksheet"></param>
        /// <param name="columnName"></param>
        /// <param name="rowIndex"></param>
        /// <returns></returns>
        private Cell GetCell(Worksheet worksheet, string columnName, uint rowIndex)
        {
            Row row = GetRow(worksheet, rowIndex);

            if (row == null)
                return null;

            return row.Elements<Cell>().First(c => String.Compare(c.CellReference.Value, columnName + rowIndex, StringComparison.OrdinalIgnoreCase) == 0);
        }

        /// <summary>
        /// Getting Work Sheet Row
        /// </summary>
        /// <param name="worksheet"></param>
        /// <param name="rowIndex"></param>
        /// <returns></returns>
        private Row GetRow(Worksheet worksheet, uint rowIndex)
        {
            return worksheet.GetFirstChild<SheetData>().Elements<Row>().First(r => r.RowIndex == rowIndex);
        }

        /// <summary>
        /// Getting worksheet based sheet in Document
        /// </summary>
        /// <param name="document"></param>
        /// <param name="sheetName"></param>
        /// <returns></returns>
        public WorksheetPart GetWorksheetPartByName(SpreadsheetDocument document, string sheetName)
        {
            IEnumerable<Sheet> sheets =
               document.WorkbookPart.Workbook.GetFirstChild<Sheets>().
               Elements<Sheet>().Where(s => s.Name == sheetName);



            string relationshipId = sheets.First().Id.Value;
            WorksheetPart worksheetPart = (WorksheetPart)
                 document.WorkbookPart.GetPartById(relationshipId);
            return worksheetPart;
        }




Send mail Using Common Method


Common  Class for sending mails for different templates


public static class NotificationManager
    {
        /// <summary>
        /// Sends the email based on passed Notification item details
        /// </summary>
        /// <param name="notificationItem"></param>
        /// <returns></returns>
        public static bool SendMail(Notification notificationItem)
        {
            try
            {
                var bMailSent = false;
                if (!ValidateNotificationItem(notificationItem)) return false;
                try
                {
                    var smtpClient = new SmtpClient
                    {
                        Host = new GmdmServerContext().GetOutBoundMailAddress()
                    };
                    notificationItem = GetEmailTemplate(notificationItem);
                    var mailContent = PlaceHolderChanges(notificationItem.Body, notificationItem.PlaceHolderValues);
                    var mailSubject = PlaceHolderChanges(notificationItem.Subject, notificationItem.PlaceHolderValues);
                    MailMessage mailMessage;
                    using (mailMessage = new MailMessage(notificationItem.From, notificationItem.To, mailSubject, mailContent))
                    {
                        mailMessage.IsBodyHtml = notificationItem.IsBodyHtml;

                        if (!String.IsNullOrEmpty(notificationItem.Cc))
                        {
                            var ccAddress = new MailAddress(notificationItem.Cc);
                            mailMessage.CC.Add(ccAddress);
                        }

                        if (notificationItem.Attachments != null)
                        {
                            foreach (MailAttachment attachment in notificationItem.Attachments)
                            {
                                attachment.FileContent.Position = 0;
                                mailMessage.Attachments.Add(new Attachment(attachment.FileContent, attachment.FileName));
                            }
                        }
                        if (notificationItem.IsSend)
                        {
                            smtpClient.Send(mailMessage);
                            bMailSent = true;
                        }
                    }
                }
                   
                catch (Exception ex) { GMDMLogger.ErrorloggerUls(Constants.UlsLogs.EntityClassNames.Notificationmanager, Constants.UlsLogs.EntityMethodNames.Sendmail, ex); bMailSent = false;  }
                return bMailSent;
            }
            catch (Exception ex) { GMDMLogger.ErrorloggerUls(Constants.UlsLogs.EntityClassNames.Notificationmanager, Constants.UlsLogs.EntityMethodNames.Sendmail, ex); return false; }
        }

        /// <summary>
        /// replaces the placesholders in template content with passed placeholder values
        /// </summary>
        /// <param name="template"></param>
        /// <param name="bodyChanges"></param>
        /// <returns></returns>
        private static string PlaceHolderChanges(string template, Dictionary<string, string> bodyChanges)
        {
            try
            {
                var mailContent = string.Empty;
                if (template == null) return mailContent;
                mailContent = template;
                return bodyChanges == null ? mailContent : bodyChanges.Aggregate(mailContent, (current, change) => current.Replace(change.Key, change.Value));
            }
            catch (Exception ex) { GMDMLogger.ErrorloggerUls(Constants.UlsLogs.EntityClassNames.Notificationmanager, Constants.UlsLogs.EntityMethodNames.Placeholderchanges, ex); return null; }
        }

        /// <summary>
        /// Gets the email template from configured SharePoint list
        /// </summary>
        /// <param name="notification"></param>
        /// <returns></returns>
        private static Notification GetEmailTemplate(Notification notification)
        {

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    var templateList = SPContext.Current.Site.RootWeb.Lists.TryGetList(GmdmConfigurationManager.GetValue(Constants.GmdmConfiguration.EmailTemplateList, "GMDMNotifications"));
                    var query = new SPQuery();
                    query.Query = string.Format(Constants.NotificationManager.NotificationQuery, notification.TemplateId);
                    query.RowLimit = 1;
                    var items = templateList.GetItems(query);
                    if (items.Count > 0)
                    {
                        foreach (SPListItem item in items)
                        {
                            notification.Subject = Convert.ToString(item[Constants.DictionaryVals.NotificationSubject]);
                            notification.Body = Convert.ToString(item[Constants.DictionaryVals.NotificationBody]);
                            notification.IsSend = Convert.ToBoolean(item[Constants.DictionaryVals.IsSend]);
                        }
                    }
                });
            }
            catch (Exception ex) { GMDMLogger.ErrorloggerUls(Constants.UlsLogs.EntityClassNames.Notificationmanager, Constants.UlsLogs.EntityMethodNames.Getemailtemplate, ex); return null; }
            return notification;
        }

        /// <summary>
        /// Validates the email properties
        /// </summary>
        /// <param name="nItem"></param>
        /// <returns></returns>
        private static bool ValidateNotificationItem(Notification nItem)
        {
            try
            {
                var isValid = !string.IsNullOrEmpty(nItem.To);
                if (string.IsNullOrEmpty(nItem.From))
                {
                    isValid = false;
                }
                if (nItem.TemplateId < 1)
                {
                    isValid = false;
                }

                return isValid;
            }
            catch (Exception ex) { GMDMLogger.ErrorloggerUls(Constants.UlsLogs.EntityClassNames.Notificationmanager, Constants.UlsLogs.EntityMethodNames.Validatenotificationitem, ex); return false; }
        }


    }



Notification Properties in mail Form

public class Notification
    {
        public  Notification()
        {
            _attachments = new List<MailAttachment>();
        }
        /// <summary>
        /// Notification Properties in mail Form
        /// </summary>
        public string To { get; set; }
        public string From { get; set; }
        public string Cc { get; set; }
        public string Subject { get; set; }
        public Dictionary<string, string> PlaceHolderValues { get; set; }
        public int TemplateId { get; set; }
        public string Body { get; set; }
        private List<MailAttachment> _attachments;
        public List<MailAttachment> Attachments {
            get
            {
                return _attachments;
            }
        }
        public string FileName { get; set; }
        public string Language { get; set; }
        public bool IsSend { get; set; }
        private bool _isBodyHtml = true;
        [DefaultValue(true)]
        public bool IsBodyHtml 
        {
             get 
             {
                return _isBodyHtml;
             }
            set 
            {
                _isBodyHtml=value;
            }
        }
    }

    /// <summary>
    /// MailAttachment
    /// </summary>
    public class MailAttachment
    {
        public string FileName { get; set; }
        public MemoryStream FileContent { get; set; }
    }


//Sample method for Sending mail


public void RequestSend(string Spu, string vendor, string createdBy, string Owner, string filepath, string requestNumber)
        {
            try
            {
               
                    using (MemoryStream memStream = new MemoryStream(File.ReadAllBytes(filepath)))
                    {
                        Requestor objUserDetails = new GmdmServerContext().GetRequestorDetails(createdBy);

                        MailAttachment attachment = new MailAttachment();
                        string email = GetCddGroups(requestingSpu);
                        StringBuilder redirectURl = new StringBuilder();
                        redirectURl.Append(Convert.ToString(SPContext.Current.Site.Url));
                        redirectURl.Append(Convert.ToString(GmdmConfigurationManager.GetValue(Constants.Url.CddRequestsForm, "")));
                        redirectURl.Append(Constants.NotificationManager.VendorNumber);
                        redirectURl.Append(requestNumber);

                        Notification notification = new Notification();
                        notification.TemplateId = 3;
                        notification.To = email;
                        notification.From = Convert.ToString(ConfigurationManager.GetValue(Constants.Configuration.FromMail, ""));
                        Dictionary<string, string> mailBoadyvalues = new Dictionary<string, string>() { 
                {Constants.NotificationManager.Team,Constants.NotificationManager.STeam},
                {Constants.NotificationManager.VendorName,vendor},
                {Constants.NotificationManager.LinkToMyTasks,Convert.ToString(redirectURl)},
                {Constants.NotificationManager.RequestorName,objUserDetails.RequestorName.Replace(',',' ')},
                {Constants.NotificationManager.Owner,Owner.Replace(',',' ')},
                {Constants.NotificationManager.RequestNumber,requestNumber}
                };
                        notification.PlaceHolderValues = mailBoadyvalues;
                        if (!string.IsNullOrEmpty(filepath))
                        {
                            attachment.FileName = filepath;

                            attachment.FileContent = memStream;
                            List<MailAttachment> attachments = new List<MailAttachment>();
                            attachments.Add(attachment);

                            notification.Attachments.Clear();
                            notification.Attachments.AddRange(attachments);
                        }

                        NotificationManager.SendMail(notification);
                    }
               
            }
            catch (Exception ex)
            {
               throw ex;
            }
        }