Ejemplo n.º 1
0
        private void GetData(SEActivities activities, Guid threadId, string kind, DateTime offset)
        {
            SPWeb web    = SPContext.Current.Web;
            int   userId = web.CurrentUser.ID;

            _regionalSettings = SPContext.Current.RegionalSettings;

            using (var connectionManager = new DBConnectionManager(web))
            {
                DBConnectionManager manager = connectionManager;

                List <DataRow> threadRows = GetThreads(manager, userId, web, 0, 0, threadId).AsEnumerable().ToList();

                List <SEActivities.Thread> threads =
                    threadRows.Select(tr => BuildThread(tr, manager, userId, 0, 0, activities, offset, kind))
                    .ToList();

                foreach (SEActivities.Thread thread in threads)
                {
                    activities.threads.Add(thread);
                }
            }

            SortThreadActivities(activities);
        }
Ejemplo n.º 2
0
        private void GetData(int page, int limit, int activityLimit, int commentLimit, SEActivities activities)
        {
            SPWeb web    = SPContext.Current.Web;
            int   userId = web.CurrentUser.ID;

            _regionalSettings = SPContext.Current.RegionalSettings;

            using (var connectionManager = new DBConnectionManager(web))
            {
                DBConnectionManager manager = connectionManager;

                List <DataRow> threadRows = GetThreads(manager, userId, web, page, limit, null).AsEnumerable().ToList();

                List <SEActivities.Thread> threads =
                    threadRows.Select(
                        tr => BuildThread(tr, manager, userId, activityLimit, commentLimit, activities, null))
                    .ToList();

                foreach (SEActivities.Thread thread in threads)
                {
                    if (thread.activities.Count != 0 || thread.comments.Count != 0)
                    {
                        activities.threads.Add(thread);
                    }
                }
            }

            activities.threads = activities.threads.Distinct().ToList();
            activities.webs    = activities.webs.Distinct().ToList();
            activities.lists   = activities.lists.Distinct().ToList();
            activities.users   = activities.users.Distinct().ToList();

            SortThreadActivities(activities);
        }
Ejemplo n.º 3
0
        private void SetLocalDateTime(DataRow tr, string column, Dictionary <DateTime, DateTime> utcTimeDict,
                                      SPRegionalSettings regionalSettings)
        {
            try
            {
                var value = (DateTime)tr[column];

                if (utcTimeDict.ContainsKey(value))
                {
                    tr[column] = utcTimeDict[value];
                }
                else
                {
                    DateTime result = regionalSettings.TimeZone.UTCToLocalTime(value);
                    tr[column] = result;

                    lock (_locker)
                    {
                        try
                        {
                            utcTimeDict.Add(value, result);
                        }
                        catch { }
                    }
                }
            }
            catch { }
        }
Ejemplo n.º 4
0
        private void SetContextSettigns(SPCalendarBase view)
        {
            SPContext context = null;

            //try
            //{
            //    context = SPContext.GetContext(this.Context);
            //}
            //catch
            //{
            //}
            if ((context != null) || (this.m_spRegionalSettings != null))
            {
                if (this.m_spRegionalSettings == null)
                {
                    this.m_spRegionalSettings = context.RegionalSettings;
                }
                view.LocaleId          = (int)this.m_spRegionalSettings.LocaleId;
                view.Calendar          = (SPCalendarType)this.m_spRegionalSettings.CalendarType;
                view.AlternateCalendar = (SPCalendarType)this.m_spRegionalSettings.AlternateCalendarType;
                view.Time24            = this.m_spRegionalSettings.Time24;
                view.HijriAdjustment   = this.m_spRegionalSettings.AdjustHijriDays;
                view.FirstDayOfWeek    = (int)this.m_spRegionalSettings.FirstDayOfWeek;
                //view.WorkWeek = SPUtility.BitsToString(this.m_spRegionalSettings.WorkDays, 7);
                view.WorkDayStartHour = this.m_spRegionalSettings.WorkDayStartHour;
                view.WorkDayEndHour   = this.m_spRegionalSettings.WorkDayEndHour;
                view.TimeZoneSpan     = SPUtility.GetTimeSpanFromTimeZone(this.m_spRegionalSettings.TimeZone);
            }
        }
Ejemplo n.º 5
0
        private static string GetExampleDateFormat(SPWeb web, string yearLabel, string monthLabel, string dayLabel)
        {
            string format = string.Empty;

            SPContext context = SPContext.GetContext(web);

            SPRegionalSettings spRegionalSettings = context.Web.CurrentUser.RegionalSettings ?? context.RegionalSettings;

            string dateSeparator     = spRegionalSettings.DateSeparator;
            var    calendarOrderType = (SPCalendarOrderType)spRegionalSettings.DateFormat;

            switch (calendarOrderType)
            {
            case SPCalendarOrderType.MDY:
                format = monthLabel + dateSeparator + dayLabel + dateSeparator + yearLabel;
                break;

            case SPCalendarOrderType.DMY:
                format = dayLabel + dateSeparator + monthLabel + dateSeparator + yearLabel;
                break;

            case SPCalendarOrderType.YMD:
                format = yearLabel + dateSeparator + monthLabel + dateSeparator + dayLabel;
                break;
            }

            return(format);
        }
Ejemplo n.º 6
0
        private void ConfigureRegionalSettings()
        {
            SPRegionalSettings regionalSettings = SPContext.Current.RegionalSettings;

            DecimalSeparator = regionalSettings.DecimalSeparator;
            GroupSeparator   = regionalSettings.ThousandSeparator;
        }
Ejemplo n.º 7
0
        public static DateOptions GetDateOptions(this SPWeb web, DateTime selectedDate)
        {
            SPRegionalSettings regSet = web.RegionalSettings;

            return(new DateOptions(regSet.LocaleId.ToString(CultureInfo.InvariantCulture), (SPCalendarType)regSet.CalendarType,
                                   BitsToString(regSet.WorkDays, 7), regSet.FirstDayOfWeek.ToString(), regSet.AdjustHijriDays.ToString(),
                                   SPUtility.GetTimeSpanFromTimeZone(regSet.TimeZone).ToString(), selectedDate.ToString(CultureInfo.InvariantCulture.DateTimeFormat)));
        }
 public SPRegionalSettings EnglishCanadianSettings(SPWeb web, bool isUserSetting)
 {
     var settings = new SPRegionalSettings(web, isUserSetting);
     settings.LocaleId = (uint)new CultureInfo("en-CA").LCID;
     settings.TimeZone.ID = DefaultTimeZoneID;
     settings.Time24 = false;
     return settings;
 }
 public SPRegionalSettings FrenchCanadianSettings(SPWeb web, bool isUserSetting)
 {
     var settings = new SPRegionalSettings(web, isUserSetting);
     settings.LocaleId = (uint)new CultureInfo("fr-CA").LCID;
     settings.TimeZone.ID = DefaultTimeZoneID; // UTC-5 (Eastern Time)
     settings.Time24 = true;
     return settings;
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Gets the date pattern.
        /// </summary>
        /// <returns></returns>
        private string GetDatePattern()
        {
            SPWeb spWeb = SPContext.Current.Web;

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

            return(cultureInfo.DateTimeFormat.ShortDatePattern.Replace('-', '/').Replace('.', '/'));
        }
Ejemplo n.º 11
0
        public ChatMessageListResult ChatMessages(int SenderID)
        {
            WebOperationContext.Current.OutgoingResponse.Headers.Add("Cache-Control", "no-cache");
            ChatMessageListResult result = null;

            try
            {
                if (SPUtility.ValidateFormDigest())
                {
                    IChatMessageRepository repo = new ChatMessageRepository();
                    // get the users timezone
                    SPTimeZone zone = SPContext.Current.Web.RegionalSettings.TimeZone;
                    if (SPContext.Current.Web.CurrentUser.RegionalSettings != null)
                    {
                        SPRegionalSettings rs = SPContext.Current.Web.CurrentUser.RegionalSettings;
                        zone = rs.TimeZone;
                    }
                    result = new ChatMessageListResult()
                    {
                        LastRequested = DateTime.Now.ToString(),
                        ChatMessages  = repo.GetUnReadByUserIDAndSenderID(SPContext.Current.Web.CurrentUser.ID, SenderID)
                                        .Select(m => new ChatMessageServiceView()
                        {
                            ID              = m.ID,
                            Created         = (zone.UTCToLocalTime(m.Created)).ToString(),
                            CreatedDateOnly = (zone.UTCToLocalTime(m.Created).Date).ToShortDateString(),
                            CreatedTimeOnly = (zone.UTCToLocalTime(m.Created)).ToString("HH:mm"),
                            CreatedBy       = m.CreatedBy.Name,
                            Message         = m.Message,
                            Receivers       = m.Receivers.Select(r => new ChatContactServiceView()
                            {
                                ID       = r.ID,
                                Name     = r.Name,
                                Username = r.Username.Split('\\').Last()
                            }).ToArray()
                        }).ToArray()
                    };
                    if (result.ChatMessages.Length > 0)
                    {
                        repo.SetChatMessagesRead(result.ChatMessages.Select(i => i.ID).ToArray());
                    }
                }
                else
                {
                    WebOperationContext.Current.OutgoingResponse.StatusCode        = System.Net.HttpStatusCode.Unauthorized;
                    WebOperationContext.Current.OutgoingResponse.StatusDescription = Language.UserNotValidated;
                }
            }
            catch (Exception ex)
            {
                Config.WriteException(ex);
                WebOperationContext.Current.OutgoingResponse.StatusCode        = System.Net.HttpStatusCode.InternalServerError;
                WebOperationContext.Current.OutgoingResponse.StatusDescription = Language.GetMessagesError;
            }
            return(result);
        }
Ejemplo n.º 12
0
        private void ParseMetaData(out int page, out int limit, out int activityLimit, out int commentLimit,
                                   out DateTime offset)
        {
            page          = 1;
            limit         = 10;
            activityLimit = 1;
            commentLimit  = 2;
            offset        = DateTime.UtcNow;

            OperationContext  context    = OperationContext.Current;
            MessageProperties properties = context.IncomingMessageProperties;
            var request = properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;

            if (request == null)
            {
                return;
            }

            string queryString = request.QueryString;

            if (string.IsNullOrEmpty(queryString))
            {
                return;
            }

            NameValueCollection parameters = HttpUtility.ParseQueryString(queryString);

            if (parameters.AllKeys.Contains("page"))
            {
                int.TryParse(parameters["page"], out page);
            }

            if (parameters.AllKeys.Contains("limit"))
            {
                int.TryParse(parameters["limit"], out limit);
            }

            if (parameters.AllKeys.Contains("activityLimit"))
            {
                int.TryParse(parameters["activityLimit"], out activityLimit);
            }

            if (parameters.AllKeys.Contains("commentLimit"))
            {
                int.TryParse(parameters["commentLimit"], out commentLimit);
            }

            if (parameters.AllKeys.Contains("offset"))
            {
                SPRegionalSettings regionalSettings = SPContext.Current.RegionalSettings;
                offset = regionalSettings.TimeZone.LocalTimeToUTC(DateTime.Parse(parameters["offset"]));
            }
        }
        public void OnPreProcessRequest(object sender, EventArgs eventArgs)
        {
            // CalendarService.ashx
            if (HttpContext.Current.Request.Path.Contains("CalendarService.ashx"))
            {
                HttpContext        context          = ((HttpApplication)sender).Context;
                string             languageCode     = Utilities.GetLanguageCode(context);
                SPRegionalSettings regionalSettings = SPContext.Current.RegionalSettings;

                int lcid = Languages.Instance.GetLcid(languageCode);

                regionalSettings.LocaleId = (uint)lcid;
            }
        }
Ejemplo n.º 14
0
 private void MapRegionalSettings(SPRegionalSettings settings, RegionalSettingsDefinition definition)
 {
     settings.AdjustHijriDays = definition.AdjustHijriDays;
     settings.AlternateCalendarType = definition.AlternateCalendarType;
     settings.CalendarType = definition.CalendarType;
     settings.Collation = definition.Collation;
     settings.FirstDayOfWeek = definition.FirstDayOfWeek;
     settings.FirstWeekOfYear = definition.FirstWeekOfYear;
     settings.LocaleId = definition.LocaleId;
     settings.WorkDayStartHour = definition.WorkDayStartHour;
     settings.WorkDayEndHour = definition.WorkDayEndHour;
     settings.WorkDays = definition.WorkDays;
     settings.ShowWeeks = definition.ShowWeeks;
     settings.Time24 = definition.Time24;
     settings.LocaleId = definition.LocaleId;
 }
Ejemplo n.º 15
0
 private void MapRegionalSettings(SPRegionalSettings settings, RegionalSettingsDefinition definition)
 {
     settings.AdjustHijriDays       = definition.AdjustHijriDays;
     settings.AlternateCalendarType = definition.AlternateCalendarType;
     settings.CalendarType          = definition.CalendarType;
     settings.Collation             = definition.Collation;
     settings.FirstDayOfWeek        = definition.FirstDayOfWeek;
     settings.FirstWeekOfYear       = definition.FirstWeekOfYear;
     settings.LocaleId         = definition.LocaleId;
     settings.WorkDayStartHour = definition.WorkDayStartHour;
     settings.WorkDayEndHour   = definition.WorkDayEndHour;
     settings.WorkDays         = definition.WorkDays;
     settings.ShowWeeks        = definition.ShowWeeks;
     settings.Time24           = definition.Time24;
     settings.LocaleId         = definition.LocaleId;
 }
Ejemplo n.º 16
0
        internal static void InitializeDatePicker(DateTimeControl datePicker)
        {
            SPWeb web = SPContext.Current.Web;
            SPRegionalSettings regionalSettings = web.CurrentUser.RegionalSettings;

            if (regionalSettings == null)
            {
                regionalSettings = web.RegionalSettings;
            }
            datePicker.LocaleId              = (int)regionalSettings.LocaleId;
            datePicker.TimeZoneID            = regionalSettings.TimeZone.ID;
            datePicker.UseTimeZoneAdjustment = false;
            datePicker.HijriAdjustment       = regionalSettings.AdjustHijriDays;
            datePicker.HoursMode24           = true; //regionalSettings.Time24;
            datePicker.Calendar              = (SPCalendarType)regionalSettings.CalendarType;
            datePicker.DatePickerFrameUrl    = SPContext.Current.Web.ServerRelativeUrl + "/_layouts/iframe.aspx";
        }
        private void MapRegionalSettings(SPRegionalSettings settings, RegionalSettingsDefinition definition)
        {
            if (definition.AdjustHijriDays.HasValue)
                settings.AdjustHijriDays = definition.AdjustHijriDays.Value;

            if (definition.AlternateCalendarType.HasValue)
                settings.AlternateCalendarType = definition.AlternateCalendarType.Value;

            if (definition.CalendarType.HasValue)
                settings.CalendarType = definition.CalendarType.Value;

            if (definition.Collation.HasValue)
                settings.Collation = definition.Collation.Value;

            if (definition.FirstDayOfWeek.HasValue)
                settings.FirstDayOfWeek = definition.FirstDayOfWeek.Value;

            if (definition.FirstWeekOfYear.HasValue)
                settings.FirstWeekOfYear = definition.FirstWeekOfYear.Value;

            if (definition.LocaleId.HasValue)
                settings.LocaleId = definition.LocaleId.Value;

            if (definition.WorkDayStartHour.HasValue)
                settings.WorkDayStartHour = definition.WorkDayStartHour.Value;

            if (definition.WorkDayEndHour.HasValue)
                settings.WorkDayEndHour = definition.WorkDayEndHour.Value;

            if (definition.WorkDays.HasValue)
                settings.WorkDays = definition.WorkDays.Value;

            if (definition.ShowWeeks.HasValue)
                settings.ShowWeeks = definition.ShowWeeks.Value;

            if (definition.Time24.HasValue)
                settings.Time24 = definition.Time24.Value;

            if (definition.LocaleId.HasValue)
                settings.LocaleId = definition.LocaleId.Value;
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Gets the regional date time.
        /// </summary>
        /// <param name="dateTime">The date time.</param>
        /// <param name="spWeb">The sp web.</param>
        /// <returns></returns>
        private static string GetRegionalDateTime(DateTime dateTime, SPWeb spWeb)
        {
            string result = string.Empty;

            using (var spSite = new SPSite(spWeb.Site.ID))
            {
                using (SPWeb web = spSite.OpenWeb(spWeb.ID))
                {
                    SPUser user = web.CurrentUser;

                    SPRegionalSettings spRegionalSettings = user.RegionalSettings ?? web.RegionalSettings;

                    if (dateTime != DateTime.MinValue)
                    {
                        DateTime utcToLocalTime = spRegionalSettings.TimeZone.UTCToLocalTime(dateTime.ToUniversalTime());
                        result = utcToLocalTime.ToString("M/d/yyyy HH:mm:ss").Replace('-', '/').Replace('.', '/');
                    }
                }
            }

            return(result);
        }
Ejemplo n.º 19
0
        // Private Methods (1) 

        private void OnActivityRegistrationRequest(ProcessActivityEventArgs args)
        {
            SPRegionalSettings regionalSettings = args.ContextWeb.CurrentUser.RegionalSettings ??
                                                  args.ContextWeb.RegionalSettings;

            string[] keys = args.Data.Keys.ToArray();

            foreach (string key in keys)
            {
                object data = args.Data[key];

                if (data == null)
                {
                    return;
                }

                if (data is DateTime)
                {
                    args.Data[key] = regionalSettings.TimeZone.LocalTimeToUTC((DateTime)data);
                }
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Gets the data.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        public string GetData(string data)
        {
            try
            {
                string           response;
                NumberFormatInfo providerEn = new System.Globalization.NumberFormatInfo();
                providerEn.NumberDecimalSeparator = ".";
                providerEn.NumberGroupSeparator   = ",";
                providerEn.NumberGroupSizes       = new int[] { 3 };

                XElement dataRootElement = XDocument.Parse(data).Root;

                if (dataRootElement == null)
                {
                    throw new APIException((int)Errors.GetDataRootElementNotFound,
                                           "Cannot find the Root AssignmentPlanner element.");
                }

                using (var workEngineAPI = new WorkEngineAPI())
                {
                    response = workEngineAPI.Execute("Reporting_GetMyWorkData",
                                                     new XElement("GetMyWorkReportingData",
                                                                  dataRootElement.Element("Params")).ToString());
                }

                XDocument myWorkDataXml = XDocument.Parse(response);

                ValidateMyWorkDataResponse(myWorkDataXml);

                var gridSafeFields = new Dictionary <string, string>();

                var bElement         = new XElement("B");
                var resourcesElement = new XElement("Resources");
                var footElement      = new XElement("Foot");

                var resources = new Dictionary <int, string>();

                SPRegionalSettings spRegionalSettings = _spWeb.CurrentUser.RegionalSettings ??
                                                        _spWeb.Site.RootWeb.RegionalSettings;

                var workDayStartHour = (short)(spRegionalSettings.WorkDayStartHour / 60);
                var workDayEndHour   = (short)(spRegionalSettings.WorkDayEndHour / 60);

                string siteUrl = _spWeb.Site.Url;
                string safeServerRelativeUrl = _spWeb.SafeServerRelativeUrl();

                foreach (
                    XElement resourceElement in
                    myWorkDataXml.Element("Result").Element("GetMyWorkData").Element("Data").Elements("Resource"))
                {
                    XElement resultElement = resourceElement.Element("Result");

                    if (!resultElement.Attribute("Status").Value.Equals("0"))
                    {
                        continue;
                    }

                    int    resourceId   = 0;
                    string resourceName = string.Empty;

                    foreach (XElement itemElement in resourceElement.Element("Data").Elements("Item"))
                    {
                        var iElement = new XElement("I");

                        int    itemId = 0;
                        Guid   listId = Guid.Empty;
                        Guid   webId  = Guid.Empty;
                        Guid   siteId = Guid.Empty;
                        string value  = string.Empty;
                        float  floatFieldValue;

                        foreach (XElement fieldElement in itemElement.Elements("Field"))
                        {
                            string field = fieldElement.Attribute("Name").Value;

                            if (!gridSafeFields.ContainsKey(field))
                            {
                                gridSafeFields.Add(field, Utils.ToGridSafeFieldName(field));
                            }

                            if (float.TryParse(fieldElement.Value.ToString(), out floatFieldValue))
                            {
                                value = floatFieldValue.ToString(providerEn);
                            }
                            else
                            {
                                value = fieldElement.Value;
                            }

                            string fieldName = field.ToLower();

                            if (fieldName.Equals("id"))
                            {
                                itemId = Convert.ToInt32(value);
                            }
                            else if (fieldName.Equals("listid"))
                            {
                                listId = new Guid(value);
                            }
                            else if (fieldName.Equals("webid"))
                            {
                                webId = new Guid(value);
                            }
                            else if (fieldName.Equals("siteid"))
                            {
                                siteId = new Guid(value);
                            }
                            else if (fieldName.Equals("assignedtoid"))
                            {
                                resourceId = Convert.ToInt32(value);
                            }
                            else if (fieldName.Equals("assignedtotext"))
                            {
                                resourceName = value;
                            }
                            else if (fieldElement.Attribute("Type").Value.Equals("System.DateTime") &&
                                     !string.IsNullOrEmpty(value))
                            {
                                DateTime localTime = SPUtility.CreateDateTimeFromISO8601DateTimeString(value);

                                if (fieldName.Equals("startdate") &&
                                    (localTime.Hour < workDayStartHour || localTime.Hour > workDayEndHour))
                                {
                                    localTime = new DateTime(localTime.Year, localTime.Month, localTime.Day,
                                                             workDayStartHour, 0, 0);
                                }
                                else if (fieldName.Equals("duedate") &&
                                         (localTime.Hour < workDayStartHour || localTime.Hour > workDayEndHour))
                                {
                                    localTime = new DateTime(localTime.Year, localTime.Month, localTime.Day,
                                                             workDayEndHour, 0, 0);
                                }

                                value = SPUtility.CreateISO8601DateTimeFromSystemDateTime(localTime);
                            }

                            iElement.Add(new XAttribute(gridSafeFields[field], value));
                        }

                        string flagQuery =
                            string.Format(
                                @"<MyPersonalization>
                                        <Keys>AssignmentPlannerFlag</Keys>
                                        <Item ID=""{0}""/>
                                        <List ID=""{1}""/>
                                        <Web ID=""{2}""/>
                                        <Site ID=""{3}"" URL=""{4}""/>
                                </MyPersonalization>",
                                itemId, listId, webId, siteId, siteUrl);

                        XDocument flagResponse = XDocument.Parse(MyPersonalization.GetMyPersonalization(flagQuery));

                        string flag = null;

                        XElement personalizationRootElement = flagResponse.Element("MyPersonalization");

                        if (personalizationRootElement != null)
                        {
                            flag = (from e in personalizationRootElement.Descendants("Personalization")
                                    let keyAttribute = e.Attribute("Key")
                                                       where keyAttribute != null && keyAttribute.Value.Equals("AssignmentPlannerFlag")
                                                       let valueAttribute = e.Attribute("Value")
                                                                            where valueAttribute != null
                                                                            select valueAttribute.Value).FirstOrDefault();
                        }

                        var flagValue = flag ?? "0";
                        var flagUrl   = safeServerRelativeUrl + "/_layouts/epmlive/images/mywork/flagged.png";
                        if (flagValue.Equals("0"))
                        {
                            flagUrl = safeServerRelativeUrl + "/_layouts/epmlive/images/mywork/unflagged.png";
                        }

                        iElement.Add(new XAttribute("Duration", string.Empty),
                                     new XAttribute("Flag", string.Format(@"<img src=""{0}"" class=""AP_Flag""/>", flagUrl)),
                                     new XAttribute("FlagValue", flagValue), new XAttribute("Height", 23));

                        if (resourceId == 0 || string.IsNullOrEmpty(resourceName))
                        {
                            continue;
                        }

                        bElement.Add(iElement);
                        if (!resources.ContainsKey(resourceId))
                        {
                            resources.Add(resourceId, resourceName);
                        }
                    }
                }

                foreach (var keyValuePair in resources)
                {
                    resourcesElement.Add(new XElement("R", new XAttribute("Name", keyValuePair.Value),
                                                      new XAttribute("Availability", 8), new XAttribute("Type", 1)));

                    footElement.Add(new XElement("I", new XAttribute("id", string.Format("-{0}", keyValuePair.Key)),
                                                 new XAttribute("Def", "Resource"),
                                                 new XAttribute("Title", keyValuePair.Value)));
                }

                return(new XElement("Grid", new XElement("Body", bElement), resourcesElement, footElement).ToString());
            }
            catch (APIException)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new APIException((int)Errors.GetData, e.Message);
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        ///     Updates the list item.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        internal static string UpdateListItem(string data)
        {
            try
            {
                var result = new XDocument();
                result.Add(new XElement("ListItems"));

                foreach (XElement xElement in GetListItemElements(data))
                {
                    var listItemElement = new XElement("ListItem");

                    int    itemId;
                    Guid   listId;
                    Guid   webId;
                    Guid   siteId;
                    string siteUrl;

                    Utils.GetItemListWebSite(data, xElement, out itemId, out listId, out webId, out siteId, out siteUrl);

                    Utils.AddItemListWebSiteToXElement(itemId, listId, webId, siteId, siteUrl, ref listItemElement);

                    listItemElement.Add(new XElement("Messages"));
                    XElement messagesElement = listItemElement.Element("Messages");

                    try
                    {
                        SPWeb              web         = SPContext.Current.Web;
                        SPUser             currentUser = web.CurrentUser;
                        SPRegionalSettings currentContextRegionalSettings = currentUser.RegionalSettings ??
                                                                            web.RegionalSettings;

                        Dictionary <string, string> fieldValues = Utils.GetFieldValues(xElement);

                        using (
                            var spSite = new SPSite(siteUrl, web.Site.RootWeb.AllUsers[currentUser.LoginName].UserToken)
                            )
                        {
                            using (SPWeb spWeb = spSite.OpenWeb(webId))
                            {
                                SPRegionalSettings spRegionalSettings = spWeb.CurrentUser.RegionalSettings ??
                                                                        spWeb.RegionalSettings;

                                spWeb.AllowUnsafeUpdates = true;

                                SPList spList = spWeb.Lists[listId];

                                SPListItem spListItem = spList.GetItemById(itemId);

                                Dictionary <string, Dictionary <string, string> > fieldProperties =
                                    Utils.GetFieldProperties(spList);

                                #region Update List Item

                                foreach (var fieldValue in fieldValues)
                                {
                                    string theField = fieldValue.Key;
                                    string theValue = fieldValue.Value;

                                    if (!spList.Fields.ContainsFieldWithInternalName(theField))
                                    {
                                        messagesElement.Add(new XElement("Message",
                                                                         new XCData(
                                                                             string.Format(
                                                                                 "Cannot find a field with internal name: {0} in the list.",
                                                                                 theField))));
                                        continue;
                                    }

                                    if (spList.Fields.GetFieldByInternalName(theField).ReadOnlyField)
                                    {
                                        messagesElement.Add(new XElement("Message",
                                                                         new XCData(
                                                                             string.Format(
                                                                                 "{0} is a read-only field. Value will not be updated.",
                                                                                 theField))));
                                        continue;
                                    }

                                    if (!theField.Equals("Complete") && !theField.Equals("CommentCount") &&
                                        !theField.Equals("Commenters") && !theField.Equals("CommentersRead"))
                                    {
                                        if (
                                            !EditableFieldDisplay.isEditable(spListItem,
                                                                             spListItem.Fields.GetFieldByInternalName(
                                                                                 theField), fieldProperties))
                                        {
                                            messagesElement.Add(new XElement("Message",
                                                                             new XCData(
                                                                                 string.Format(
                                                                                     "{0} is not an editable field. The value for {0} will not be updated.",
                                                                                     theField))));
                                            continue;
                                        }
                                    }

                                    SPField spField = spListItem.Fields.GetFieldByInternalName(theField);
                                    if (spField.Type == SPFieldType.DateTime)
                                    {
                                        try
                                        {
                                            var dateTime =
                                                new DateTime((Convert.ToInt64(theValue) * 10000) + 621355968000000000);
                                            DateTime localTimeToUtc =
                                                currentContextRegionalSettings.TimeZone.LocalTimeToUTC(dateTime);
                                            DateTime utcToLocalTime =
                                                spRegionalSettings.TimeZone.UTCToLocalTime(localTimeToUtc);

                                            theValue = utcToLocalTime.ToString(CultureInfo.InvariantCulture);
                                        }
                                        catch
                                        {
                                        }
                                    }

                                    spListItem[theField] = theValue;
                                }

                                #endregion

                                spListItem.Update();
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        messagesElement.Add(new XElement("Message", new XCData(exception.Message)));
                    }

                    result.Element("ListItems").Add(listItemElement);
                }

                return(result.ToString());
            }
            catch (APIException)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new APIException(6050, e.Message);
            }
        }
Ejemplo n.º 22
0
        // Internal Methods (3) 

        /// <summary>
        ///     Gets the list item.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        internal static string GetListItem(string data)
        {
            try
            {
                var result = new XDocument();
                result.Add(new XElement("ListItem"));

                int    itemId;
                Guid   listId;
                Guid   webId;
                Guid   siteId;
                string siteUrl;

                Utils.GetItemListWebSite(data, GetListItemElement(data), out itemId, out listId, out webId, out siteId,
                                         out siteUrl);

                XElement listItemElement = result.Element("ListItem");
                Utils.AddItemListWebSiteToXElement(itemId, listId, webId, siteId, siteUrl, ref listItemElement);

                SPWeb              web         = SPContext.Current.Web;
                SPUser             currentUser = web.CurrentUser;
                SPRegionalSettings currentContextRegionalSettings = currentUser.RegionalSettings ?? web.RegionalSettings;

                using (var spSite = new SPSite(siteUrl))
                {
                    using (SPWeb spWeb = spSite.OpenWeb(webId))
                    {
                        SPRegionalSettings spRegionalSettings = spWeb.CurrentUser.RegionalSettings ??
                                                                spWeb.RegionalSettings;

                        listItemElement.Add(new XElement("Fields"));
                        XElement fieldsElement = listItemElement.Element("Fields");

                        SPList spList = spWeb.Lists[listId];

                        SPListItem spListItem = spList.GetItemById(itemId);

                        foreach (
                            SPField field in
                            spListItem.Fields.Cast <SPField>().Where(
                                field =>
                                !field.Hidden || field.InternalName.Equals("CommentCount") ||
                                field.InternalName.Equals("Commenters") ||
                                field.InternalName.Equals("CommentersRead")))
                        {
                            try
                            {
                                string value = spListItem[field.Id].ToString();

                                if (field.Type == SPFieldType.Number || field.Type == SPFieldType.Currency)
                                {
                                    if (!string.IsNullOrEmpty(value))
                                    {
                                        try
                                        {
                                            value = Decimal.Parse(value,
                                                                  new CultureInfo(
                                                                      (int)currentContextRegionalSettings.LocaleId))
                                                    .ToString(CultureInfo.InvariantCulture);
                                        }
                                        catch
                                        {
                                        }
                                    }
                                }
                                else if (field.Type == SPFieldType.DateTime)
                                {
                                    if (!string.IsNullOrEmpty(value))
                                    {
                                        DateTime dateTime = currentContextRegionalSettings
                                                            .TimeZone.UTCToLocalTime(spRegionalSettings.TimeZone
                                                                                     .LocalTimeToUTC(
                                                                                         DateTime.Parse(value)));

                                        value = dateTime.ToString("MMM dd, yyyy HH:mm:ss", CultureInfo.InvariantCulture);
                                    }
                                }

                                var fieldElement = new XElement("Field", new XCData(value));
                                fieldElement.Add(new XAttribute("Name", field.InternalName));
                                fieldElement.Add(new XAttribute("Type", field.Type));
                                fieldElement.Add(new XAttribute("Format", Utils.GetFormat(field)));

                                fieldsElement.Add(fieldElement);
                            }
                            catch
                            {
                            }
                        }
                    }
                }

                return(result.ToString());
            }
            catch (APIException)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new APIException(6060, e.Message);
            }
        }
Ejemplo n.º 23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RegionalSettings"/> class.
 /// </summary>
 /// <param name="regionalSettings">The regional settings.</param>
 public RegionalSettings(SPRegionalSettings regionalSettings)
 {
     this.LocaleId = (int)regionalSettings.LocaleId;
     this.TimeZoneId = regionalSettings.TimeZone.ID;
 }
Ejemplo n.º 24
0
        /// <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);
            }
        }
Ejemplo n.º 25
0
        public Logs GetLogs()
        {
            var logs = new Logs();

            try
            {
                SPWeb contextWeb = SPContext.Current.Web;

                if (!contextWeb.CurrentUser.IsSiteAdmin &&
                    !contextWeb.DoesUserHavePermissions(SPBasePermissions.FullMask))
                {
                    throw new UnauthorizedAccessException("You need to be either Web or Site Collection Administrator.");
                }

                const string SQL = @"
                    SELECT  dbo.SS_Logs.Id, dbo.SS_Logs.Message, dbo.SS_Logs.StackTrace, dbo.SS_Logs.Details, dbo.SS_Logs.Kind, dbo.SS_Logs.DateTime, 
                            dbo.SS_Logs.UserId, dbo.LSTUserInformationList.Title AS UserName, dbo.LSTUserInformationList.Name AS UserAccount, dbo.SS_Logs.WebId, 
                            dbo.RPTWeb.WebTitle, dbo.RPTWeb.WebUrl
                    FROM    dbo.SS_Logs LEFT OUTER JOIN dbo.RPTWeb ON dbo.SS_Logs.WebId = dbo.RPTWeb.WebId LEFT OUTER JOIN
                            dbo.LSTUserInformationList ON dbo.SS_Logs.UserId = dbo.LSTUserInformationList.ID 
                    WHERE   (dbo.RPTWeb.WebUrl = @WebUrl) OR (dbo.RPTWeb.WebUrl LIKE @WebUrl + '/')
                    ORDER BY dbo.SS_Logs.DateTime DESC";

                var ssLogs = new DataTable();

                using (var manager = new DBConnectionManager(contextWeb))
                {
                    var sqlCommand = new SqlCommand(SQL, manager.SqlConnection);
                    sqlCommand.Parameters.AddWithValue("@WebUrl", contextWeb.SafeServerRelativeUrl());

                    SqlDataReader reader = sqlCommand.ExecuteReader();
                    ssLogs.Load(reader);
                }

                SPRegionalSettings regionalSettings = SPContext.Current.RegionalSettings;

                foreach (DataRow row in ssLogs.Rows)
                {
                    var log = new Logs.Log
                    {
                        id         = (Guid)row["Id"],
                        message    = row["Message"] as string,
                        stackTrace = row["StackTrace"] as string,
                        details    = row["Details"] as string,
                        kind       = ((LogKind)row["Kind"]).ToString(),
                        time       = regionalSettings.TimeZone.UTCToLocalTime((DateTime)row["DateTime"])
                    };

                    object userId = row["UserId"];
                    if (userId != null && userId != DBNull.Value)
                    {
                        log.user = (int)userId;

                        if (logs.users.All(u => u.id != log.user))
                        {
                            logs.users.Add(new SEActivities.User
                            {
                                id          = (int)userId,
                                displayName = row["UserName"] as string,
                                name        = row["UserAccount"] as string
                            });
                        }
                    }

                    object webId = row["WebId"];
                    if (webId != null && webId != DBNull.Value)
                    {
                        log.web = (Guid)webId;

                        if (logs.webs.All(w => w.id != log.web))
                        {
                            logs.webs.Add(new SEActivities.Web
                            {
                                id    = (Guid)webId,
                                title = row["WebTitle"] as string,
                                url   = row["WebUrl"] as string
                            });
                        }
                    }

                    logs.collection.Add(log);
                }
            }
            catch (Exception exception)
            {
                if (exception is AggregateException)
                {
                    exception = ((AggregateException)exception).Flatten();
                }

                logs.error = new Error
                {
                    message    = exception.Message,
                    stackTrace = exception.StackTrace,
                    kind       = typeof(Exception).ToString()
                };
            }

            return(logs);
        }
Ejemplo n.º 26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RegionalSettings"/> class.
 /// </summary>
 /// <param name="regionalSettings">The regional settings.</param>
 public RegionalSettings(SPRegionalSettings regionalSettings)
 {
     this.LocaleId   = (int)regionalSettings.LocaleId;
     this.TimeZoneId = regionalSettings.TimeZone.ID;
 }
Ejemplo n.º 27
0
        /// <summary>
        /// Gets the layout.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        public string GetLayout(string data)
        {
            try
            {
                XDocument layoutXml = XDocument.Parse(Resources.AssignmentPlannerGridLayout);

                if (layoutXml.Root == null)
                {
                    throw new APIException((int)Errors.NoGridElementFound, "Cannot find the Grid element.");
                }

                XElement headerElement = layoutXml.Root.Element("Header");

                if (headerElement == null)
                {
                    throw new APIException((int)Errors.NoHeaderElementFound, "Cannot find the Header element.");
                }

                XElement colsElement = layoutXml.Root.Element("Cols");

                if (colsElement == null)
                {
                    throw new APIException((int)Errors.NoColsElementFound, "Cannot find the Cols element.");
                }

                string fieldsResponse;

                using (var workEngineAPI = new WorkEngineAPI())
                {
                    fieldsResponse = workEngineAPI.Execute("Reporting_GetMyWorkFields", string.Empty);
                }

                XElement errorElement = XDocument.Parse(fieldsResponse).Root.Descendants("Error").FirstOrDefault();

                if (errorElement != null)
                {
                    if (errorElement.Value.Contains("ExecuteReader requires an open and available Connection."))
                    {
                        throw new APIException((int)Errors.ReportingConnection, ReportingConnectionError);
                    }
                }

                XDocument dataXml = XDocument.Parse(Utilities.DecodeGridData(data));
                RegisterGridIdAndCss(layoutXml.Root, dataXml);

                XDocument fieldsXml = XDocument.Parse(fieldsResponse);

                List <string> fields =
                    fieldsXml.Root.Element("GetMyWorkFields").Element("Data").Elements("Field").Select(
                        e => e.Attribute("Name").Value).ToList();

                using (var spSite = new SPSite(_spWeb.Site.ID))
                {
                    using (SPWeb spWeb = spSite.OpenWeb())
                    {
                        SPList spList = spWeb.Lists["My Work"];

                        SPRegionalSettings regionalSettings = spWeb.RegionalSettings;

                        SPRegionalSettings spRegionalSettings = _spWeb.CurrentUser.RegionalSettings ?? regionalSettings;

                        var cultureInfo = new CultureInfo((int)spRegionalSettings.LocaleId);

                        string currencyFormat = string.Format("{0}#.00", cultureInfo.NumberFormat.CurrencySymbol);
                        string datePattern    = cultureInfo.DateTimeFormat.ShortDatePattern;

                        var defaultColumns = new List <string>();

                        var workDayStartHour = (short)(regionalSettings.WorkDayStartHour / 60);
                        var workDayEndHour   = (short)(regionalSettings.WorkDayEndHour / 60);

                        ConfigureDefaultColumns(spList, datePattern, currencyFormat, spWeb, workDayStartHour,
                                                workDayEndHour,
                                                GetGanttExclude(regionalSettings, spWeb, workDayStartHour,
                                                                workDayEndHour), ref layoutXml,
                                                ref defaultColumns);

                        ConfigureColumns(spWeb, currencyFormat, ref headerElement, ref colsElement, datePattern,
                                         defaultColumns, fields, spList);
                    }
                }

                return(layoutXml.ToString());
            }
            catch (APIException)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new APIException((int)Errors.GetLayout, e.Message);
            }
        }
Ejemplo n.º 28
0
        private void MapRegionalSettings(SPRegionalSettings settings, RegionalSettingsDefinition definition)
        {
            if (definition.AdjustHijriDays.HasValue)
            {
                settings.AdjustHijriDays = definition.AdjustHijriDays.Value;
            }

            if (definition.AlternateCalendarType.HasValue)
            {
                settings.AlternateCalendarType = definition.AlternateCalendarType.Value;
            }

            if (definition.CalendarType.HasValue)
            {
                settings.CalendarType = definition.CalendarType.Value;
            }

            if (definition.Collation.HasValue)
            {
                settings.Collation = definition.Collation.Value;
            }

            if (definition.FirstDayOfWeek.HasValue)
            {
                settings.FirstDayOfWeek = definition.FirstDayOfWeek.Value;
            }

            if (definition.FirstWeekOfYear.HasValue)
            {
                settings.FirstWeekOfYear = definition.FirstWeekOfYear.Value;
            }

            if (definition.LocaleId.HasValue)
            {
                settings.LocaleId = definition.LocaleId.Value;
            }

            if (definition.WorkDayStartHour.HasValue)
            {
                settings.WorkDayStartHour = definition.WorkDayStartHour.Value;
            }

            if (definition.WorkDayEndHour.HasValue)
            {
                settings.WorkDayEndHour = definition.WorkDayEndHour.Value;
            }

            if (definition.WorkDays.HasValue)
            {
                settings.WorkDays = definition.WorkDays.Value;
            }

            if (definition.ShowWeeks.HasValue)
            {
                settings.ShowWeeks = definition.ShowWeeks.Value;
            }

            if (definition.Time24.HasValue)
            {
                settings.Time24 = definition.Time24.Value;
            }

            if (definition.LocaleId.HasValue)
            {
                settings.LocaleId = definition.LocaleId.Value;
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Gets the gantt exclude.
        /// </summary>
        /// <param name="regionalSettings">The regional settings.</param>
        /// <param name="spWeb">The sp web.</param>
        /// <param name="workDayStartHour">The work day start hour.</param>
        /// <param name="workDayEndHour">The work day end hour.</param>
        /// <returns></returns>
        private string GetGanttExclude(SPRegionalSettings regionalSettings, SPWeb spWeb, short workDayStartHour,
                                       short workDayEndHour)
        {
            try
            {
                short lunchStartHour = 12;
                short lunchEndHour   = 13;

                Guid lockedWeb = CoreFunctions.getLockedWeb(_spWeb);
                using (SPWeb configWeb = Utils.GetConfigWeb(_spWeb, lockedWeb))
                {
                    string startHour = CoreFunctions.getConfigSetting(configWeb,
                                                                      "EPMLive_MyWork_GeneralSettings_LunchStartHour");
                    if (!string.IsNullOrEmpty(startHour))
                    {
                        lunchStartHour = Convert.ToInt16(startHour);
                    }

                    string endHour = CoreFunctions.getConfigSetting(configWeb,
                                                                    "EPMLive_MyWork_GeneralSettings_LunchEndHour");
                    if (!string.IsNullOrEmpty(endHour))
                    {
                        lunchEndHour = Convert.ToInt16(endHour);
                    }
                }

                var stringBuilder = new StringBuilder();

                stringBuilder.Append("d#0:00~");
                stringBuilder.Append(workDayStartHour);
                stringBuilder.Append(":00#4;");

                stringBuilder.Append("d#");
                stringBuilder.Append(lunchStartHour);
                stringBuilder.Append(":00~");
                stringBuilder.Append(lunchEndHour);
                stringBuilder.Append(":00#4;");

                stringBuilder.Append("d#");
                stringBuilder.Append(workDayEndHour);
                stringBuilder.Append(":00~24:00#4;");

                short workingDays = regionalSettings.WorkDays;
                var   jan62008    = new DateTime(633351744000000000);

                for (byte i = 0; i < 7; i++)
                {
                    if (((workingDays >> i) & 0x01) == 0x01)
                    {
                        continue;
                    }

                    DateTime dateTime = jan62008.AddDays(i);

                    stringBuilder.Append("w#");
                    stringBuilder.Append(dateTime.ToString("yyyy-MM-dd"));
                    stringBuilder.Append("~");

                    dateTime = dateTime.AddDays(1);

                    stringBuilder.Append(dateTime.ToString("yyyy-MM-dd"));
                    stringBuilder.Append("#5;");
                }

                try
                {
                    foreach (DataRow dataRow in spWeb.Lists["Holidays"].Items.GetDataTable().Rows)
                    {
                        DateTime dateTime = DateTime.Parse(dataRow["Date"].ToString());

                        if (string.IsNullOrEmpty(dataRow["Hours"].ToString()))
                        {
                            stringBuilder.Append(dateTime.ToString("yyyy-MM-dd"));
                            stringBuilder.Append("~");
                            dateTime = dateTime.AddDays(1);

                            stringBuilder.Append(dateTime.ToString("yyyy-MM-dd"));
                            stringBuilder.Append("#3;");
                        }
                        else
                        {
                            stringBuilder.Append(dateTime.ToString("yyyy-MM-dd"));
                            stringBuilder.Append(" 00:00~");
                            stringBuilder.Append(dateTime.ToString("yyyy-MM-dd"));
                            stringBuilder.Append(" ");
                            stringBuilder.Append(workDayStartHour);
                            stringBuilder.Append(":00;");

                            stringBuilder.Append(dateTime.ToString("yyyy-MM-dd"));
                            stringBuilder.Append(" ");
                            stringBuilder.Append((workDayEndHour) - int.Parse(dataRow["Hours"].ToString()));
                            stringBuilder.Append(":00~");

                            dateTime = dateTime.AddDays(1);

                            stringBuilder.Append(dateTime.ToString("yyyy-MM-dd"));
                            stringBuilder.Append(" 24:00#3;");
                        }
                    }
                }
                catch (Exception)
                {
                }

                return(stringBuilder.ToString().Trim(';'));
            }
            catch (Exception exception)
            {
                throw new APIException((int)Errors.GetGanttExclude, exception.GetBaseException().Message);
            }
        }
Ejemplo n.º 30
0
        private void MapRegionalSettings(SPRegionalSettings settings, RegionalSettingsDefinition definition)
        {
            if (definition.AdjustHijriDays.HasValue)
            {
                settings.AdjustHijriDays = definition.AdjustHijriDays.Value;
            }

            if (definition.AlternateCalendarType.HasValue)
            {
                settings.AlternateCalendarType = definition.AlternateCalendarType.Value;
            }

            if (definition.CalendarType.HasValue)
            {
                settings.CalendarType = definition.CalendarType.Value;
            }

            if (definition.Collation.HasValue)
            {
                settings.Collation = definition.Collation.Value;
            }

            if (definition.FirstDayOfWeek.HasValue)
            {
                settings.FirstDayOfWeek = definition.FirstDayOfWeek.Value;
            }

            if (definition.FirstWeekOfYear.HasValue)
            {
                settings.FirstWeekOfYear = definition.FirstWeekOfYear.Value;
            }

            if (definition.LocaleId.HasValue)
            {
                settings.LocaleId = definition.LocaleId.Value;
            }

            if (definition.WorkDayStartHour.HasValue)
            {
                settings.WorkDayStartHour = definition.WorkDayStartHour.Value;
            }

            if (definition.WorkDayEndHour.HasValue)
            {
                settings.WorkDayEndHour = definition.WorkDayEndHour.Value;
            }

            if (definition.WorkDays.HasValue)
            {
                settings.WorkDays = definition.WorkDays.Value;
            }

            if (definition.ShowWeeks.HasValue)
            {
                settings.ShowWeeks = definition.ShowWeeks.Value;
            }

            if (definition.Time24.HasValue)
            {
                settings.Time24 = definition.Time24.Value;
            }

            if (definition.LocaleId.HasValue)
            {
                settings.LocaleId = definition.LocaleId.Value;
            }

            if (definition.TimeZoneId.HasValue)
            {
                var targetZone = settings.TimeZones
                                 .OfType <SPTimeZone>()
                                 .FirstOrDefault(z => z.ID == definition.TimeZoneId.Value);

                if (targetZone == null)
                {
                    throw new SPMeta2Exception(
                              string.Format("Cannot find TimeZone by ID:[{0}]", definition.TimeZoneId));
                }

                settings.TimeZone.ID = definition.TimeZoneId.Value;
            }
        }