Пример #1
0
        public int CreateEventItem(EventItem eventItem)
        {
            int id;

            SqlCommand cmd = new SqlCommand("CreateEventItem") { CommandType = CommandType.StoredProcedure };
            cmd.Parameters.AddWithValue("@Name", eventItem.Name);
            cmd.Parameters.AddWithValue("@Description", eventItem.Description);
            cmd.Parameters.AddWithValue("@ImageID", eventItem.ImageID);
            cmd.Parameters.AddWithValue("@StartDate", eventItem.StartDate);
            cmd.Parameters.AddWithValue("@EndDate", eventItem.EndDate);
            cmd.Parameters.AddWithValue("@IsAllDay", eventItem.IsAllDay);
            SqlParameter param = new SqlParameter("@ID", SqlDbType.Int);
            param.Direction = ParameterDirection.Output;
            cmd.Parameters.Add(param);

            try
            {
                _repo.ExecuteNonQuery(cmd);
                id = (int)cmd.Parameters["@ID"].Value;
            }
            catch (Exception exc)
            {
                throw exc;
            }

            return id;
        }
Пример #2
0
        public override void Execute(CommandContext context)
        {
            string itemId = System.Web.HttpContext.Current.Request.QueryString["id"];

            var    eventItem = new EventItem(ItemUtil.GetContentItem(Guid.Parse(itemId)));
            string userName  = context.Parameters["ids"];

            if (string.IsNullOrWhiteSpace(userName))
            {
                throw new Exception("There was no one selected");
            }

            User user = User.FromName(string.Format("extranet\\{0}", userName.TrimStart('{').TrimEnd('}')), false);

            eventItem.SendConfirmationEmail(user);
        }
Пример #3
0
    public void RegisterEvent(EEventType eType, HandleEvent handle)
    {
        if (null == m_EventItemArray)
        {
            return;
        }

        EventItem item = GetEventItem(eType);

        if (null == item)
        {
            item = new EventItem();
        }

        item.Add(handle);
    }
Пример #4
0
    public void UnRegisterEvent(EEventType eType, HandleEvent handle)
    {
        if (null == m_EventItemArray)
        {
            return;
        }

        EventItem item = GetEventItem(eType);

        if (null == item)
        {
            return;
        }

        item.Remove(handle);
    }
Пример #5
0
        /// <summary>
        /// Gets the eventItem.
        /// </summary>
        /// <param name="eventItemId">The eventItem identifier.</param>
        /// <returns></returns>
        private EventItem GetEventItem(int eventItemId, RockContext rockContext = null)
        {
            string    key       = string.Format("EventItem:{0}", eventItemId);
            EventItem eventItem = RockPage.GetSharedItem(key) as EventItem;

            if (eventItem == null)
            {
                rockContext = rockContext ?? new RockContext();
                eventItem   = new EventItemService(rockContext).Queryable()
                              .Where(e => e.Id == eventItemId)
                              .FirstOrDefault();
                RockPage.SaveSharedItem(key, eventItem);
            }

            return(eventItem);
        }
        protected void Signup(object sender, EventArgs e)
        {
            var eventItem = new EventItem(Sitecore.Context.Item);

            var username          = Sitecore.Context.Domain.GetFullName(this.Name.Text);
            PasswordGenerator asd = new PasswordGenerator();
            var generate          = asd.Generate();

            Membership.CreateUser(username, generate, this.Email.Text);
            var user = User.FromName(username, true);

            user.Profile.Email    = this.Email.Text;
            user.Profile.FullName = this.Name.Text;
            user.Profile.Save();

            eventItem.RegisterUser(user);
        }
Пример #7
0
        /// <summary>
        /// 
        /// </summary>
        /// 
        /// <param name="@event"></param>
        /// 
        public void Send(CanonicalEvent @event)
        {
            EventItem<CanonicalEvent> item = new EventItem<CanonicalEvent>(@event);
            lock (queue)
            {
                if (Logger.IsDebugEnabled)
                {
                    LogDebug("channel size: {0}.", queue.Count);
                }

                queue.Enqueue(item);
                Monitor.Pulse(queue);

                // disable the following line to make this a blocking channel.
                // Monitor.Wait(queue);
            }
        }
Пример #8
0
        public List <EventItem> GetEventItems()
        {
            List <EventVM> events = GetEvents();
            var            items  = new List <EventItem>();

            foreach (var ev in events)
            {
                var model = new EventItem
                {
                    Name    = ev.Name,
                    EventId = ev.Id
                };
                items.Add(model);
            }

            return(items);
        }
Пример #9
0
        public async Task <IActionResult> UpdateProduct(
            [FromBody] EventItem productToUpdate)
        {
            var eventItem = await _context.EventItems
                            .SingleOrDefaultAsync
                                (i => i.Id == productToUpdate.Id);

            if (eventItem == null)
            {
                return(NotFound(new { Message = $"Item with id {productToUpdate.Id} not found." }));
            }
            eventItem = productToUpdate;
            _context.EventItems.Update(eventItem);
            await _context.SaveChangesAsync();

            return(CreatedAtAction(nameof(GetItemsById), new { id = productToUpdate.Id }));
        }
Пример #10
0
        public IActionResult UpdateEvent(Guid id, [FromBody] EventItem item)
        {
            if (item == null || item.Id != id)
            {
                return(BadRequest());
            }

            try
            {
                _service.UpdateEvent(item);

                return(new NoContentResult());
            }
            catch (EntityNotFoundException)
            {
                return(new NotFoundResult());
            }
        }
Пример #11
0
        /// <summary>
        /// Updates an event.
        /// </summary>
        /// <param name="eventItem">The event to update.</param>
        /// <param name="cancellationToken">A token to observe while waiting for the task to complete.</param>
        /// <returns>
        /// A task that represents the asynchronous operation.
        /// </returns>
        public virtual async Task <ValidationResult> UpdateAsync(EventItem eventItem, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            ThrowIfDisposed();
            if (eventItem == null)
            {
                throw new ArgumentNullException(nameof(eventItem));
            }
            var eventEntity = await Events.FindAsync(cancellationToken, eventItem.Id);

            if (eventEntity == null)
            {
                throw new InvalidOperationException("");
            }
            await SaveChangesAsync(cancellationToken);

            return(ValidationResult.Success);
        }
Пример #12
0
        public void Save()
        {
            IEventRepository iEventRepository = new EventRepository(this.connectionString);

            EventItem eventItem = new EventItem
                                  (
                "data",
                AppActs.DomainModel.Enum.EventType.ApplicationOpen,
                "openScreen",
                100,
                "Main",
                Guid.NewGuid(),
                DateTime.Now,
                "1.1"
                                  );

            iEventRepository.Save(this.Application.Id, this.Device.Id, eventItem);
        }
Пример #13
0
        public async Task <IActionResult> CreateProduct(
            [FromBody] EventItem product)
        {
            var item = new EventItem
            {
                EventCityId = product.EventCityId,
                EventTypeId = product.EventTypeId,
                Description = product.Description,
                Name        = product.Name,
                PictureUrl  = product.PictureUrl,
                Price       = product.Price
            };

            _context.EventItems.Add(item);
            await _context.SaveChangesAsync();

            return(CreatedAtAction(nameof(GetItemsById), new { id = item.Id }));
        }
Пример #14
0
        public EventDetailsViewController(EventItem eventItem)
        {
            AutomaticallyAdjustsScrollViewInsets = false;

            EventItem currentEvent = eventItem ?? EventItem.NullEvent();

            _contentView = new EventDetailsView(this)
            {
                Image = Converters.FromBase64(currentEvent.LargeImage),
                Name  = currentEvent.Name,
                LocationDescription = "Стадион школы №1037",
                Date = currentEvent.Date.ToString("dd.MM"),
                Time = "в " + currentEvent.Date.ToString("hh:mm"),
                ParticipantsCount    = 2.ToString(),
                ParticipantCountWord = "участника",
                DescriptionText      = currentEvent.Description
            };
        }
Пример #15
0
        protected override void Subscription_DataUpdated(Subscription subscription, DataChangedEventArgs args)
        {
            foreach (var change in args.DataChanges)
            {
                EventItem data = new EventItem
                {
                    Tag       = change.MonitoredItem.UserData.ToString(),
                    Value     = float.Parse(change.Value.Value.ToString()),
                    Timestamp = change.Value.SourceTimestamp,
                    Status    = change.Value.StatusCode.Message
                };

                log.Debug($"Event Received: \n" +
                          $"{data.ToJson()}");

                _newEventCallback(data);
            }
        }
Пример #16
0
        private void MatchAddListener(string allContent)
        {
            MatchCollection matches = Regex.Matches(allContent, AddListenerMatch);

            foreach (Match match in matches)
            {
                string    eventName  = match.Groups["STR"].Value;
                string    actionName = match.Groups["STR2"].Value;
                EventItem eventItem  = curOutPut.GetEventItem(eventName);
                int       count;
                if (eventItem.addCount.TryGetValue(actionName, out count) == false)
                {
                    count = 0;
                }
                count++;
                eventItem.addCount[actionName] = count;
            }
        }
        public void Save()
        {
            IEventRepository iEventRepository = new EventRepository(this.connectionString);

            EventItem eventItem = new EventItem
                (
                    "data",
                    AppActs.DomainModel.Enum.EventType.ApplicationOpen,
                    "openScreen",
                    100,
                    "Main",
                    Guid.NewGuid(),
                    DateTime.Now,
                    "1.1"
                );

            iEventRepository.Save(this.Application.Id, this.Device.Id, eventItem);
        }
Пример #18
0
        public ActionResult EditEventItem(EventItem item)
        {
            string message = "";
            string messageClass = "";

            if (ModelState.IsValid)
            {
                try
                {
                    ACRepository.UpdateEventItem(item);

                    /*
                    if (file.ContentLength < 4194304) // 524288)
                    {
                        newImage.Name = file.FileName;
                        newImage.AlternateText = String.Empty;
                        newImage.MediaType = file.ContentType;
                        Int32 length = file.ContentLength;
                        byte[] tempImage = new byte[length];
                        file.InputStream.Read(tempImage, 0, length);
                        newImage.Data = tempImage;
                    }
                    */

                    message = "Update successful.";
                    messageClass = "success";
                }
                catch (Exception exc)
                {
                    message = exc.Message;
                    messageClass = "error";
                }
            }
            else
            {
                message = "Not all information was valid. See messages below.";
                messageClass = "info";
            }

            ViewData["Message"] = message;
            ViewData["MessageClass"] = messageClass;
            return View(item);
        }
        public void Start(EventItem eventItem)
        {
            this.ClientAgent = eventItem.Agent;
            log.Info(providerName + " Startup");

            TimeStamp currentTime = TimeStamp.UtcNow;

            currentTime.AddSeconds(timeSeconds);
            taskTimer.Start(currentTime);
            if (debug)
            {
                log.Debug("Created timer. (Default startTime: " + taskTimer.StartTime + ")");
            }

            CreateNewSocket();
            retryTimeout = Factory.Parallel.TickCount + retryDelay * 1000;
            log.Info("Connection will timeout and retry in " + retryDelay + " seconds.");
            isStarted = true;
        }
Пример #20
0
        /// <summary>
        /// Adds the event to a Calendar.
        /// </summary>
        /// <param name="eventItem">The event</param>
        /// <param name="calendar">The calendar</param>
        /// <param name="created">If a new calendar item was created</param>
        /// <returns>The calendar item for the event</returns>
        public static EventCalendarItem AddToCalendar(this EventItem eventItem, EventCalendarCache calendar, out bool created)
        {
            created = false;
            if (calendar == null)
            {
                return(null);
            }
            var calendarItem = eventItem.EventCalendarItems.FirstOrDefault(ci => ci.EventCalendarId == calendar.Id);

            if (calendarItem == null)
            {
                created      = true;
                calendarItem = new EventCalendarItem {
                    EventCalendarId = calendar.Id
                };
                eventItem.EventCalendarItems.Add(calendarItem);
            }
            return(calendarItem);
        }
Пример #21
0
        /// <summary>
        /// Sets the value where value is the EventItem.Guid as a string (or null)
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="configurationValues"></param>
        /// <param name="value">The value.</param>
        public override void SetEditValue(Control control, Dictionary <string, ConfigurationValue> configurationValues, string value)
        {
            var picker = control as EventItemPicker;

            if (picker != null)
            {
                EventItem eventItem     = null;
                Guid?     eventItemGuid = value.AsGuidOrNull();
                if (eventItemGuid.HasValue)
                {
                    using (var rockContext = new RockContext())
                    {
                        eventItem = new EventItemService(rockContext).Get(eventItemGuid.Value);
                    }
                }

                picker.SetValue(eventItem);
            }
        }
        private void btnDeleteSurveyQuestion_Click(object sender, RoutedEventArgs e)
        {
            EventItemDetails selectedEID = new EventItemDetails();

            if (lstCurrentSurveyQuestions.SelectedItem != null)
            {
                selectedEID = (EventItemDetails)lstCurrentSurveyQuestions.SelectedItem;
            }
            try
            {
                EventItem eventItem = eventItemRepository.GetEventItem(selectedEID.EIDEventItemID);  //make the getEvents more specific by only selecting events that match the ID of the current event
                eventItemRepository.DeleteEventItem(eventItem);
                FillFields();
            }
            catch
            {
                Jeeves.ShowMessage("Error", "Failure; please try again");
            }
        }
Пример #23
0
 public static Event ToEvent(this EventItem inputEvent)
 {
     return(new Event()
     {
         ID = inputEvent.ID,
         Name = inputEvent.Name,
         Location = inputEvent.Location,
         //StartTime = inputEvent.StartDate + inputEvent.StartHour.TimeOfDay,
         StartTime = DateTime.Parse(inputEvent.StartDate + " " + inputEvent.StartHour),
         //EndTime = inputEvent.EndDate + inputEvent.EndHour.TimeOfDay,
         EndTime = DateTime.Parse(inputEvent.EndDate + " " + inputEvent.EndHour),
         HoursOffset = inputEvent.HoursOffset,
         MaxUsers = inputEvent.MaxUsers,
         UnitState = UnitState.Unchanged,
         GroupID = inputEvent.GroupID,
         OwnerID = inputEvent.OwnerID,
         IsPublic = inputEvent.IsPublic
     });
 }
Пример #24
0
        public ActionResult EventCreate(EventItem eventItem)
        {
            if (!BLL.PermissionManager.HasPermission(Core.SessionManager.UserID, DML.Enums.PermissionsItem.CanCreateEvent) &&
                !BLL.GroupManager.IsOwner(Core.SessionManager.UserID, eventItem.GroupID) &&
                !BLL.UsersToGroupManager.IsModerator(CountMeIn.Core.SessionManager.UserID, eventItem.GroupID))
            {
                return(RedirectToAction("NotFound", "Error"));
            }

            if (eventItem.HoursOffset == 0)
            {
                ModelState["HoursOffset"].Errors.Clear();
            }

            try
            {
                if ((string.IsNullOrEmpty(eventItem.StartDate) && string.IsNullOrEmpty(eventItem.EndDate)) || DateTime.Parse(eventItem.StartDate) > DateTime.Parse(eventItem.EndDate))
                {
                    ModelState.AddModelError("EndDate", "Крайната дата не може да е преди Началната");
                }

                if ((string.IsNullOrEmpty(eventItem.StartHour) && string.IsNullOrEmpty(eventItem.EndHour)) || DateTime.Parse(eventItem.StartHour) > DateTime.Parse(eventItem.EndHour))
                {
                    ModelState.AddModelError("EndHour", "Крайния час не може да е преди Началния");
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("StartDate", ex.Source);
            }

            if (ModelState.IsValid)
            {
                Event inputEvent = eventItem.ToEvent();
                inputEvent.OwnerID = SessionManager.UserID;
                inputEvent.GroupID = eventItem.GroupID; //SessionManager.GroupID;
                BLL.EventManager.Add(inputEvent);
                return(RedirectToAction("EventsList", "Event"));
            }

            return(View(eventItem));
        }
Пример #25
0
        //
        // IEventStore
        //

        /// <summary>
        /// Creates new web events and adds there to the database in a bulk operation.
        /// </summary>
        /// <param name="eventItem">The event descriptor object.</param>
        /// <param name="users">The users.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// Returns the unique identifier (GUID) for a group of events.
        /// </returns>
        public virtual async Task <ValidationResult> CreateAsync(EventItem eventItem, IEnumerable <AccountItem> users, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            ThrowIfDisposed();
            if (eventItem == null)
            {
                throw new ArgumentNullException(nameof(eventItem));
            }
            if (users == null)
            {
                throw new ArgumentNullException(nameof(users));
            }

            var eventEntity = Context.Add(new LoggingEvent
            {
                ObjectType     = eventItem.ObjectType,
                ObjectId       = eventItem.ObjectId,
                ContactId      = eventItem.Contact?.Id,
                ContactState   = eventItem.ContactState,
                ProjectId      = eventItem.Project?.Id,
                BrowserBrand   = eventItem.BrowserBrand,
                BrowserVersion = eventItem.BrowserVersion,
                MobileDevice   = eventItem.MobileDevice,
                AnonymId       = eventItem.AnonymId,
                ClientId       = eventItem.ClientId,
                CustomUri      = eventItem.CustomUri,
                ReferrerUrl    = eventItem.ReferrerUrl,
                Message        = eventItem.Message
            });

            foreach (var user in users)
            {
                eventEntity.Users.Add(new LoggingEventSharing {
                    UserId = user.Id
                });
            }

            await SaveChangesAsync(cancellationToken);

            eventItem.Id = eventEntity.Id;
            return(ValidationResult.Success);
        }
        public void Save()
        {
            IEventRepository iEventRepository = new EventRepository(this.client, this.database);

            EventItem eventItem = new EventItem
                (
                    this.Application.Id,
                    this.Device.Id,
                    "07545197580",
                    AppActs.DomainModel.Enum.EventType.Event,
                    "searched",
                    30,
                    "Main",
                    Guid.NewGuid(),
                    DateTime.Now,
                    "1.1.1.1"
                 );

            iEventRepository.Save(eventItem);
        }
Пример #27
0
        public void Save()
        {
            IEventRepository iEventRepository = new EventRepository(this.client, this.database);

            EventItem eventItem = new EventItem
                                  (
                this.Application.Id,
                this.Device.Id,
                "07545197580",
                AppActs.DomainModel.Enum.EventType.Event,
                "searched",
                30,
                "Main",
                Guid.NewGuid(),
                DateTime.Now,
                "1.1.1.1"
                                  );

            iEventRepository.Save(eventItem);
        }
Пример #28
0
        private void OnPhoneAccelerometerReading(AccelerometerReadingChangedEventArgs args)
        {
            AccelerometerReading reading = args.Reading;
            DateTimeOffset       ts      = reading.Timestamp;
            EventItem            accX    = new EventItem {
                Stream = StreamsEnum.PhoneAccelerometerX, Timestamp = ts, Value = reading.AccelerationX
            };
            EventItem accY = new EventItem {
                Stream = StreamsEnum.PhoneAccelerometerY, Timestamp = ts, Value = reading.AccelerationY
            };
            EventItem accZ = new EventItem {
                Stream = StreamsEnum.PhoneAccelerometerZ, Timestamp = ts, Value = reading.AccelerationZ
            };

            //IList<EventItem> events = new[] { accX };
            IList <EventItem> events = new[] { accX, accY, accZ };

            //Debug.WriteLine(DateTime.Now);
            SendToQueue(events);
        }
Пример #29
0
        public void OnPhoneGeopositionReading(PositionChangedEventArgs args)
        {
            Geoposition geo = args.Position;

            double lat = geo.Coordinate.Point.Position.Latitude;
            double lng = geo.Coordinate.Point.Position.Longitude;

            DateTimeOffset ts = geo.Coordinate.Timestamp;

            EventItem latEvent = new EventItem {
                Stream = StreamsEnum.GeopositionLatitude, Timestamp = ts, Value = lat
            };
            EventItem lngEvent = new EventItem {
                Stream = StreamsEnum.GeopositionLongitude, Timestamp = ts, Value = lng
            };

            IList <EventItem> events = new[] { latEvent, lngEvent };

            //SendToQueue(events);
        }
Пример #30
0
        /// <summary>
        /// Adds an event handler to collection of listeners.
        /// </summary>
        /// <param name="handler">
        /// The handler to add.
        /// </param>
        /// <returns>
        /// <c> true </c> if the handler is added; otherwise <c> false </c> (value is <c> null </c> or already subscribed).
        /// </returns>
        public bool Add(EventHandler <TEventArgs> handler)
        {
            if (handler == null)
            {
                return(false);
            }

            Cleanup();
            // ReSharper disable once InconsistentlySynchronizedField
            var original = _listeners;

            lock (_lockObject)
            {
                var item = new EventItem(handler);
                _listeners = _listeners.Add(item);
            }

            // ReSharper disable once InconsistentlySynchronizedField
            return(!ReferenceEquals(original, _listeners));
        }
Пример #31
0
        public System.Collections.ObjectModel.Collection <EventItem> FindEventItemList(Character target)
        {
            //HELPER VARIABLES
            MySqlConnection connection = ConnectionPool.Request();
            MySqlCommand    command    = new MySqlCommand(_query_21, connection);
            MySqlDataReader reader     = null;

            command.Parameters.AddWithValue("CharId", target.ModelId);
            System.Collections.ObjectModel.Collection <EventItem> collection = new System.Collections.ObjectModel.Collection <EventItem>();

            try
            {
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    EventItem b = new EventItem();
                    b.EventId   = reader.GetUInt32(0);
                    b.ItemId    = reader.GetUInt32(2);
                    b.ItemCount = reader.GetByte(3);
                    collection.Add(b);
                }

                reader.Close();

                return(collection);
            }
            catch (Exception e)
            {
                __dbtracelog.WriteError("Database", e.Message);
                return(collection);
            }
            finally
            {
                //ALWAYS CLOSE THE CONNECTION AND REPOOL THE ITEMS
                ConnectionPool.Release(connection);
                if (reader != null)
                {
                    reader.Close();
                }
            }
        }
Пример #32
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>EventItem
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            int?eventItemId = PageParameter("EventItemId").AsIntegerOrNull();

            if (eventItemId.HasValue)
            {
                string key = string.Format("EventItem:{0}", eventItemId);
                _eventItem = RockPage.GetSharedItem(key) as EventItem;
                if (_eventItem == null)
                {
                    _eventItem = new EventItemService(new RockContext()).Queryable()
                                 .Where(i => i.Id == eventItemId)
                                 .FirstOrDefault();
                    RockPage.SaveSharedItem(key, _eventItem);
                }

                if (_eventItem != null)
                {
                    rFilter.ApplyFilterClick += rFilter_ApplyFilterClick;

                    gCalendarItemOccurrenceList.DataKeyNames      = new string[] { "Id" };
                    gCalendarItemOccurrenceList.Actions.ShowAdd   = true;
                    gCalendarItemOccurrenceList.Actions.AddClick += gCalendarItemOccurrenceList_Add;
                    gCalendarItemOccurrenceList.GridRebind       += gCalendarItemOccurrenceList_GridRebind;

                    var registrationField = gCalendarItemOccurrenceList.ColumnsOfType <HyperLinkField>().FirstOrDefault(a => a.HeaderText == "Registration");
                    if (registrationField != null)
                    {
                        registrationField.DataNavigateUrlFormatString = LinkedPageUrl("RegistrationInstancePage") + "?RegistrationInstanceId={0}";
                    }

                    var groupField = gCalendarItemOccurrenceList.ColumnsOfType <HyperLinkField>().FirstOrDefault(a => a.HeaderText == "Group");
                    if (groupField != null)
                    {
                        groupField.DataNavigateUrlFormatString = LinkedPageUrl("GroupDetailPage") + "?GroupId={0}";
                    }
                }
            }
        }
Пример #33
0
        public async Task <IActionResult> CreateProduct(
            [FromBody] EventItem product)
        {
            var item = new EventItem
            {
                EventDateId     = product.EventDateId,
                EventLocationId = product.EventLocationId,
                EventTypeId     = product.EventTypeId,
                Description     = product.Description,
                Name            = product.Name,
                PictureURL      = product.PictureURL,
                Fee             = product.Fee,
                EventStartTime  = product.EventStartTime,
                EventEndTime    = product.EventEndTime
            };

            _context.EventItems.Add(item);
            await _context.SaveChangesAsync();

            return(CreatedAtAction(nameof(GetItemsById), new { id = item.Id }));
        }
Пример #34
0
        public bool isValid(EventItem togo)
        {
            var valid = true;

            if (string.IsNullOrWhiteSpace(togo.Description))
            {
                valid &= false;
            }

            if (string.IsNullOrWhiteSpace(togo.Owner))
            {
                valid &= false;
            }

            if (togo.Team == TeamType.None)
            {
                valid &= false;
            }

            if (togo.Faction == FactionType.None)
            {
                valid &= false;
            }

            if ((togo.Team == TeamType.WaterBuffaloes ||
                 togo.Team == TeamType.Goons ||
                 togo.Team == TeamType.Mutants) && togo.Faction != FactionType.Horde)
            {
                valid &= false;
            }

            if ((togo.Team == TeamType.Sparkles ||
                 togo.Team == TeamType.Flowers ||
                 togo.Team == TeamType.ArgyleSox) && togo.Faction != FactionType.Alliance)
            {
                valid &= false;
            }

            return(valid);
        }
        public void GetEventItems()
        {
            //Read reviews into Arraylist
            string sAppPath = System.AppDomain.CurrentDomain.BaseDirectory;
            try
            {
                using (StreamReader sr = new StreamReader(String.Format("{0}/Files/Events.txt", sAppPath), Encoding.GetEncoding("iso-8859-1")))
                {
                    while (sr.Peek() >= 0)
                    {
                        int count = 0;
                        String line = sr.ReadLine();
                        if (!string.IsNullOrEmpty(line))
                        {
                            string[] array;
                            array = line.Split('|');

                            //Convert the num of days to an int
                            int days;
                            int.TryParse(array[3], out days);

                            //Convert the file string to Date
                            string[] format = { "dd/MM/yyyy" };
                            DateTime date;
                            DateTime.TryParseExact(array[2], format, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out date);

                            EventItem t = new EventItem(count, array[0], array[1], days, date);
                            events.Add(t);
                            ++count;
                        }
                    }
                }
                events.Sort(new EventComparer());
            }
            catch (Exception)
            {
                Master.AddErrorMessage("An error occurred retrieving the events. Please try again soon or contact the crèche for assistance.");
            }
        }
Пример #36
0
        /// <summary>
        /// Creates the event description from the lava template. Default is used if one is not specified in the request.
        /// </summary>
        /// <param name="eventItem">The event item.</param>
        /// <param name="occurrence">The occurrence.</param>
        /// <returns></returns>
        private string CreateEventDescription(EventItem eventItem, EventItemOccurrence occurrence)
        {
            // get the lava template
            int templateDefinedValueId   = 0;
            var iCalTemplateDefinedValue = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.DEFAULT_ICAL_DESCRIPTION);

            if (request.QueryString["templateid"] != null)
            {
                int.TryParse(request.QueryString["templateid"], out templateDefinedValueId);
                if (templateDefinedValueId > 0)
                {
                    iCalTemplateDefinedValue = DefinedValueCache.Get(templateDefinedValueId);
                }
            }

            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null);

            mergeFields.Add("EventItem", eventItem);
            mergeFields.Add("EventItemOccurrence", occurrence);

            return(iCalTemplateDefinedValue.GetAttributeValue("Template").ResolveMergeFields(mergeFields));
        }
Пример #37
0
        /// <overloads>Formats the data into an HTML table.</overloads>
        /// <summary>
        ///   Formats the <paramref name="item" /> into an HTML table. Valid only for <see cref="EventItem" /> values that are collections.
        /// </summary>
        /// <param name="item">
        ///   The item to format into an HTML table. Must be one of the following enum values: FormVariables, Cookies,
        ///   SessionVariables, ServerVariables
        /// </param>
        /// <returns>Returns an HTML table.</returns>
        private string ToHtmlTable(EventItem item)
        {
            string htmlValue;

            switch (item)
            {
                case EventItem.FormVariables:
                    htmlValue = ToHtmlTable(FormVariables);
                    break;
                case EventItem.Cookies:
                    htmlValue = ToHtmlTable(Cookies);
                    break;
                case EventItem.SessionVariables:
                    htmlValue = ToHtmlTable(SessionVariables);
                    break;
                case EventItem.ServerVariables:
                    htmlValue = ToHtmlTable(ServerVariables);
                    break;
                default:
                    throw new BusinessException(String.Format(CultureInfo.CurrentCulture, "Encountered unexpected EventItem enum value {0}. Event.ToHtmlTable() is not designed to handle this enum value. The function must be updated.", item));
            }

            return htmlValue;
        }
        protected string CreateEventLineStringFromEventItem(int id, EventItem card)
        {
            try
            {
                //Create the new item
                String line = string.Empty;
                line += card.Title + "|";
                line += card.Description + "|";
                line += card.Date.ToString("dd/MM/yyyy") + "|";
                line += card.Days.ToString() + "|";
                line += System.Environment.NewLine;

                //Edit the event item by replacing it with this nice new one
                return line;
            }
            catch (Exception)
            {
                Master.AddErrorMessage("There was an error adding a new item.");

            }
            return string.Empty;
        }
Пример #39
0
        public void UpdateEventItem(EventItem eventItem)
        {
            SqlCommand cmd = new SqlCommand("UpdateEventItem") { CommandType = CommandType.StoredProcedure };
            cmd.Parameters.AddWithValue("@ID", eventItem.ID);
            cmd.Parameters.AddWithValue("@Name", eventItem.Name);
            cmd.Parameters.AddWithValue("@Description", eventItem.Description);
            cmd.Parameters.AddWithValue("@ImageID", eventItem.ImageID);
            cmd.Parameters.AddWithValue("@StartDate", eventItem.StartDate);
            cmd.Parameters.AddWithValue("@EndDate", eventItem.EndDate);
            cmd.Parameters.AddWithValue("@IsAllDay", eventItem.IsAllDay);
            cmd.Parameters.AddWithValue("@IsActive", eventItem.IsActive);

            try
            {
                _repo.ExecuteNonQuery(cmd);
            }
            catch (Exception exc)
            {
                throw exc;
            }
        }
Пример #40
0
        /// <summary>
        /// Shows the readonly details.
        /// </summary>
        /// <param name="eventItem">The event item.</param>
        private void ShowReadonlyDetails( EventItem eventItem )
        {
            SetEditMode( false );

            hfEventItemId.SetValue( eventItem.Id );

            lReadOnlyTitle.Text = eventItem.Name.FormatAsHtmlTitle();

            SetLabels( eventItem );

            string imgTag = GetImageTag( eventItem.PhotoId, 300, 300, false, true );
            if ( eventItem.PhotoId.HasValue )
            {
                string imageUrl = ResolveRockUrl( String.Format( "~/GetImage.ashx?id={0}", eventItem.PhotoId.Value ) );
                lImage.Text = string.Format( "<a href='{0}'>{1}</a>", imageUrl, imgTag );
                divImage.Visible = true;
            }
            else
            {
                divImage.Visible = false;
            }

            lSummary.Visible = !string.IsNullOrWhiteSpace( eventItem.Summary );
            lSummary.Text = eventItem.Summary;

            var calendars = eventItem.EventCalendarItems
                .Select( c => c.EventCalendar.Name ).ToList();
            if ( calendars.Any() )
            {
                lCalendar.Visible = true;
                lCalendar.Text = calendars.AsDelimited( ", " );
            }
            else
            {
                lCalendar.Visible = false;
            }

            var audiences = eventItem.EventItemAudiences
                .Select( a => a.DefinedValue.Value ).ToList();
            if ( audiences.Any() )
            {
                lAudiences.Visible = true;
                lAudiences.Text = audiences.AsDelimited( ", " );
            }
            else
            {
                lAudiences.Visible = false;
            }

            phAttributesView.Controls.Clear();
            foreach ( var eventCalendarItem in eventItem.EventCalendarItems )
            {
                eventCalendarItem.LoadAttributes();
                if ( eventCalendarItem.Attributes.Count > 0 )
                {
                    foreach ( var attr in eventCalendarItem.Attributes )
                    {
                        string value = eventCalendarItem.GetAttributeValue( attr.Key );
                        if ( !string.IsNullOrWhiteSpace( value ) )
                        {
                            var rl = new RockLiteral();
                            rl.ID = "attr_" + attr.Key;
                            rl.Label = attr.Value.Name;
                            rl.Text = attr.Value.FieldType.Field.FormatValueAsHtml( null, value, attr.Value.QualifierValues, false );
                            phAttributesView.Controls.Add( rl );
                        }
                    }
                }
            }
        }
Пример #41
0
        public EventItem GetEventItem(int ID)
        {
            EventItem item = new EventItem();

            SqlCommand cmd = new SqlCommand("GetEventItem") { CommandType = CommandType.StoredProcedure };
            cmd.Parameters.AddWithValue("@ID", ID);

            using (SqlDataReader rdr = (SqlDataReader)_repo.ExecuteReader(cmd))
            {
                while (rdr.Read())
                {
                    item = new EventItem()
                    {
                        ID = (int)rdr["ID"]
                        ,
                        Name = rdr["Name"] != DBNull.Value ? rdr["Name"].ToString() : ""
                        ,
                        Description = rdr["Description"] != DBNull.Value ? rdr["Description"].ToString() : ""
                        ,
                        ImageID = rdr["ImageID"] != DBNull.Value ? (int)rdr["ImageID"] : 0
                        ,
                        StartDate = rdr["StartDate"] != DBNull.Value ? (DateTime)rdr["StartDate"] : DateTime.MinValue
                        ,
                        EndDate = rdr["EndDate"] != DBNull.Value ? (DateTime)rdr["EndDate"] : DateTime.MinValue
                        ,
                        IsAllDay = rdr["IsAllDay"] != DBNull.Value ? (bool)rdr["IsAllDay"] : false
                        ,
                        DateInserted = (DateTime)rdr["DateInserted"]
                        ,
                        DateUpdated = rdr["DateUpdated"] != DBNull.Value ? (DateTime?)rdr["DateUpdated"] : DateTime.MinValue
                        ,
                        IsActive = (bool)rdr["IsActive"]
                    };
                }
            }
            return item;
        }
Пример #42
0
        /// <summary>
        /// Shows the edit details.
        /// </summary>
        /// <param name="eventItem">The eventItem.</param>
        private void ShowEditDetails( EventItem eventItem )
        {
            if ( eventItem == null )
            {
                eventItem = new EventItem();
                eventItem.IsApproved = _canApprove;
            }
            if ( eventItem.Id == 0 )
            {
                lReadOnlyTitle.Text = ActionTitle.Add( "Event Item" ).FormatAsHtmlTitle();
                hlStatus.Visible = false;
                hlApproved.Visible = false;
            }
            else
            {
                lReadOnlyTitle.Text = eventItem.Name.FormatAsHtmlTitle();
                SetLabels( eventItem );
            }

            SetEditMode( true );

            hfEventItemId.SetValue( eventItem.Id );

            tbName.Text = eventItem.Name;
            cbIsActive.Checked = eventItem.IsActive;
            cbIsApproved.Checked = eventItem.IsApproved;
            cbIsApproved.Enabled = _canApprove;
            if ( eventItem.IsApproved &&
                eventItem.ApprovedOnDateTime.HasValue &&
                eventItem.ApprovedByPersonAlias != null &&
                eventItem.ApprovedByPersonAlias.Person != null )
            {
                lApproval.Text = string.Format("Approved at {0} on {1} by {2}.",
                    eventItem.ApprovedOnDateTime.Value.ToShortTimeString(),
                    eventItem.ApprovedOnDateTime.Value.ToShortDateString(),
                    eventItem.ApprovedByPersonAlias.Person.FullName );
            }

            htmlDescription.Text = eventItem.Description;
            tbSummary.Text = eventItem.Summary;
            imgupPhoto.BinaryFileId = eventItem.PhotoId;
            tbDetailUrl.Text = eventItem.DetailsUrl;

            if ( eventItem.EventCalendarItems != null )
            {
                cblCalendars.SetValues( eventItem.EventCalendarItems.Select( c => c.EventCalendarId ).ToList() );
            }

            AudiencesState = eventItem.EventItemAudiences.Select( a => a.DefinedValueId ).ToList();
            ItemsState = eventItem.EventCalendarItems.ToList();

            ShowItemAttributes();

            BindAudienceGrid();
        }
Пример #43
0
        private void SetLabels( EventItem eventItem )
        {
            if ( eventItem.IsActive )
            {
                hlStatus.Text = "Active";
                hlStatus.LabelType = LabelType.Success;
            }
            else
            {
                hlStatus.Text = "Inactive";
                hlStatus.LabelType = LabelType.Danger;
            }

            if ( eventItem.IsApproved )
            {
                hlApproved.Text = "Approved";
                hlApproved.LabelType = LabelType.Info;
            }
            else
            {
                hlApproved.Text = "Not Approved";
                hlApproved.LabelType = LabelType.Warning;
            }
        }
Пример #44
0
 /// <summary>
 ///   Formats the specified <paramref name="item" /> into an HTML paragraph tag with a class attribute of
 ///   <paramref name="cssClassName" />. The string representation of <paramref name="item" />
 ///   is extracted from a resource file and will closely resemble the enum value. Example: If <paramref name="item" /> = ErrorItem.StackTrace,
 ///   the text "Stack Trace" is used.
 /// </summary>
 /// <param name="item">The enum value to be used as the content of the paragraph element. It is HTML encoded.</param>
 /// <param name="cssClassName">The name of the CSS class to assign to the paragraph element.</param>
 /// <returns>Returns an HTML paragraph tag.</returns>
 private static string ToHtmlParagraph(EventItem item, string cssClassName)
 {
     return ToHtmlParagraph(EventController.GetFriendlyEnum(item), cssClassName);
 }
Пример #45
0
 /// <summary>
 ///   Formats the name of the specified <paramref name="item" /> into an HTML paragraph tag. Example: If
 ///   <paramref name="item" /> = ErrorItem.StackTrace, the text "Stack Trace" is returned as the content of the tag.
 /// </summary>
 /// <param name="item">The enum value to be used as the content of the paragraph element. It is HTML encoded.</param>
 /// <returns>Returns an HTML paragraph tag.</returns>
 public string ToHtmlName(EventItem item)
 {
     return ToHtmlParagraph(item, "gsp_event_item");
 }
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>EventItem
        protected override void OnInit( EventArgs e )
        {
            base.OnInit( e );

            int? eventItemId = PageParameter( "EventItemId" ).AsIntegerOrNull();
            if ( eventItemId.HasValue )
            {
                string key = string.Format( "EventItem:{0}", eventItemId );
                _eventItem = RockPage.GetSharedItem( key ) as EventItem;
                if ( _eventItem == null )
                {
                    _eventItem = new EventItemService( new RockContext() ).Queryable()
                        .Where( i => i.Id == eventItemId )
                        .FirstOrDefault();
                    RockPage.SaveSharedItem( key, _eventItem );
                }

                if ( _eventItem != null )
                {
                    rFilter.ApplyFilterClick += rFilter_ApplyFilterClick;

                    gCalendarItemOccurrenceList.DataKeyNames = new string[] { "Id" };
                    gCalendarItemOccurrenceList.Actions.ShowAdd = true;
                    gCalendarItemOccurrenceList.Actions.AddClick += gCalendarItemOccurrenceList_Add;
                    gCalendarItemOccurrenceList.GridRebind += gCalendarItemOccurrenceList_GridRebind;

                    var registrationCol = gCalendarItemOccurrenceList.Columns[3] as HyperLinkField;
                    registrationCol.DataNavigateUrlFormatString = LinkedPageUrl("RegistrationInstancePage") + "?RegistrationInstanceId={0}";

                    var groupCol = gCalendarItemOccurrenceList.Columns[4] as HyperLinkField;
                    groupCol.DataNavigateUrlFormatString = LinkedPageUrl("GroupDetailPage") + "?GroupId={0}";

                }
            }
        }
Пример #47
0
 /// <summary>
 /// Gets a human readable text representation for the specified <paramref name="enumItem"/>. The text is returned from the resource
 /// file. Example: If <paramref name="enumItem"/> = ErrorItem.StackTrace, the text "Stack Trace" is used.
 /// </summary>
 /// <param name="enumItem">The enum value for which to get human readable text.</param>
 /// <returns>Returns human readable text representation for the specified <paramref name="enumItem"/></returns>
 internal static string GetFriendlyEnum(EventItem enumItem)
 {
     switch (enumItem)
     {
         case EventItem.EventId: return Resources.Err_AppErrorId_Lbl;
         case EventItem.EventType: return Resources.Err_EventType_Lbl;
         case EventItem.Url: return Resources.Err_Url_Lbl;
         case EventItem.Timestamp: return Resources.Err_Timestamp_Lbl;
         case EventItem.ExType: return Resources.Err_ExceptionType_Lbl;
         case EventItem.Message: return Resources.Err_Message_Lbl;
         case EventItem.ExSource: return Resources.Err_Source_Lbl;
         case EventItem.ExTargetSite: return Resources.Err_TargetSite_Lbl;
         case EventItem.ExStackTrace: return Resources.Err_StackTrace_Lbl;
         case EventItem.ExData: return Resources.Err_ExceptionData_Lbl;
         case EventItem.InnerExType: return Resources.Err_InnerExType_Lbl;
         case EventItem.InnerExMessage: return Resources.Err_InnerExMessage_Lbl;
         case EventItem.InnerExSource: return Resources.Err_InnerExSource_Lbl;
         case EventItem.InnerExTargetSite: return Resources.Err_InnerExTargetSite_Lbl;
         case EventItem.InnerExStackTrace: return Resources.Err_InnerExStackTrace_Lbl;
         case EventItem.InnerExData: return Resources.Err_InnerExData_Lbl;
         case EventItem.GalleryId: return Resources.Err_GalleryId_Lbl;
         case EventItem.HttpUserAgent: return Resources.Err_HttpUserAgent_Lbl;
         case EventItem.FormVariables: return Resources.Err_FormVariables_Lbl;
         case EventItem.Cookies: return Resources.Err_Cookies_Lbl;
         case EventItem.SessionVariables: return Resources.Err_SessionVariables_Lbl;
         case EventItem.ServerVariables: return Resources.Err_ServerVariables_Lbl;
         default: throw new CustomExceptions.BusinessException(String.Format(CultureInfo.CurrentCulture, "Encountered unexpected EventItem enum value {0}. EventController.GetFriendlyEnum is not designed to handle this enum value. The function must be updated.", enumItem));
     }
 }
        protected void EditItemFromForm()
        {
            int id = Convert.ToInt32(txtHiddenId.Value);
            try
            {
                //Grab how many days the event spans
                int days = 1;

                //Convert the file string to Date
                if (!string.IsNullOrEmpty(txtEventEndDate.Value) || !string.IsNullOrEmpty(txtEventStartDate.Value))
                {
                    string[] format = { "dd/MM/yyyy" };
                    DateTime dateStart;
                    DateTime dateEnd;
                    DateTime.TryParseExact(txtEventStartDate.Value.ToString(), format, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dateStart);

                    if (!string.IsNullOrEmpty(txtEventEndDate.Value))
                    {
                        DateTime.TryParseExact(txtEventEndDate.Value.ToString(), format, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dateEnd);
                        days = (dateEnd - dateStart).Days;
                    }

                    //Edit the event item by replacing it with this nice new one
                    EventItem card = new EventItem(id, txtEventTitle.Value, txtEvent.Value, days, dateStart);
                    events.RemoveAt(id);
                    events.Insert(id, card);
                }
            }
            catch (Exception)
            {
                Master.AddErrorMessage("There was an error adding a new item.");
            }
        }
Пример #49
0
 /// <summary>
 ///   Formats the value of the specified <paramref name="item" /> into an HTML paragraph tag. Example: If
 ///   <paramref name="item" /> = ErrorItem.StackTrace, the action stack trace data associated with the current error
 ///   is returned as the content of the tag. If present, line breaks (\r\n) are converted to &lt;br /&gt; tags.
 /// </summary>
 /// <param name="item">
 ///   The enum value indicating the error item to be used as the content of the paragraph element.
 ///   The text is HTML encoded.
 /// </param>
 /// <returns>Returns an HTML paragraph tag.</returns>
 public string ToHtmlValue(EventItem item)
 {
     switch (item)
     {
         case EventItem.EventId:
             return ToHtmlParagraph(EventId.ToString(CultureInfo.InvariantCulture));
         case EventItem.EventType:
             return ToHtmlParagraph(EventType.ToString());
         case EventItem.Url:
             return ToHtmlParagraph(Url);
         case EventItem.Timestamp:
             return ToHtmlParagraph(TimestampUtc.ToString(CultureInfo.CurrentCulture));
         case EventItem.ExType:
             return ToHtmlParagraph(ExType);
         case EventItem.Message:
             return ToHtmlParagraph(Message);
         case EventItem.ExSource:
             return ToHtmlParagraph(ExSource);
         case EventItem.ExTargetSite:
             return ToHtmlParagraph(ExTargetSite);
         case EventItem.ExStackTrace:
             return ToHtmlParagraph(ExStackTrace);
         case EventItem.ExData:
             return ToHtmlParagraphs(EventData);
         case EventItem.InnerExType:
             return ToHtmlParagraph(InnerExType);
         case EventItem.InnerExMessage:
             return ToHtmlParagraph(InnerExMessage);
         case EventItem.InnerExSource:
             return ToHtmlParagraph(InnerExSource);
         case EventItem.InnerExTargetSite:
             return ToHtmlParagraph(InnerExTargetSite);
         case EventItem.InnerExStackTrace:
             return ToHtmlParagraph(InnerExStackTrace);
         case EventItem.InnerExData:
             return ToHtmlParagraphs(InnerExData);
         case EventItem.GalleryId:
             return ToHtmlParagraph(GalleryId.ToString(CultureInfo.InvariantCulture));
         case EventItem.HttpUserAgent:
             return ToHtmlParagraph(HttpUserAgent);
         case EventItem.FormVariables:
             return ToHtmlParagraphs(FormVariables);
         case EventItem.Cookies:
             return ToHtmlParagraphs(Cookies);
         case EventItem.SessionVariables:
             return ToHtmlParagraphs(SessionVariables);
         case EventItem.ServerVariables:
             return ToHtmlParagraphs(ServerVariables);
         default:
             throw new BusinessException(String.Format(CultureInfo.CurrentCulture, "Encountered unexpected EventItem enum value {0}. Event.ToHtmlValue() is not designed to handle this enum value. The function must be updated.", item));
     }
 }
Пример #50
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            EventItem eventItem = null;

            using ( var rockContext = new RockContext() )
            {
                var validationMessages = new List<string>();

                var eventItemService = new EventItemService( rockContext );
                var eventCalendarItemService = new EventCalendarItemService( rockContext );
                var eventItemAudienceService = new EventItemAudienceService( rockContext );

                int eventItemId = hfEventItemId.ValueAsInt();
                if ( eventItemId != 0 )
                {
                    eventItem = eventItemService
                        .Queryable( "EventItemAudiences,EventItemOccurrences.Linkages,EventItemOccurrences" )
                        .Where( i => i.Id == eventItemId )
                        .FirstOrDefault();
                }

                if ( eventItem == null )
                {
                    eventItem = new EventItem();
                    eventItemService.Add( eventItem );
                }

                eventItem.Name = tbName.Text;
                eventItem.IsActive = cbIsActive.Checked;

                if ( !eventItem.IsApproved && cbIsApproved.Checked )
                {
                    eventItem.ApprovedByPersonAliasId = CurrentPersonAliasId;
                    eventItem.ApprovedOnDateTime = RockDateTime.Now;
                }
                eventItem.IsApproved = cbIsApproved.Checked;
                if ( !eventItem.IsApproved )
                {
                    eventItem.ApprovedByPersonAliasId = null;
                    eventItem.ApprovedByPersonAlias = null;
                    eventItem.ApprovedOnDateTime = null;
                }
                eventItem.Description = htmlDescription.Text;
                eventItem.Summary = tbSummary.Text;
                eventItem.DetailsUrl = tbDetailUrl.Text;

                int? orphanedImageId = null;
                if ( eventItem.PhotoId != imgupPhoto.BinaryFileId )
                {
                    orphanedImageId = eventItem.PhotoId;
                    eventItem.PhotoId = imgupPhoto.BinaryFileId;
                }

                // Remove any audiences that were removed in the UI
                foreach ( var eventItemAudience in eventItem.EventItemAudiences.Where( r => !AudiencesState.Contains( r.DefinedValueId ) ).ToList() )
                {
                    eventItem.EventItemAudiences.Remove( eventItemAudience );
                    eventItemAudienceService.Delete( eventItemAudience );
                }

                // Add or Update audiences from the UI
                foreach ( int audienceId in AudiencesState )
                {
                    EventItemAudience eventItemAudience = eventItem.EventItemAudiences.Where( a => a.DefinedValueId == audienceId ).FirstOrDefault();
                    if ( eventItemAudience == null )
                    {
                        eventItemAudience = new EventItemAudience();
                        eventItemAudience.DefinedValueId = audienceId;
                        eventItem.EventItemAudiences.Add( eventItemAudience );
                    }
                }

                // remove any calendar items that removed in the UI
                var calendarIds = new List<int>();
                calendarIds.AddRange( cblCalendars.SelectedValuesAsInt );
                var uiCalendarGuids = ItemsState.Where( i => calendarIds.Contains( i.EventCalendarId ) ).Select( a => a.Guid );
                foreach ( var eventCalendarItem in eventItem.EventCalendarItems.Where( a => !uiCalendarGuids.Contains( a.Guid ) ).ToList() )
                {
                    // Make sure user is authorized to remove calendar (they may not have seen every calendar due to security)
                    if ( UserCanEdit || eventCalendarItem.EventCalendar.IsAuthorized( Authorization.EDIT, CurrentPerson ) )
                    {
                        eventItem.EventCalendarItems.Remove( eventCalendarItem );
                        eventCalendarItemService.Delete( eventCalendarItem );
                    }
                }

                // Add or Update calendar items from the UI
                foreach ( var calendar in ItemsState.Where( i => calendarIds.Contains( i.EventCalendarId ) ) )
                {
                    var eventCalendarItem = eventItem.EventCalendarItems.Where( a => a.Guid == calendar.Guid ).FirstOrDefault();
                    if ( eventCalendarItem == null )
                    {
                        eventCalendarItem = new EventCalendarItem();
                        eventItem.EventCalendarItems.Add( eventCalendarItem );
                    }
                    eventCalendarItem.CopyPropertiesFrom( calendar );
                }

                if ( !eventItem.EventCalendarItems.Any() )
                {
                    validationMessages.Add( "At least one calendar is required." );
                }

                if ( !Page.IsValid )
                {
                    return;
                }

                if ( !eventItem.IsValid )
                {
                    // Controls will render the error messages
                    return;
                }

                if ( validationMessages.Any() )
                {
                    nbValidation.Text = "Please Correct the Following<ul><li>" + validationMessages.AsDelimited( "</li><li>" ) + "</li></ul>";
                    nbValidation.Visible = true;
                    return;
                }

                // use WrapTransaction since SaveAttributeValues does it's own RockContext.SaveChanges()
                rockContext.WrapTransaction( () =>
                {
                    rockContext.SaveChanges();
                    foreach ( EventCalendarItem eventCalendarItem in eventItem.EventCalendarItems )
                    {
                        eventCalendarItem.LoadAttributes();
                        Rock.Attribute.Helper.GetEditValues( phAttributes, eventCalendarItem );
                        eventCalendarItem.SaveAttributeValues();
                    }

                    if ( orphanedImageId.HasValue )
                    {
                        BinaryFileService binaryFileService = new BinaryFileService( rockContext );
                        var binaryFile = binaryFileService.Get( orphanedImageId.Value );
                        if ( binaryFile != null )
                        {
                            // marked the old images as IsTemporary so they will get cleaned up later
                            binaryFile.IsTemporary = true;
                            rockContext.SaveChanges();
                        }
                    }
                } );

                // Redirect back to same page so that item grid will show any attributes that were selected to show on grid
                var qryParams = new Dictionary<string, string>();
                if ( _calendarId.HasValue )
                {
                    qryParams["EventCalendarId"] = _calendarId.Value.ToString();
                }
                qryParams["EventItemId"] = eventItem.Id.ToString();
                NavigateToPage( RockPage.Guid, qryParams );
            }
        }
Пример #51
0
 /// <summary>
 ///   Add an HTML formatted section to <paramref name="sb" /> with data related to <paramref name="item" />.
 /// </summary>
 /// <param name="sb">The StringBuilder to add HTML data to.</param>
 /// <param name="item">The <see cref="EventItem" /> value specifying the error section to build.</param>
 private void AddEventSection(StringBuilder sb, EventItem item)
 {
     sb.AppendLine(ToHtmlParagraph(item, "gsp_event_h2"));
     sb.AppendLine(ToHtmlTable(item));
 }
Пример #52
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="eventItemId">The eventItem identifier.</param>
        public void ShowDetail( int eventItemId )
        {
            pnlEditDetails.Visible = false;

            EventItem eventItem = null;

            var rockContext = new RockContext();

            if ( !eventItemId.Equals( 0 ) )
            {
                eventItem = GetEventItem( eventItemId, rockContext );
                pdAuditDetails.SetEntity( eventItem, ResolveRockUrl( "~" ) );
            }

            if ( eventItem == null )
            {
                eventItem = new EventItem { Id = 0, IsActive = true, Name = "" };
                eventItem.IsApproved = _canApprove;
                var calendarItem = new EventCalendarItem { EventCalendarId = ( _calendarId ?? 0 ) };
                eventItem.EventCalendarItems.Add( calendarItem );
                // hide the panel drawer that show created and last modified dates
                pdAuditDetails.Visible = false;
            }

            eventItem.LoadAttributes( rockContext );

            FollowingsHelper.SetFollowing( eventItem, pnlFollowing, this.CurrentPerson );

            bool readOnly = false;
            nbEditModeMessage.Text = string.Empty;

            if ( !_canEdit )
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( EventItem.FriendlyTypeName );
            }
            else
            {
                if ( eventItem.Id != 0 && !eventItem.EventCalendarItems.Any( i => i.EventCalendarId == ( _calendarId ?? 0 ) ) )
                {
                    readOnly = true;
                }
            }

            if ( readOnly )
            {
                btnEdit.Visible = false;
                btnDelete.Visible = false;
                ShowReadonlyDetails( eventItem );
            }
            else
            {
                btnEdit.Visible = true;
                btnDelete.Visible = true;

                if ( !eventItemId.Equals( 0 ) )
                {
                    ShowReadonlyDetails( eventItem );
                }
                else
                {
                    ShowEditDetails( eventItem );
                }

            }
        }
Пример #53
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="eventItemId">The eventItem identifier.</param>
        public void ShowDetail( int eventItemId )
        {
            pnlEditDetails.Visible = false;

            EventItem eventItem = null;

            var rockContext = new RockContext();

            if ( !eventItemId.Equals( 0 ) )
            {
                eventItem = GetEventItem( eventItemId, rockContext );
            }

            if ( eventItem == null )
            {
                eventItem = new EventItem { Id = 0, IsActive = true, Name = "" };
                eventItem.IsApproved = _canApprove;
            }

            eventItem.LoadAttributes( rockContext );

            bool readOnly = false;
            nbEditModeMessage.Text = string.Empty;

            if ( !_canEdit )
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( EventItem.FriendlyTypeName );
            }
            else
            {
                if ( eventItem.Id != 0 && !eventItem.EventCalendarItems.Any( i => i.EventCalendarId == _calendarId ) )
                {
                    readOnly = true;
                }
            }

            if ( readOnly )
            {
                btnEdit.Visible = false;
                btnDelete.Visible = false;
                ShowReadonlyDetails( eventItem );
            }
            else
            {
                btnEdit.Visible = true;
                btnDelete.Visible = true;

                if ( !eventItemId.Equals( 0 ) )
                {
                    ShowReadonlyDetails( eventItem );
                }
                else
                {
                    ShowEditDetails( eventItem );
                }

            }
        }
        protected void ShowItemInForm(int index, EventItem card)
        {
            txtHiddenId.Value = index.ToString();
            txtEvent.Value = card.Description;
            txtEventTitle.Value = card.Title;
            txtEventStartDate.Value = card.Date.ToString("dd/MM/yyyy");

            if (card.Days > 1)
            {
                DateTime dateEnd;
                dateEnd = card.Date.AddDays((double)card.Days);
                txtEventEndDate.Value = dateEnd.ToString("dd/MM/yyyy");
            }
        }