public async Task<ActionResult> Export()
        {
            var userId = GetUserId();
            var context = this.DbContext;

            var filters = context.Filters
                .Include(o => o.FilterProperties)
                .Where(o => o.UserId == userId)
                .ToArray();

            if (!filters.Any())
                return RedirectToAction("Index");

            var filterComponent = new MessageFilterComponent();

            var document = filterComponent.ToXml(filters);

            var stream = new System.IO.MemoryStream();
            using (var writer = System.Xml.XmlWriter.Create(stream, new System.Xml.XmlWriterSettings
            {
                OmitXmlDeclaration = false,
                Indent = true
            }))
            {
                document.WriteTo(writer);
            }
            stream.Position = 0;

            await Task.Run(() => new TelemetryClient().TrackEvent("ExportFilter"));

            return File(stream, "text/xml", string.Format("Export_{0}.xml", DateTime.UtcNow.ToFileTime()));
        }
        private async Task<ActionResult> ImportContinue(ReviewViewModel viewModel)
        {
            System.Diagnostics.Debug.Assert(viewModel != null);

            var userId = GetUserId();

            var mongoDbComponent = new MongoDbComponent();
            var collection = mongoDbComponent.MessageFilters;

            //Pull down the file data.
            var messageFilter = await collection.FindOneByObjectIdUserIdAsync(viewModel.MessageFilterId, userId);
            if (messageFilter == null)
                return new HttpNotFoundResult("Could not find import file.");

            //Throw the selected entry ids into a hashset.
            var selectedEntries = viewModel.Entries
                .Where(o => o.IsSelected)
                .Select(o => o.EntryId)
                .ToHashSet();

            var context = this.DbContext;
            bool hasAdded = false;

            var dateCreatedUtc = DateTime.UtcNow;

            //Add it to the SQL server collection.
            var filterComponent = new MessageFilterComponent();
            foreach (var item in messageFilter.Entries)
            {
                var itemId = filterComponent.GetFilterIdPart(item.IdTag);
                if (!selectedEntries.Contains(itemId))
                    continue;

                context.Filters.Add(new GMailLabelCleanup.Data.Models.Filters.Filter
                {
                    UserId = userId,
                    ImportId = itemId,
                    Description = filterComponent.CreateDescription(item),
                    DateCreatedUtc = dateCreatedUtc,
                    FilterProperties = item.Properties.Select(o => new FilterProperty
                    {
                        IsIncluded = true,
                        Name = o.Name,
                        Value = o.Value,
                        DateCreatedUtc = dateCreatedUtc
                    }).ToList()
                });
                hasAdded = true;
            }

            if (hasAdded)
            {
                await context.SaveChangesAsync();
            }

            //Remove it from the MongoDb storage.
            await collection.RemoveAsync(messageFilter);

            return RedirectToAction("Index");
        }
        public async Task<ActionResult> ImportReview(string id)
        {
            if (string.IsNullOrEmpty(id))
                return new HttpNotFoundResult("Could not find import file.");

            var userId = GetUserId();

            var mongoDbComponent = new MongoDbComponent();
            var collection = mongoDbComponent.MessageFilters;

            //Pull down the file data.
            var messageFilter = await collection.FindOneByObjectIdUserIdAsync(id, userId);
            if (messageFilter == null)
                return new HttpNotFoundResult("Could not find import file.");

            var filterComponent = new MessageFilterComponent();

            var viewModel = new ReviewViewModel
            {
                MessageFilterId = messageFilter.Id.ToString(),
                Entries = messageFilter.Entries.Select(o => new ChooseMessageFilterEntryViewModel
                {
                    IsSelected = true,
                    EntryId = filterComponent.GetFilterIdPart(o.IdTag),
                    CriteriaProperties = filterComponent.GetCriteriaProperties(o.Properties).ToList(),
                    ActionProperties = filterComponent.GetActionProperties(o.Properties).ToList()
                }).ToList(),
                SelectAll = true
            };
            return View(viewModel);
        }
        public async Task<ActionResult> Import(ImportViewModel viewModel)
        {
            if (!ModelState.IsValid)
                return View(viewModel);

            XDocument document;
            try
            {
                document = XDocument.Load(viewModel.UploadFile.InputStream);
            }
            catch (Exception)
            {
                ModelState.AddModelError("UploadFile", "Received invalid XML.");
                return View(viewModel);
            }

            var userId = GetUserId();

            await Task.Run(() => new TelemetryClient().TrackEvent("ImportFilters"));

            //Use MongoDb to temporarily store instead of the session.
            var mongoDbComponent = new MongoDbComponent();
            var collection = mongoDbComponent.MessageFilters;

            var filterComponent = new MessageFilterComponent();
            var id = await collection.InsertAsync(filterComponent.FromXml(document, userId));

            return RedirectToAction("ImportReview", new { id = id });
        }
        private EditPropertyViewModel CreateEditPropertyViewModel(
            MessageFilterComponent component,
            FilterProperty existingProperty,
            string name
            )
        {
            System.Diagnostics.Debug.Assert(component != null);

            var isCheckType = component.GetIsBooleanProperty(name);

            return new EditPropertyViewModel
            {
                IsIncluded = existingProperty != null && existingProperty.IsIncluded,
                Id = existingProperty != null ? (int?)existingProperty.FilterPropertyId : null,
                Timestamp = existingProperty != null ? existingProperty.Timestamp : null,
                Name = name,
                Value = existingProperty != null ? existingProperty.Value : string.Empty,
                IsCheckType = isCheckType,
                IsChecked = isCheckType && existingProperty != null ? string.Equals(existingProperty.Value, "true", StringComparison.OrdinalIgnoreCase) : false
            };
        }
        private void InitializeEditProperties(EditViewModel viewModel, IList<FilterProperty> properties)
        {
            System.Diagnostics.Debug.Assert(viewModel != null);
            System.Diagnostics.Debug.Assert(properties != null);

            var component = new MessageFilterComponent();

            viewModel.CriteriaProperties = new List<EditPropertyViewModel>();
            viewModel.ActionProperties = new List<EditPropertyViewModel>();

            foreach (var pair in MessageFilterComponent.CriteriaPropertyNames)
            {
                var existingProperty = properties
                    .FirstOrDefault(o => o.Name == pair.Value);

                viewModel.CriteriaProperties.Add(CreateEditPropertyViewModel(component, existingProperty, pair.Value));
            }

            foreach (var pair in MessageFilterComponent.ActionPropertyNames)
            {
                var existingProperty = properties
                    .FirstOrDefault(o => o.Name == pair.Value);

                viewModel.ActionProperties.Add(CreateEditPropertyViewModel(component, existingProperty, pair.Value));
            }
        }