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;
            }
        }

Thursday 10 March 2016

JQuery tool tip for text box text

please download and add below files into solution
Jquery-ui.css
Jquery-UI.js
Jquery.min.js

add reference to your page and add below code into your page for getting tooltip


<script type="text/javascript">

             //Initial bind
             $(document).ready(function () {


                 BindControlEvents();
             });

             function BindControlEvents() {

            //changing attribute title to Value
                 $('img').each(function () {
                     var $t = $(this);
                     $t.attr({
                         Value: $t.attr('title')
                     }).removeAttr('title');
                 });


                 $('input[type=text]').tooltip(); //binding tooltip to text box
                 $('img').tooltip(); //binding tooltip to Image

             }


             //Re-bind for callbacks
             var prm = Sys.WebForms.PageRequestManager.getInstance();

             prm.add_endRequest(function () {
                 BindControlEvents();
             });

    </script>

Calling Javascript/Jquery on callbacks

JavaScript or JQuery some methods won't work in callback if you are using below it will work

<script type="text/javascript">

             //Initial bind
             $(document).ready(function () {


                 BindControlEvents();
             });

             function BindControlEvents() {

                ////your code here

             }


             //Re-bind for callbacks
             var prm = Sys.WebForms.PageRequestManager.getInstance();

             prm.add_endRequest(function () {
                 BindControlEvents();
             });

    </script>

Friday 8 January 2016

Fetching values from Web.config in SharePoint if scope is site

Fetching values from Web.config in SharePoint in webapplication level if scope is site it won't allow directly to web.config we can able to fetch the data using below method


public string GetConnectionstring(string Url, string Key)
        {
            try
            {
                using (SPSite site = new SPSite(Url))
                {
                    Configuration config = WebConfigurationManager.OpenWebConfiguration("/", site.WebApplication.Name);
                    return config.AppSettings.Settings[Key].Value;
                }
            }
            catch (Exception ex)
            {
                logToList(ex.Message);
                return string.Empty;
            }
        }

Maintaining Cache in Application Level

1. Create Cache Manager Class
public class CacheManager
    {
    }

2. Add below method into CacheManager Class for Adding Data to Cache
     
        /// <summary>
        /// Add data to Cache
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="bShortTime"></param>
        public static void AddToCache<T>(string key, T value, bool bShortTime)
        {
            try
            {
                if (bShortTime)
                {
                    HttpContext.Current.Cache.Insert(key,
                     value,
                    null,
                    DateTime.Now.AddMinutes(20),
                    System.Web.Caching.Cache.NoSlidingExpiration);
                }
                else
                {
                    AddToCache(key, value);
                }
            }
            catch (Exception ex) {
                throw ex; ;
                 }

        }
     

3. Add below method into CacheManager Class for Adding Data to Cache
        /// <summary>
        /// Add data to Cache
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        private static void AddToCache<T>(string key, T value)
        {
            try
            {
                HttpContext.Current.Cache.Insert(key,
                 value,
                null,
               System.Web.Caching.Cache.NoAbsoluteExpiration,
                System.Web.Caching.Cache.NoSlidingExpiration);
            }
            catch (Exception ex) { throw ex; }

        }


4. Add below method into CacheManager Class for Checking Cache Exists or not based on key
        /// <summary>
        /// Checking Cache Exists or not
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool Exists(string key)
        {
            try
            {
                bool bKey = false;
                if (HttpContext.Current.Cache.Get(key) != null)
                {
                    bKey = true;
                }
                return bKey;
            }
            catch (Exception ex) { throw ex; }
        }

        /// <summary>
        /// ReadFromCache
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T ReadFromCache<T>(string key)
        {
            T value;
            value = (T)HttpContext.Current.Cache.Get(key);
            return value;
        }


5. Add below method into CacheManager Class for Remove data From Cache based on key
        /// <summary>
        /// Remove data From Cache
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool RemoveFromCache(string key)
        {
            try
            {
                bool bKey = false;
                if (HttpContext.Current.Cache.Get(key) != null)
                {
                    HttpContext.Current.Cache.Remove(key);
                    bKey = true;
                }
                return bKey;
            }
            catch (Exception ex) { throw ex; }
        }
     
Creating Property class for Cache
/// <summary>
        /// Cache Properties for RequestType
        /// </summary>
        public class RequestType
        {
            public int RequestTypeID { get; set; }
            public string RequestTypeName { get; set; }
        }


Using below method we can able to interact data to through Cache


public List<CacheProperties.RequestType> GetRequestType()
        {
            List<CacheProperties.RequestType> RequestType = null;
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    if (!CacheManager.Exists("RequestType"))
                    {
                        RequestType = BusinessLogicLayer.GetBusinessLogicLayerInstance.MainForm.GetRequestType();
                        CacheManager.AddToCache<List<CacheProperties.RequestType>>("RequestType", RequestType, true);
                    }
                    else
                    {
                        RequestType = CacheManager.ReadFromCache<List<CacheProperties.RequestType>>("RequestType");
                    }
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return RequestType;
        }


Maintaining Data in Cache and Fetching with key value fields

Create ConfigurationManager Class
 public static class ConfigurationManager
    {
     }

Add below Code in ConfigurationManager Class for maintaining Context
        private static ServerContext serverContext = null;

Add below Code in ConfigurationManager Class for Creating instance of
        /// <summary>
        /// ConfigurationManager
        /// </summary>
        static  ConfigurationManager()
        {
            try
            {
                serverContext =  ServerContext.GetServerContextInstance;
            }
            catch (Exception ex) { throw ex;  }
        }

Add below Code in ConfigurationManager Class for getting values using key and default value
        /// <summary>
        /// GetValue
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static string GetValue(string Key, string defaultValue)
        {
            try
            {
                Dictionary<string, string> configurationSetting = new Dictionary<string, string>();
                //if (null != Key)
                //{
                //    throw new ArgumentNullException();
                //}

                if (CacheManager.Exists(Constants.Cache.CONFIGURATION_KEY))
                {
                    configurationSetting = CacheManager.ReadFromCache<Dictionary<string, string>>(Constants.Cache.CONFIGURATION_KEY);
                }
                else
                {
                    configurationSetting = serverContext.GetConfiguration();
                    CacheManager.AddToCache<Dictionary<string, string>>(Constants.Cache.CONFIGURATION_KEY, configurationSetting, true);
                }

                if (configurationSetting.ContainsKey(Key))
                {
                    defaultValue = configurationSetting[Key];
                }
                return defaultValue;
            }
            catch (Exception ex) { return null; }
        }


/// <summary>
        /// GetConfiguration
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public Dictionary<string, string> GetConfiguration()
        {
            try
            {
                Dictionary<string, string> configurationSetting = new Dictionary<string, string>();
                SPList configurationList = SPContext.Current.Site.RootWeb.Lists.TryGetList(Constants.ServerContext.CONFIGURATION_SETTINGS_LIST);
                SPQuery query = new SPQuery();
                SPListItemCollection items = configurationList.Items;
                foreach (SPListItem item in items)
                {
                    configurationSetting.Add(item["Key"].ToString().Trim(), item["Value"].ToString().Trim());
                }
                return configurationSetting;
            }
            catch (Exception ex) {  return null; }
        }

Custom Webpart Properties

Adding Custom webpart properties in SharePoint Visual Webpart

1. Add Property in  Webpart1.ascx.cs Page

public Webpart1 WebPart { get; set; }//Change Webpart class name in place of "Webpart1"


2.Overrite CreateChildControls method in Webpart1.cs Page

protected override void CreateChildControls()
        {
            Control control = Page.LoadControl(_ascxPath);
            if (control != null)
            {
                ((Webpart1UserControl)control).WebPart = this; //Change Webpart User Control Name
            }
            Controls.Add(control);
        }

3.Add Custom Properties in Webpart1.cs page

        #region Custom Properties

        [Category("GMDM Properties"), //Change Custom Property Group Name
        Personalizable(PersonalizationScope.Shared),
        WebBrowsable(true),
        WebDisplayName("URL"), //Change Property name
        WebDescription("Please Enter URL")] //Change Property Description

        public string strUrl
        {
            get;
            set;
        }
        #endregion