// Private Methods (10) 

        /// <summary>
        /// Builds the notification element.
        /// </summary>
        /// <param name="result">The result.</param>
        /// <param name="epmNotification">The epm notification.</param>
        private static void BuildNotificationElement(XDocument result, EPMNotification epmNotification)
        {
            var xElement = new XElement("Notification");

            xElement.Add(new XAttribute("ID", epmNotification.Id));
            xElement.Add(new XAttribute("Type", epmNotification.Type));
            xElement.Add(new XAttribute("CreatedBy", epmNotification.CreatedBy));
            xElement.Add(new XAttribute("CreatedAt", epmNotification.CreatedAt));
            xElement.Add(new XAttribute("CreatedAtDateString", epmNotification.CreatedAtDateString));
            xElement.Add(new XAttribute("CreatorName", epmNotification.CreatorName));
            xElement.Add(new XAttribute("CreatorThumbnail", epmNotification.CreatorThumbnail));
            xElement.Add(new XAttribute("SiteId", epmNotification.SiteId));
            xElement.Add(new XAttribute("WebId", epmNotification.WebId));
            xElement.Add(new XAttribute("ListId", epmNotification.ListId));
            xElement.Add(new XAttribute("ItemId", epmNotification.ItemId));
            xElement.Add(new XAttribute("NotificationRead", epmNotification.NotificationRead));
            xElement.Add(new XAttribute("UserEmailed", epmNotification.UserEmailed));
            xElement.Add(new XAttribute("Emailed", epmNotification.Emailed));
            xElement.Add(new XAttribute("PersonalizationId", epmNotification.PersonalizationId));
            xElement.Add(new XAttribute("PersonalizationSiteId", epmNotification.PersonalizationSiteId));

            if (!string.IsNullOrEmpty(epmNotification.SiteCreationDate))
            {
                xElement.Add(new XAttribute("SiteCreationDate", epmNotification.SiteCreationDate));
            }

            xElement.Add(new XElement("Title", new XCData(epmNotification.Title)));
            xElement.Add(new XElement("Message", new XCData(epmNotification.Message)));

            if (result.Root != null)
            {
                result.Root.Add(xElement);
            }
        }
        /// <summary>
        /// Sets the notification flag.
        /// </summary>
        /// <param name="epmNotification">The epm notification.</param>
        /// <param name="sqlConnection">The SQL connection.</param>
        /// <param name="user">The user.</param>
        private static void SetNotificationFlag(EPMNotification epmNotification, SqlConnection sqlConnection, SPUser user)
        {
            if (sqlConnection == null)
            {
                throw new ArgumentNullException(nameof(sqlConnection));
            }

            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            using (var sqlCommand = new SqlCommand("spNSetBit", sqlConnection))
            {
                sqlCommand.CommandType = CommandType.StoredProcedure;

                var notificationId = sqlCommand.Parameters.Add("@FK", SqlDbType.UniqueIdentifier);
                var userId         = sqlCommand.Parameters.Add("@userid", SqlDbType.VarChar);
                var index          = sqlCommand.Parameters.Add("@index", SqlDbType.Int);
                var bit            = sqlCommand.Parameters.Add("@val", SqlDbType.Bit);

                notificationId.Value = epmNotification.Id;
                userId.Value         = epmNotification.Type > 1 ? user.ID.ToString() : user.LoginName;
                index.Value          = epmNotification.FlagToSet;
                bit.Value            = true;

                try
                {
                    SPSecurity.RunWithElevatedPrivileges(() =>
                    {
                        sqlConnection.Open();
                        sqlCommand.ExecuteNonQuery();
                    });
                }
                catch (SqlException sqlException)
                {
                    Trace.WriteLine(sqlException.ToString());
                    throw new APIException(SqlExceptionId1, sqlException.Message);
                }
                finally
                {
                    sqlConnection.Close();
                }
            }
        }
        /// <summary>
        /// Translates the notification to personalization.
        /// </summary>
        /// <param name="epmNotification">The epm notification.</param>
        /// <param name="sqlConnection">The SQL connection.</param>
        /// <param name="user">The user.</param>
        private static void TranslateNotificationToPersonalization(EPMNotification epmNotification, SqlConnection sqlConnection, SPUser user)
        {
            if (sqlConnection == null)
            {
                throw new ArgumentNullException(nameof(sqlConnection));
            }

            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            using (var sqlCommand = new SqlCommand("spNTranslateNotificationToPersonalization", sqlConnection))
            {
                sqlCommand.CommandType = CommandType.StoredProcedure;

                var notificationId = sqlCommand.Parameters.Add("@NotificationId", SqlDbType.UniqueIdentifier);
                var userName       = sqlCommand.Parameters.Add("@UserName", SqlDbType.NVarChar);
                var userId         = sqlCommand.Parameters.Add("@UserId", SqlDbType.NVarChar);

                notificationId.Value = epmNotification.Id;
                userName.Value       = user.LoginName;
                userId.Value         = user.ID;

                try
                {
                    SPSecurity.RunWithElevatedPrivileges(() =>
                    {
                        sqlConnection.Open();
                        sqlCommand.ExecuteNonQuery();
                    });
                }
                catch (SqlException sqlException)
                {
                    Trace.WriteLine(sqlException.ToString());
                    throw new APIException(SqlExceptionId2, sqlException.Message);
                }
                finally
                {
                    sqlConnection.Close();
                }
            }
        }
        /// <summary>
        /// Builds the notifications.
        /// </summary>
        /// <param name="epmNotifications">The epm notifications.</param>
        /// <param name="sqlCommand">The SQL command.</param>
        /// <param name="sqlConnection">The SQL connection.</param>
        /// <param name="spWeb">The sp web.</param>
        private static void BuildNotifications(List <EPMNotification> epmNotifications, SqlCommand sqlCommand,
                                               SqlConnection sqlConnection, SPWeb spWeb)
        {
            sqlConnection.Open();

            SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();

            while (sqlDataReader.Read())
            {
                var epmNotification = new EPMNotification
                {
                    Id    = sqlDataReader.GetGuid(sqlDataReader.GetOrdinal("ID")),
                    Type  = sqlDataReader.GetInt32(sqlDataReader.GetOrdinal("Type")),
                    Title = sqlDataReader.GetString(sqlDataReader.GetOrdinal("Title"))
                };


                if (sqlDataReader.GetValue(sqlDataReader.GetOrdinal("Message")) != DBNull.Value)
                {
                    epmNotification.Message = sqlDataReader.GetString(sqlDataReader.GetOrdinal("Message"));
                }

                if (sqlDataReader.GetValue(sqlDataReader.GetOrdinal("CreatedBy")) != DBNull.Value)
                {
                    epmNotification.CreatedBy = sqlDataReader.GetInt32(sqlDataReader.GetOrdinal("CreatedBy"));
                }

                if (sqlDataReader.GetValue(sqlDataReader.GetOrdinal("SiteId")) != DBNull.Value)
                {
                    epmNotification.SiteId = sqlDataReader.GetGuid(sqlDataReader.GetOrdinal("SiteId"));
                }

                if (sqlDataReader.GetValue(sqlDataReader.GetOrdinal("WebId")) != DBNull.Value)
                {
                    epmNotification.WebId = sqlDataReader.GetGuid(sqlDataReader.GetOrdinal("WebId"));
                }

                if (sqlDataReader.GetValue(sqlDataReader.GetOrdinal("ListId")) != DBNull.Value)
                {
                    epmNotification.ListId = sqlDataReader.GetGuid(sqlDataReader.GetOrdinal("ListId"));
                }

                if (sqlDataReader.GetValue(sqlDataReader.GetOrdinal("ItemId")) != DBNull.Value)
                {
                    epmNotification.ItemId = sqlDataReader.GetInt32(sqlDataReader.GetOrdinal("ItemId"));
                }

                if (sqlDataReader.GetValue(sqlDataReader.GetOrdinal("UserEmailed")) != DBNull.Value)
                {
                    epmNotification.UserEmailed = sqlDataReader.GetBoolean(sqlDataReader.GetOrdinal("UserEmailed"));
                }

                if (sqlDataReader.GetValue(sqlDataReader.GetOrdinal("NotificationRead")) != DBNull.Value)
                {
                    epmNotification.NotificationRead =
                        sqlDataReader.GetBoolean(sqlDataReader.GetOrdinal("NotificationRead"));
                }

                if (sqlDataReader.GetValue(sqlDataReader.GetOrdinal("Emailed")) != DBNull.Value)
                {
                    epmNotification.Emailed = sqlDataReader.GetBoolean(sqlDataReader.GetOrdinal("Emailed"));
                }

                if (sqlDataReader.GetValue(sqlDataReader.GetOrdinal("PersonalizationId")) != DBNull.Value)
                {
                    epmNotification.PersonalizationId =
                        sqlDataReader.GetGuid(sqlDataReader.GetOrdinal("PersonalizationId"));
                }

                if (sqlDataReader.GetValue(sqlDataReader.GetOrdinal("PersonalizationSiteId")) != DBNull.Value)
                {
                    epmNotification.PersonalizationSiteId =
                        sqlDataReader.GetGuid(sqlDataReader.GetOrdinal("PersonalizationSiteId"));
                }

                if (sqlDataReader.GetValue(sqlDataReader.GetOrdinal("CreatedAt")) != DBNull.Value)
                {
                    epmNotification.CreatedAt =
                        GetRegionalDateTime(sqlDataReader.GetDateTime(sqlDataReader.GetOrdinal("CreatedAt")), spWeb);
                }

                if (sqlDataReader.GetValue(sqlDataReader.GetOrdinal("SiteCreationDate")) != DBNull.Value)
                {
                    epmNotification.SiteCreationDate =
                        GetRegionalDateTime(sqlDataReader.GetDateTime(sqlDataReader.GetOrdinal("SiteCreationDate")),
                                            spWeb);
                }

                SPRegionalSettings spRegionalSettings = spWeb.CurrentUser.RegionalSettings ?? spWeb.RegionalSettings;
                var cultureInfo = new CultureInfo((int)spRegionalSettings.LocaleId);

                string[] dateParts = epmNotification.CreatedAt.Split(' ')[0].Split('/');
                var      dateTime  = new DateTime(Convert.ToInt32(dateParts[2]), Convert.ToInt32(dateParts[0]), Convert.ToInt32(dateParts[1]));

                epmNotification.CreatedAtDateString = dateTime.ToString(cultureInfo.DateTimeFormat.ShortDatePattern);

                epmNotification.CreatorThumbnail = string.Format("{0}/_layouts/15/epmlive/images/default-avatar.png",
                                                                 spWeb.SafeServerRelativeUrl());

                epmNotification.CreatorName = "System";

                if (epmNotification.CreatedBy != 0)
                {
                    if (epmNotification.SiteId != Guid.Empty)
                    {
                        using (var site = new SPSite(epmNotification.SiteId))
                        {
                            using (SPWeb web = site.OpenWeb())
                            {
                                SPUser user = null;
                                try
                                {
                                    user = web.SiteUsers.GetByID(epmNotification.CreatedBy);
                                }
                                catch { }

                                if (user != null)
                                {
                                    epmNotification.CreatorName = Regex.Replace(user.Name ?? user.LoginName, @"\\",
                                                                                @"\\");

                                    SPList spList = spWeb.Site.RootWeb.SiteUserInfoList;

                                    SPListItem spListItem = spList.GetItemById(user.ID);

                                    var creatorThumbnail = spListItem["Picture"] as string;

                                    if (!string.IsNullOrEmpty(creatorThumbnail))
                                    {
                                        epmNotification.CreatorThumbnail = creatorThumbnail.IndexOf(',') >= 0 ? creatorThumbnail.Remove(creatorThumbnail.IndexOf(',')) : creatorThumbnail;
                                    }
                                }
                            }
                        }
                    }
                }

                epmNotifications.Add(epmNotification);
            }
        }
        /// <summary>
        /// Sets the notification flags.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        internal static string SetNotificationFlags(string data)
        {
            try
            {
                var result = new XDocument();
                result.Add(new XElement("Notifications"));

                XDocument xDocument = XDocument.Parse(data);

                ValidateSetNotificationFlagsInputData(xDocument);

                XAttribute markAllReadAttr = xDocument.Root.Attribute("MarkAllRead");
                if (markAllReadAttr != null && markAllReadAttr.Value.Equals("true"))
                {
                    var notifications = new List <EPMNotification>();

                    foreach (EPMNotification epmNotification in GetNotifications("NEW", 0, 0, 0))
                    {
                        EPMNotification notification = epmNotification;

                        notification.FlagToSet = 2;
                        notifications.Add(notification);
                    }

                    SetNotificationFlags(notifications);

                    return(result.ToString());
                }

                var epmNotifications = new List <EPMNotification>();

                foreach (XElement notificationElement in xDocument.Root.Elements("Notification"))
                {
                    var epmNotification = new EPMNotification
                    {
                        Id   = new Guid(notificationElement.Attribute("ID").Value),
                        Type = Convert.ToInt32(notificationElement.Attribute("Type").Value)
                    };

                    foreach (XElement flagElement in notificationElement.Elements("Flag"))
                    {
                        string value = flagElement.Attribute("Value").Value;

                        int flagToSet = 0;
                        switch (flagElement.Attribute("Type").Value)
                        {
                        case "EMAILED":
                            epmNotification.UserEmailed = Boolean.Parse(value);
                            flagToSet = 1;
                            break;

                        case "READ":
                            epmNotification.NotificationRead = Boolean.Parse(value);
                            flagToSet = 2;
                            break;
                        }


                        epmNotification.FlagToSet = flagToSet;
                    }

                    epmNotifications.Add(epmNotification);
                }

                SetNotificationFlags(epmNotifications);

                return(result.ToString());
            }
            catch (APIException)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new APIException(10500, e.Message);
            }
        }