Exemplo n.º 1
0
        public IDictionary<ReleaseRepository, IEnumerable<GitLogEntity>> GetGitLog(IEnumerable<ReleaseRepository> repositories)
        {
            if (repositories.IsNullOrEmpty())
                return null;

            Log.DebugFormat("Starting connecting to Gerrit throught SSH");
            using (var sshClient = SshClientFactory())
            {
                sshClient.Connect();
                Log.DebugFormat("Connection to Gerrit established, starting executing command");

                var results = new ConcurrentDictionary<ReleaseRepository, IEnumerable<GitLogEntity>>();
                Parallel.ForEach(repositories, repository =>
                {
                    if (sshClient == null) return;

                    var command = string.Format(GitLogCommandTemplate, repository.Repository,
                        repository.ChangesFrom, repository.ChangesTo);
                    Log.DebugFormat("Executing command  [{0}]", command);

                    var result = sshClient.ExecuteCommand(command);

                    if (!string.IsNullOrWhiteSpace(result)
                        && !results.TryAdd(repository, GitLogParser.Parse(result)
                        .Where(x => x.CommitType == CommitType.Typical).ToArray())) { }

                    Log.DebugFormat("Finished executing command  [{0}]", command);
                });

                return results;
            }
        }
Exemplo n.º 2
0
        public Reference(int rowNum, IEnumerable<ReferenceFields> order, IEnumerable<string> values)
        {
            if (values.IsNullOrEmpty()) throw new ArgumentException("values");
            if (order.IsNullOrEmpty()) throw new ArgumentException("order");

            RowNum = rowNum;
            var vs = values.ToArray();
            var fs = order.ToArray();

            if (vs.Length != fs.Length) throw new InvalidOperationException();

            var fillErrors = new List<ReferenceFields>();

            for (var i = 0; i < vs.Length; i++)
            {
                try
                {
                    SetValue(fs[i], vs[i]);
                }
                catch
                {
                    fillErrors.Add(fs[i]);
                }
            }

            if (fillErrors.Any())
            {
                throw new Exception("Error reading following fields: {0}".
                    Fill(fillErrors.Cast<String>().CommaSeparated()));
            }
        }
Exemplo n.º 3
0
        public static void SetInvocationList(this EventInfo evt, Object host, IEnumerable<Delegate> chain)
        {
            var combo = chain.IsNullOrEmpty() ? null : 
                chain.Aggregate((agg, curr) => agg == null ? curr : Delegate.Combine(agg, curr));

            var f = evt.GetUnderlyingField().AssertNotNull();
            f.SetValue(host, combo);
        }
Exemplo n.º 4
0
        public ISignatureBuilder Append(IEnumerable<byte> bytes)
        {
            if (bytes.IsNullOrEmpty()) throw new ArgumentNullException("bytes");

            _bytes = _bytes.Concat(bytes);

            return this;
        }
        public string ExecuteMultipartQuery(ITwitterQuery twitterQuery, string contentId, IEnumerable<byte[]> binaries)
        {
            if (binaries.IsNullOrEmpty())
            {
                return ExecuteQuery(twitterQuery);
            }

            return _webRequestExecutor.ExecuteMultipartQuery(twitterQuery, contentId, binaries);
        }
        public void IsNullOrEmpty_ThreeItemsCollection_ReturnsFalse(IEnumerable<object> threeItemsEnumerable)
        {
            // arrange

            // act

            // assert
            Assert.False(threeItemsEnumerable.IsNullOrEmpty());
        }
Exemplo n.º 7
0
        public string GetTweetsQuery(IEnumerable<long> tweetIds)
        {
            if (tweetIds.IsNullOrEmpty())
            {
                return null;
            }

            var idsParameter = string.Join("%2C", tweetIds);
            return string.Format(Resources.Tweet_Lookup, idsParameter);
        }
Exemplo n.º 8
0
        public Params(IEnumerable<string> args, TextWriter outputWriter)
        {
            _outputWriter = outputWriter;

            var showHelp = false;
            var p = new OptionSet
                        {
                            { "s|source=", "Source Word document (*.doc[x] file)", v => SourceFile = v },
                            { "d|destination=", "Processed document name", v => DestFile = v },
                            { "r|references=", "References spreadsheet (*.xls[x] file)", v => RefFile = v },
                            { "o|order=", "Sort order for references (alpha|mention)", v => Order = v.GetEnumValueOrDefault<ReferenceOrder>() },
                            { "h|help", "Show this message and exit", v => showHelp = (v != null) }
                        };

            if (args.IsNullOrEmpty())
            {
                showHelp = true;
            }
            else
            {
                try
                {
                    p.Parse(args);
                }
                catch (OptionException e)
                {
                    WriteMessage(e.Message);
                    Ready = false;
                    return;
                }
            }

            if (showHelp)
            {
                ShowHelp(p);
                Ready = false;
                return;
            }

            var noSource = SourceFile.IsNullOrBlank();
            var noRef = RefFile.IsNullOrBlank();

            if (noSource || noRef)
            {
                if (noSource) WriteMessage("Source file not specified");
                if (noRef) WriteMessage("Reference file not specified");
                Ready = false;
                return;
            }

            if (DestFile.IsNullOrBlank()) DestFile = GetDestinationFileName(SourceFile);

            Ready = true;
        }
Exemplo n.º 9
0
        public static bool ContainsAny(this string target, IEnumerable<string> strings)
        {
            if (target.IsNullOrEmpty() || strings.IsNullOrEmpty())
                return false;

            foreach (var s in strings)
            {
                if (target.Contains(s))
                    return true;
            }

            return false;
        }
		/// <summary>
		/// Formats the specified list of <see cref="ICommandLineParserError"/> to a <see cref="System.String"/> suitable for the end user.
		/// </summary>
		/// <param name="parserErrors">The errors to format.</param>
		/// <returns>A <see cref="System.String"/> describing the specified errors.</returns>
		public string Format(IEnumerable<ICommandLineParserError> parserErrors)
		{
			if (parserErrors.IsNullOrEmpty()) return null;

			var builder = new StringBuilder();

			foreach (var error in parserErrors)
			{
				builder.AppendLine(Format(error));
			}

			return builder.ToString();
		}
Exemplo n.º 11
0
        public void AddCheckListQuestions(IEnumerable<BusinessCheckListQuestion> questions, Guid releaseWindowId)
        {
            if (questions.IsNullOrEmpty())
                return;

            CheckListQuestionRepository.Insert(questions
                .Select(x => new CheckListQuestion
                {
                    Content = x.Question,
                    ExternalId = x.ExternalId
                }));

            AssociateCheckListQuestionWithPackage(questions, releaseWindowId);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Converts a LinkCategoryCollection into a single LinkCategory with its own LinkCollection.
        /// </summary>
        public static LinkCategory MergeLinkCategoriesIntoSingleLinkCategory(string title, CategoryType catType,
                                                                             IEnumerable<LinkCategory> links,
                                                                             BlogUrlHelper urlHelper, Blog blog)
        {
            if (!links.IsNullOrEmpty())
            {
                var mergedLinkCategory = new LinkCategory { Title = title };

                var merged = from linkCategory in links
                             select GetLinkFromLinkCategory(linkCategory, catType, urlHelper, blog);
                mergedLinkCategory.Links.AddRange(merged);
                return mergedLinkCategory;
            }

            return null;
        }
Exemplo n.º 13
0
        private void PrintMethods(IEnumerable<MethodInfo> methods, string[] importedNamespaces)
        {
            if (!methods.IsNullOrEmpty())
            {
                _console.WriteLine("** Methods **");
                foreach (var method in methods)
                {
                    var methodParams = method.GetParametersWithoutExtensions()
                        .Select(p => string.Format("{0} {1}", GetPrintableType(p.ParameterType, importedNamespaces), p.Name));
                    var methodSignature = string.Format(" - {0} {1}({2})", GetPrintableType(method.ReturnType, importedNamespaces), method.Name,
                        string.Join(", ", methodParams));

                    _console.WriteLine(methodSignature);
                }
                _console.WriteLine();
            }
        }
        /// <summary>
        /// The map from.
        /// </summary>
        /// <param name="userBlogs">
        /// The userBlogs.
        /// </param>
        /// <returns>
        /// The mapped blog user page view model.
        /// </returns>
        public BlogUserPageViewModel MapFrom(IEnumerable<Blog> userBlogs)
        {
            var model = new BlogUserPageViewModel
                {
                    Blogs = userBlogs
                        .ToList()
                        .MapAllUsing(this.blogSummaryViewModelMapper)
                        .OrderByDescending(x => x.CreationDate, new StringDateComparer())
                };

            if (!userBlogs.IsNullOrEmpty())
            {
                model.Author = userBlogs.First().Author.Username;
            }

            return model;
        }
        /// <summary>
        /// The map from.
        /// </summary>
        /// <param name="blogPosts">
        /// The input.
        /// </param>
        /// <returns>
        /// The mapped blog post archive page view model.
        /// </returns>
        public BlogPostArchivePageViewModel MapFrom(IEnumerable<BlogPost> blogPosts)
        {
            var model = new BlogPostArchivePageViewModel
                {
                    Results = blogPosts
                    .MapAllUsing(this.blogPostSummaryPageViewModelMapper)
                    .OrderByDescending(x => x.PostDate, new StringDateComparer()).ToList()
                };

            if (!blogPosts.IsNullOrEmpty())
            {
                var blog = blogPosts.First().Blog;
                model.ArchiveSectionViewModel = this.archiveSectionViewModelMapper.MapFrom(blog);
            }

            return model;
        }
Exemplo n.º 16
0
        public JsonResult Save(HeroModel model, IEnumerable<HttpPostedFileBase> images) 
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var hero = new Hero();
                    var photos = new List<IPostedFile>();
                    Mapper.Map(model, hero);

                    if (!images.IsNullOrEmpty())
                    {
                        foreach (var image in images)
                        {
                            if (image.ContentLength > 0)
                            {
                                var file = new PostedFile(image);
                                if (image.FileName.Equals(model.Thumbnail, StringComparison.OrdinalIgnoreCase))
                                {
                                    file.Attributes.Add("IsThumbnail", "1");
                                }
                                file.Attributes.Add("FileName", string.Concat(Guid.NewGuid(), Path.GetExtension(image.FileName)));
                                photos.Add(file);
                            }
                        }
                    }
                    hero.UpdatedBy = AppUser.UserId;
                    if (model.IsNew)
                    {
                        hero.LanguageId = AppUser.LanguageId;
                        hero.HeroId = _heroRepository.CreateHero(hero, photos);
                    }
                    else
                    {
                        _heroRepository.UpdateHero(hero, photos);
                    }
                    return Json(new { Ok = true, HeroId = hero.HeroId });
                }
                catch (Exception)
                {                    
                }
            }
            return Json(new {Ok = false});
        }
Exemplo n.º 17
0
        public void AssociateCheckListQuestionWithPackage(IEnumerable<BusinessCheckListQuestion> questions, Guid releaseWindowId)
        {
            if (questions.IsNullOrEmpty())
                return;

            var window = ReleaseWindowRepository.GetSatisfiedBy(w => w.ExternalId == releaseWindowId);
            if (window == null)
                throw new EntityNotFoundException(typeof(ReleaseWindow), releaseWindowId);

            var packageIds = window.ReleaseProducts.Select(x => x.ProductId).ToArray();

            var questionExternalIds = questions.Select(x => x.ExternalId).ToArray();

            var dataQuestions = CheckListQuestionRepository
                .GetAllSatisfiedBy(c => questionExternalIds.Any(id => id == c.ExternalId))
                .ToArray();

            var questionsToAdd = packageIds.SelectMany(x => dataQuestions, (id, q) => new {PackageId = id, Question = q})
                .Where(x => !CheckListQuestionToProductRepository.Entities
                    .Any(c => c.ProductId == x.PackageId && c.CheckListQuestionId == x.Question.CheckListQuestionId))
                .Select(x => new CheckListQuestionToProduct
                {
                    ProductId = x.PackageId,
                    CheckListQuestionId = x.Question.CheckListQuestionId,
                })
                .ToArray();

            CheckListQuestionToProductRepository.Insert(questionsToAdd);

            var checkListItemsToAdd = (from bq in questions
                join dq in dataQuestions on bq.ExternalId equals dq.ExternalId
                where window.CheckList.All(x => x.CheckListQuestionId != dq.CheckListQuestionId)
                select new CheckList
                {
                    ExternalId = bq.CheckListId,
                    ReleaseWindowId = window.ReleaseWindowId,
                    CheckListQuestionId = dq.CheckListQuestionId,
                }).ToArray();

            CheckListRepository.Insert(checkListItemsToAdd);
        }
Exemplo n.º 18
0
    public bool HasUniqueKey(IEnumerable<string> keyNames)
    {
        Assert.IsTrue(!keyNames.IsNullOrEmpty(), "No key name");
        Assert.IsTrue(!keyNames.HasDuplication(), string.Format("Has duplicated keys in {0} \n {1}", filePath, keyNames.ToStringList(", ")));
        Assert.IsTrue(keyNames.All(x => columnInfo.ContainsKey(x)), string.Format("Has unknown key in {0} \n {1}", filePath, keyNames.ToStringList(", ")));

        var tempList = new List<RowData>(rows);
        return rows.All(delegate(RowData currRow)
        {
            bool result = tempList.Remove(currRow);
            Assert.IsTrue(result);
            IEnumerable<int> indexes = (from key in keyNames select columnInfo.IndexOf(key));
            bool notHaveSameKey = tempList.TrueForAll(x => !currRow.HasSameValueInAll(x, indexes));
            if (!notHaveSameKey)
            {
                List<RowData> errDatas = tempList.FindAll(x => currRow.HasSameValueInAll(x, indexes));
                Debug.LogError((from row in errDatas select row.Dump().RemoveWhiteSpace()).ToStringList("\n"));
            }
            return notHaveSameKey;
        });
    }
 /// <summary>
 /// 判断非null,非空枚举器
 /// </summary>
 /// <param name="value">要判断的字典</param>
 /// <returns>判断结果,null或空枚举器返回true,否则返回false</returns>
 public static bool IsNotNullOrEmpty(this IEnumerable value)
 {
     return(!value.IsNullOrEmpty());
 }
Exemplo n.º 20
0
        internal void CreateAssemblyPolicies()
        {
            // -----------------------------------------------------------------------------------------------------------------------------------
            // Step 5 : Build Assembly Manifests, catalog files and policy files
            var policyRule = Source.CompatabilityPolicyRules.FirstOrDefault();
            if (policyRule == null) {
                return;
            }

            // figure out what major/minor versions we need are overriding.
            var minimum = (FourPartVersion)policyRule["minimum"].Value;
            var maximum = (FourPartVersion)policyRule["maximum"].Value;

            if (minimum != 0 && maximum == 0) {
                maximum = Version - 1;
            }

            _versionRedirects = policyRule["versions"].Values.Select(each => (TwoPartVersion)each);

            if (_versionRedirects.IsNullOrEmpty()) {
                // didn't specify versions explicitly.
                // we can check for overriding versions.
                // TODO: SOON
            }

            if (maximum > 0L) {
                BindingPolicy = new BindingPolicy {
                    Minimum = minimum,
                    Maximum = maximum
                };

                CreateNativeAssemblyPolicies();
                CreateManagedAssemblyPolicies();
            }
        }
        public void CreateZipFile()
        {
            try
            {
                if (_accountIds.IsNullOrEmpty())
                {
                    return;
                }
                var corporateAccounts = _corporateAccountRepository.GetByIds(_accountIds);
                foreach (var account in corporateAccounts)
                {
                    try
                    {
                        _logger.Info(string.Format("Creating zip for accountId {0} and account tag {1}. ", account.Id, account.Tag));

                        var fileName = account.FolderName.Replace("_", "") + "_DATA_" + DateTime.Today.ToString("MMyydd");

                        var sourceFile      = string.Format(_optumZipFolderDownloadFromPath, account.FolderName);
                        var destinationPath = string.Format(_optumZipFolderPostToPath, account.FolderName);

                        if (_monarchAccountIds.Contains(account.Id))
                        {
                            destinationPath = string.Format(_monarchZipFolderPath, account.FolderName);
                            fileName        = account.FolderName + "_DATA_" + DateTime.Today.ToString("yyyyMMdd");
                        }

                        _logger.Info("Destination Path:" + destinationPath);

                        if (!DirectoryOperationsHelper.IsDirectoryExist(destinationPath))
                        {
                            Directory.CreateDirectory(destinationPath);
                        }

                        var destinationfile = destinationPath + "\\" + fileName + ".zip";

                        if (DirectoryOperationsHelper.IsFileExist(destinationfile))
                        {
                            DirectoryOperationsHelper.Delete(destinationfile);
                        }

                        var directoryToDeleteFrom = new DirectoryInfo(destinationPath);

                        if (_monarchAccountIds.Contains(account.Id))
                        {
                            var zipFiles = directoryToDeleteFrom.GetFiles(account.FolderName + "_DATA_*.zip");

                            foreach (var file in zipFiles)
                            {
                                _logger.Info("Deleting zip file : " + file.Name);
                                file.Delete();
                            }
                        }
                        else
                        {
                            var fileNotToBeDelete = GetFileNotDeleted();

                            var zipFiles = directoryToDeleteFrom.GetFiles(account.FolderName.Replace("_", "") + "_DATA_*.zip");

                            foreach (var file in zipFiles)
                            {
                                if (fileNotToBeDelete.Any(x => file.Name.EndsWith(x)))
                                {
                                    continue;
                                }

                                _logger.Info("Deleting zip file : " + file.Name);
                                file.Delete();
                            }
                        }

                        _zipHelper.CreateZipFiles(sourceFile, destinationfile, true);


                        if (_monarchAccountIds.Contains(account.Id))
                        {
                            var sftpCridential = _sftpCridentialManager.Deserialize(_sftpResouceFilePath + account.Tag + ".xml");

                            try
                            {
                                ExportResultInSftp(fileName + ".zip", destinationfile, sftpCridential);
                            }
                            catch (Exception exception)
                            {
                                _logger.Error("message: " + exception.Message);
                                _logger.Error("stack trace: " + exception.StackTrace);
                            }

                            var archiveDestinationPath = string.Format(_monarchResultPdfArchive, account.FolderName);

                            DirectoryOperationsHelper.CreateDirectoryIfNotExist(archiveDestinationPath + "\\pdfs\\");

                            var sourceDir      = new DirectoryInfo(sourceFile + "/pdfs/");
                            var destinationDir = new DirectoryInfo(archiveDestinationPath + "\\pdfs\\");

                            DeepCopy(sourceDir, destinationDir);
                            Directory.Delete(sourceFile + "/pdfs/", true);
                        }

                        _logger.Info("Zip File Created");
                    }
                    catch (Exception ex)
                    {
                        _logger.Error("Some Error occurred for Account Id " + account.Id + " Account Tag " + account.Tag);
                        _logger.Error("Message " + ex.Message);
                        _logger.Error("Stack Trace " + ex.StackTrace);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Some Error occurred ");
                _logger.Error("Message " + ex.Message);
                _logger.Error("Stack Trace " + ex.StackTrace);
            }
        }
Exemplo n.º 22
0
 public static string Implode <T>(this IEnumerable <T> values, string delimiter)
 {
     return(values.IsNullOrEmpty()
         ? String.Empty
         : String.Join(delimiter, values.Select(v => v.ToString()).ToArray()));
 }
Exemplo n.º 23
0
        public async Task <IActionResult> OnGet(IEnumerable <int> versions, string calculationId)
        {
            if (string.IsNullOrWhiteSpace(calculationId))
            {
                return(new BadRequestObjectResult(ErrorMessages.CalculationIdNullOrEmpty));
            }

            Guard.ArgumentNotNull(versions, nameof(versions));
            if (versions.Count() != 2)
            {
                return(new BadRequestObjectResult("Two versions not requested"));
            }

            ApiResponse <Calculation> calculationResponse = await _calcClient.GetCalculationById(calculationId);

            if (calculationResponse == null || calculationResponse.StatusCode == HttpStatusCode.NotFound)
            {
                return(new NotFoundObjectResult(ErrorMessages.CalculationNotFoundInCalcsService));
            }

            Calculation calculation = calculationResponse.Content;

            CalculationName       = calculation.Name;
            CalculationPeriodName = calculation.FundingPeriodName;
            CalculationId         = calculation.Id;

            ApiResponse <Clients.SpecsClient.Models.CalculationCurrentVersion> specCalculation = await _specsClient.GetCalculationById(calculation.SpecificationId, calculation.CalculationSpecification.Id);

            if (specCalculation == null || specCalculation.StatusCode == HttpStatusCode.NotFound)
            {
                return(new NotFoundObjectResult(ErrorMessages.CalculationNotFoundInSpecsService));
            }

            CalculationDescription = specCalculation.Content.Description;

            ApiResponse <IEnumerable <CalculationVersion> > calculationVersionsResponse = await _calcClient.GetMultipleVersionsByCalculationId(versions, calculationId);

            if (calculationVersionsResponse == null || calculationVersionsResponse.StatusCode != HttpStatusCode.OK)
            {
                throw new InvalidOperationException($"Unable to retreive selected versions of calculations. Status Code = {calculationVersionsResponse?.StatusCode}");
            }

            if (calculationVersionsResponse.StatusCode == HttpStatusCode.OK)
            {
                IEnumerable <CalculationVersion> calculationVersions = calculationVersionsResponse.Content;

                if (calculationVersions.IsNullOrEmpty())
                {
                    throw new InvalidOperationException($"Unable to retrieve calculationVersion model from the response. Calculation version value = {calculationVersions.ToString()}");
                }
                else
                {
                    if (calculationVersions.Count() < 2)
                    {
                        throw new InvalidOperationException($"There are less than two previous versions available. Calculation version count ={calculationVersions.Count()}");
                    }

                    List <CalculationVersion> calculationVersionsList = calculationVersions.OrderBy(c => c.Version).ToList();

                    LeftCalcualationDiffModel = _mapper.Map <CalculationVersionViewModel>(calculationVersionsList[0]);
                    RightCalculationDiffModel = _mapper.Map <CalculationVersionViewModel>(calculationVersionsList[1]);
                }
            }

            return(Page());
        }
Exemplo n.º 24
0
        public async Task ProcessMessages()
        {
            isActive = true;
            bool connected = true;

            using (tcpClient)
                using (var buffer = new Buffer())
                    using (networkStream)
                    {
                        var byteBuffer = new byte[tcpClient.ReceiveBufferSize];

                        while (connected && tcpClient.Connected && !cancellationToken.IsCancellationRequested)
                        {
                            Exception exToHandle = null;
                            try
                            {
                                do
                                {
                                    int bytes = await networkStream.ReadAsync(byteBuffer, 0, byteBuffer.Length);

                                    if (bytes == 0)
                                    {
                                        // Still there?
                                        // ns.Write(Constants.CRLF, 0, 2);
                                        connected = false;
                                        break;
                                    }
                                    else
                                    {
                                        buffer.Push(byteBuffer, bytes);
                                    }
                                }while (networkStream.DataAvailable && !cancellationToken.IsCancellationRequested);

                                if (!connected)
                                {
                                    break;
                                }

                                IEnumerable <Message> messages = buffer.GetMessages();
                                if (!messages.IsNullOrEmpty())
                                {
                                    var awaitables = new List <Task>();
                                    foreach (Message message in messages)
                                    {
                                        if (cancellationToken.IsCancellationRequested)
                                        {
                                            break;
                                        }
                                        var messageWriter  = new MessageWriter(networkStream);
                                        var messageHandler = new MessageHandler(containerManager, jobManager, cancellationToken, messageWriter);
                                        awaitables.Add(messageHandler.Handle(message));
                                    }
                                    await Task.WhenAll(awaitables);

                                    log.Trace("Processed '{0}' message tasks.", awaitables.Count);
                                }
                            }
                            catch (Exception exception)
                            {
                                var  socketExceptionHandler = new SocketExceptionHandler(exception);
                                bool exceptionHandled       = socketExceptionHandler.Handle();
                                if (!exceptionHandled)
                                {
                                    exToHandle = exception;
                                }
                            }

                            if (exToHandle != null)
                            {
                                var messageWriter          = new MessageWriter(networkStream);
                                var wardenExceptionHandler = new WardenExceptionHandler(log, exToHandle, messageWriter);
                                await wardenExceptionHandler.HandleAsync();
                            }
                        }

                        MarkAsDisconnected();
                    }
        }
Exemplo n.º 25
0
        private EventListGmsListModel GetEventListGmsModel(IEnumerable <Event> eventList)
        {
            if (eventList.IsNullOrEmpty())
            {
                return(null);
            }

            var listModel = new EventListGmsListModel();
            var dataModel = new List <EventListGmsModel>();
            var eventIds  = eventList.Select(x => x.Id);
            var hosts     = _hostRepository.GetEventHosts(eventIds);
            var eventIdCorporateNamePairs = _corporateAccountRepository.GetEventIdCorporateAccountNamePair(eventIds);

            var eventAppointmentStats = _eventAppointmentStatsService.GetStats(eventList);

            foreach (var @event in eventList)
            {
                var     eventListGmsModel = new EventListGmsModel();
                Address eventAddress      = new Address();
                var     eventId           = @event.Id;

                //var slotsForCurrentEvent = eventSchedulingSlots.Where(x => x.EventId == eventId);
                //var availableSlots = slotsForCurrentEvent.Count(x => x.Status != AppointmentStatus.Blocked && x.Status != AppointmentStatus.Booked);

                var appointmentStats = eventAppointmentStats.FirstOrDefault(x => x.EventId == eventId);
                var availableSlots   = 0;
                if (appointmentStats == null)
                {
                    continue;
                }

                availableSlots = appointmentStats.FreeSlots;

                var host = hosts.SingleOrDefault(x => x.Id == @event.HostId);

                if (availableSlots == 0)
                {
                    continue;
                }
                if (host == null)
                {
                    continue;
                }
                eventAddress = host.Address;

                eventListGmsModel.EventId        = @event.Id;
                eventListGmsModel.EventDate      = @event.EventDate.ToString("MM/dd/yyyy");
                eventListGmsModel.HealthPlanName = eventIdCorporateNamePairs.Where(x => x.FirstValue == @event.Id).Select(x => x.SecondValue).Single();
                eventListGmsModel.TotalSlots     = appointmentStats.TotalSlots;
                eventListGmsModel.AvailableSlots = availableSlots;

                eventListGmsModel.EventAddressStreet12 = eventAddress.StreetAddressLine1 + "" + eventAddress.StreetAddressLine2;
                eventListGmsModel.EventCity            = eventAddress.City;
                eventListGmsModel.EventStateName       = eventAddress.State;
                eventListGmsModel.EventZipCode         = eventAddress.ZipCode.ToString();
                eventListGmsModel.HostId = host.Id;

                //eventListGmsModel.EventLocation = eventAddress.ToString();
                dataModel.Add(eventListGmsModel);
            }
            listModel.Collection = dataModel;
            return(listModel);
        }
Exemplo n.º 26
0
 public static bool HasValues <T>(this IEnumerable <T> enumerable)
 {
     return(!enumerable.IsNullOrEmpty());
 }
Exemplo n.º 27
0
 public static IEnumerable <TSource> Data <TSource>(this IEnumerable <TSource> source)
 {
     return(source.IsNullOrEmpty() ? new List <TSource>() : source);
 }
Exemplo n.º 28
0
 public static string ContentsToString <T>(this IEnumerable <T> self)
 {
     return(self.IsNullOrEmpty() ? "[]" : "[" + self.Select(each => object.Equals(each, default(T)) ? "null" : each.ToString()).Aggregate((result, each) => result + ", " + each) + "]");
 }
Exemplo n.º 29
0
        /// <summary>
        /// 数据列表加载额外的对象数据
        /// </summary>
        /// <param name="datas">数据信息</param>
        /// <param name="query">查询对象</param>
        List <ExecuteLog> LoadOtherObjectData(IEnumerable <ExecuteLog> datas, IQuery query)
        {
            #region 参数判断

            if (datas.IsNullOrEmpty())
            {
                return(new List <ExecuteLog>(0));
            }
            if (query == null || query.LoadPropertys == null || query.LoadPropertys.Count <= 0)
            {
                return(datas.ToList());
            }

            #endregion

            #region  务信息

            List <ServerNode> serverList = null;
            if (query.AllowLoad <ExecuteLog>(c => c.Server))
            {
                List <string> serverIds = datas.Select(c => c.Server?.Id).Distinct().ToList();
                serverList = serverNodeService.GetServerNodeList(serverIds);
            }

            #endregion

            #region 工作信息

            List <Job> jobList = null;
            if (query.AllowLoad <ExecuteLog>(c => c.Job))
            {
                List <string> jobIds = datas.Select(c => c.Job?.Id).Distinct().ToList();
                jobList = jobService.GetJobList(jobIds);
            }

            #endregion

            #region 执行计划

            List <Trigger> triggerList = null;
            if (query.AllowLoad <ExecuteLog>(c => c.Trigger))
            {
                List <string> triggerIds = datas.Select(c => c.Trigger?.Id).Distinct().ToList();
                triggerList = triggerService.GetTriggerList(triggerIds);
            }

            #endregion

            foreach (var log in datas)
            {
                if (!serverList.IsNullOrEmpty())
                {
                    log.SetServer(serverList.FirstOrDefault(c => c.Id == log.Server?.Id));
                }
                if (!jobList.IsNullOrEmpty())
                {
                    log.SetJob(jobList.FirstOrDefault(c => c.Id == log.Job?.Id));
                }
                if (!triggerList.IsNullOrEmpty())
                {
                    log.SetTrigger(triggerList.FirstOrDefault(c => c.Id == log.Trigger?.Id));
                }
            }
            return(datas.ToList());
        }
    public static void Main()
    {
        IEnumerable <string> en = GetSomeStrings();

        Console.WriteLine(en.IsNullOrEmpty() ? "true" : "false");
    }
Exemplo n.º 31
0
        public void ShouldBeTrueWhenListIsNull()
        {
            var result = _list.IsNullOrEmpty();

            Assert.IsTrue(result);
        }
Exemplo n.º 32
0
        /// <summary>
        /// Select implementation. The public method automatically remaps a selector with the knowledge
        /// that the context is external (and not part of a chain)
        /// </summary>
        ///
        /// <exception cref="ArgumentNullException">
        /// Thrown when one or more required arguments are null.
        /// </exception>
        ///
        /// <param name="context">
        /// The context in which the selector applies. If null, the selector is run against the entire
        /// Document. If not, the selector is run against this sequence of elements.
        /// </param>
        ///
        /// <returns>
        /// A list of elements. This method returns a list (rather than a sequence) because the sequence
        /// must be enumerated to ensure that end-users don't cause the selector to be rerun repeatedly,
        /// and that the values are not mutable (e.g. if the underlying source changes).
        /// </returns>

        public IList<IDomObject> Select(IEnumerable<IDomObject> context)
        {
            // this holds the final output

            HashSet<IDomObject> output = new HashSet<IDomObject>();

            if (Selector == null )
            {
                throw new ArgumentNullException("The selector cannot be null.");
            }

            if (Selector.Count == 0)
            {
                return EmptyEnumerable().ToList();
            }

            ActiveSelectors = new List<SelectorClause>(Selector);

            // First just check if we ended up here with an HTML selector; if so, hand it off.
            
            var firstSelector = ActiveSelectors[0];
            if (firstSelector.SelectorType == SelectorType.HTML)
            {
                return CsQuery.Implementation.
                    DomDocument.Create(firstSelector.Html, HtmlParsingMode.Fragment)
                        .ChildNodes
                        .ToList();
            } 

            // this holds any results that carried over from the previous loop for chaining

            IEnumerable<IDomObject> lastResult = null;

            // this is the source from which selections are made in a given iteration; it could be the DOM
            // root, a context, or the previous result set. 
            
            IEnumerable<IDomObject> selectionSource=null;

            // Disable the index if there is no context (e.g. disconnected elements)
            // or if the first element is not indexed, or the context is not from the same
            // document as this selector is bound.

            bool useIndex = context.IsNullOrEmpty() || 
                (!context.First().IsDisconnected && context.First().IsIndexed && context.First().Document==Document);


            for (activeSelectorId = 0; activeSelectorId < ActiveSelectors.Count; activeSelectorId++)
            {

                var selector = ActiveSelectors[activeSelectorId].Clone();

                if (lastResult != null && 
                    (selector.CombinatorType == CombinatorType.Root || selector.CombinatorType == CombinatorType.Context))
                {
                    // we will alter the selector during each iteration to remove the parts that have already been
                    // parsed, so use a copy. This is a selector that was chained with the selector grouping
                    // combinator "," -- we always output the results so far when beginning a new group. 
                    
                    output.AddRange(lastResult);
                    lastResult = null;
                }

                // For "and" combinator types, we want to leave everything as it was -- the results of this
                // selector should compound with the prior. This is not an actual CSS combinator, this is the
                // equivalent of grouping parenthesis. That is, in CSS there's no way to say "(input[submit],
                // button):visible" - that is group the results on selector part and apply a filter to it. But
                // we need to do exactly this for certain selector types (for example the jQuery :button
                // selector). 

                if (selector.CombinatorType != CombinatorType.Grouped)
                {

                    selectionSource = GetSelectionSource(selector, context, lastResult);
                    lastResult = null;
                }
                
                string key = "";
                SelectorType removeSelectorType = 0;

                if (useIndex && !selector.NoIndex)
                {

#if DEBUG_PATH

                    if (selector.SelectorType.HasFlag(SelectorType.AttributeValue) 
                        && selector.AttributeSelectorType != AttributeSelectorType.NotExists
                        && selector.AttributeSelectorType != AttributeSelectorType.NotEquals)
                    {
                        key = "!" + selector.AttributeName.ToLower();

                        // AttributeValue must still be matched manually - so remove this flag only if the
                        // selector is conclusive without further checking
                        
                        if (selector.AttributeSelectorType == AttributeSelectorType.Exists)
                        {
                            removeSelectorType = SelectorType.AttributeValue;
                        }
                    }
                    else if (selector.SelectorType.HasFlag(SelectorType.Tag))
                    {
                        key = "+"+selector.Tag.ToLower();
                        removeSelectorType=SelectorType.Tag;
                    }
                    else if (selector.SelectorType.HasFlag(SelectorType.ID))
                    {
                        key = "#" + selector.ID;
                        removeSelectorType=SelectorType.ID;
                    }
                    else if (selector.SelectorType.HasFlag(SelectorType.Class))
                    {
                        key = "." + selector.Class;
                        removeSelectorType=SelectorType.Class;
                    }

#else
                    // We don't want to use the index for "NotEquals" selectors because a missing attribute
                    // is considered a valid match
                    
                    if (selector.SelectorType.HasFlag(SelectorType.AttributeValue)
                        && selector.AttributeSelectorType != AttributeSelectorType.NotExists
                        && selector.AttributeSelectorType != AttributeSelectorType.NotEquals)
                    {
                        key = "!" + (char)HtmlData.Tokenize(selector.AttributeName);

                        // AttributeValue must still be matched manually - so remove this flag only if the
                        // selector is conclusive without further checking
                        
                        if (selector.AttributeSelectorType == AttributeSelectorType.Exists)
                        {
                            removeSelectorType = SelectorType.AttributeValue;
                        }
                    }
                    else if (selector.SelectorType.HasFlag(SelectorType.Tag))
                    {
                        key = "+" + (char)HtmlData.Tokenize(selector.Tag);
                        removeSelectorType=SelectorType.Tag;
                    }
                    else if (selector.SelectorType.HasFlag(SelectorType.ID))
                    {
                        key = "#" + (char)HtmlData.TokenizeCaseSensitive(selector.ID);
                        removeSelectorType=SelectorType.ID;
                    }
                    else if (selector.SelectorType.HasFlag(SelectorType.Class))
                    {
                        key = "." + (char)HtmlData.TokenizeCaseSensitive(selector.Class);
                        removeSelectorType=SelectorType.Class;
                    }
#endif
                }

                // If part of the selector was indexed, key will not be empty. Return initial set from the
                // index. If any selectors remain after this they will be searched the hard way.

                IEnumerable<IDomObject> result = null;

                if (key != String.Empty)
                {
                    // This is the main index access point: if we have an index key, we'll get as much as we can from the index.
                    // Anything else will be handled manually.

                    int depth = 0;
                    bool descendants = true;
                    
                    switch (selector.TraversalType)
                    {
                        case TraversalType.Child:
                            depth = selector.ChildDepth;
                            descendants = false;
                            break;
                        case TraversalType.Filter:
                        case TraversalType.Adjacent:
                        case TraversalType.Sibling:
                            depth = 0;
                            descendants = false;
                            break;
                        case TraversalType.Descendent:
                            depth = 1;
                            descendants = true;
                            break;
                        // default: fall through with default values set above.
                    }
       
                    if (selectionSource == null)
                    {
                        result = Document.DocumentIndex.QueryIndex(key + HtmlData.indexSeparator, depth, descendants);
                    }
                    else
                    {
                        HashSet<IDomObject> elementMatches = new HashSet<IDomObject>();
                        result = elementMatches;

                        foreach (IDomObject obj in selectionSource)
                        {
                            elementMatches.AddRange(Document.DocumentIndex.QueryIndex(key + HtmlData.indexSeparator + obj.Path,
                                    depth, descendants));
                        }
                    }

                    selector.SelectorType &= ~removeSelectorType;

                    // Special case for attribute selectors: when Attribute Value attribute selector is present, we
                    // still need to filter for the correct value afterwards. But we need to change the traversal
                    // type because any nodes with the correct attribute type have already been selected. 
                    
                    if (selector.SelectorType.HasFlag(SelectorType.AttributeValue))
                    {
                        selector.TraversalType = TraversalType.Filter;
                    }
                    
                }
                else if (selector.SelectorType.HasFlag(SelectorType.Elements))
                {
                    HashSet<IDomObject> elementMatches = new HashSet<IDomObject>();
                    result = elementMatches;
                    foreach (IDomObject obj in GetAllChildOrDescendants(selector.TraversalType,selectionSource))
                    {

                        //key = HtmlData.indexSeparator + obj.Path;
                        HashSet<IDomObject> srcKeys = new HashSet<IDomObject>(Document.DocumentIndex.QueryIndex(HtmlData.indexSeparator + obj.Path));
                        foreach (IDomObject match in selector.SelectElements)
                        {
                            if (srcKeys.Contains(match))
                            {
                                elementMatches.Add(match);
                            }
                        }
                    }

                    selector.SelectorType &= ~SelectorType.Elements;
                }

                // If any selectors were not handled via the index, match them manually
                
                if (selector.SelectorType != 0)
                {
      
                    // if there are no temporary results (b/c there was no indexed selector) then use selection
                    // source instead (e.g. start from the same point that the index would have) 

                    result = GetMatches(result ?? selectionSource ?? Document.ChildElements, selector);
                }
                
                lastResult = lastResult == null ?
                    result : lastResult.Concat(result); 
                
            }

            // After the loop has finished, output any results from the last iteration.

            output.AddRange(lastResult);

            // Return the results as a list so that any user will not cause the selector to be run again
            
            return output.OrderBy(item => item.Path, StringComparer.Ordinal).ToList();

        }
Exemplo n.º 33
0
 /// <summary>
 /// Ensure that a parameter is not null nor empty, otherwise throws an argument exception with a specific message.
 /// </summary>
 /// <param name="value">The parameter value.</param>
 /// <param name="paramName">The parameter's name.</param>
 /// <param name="errorMessage">The specific error message.</param>
 public static void IsNotNullNorEmpty <T>(IEnumerable <T> value, string paramName, string errorMessage)
 => EvaluateParameter(value.IsNullOrEmpty(), paramName, errorMessage);
 public static string ToCommentsExtendedString(this IEnumerable <Alert> alerts)
 {
     return(alerts.IsNullOrEmpty() ? "" : alerts.Aggregate("", (current, alert) => current + $" - {alert}"));
 }
Exemplo n.º 35
0
        public LabsInboundListModel Create(IEnumerable <CustomerEventTestState> eventTestStates, IEnumerable <CustomerEventScreeningTests> eventScreeningTests, IEnumerable <EventCustomer> eventCustomers, IEnumerable <Customer> customers,
                                           IEnumerable <ChaseOutbound> chaseOutbounds, IEnumerable <CustomerChaseCampaign> customerChaseCampaigns, IEnumerable <ChaseCampaign> chaseCampaigns, IEnumerable <Test> tests, IEnumerable <Event> events,
                                           IEnumerable <EventCustomerResult> eventCustomerResults)
        {
            var collection = new List <LabsInboundViewModel>();

            foreach (var eventTestState in eventTestStates)
            {
                var customerEventScreeningTest = eventScreeningTests.First(x => x.Id == eventTestState.CustomerEventScreeningTestId);

                if (customerEventScreeningTest.TestId == (long)TestType.DPN || customerEventScreeningTest.TestId == (long)TestType.eAWV || customerEventScreeningTest.TestId == (long)TestType.FocAttestation)
                {
                    continue;
                }

                var eventCustomer       = eventCustomers.First(x => x.Id == customerEventScreeningTest.EventCustomerResultId);
                var eventCustomerResult = eventCustomerResults.First(x => x.Id == customerEventScreeningTest.EventCustomerResultId);

                var theEvent        = events.First(x => x.Id == eventCustomer.EventId);
                var isNewResultFlow = theEvent.EventDate >= _settings.ResultFlowChangeDate;
                var customer        = customers.First(x => x.CustomerId == eventCustomer.CustomerId);
                var chaseOutbound   = chaseOutbounds.FirstOrDefault(x => x.CustomerId == customer.CustomerId);
                if (chaseOutbound == null)
                {
                    continue;
                }
                var customerChaseCampaign = !customerChaseCampaigns.IsNullOrEmpty() ? customerChaseCampaigns.FirstOrDefault(x => x.CustomerId == customer.CustomerId) : null;
                var campaign = !chaseCampaigns.IsNullOrEmpty() && customerChaseCampaign != null?chaseCampaigns.FirstOrDefault(x => x.Id == customerChaseCampaign.ChaseCampaignId) : null;

                var test = tests.First(x => x.Id == customerEventScreeningTest.TestId);

                var labInboundViewModel = new LabsInboundViewModel
                {
                    TenantId             = chaseOutbound.TenantId,
                    ClientId             = chaseOutbound.ClientId,
                    CampaignId           = campaign != null ? campaign.CampaignId : "",
                    IndividualIDNumber   = chaseOutbound.IndividualId,
                    ContractNumber       = chaseOutbound.ContractNumber,
                    ContractPersonNumber = chaseOutbound.ContractPersonNumber,
                    ConsumerId           = chaseOutbound.ConsumerId,
                    VendorPersonId       = customer.CustomerId.ToString(),
                    LabType   = TestAbbreviation(test.Id, test.Name),
                    LabDate   = theEvent.EventDate,
                    LabResult = "",
                    LabAction = eventCustomerResult.RegenerationDate != null ? "Update" : "Insert"
                };

                if (customerEventScreeningTest.TestId == (long)TestType.Lead || customerEventScreeningTest.TestId == (long)TestType.Monofilament)
                {
                    var leftModel = ObjectCloneExtension.Clone(labInboundViewModel);
                    leftModel = SetLabResults(leftModel, eventCustomer.CustomerId, eventCustomer.EventId, test.Id, isNewResultFlow, true);

                    if (!string.IsNullOrWhiteSpace(leftModel.LabResult))
                    {
                        collection.Add(leftModel);
                    }
                }

                labInboundViewModel = SetLabResults(labInboundViewModel, eventCustomer.CustomerId, eventCustomer.EventId, test.Id, isNewResultFlow);

                if (!string.IsNullOrWhiteSpace(labInboundViewModel.LabResult))
                {
                    collection.Add(labInboundViewModel);
                }
            }

            return(new LabsInboundListModel
            {
                Collection = collection
            });
        }
 public static string ToCodeString(this IEnumerable <Alert> alerts)
 {
     return(alerts.IsNullOrEmpty() ? string.Empty : string.Join(",", alerts.Select(a => a.AlertCode)));
 }
Exemplo n.º 37
0
        internal static ConstructorInfo GetMatchingConstructor(IEnumerable <ConstructorInfo> ctors, object[] args)
        {
            if (ctors.IsNullOrEmpty())
            {
                return(null);
            }

            // no arguments were passed, will use default constructor
            if (args.IsNullOrEmpty())
            {
                foreach (var ctor in ctors)
                {
                    if (!ctor.IsPublic || ctor.IsStatic)
                    {
                        continue;
                    }

                    var paramsInfo = ctor.GetParameters();
                    if (!paramsInfo.IsNullOrEmpty())
                    {
                        continue;
                    }

                    return(ctor);
                }
                return(null);
            }

            // arguments were passed, will try to find matching constructor
            foreach (var ctor in ctors)
            {
                if (!ctor.IsPublic || ctor.IsStatic)
                {
                    continue;
                }

                var paramsInfo = ctor.GetParameters();
                if (paramsInfo.IsNullOrEmpty() || paramsInfo.Length != args.Length)
                {
                    continue;
                }

                var match = true;
                for (var i = 0; i < paramsInfo.Length; i++)
                {
                    var paramInfo = paramsInfo[i];
                    if (paramInfo == null)
                    {
                        break;
                    }

                    var arg     = args[i];
                    var argType = arg != null?arg.GetType() : paramInfo.ParameterType;

                    var isAssignable = paramInfo.ParameterType.IsAssignableFrom(argType);
                    if (isAssignable)
                    {
                        continue;
                    }

                    match = false;
                    break;
                }
                if (!match)
                {
                    continue;
                }

                return(ctor);
            }
            return(null);
        }
Exemplo n.º 38
0
        public void PollForAppointmentBookExport()
        {
            try
            {
                if (_accountIds.IsNullOrEmpty())
                {
                    return;
                }

                var accounts = (_corporateAccountRepository).GetByIds(_accountIds);

                if (accounts.IsNullOrEmpty())
                {
                    _logger.Info("Accounts can't be null");
                    return;
                }

                foreach (var account in accounts)
                {
                    _logger.Info("Running for account " + account.Tag);
                    var list = new List <AppointmentsBookedModel>();

                    var toDate          = DateTime.Today.GetLastDateOfYear();
                    var destinationPath = string.Format(_destinationAppointmentBookedReportPath, toDate.Year);
                    destinationPath = Path.Combine(destinationPath, account.FolderName);

                    var sourcePath = destinationPath + string.Format(@"\WCR_AppointmentBookedReport_{0}.csv", DateTime.Today.ToString("yyyyMMdd"));

                    var appointmentSettings = string.Format(_appointmentSettings, "WellCareToWellmed");
                    var customSettings      = _customSettingManager.Deserialize(appointmentSettings);
                    customSettings = customSettings ?? new CustomSettings();

                    var fromDate = (customSettings.LastTransactionDate == null) ? _cutOfDate : DateTime.Today.GetFirstDateOfYear();

                    _logger.Info(string.Format("Generating AppointmentBooked for accountId {0} and account tag {1}. ", account.Id, account.Tag));

                    CreateDistinationDirectory(destinationPath);

                    list.AddRange(AppointmentsBooked(new AppointmentsBookedListModelFilter {
                        EventFrom = fromDate, EventTo = toDate.Date, AccountId = account.Id, Tag = account.Tag
                    }));

                    if (File.Exists(sourcePath))
                    {
                        sourcePath = _pgpFileEncryptionHelper.EncryptFile(account, sourcePath);
                    }

                    customSettings.LastTransactionDate = toDate;
                    _customSettingManager.SerializeandSave(appointmentSettings, customSettings);

                    if (list.Any())
                    {
                        _appointmentBookedExportCsvHelper.WriteCsv(list, sourcePath, _logger);

                        if (_sendReportToSftp)
                        {
                            var sftpFolderAppointmentBookedReportDirectory = string.Format(_destinationSftpFolderAppointmentBookedReportPath, toDate.Year);

                            sftpFolderAppointmentBookedReportDirectory = sftpFolderAppointmentBookedReportDirectory + "\\" + account.FolderName;

                            _logger.Info("source path:" + sourcePath);

                            var processFtp = new ProcessFtp(_logger, _sftpHost, _sftpUserName, _sftpPassword);
                            processFtp.UploadSingleFile(sourcePath, sftpFolderAppointmentBookedReportDirectory, "");

                            _logger.Info("destination :" + sftpFolderAppointmentBookedReportDirectory);
                        }
                    }
                    else
                    {
                        _logger.Info("No Records Found for account " + account.Tag);
                    }

                    _logger.Info("********** Completed for Account " + account.Tag + " *****************");
                }
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("Main App: \n Error {0} \n Trace: {1} \n\n\n", ex.Message, ex.StackTrace));
            }
        }
Exemplo n.º 39
0
        public ActionResult Detail()
        {
            #region

            string absoluteUrl = "";
            if (EnvSettings.Domain.IsInvalid(out absoluteUrl))
            {
                return(Redirect(absoluteUrl));
            }

            #endregion

            SetReadMode();
            Novel novel = _bookService.GetNovel(NovelId);
            if (novel != null && novel.Id > 0)
            {
                InitializeChapterPager();

                Chapter chapter = _chapterService.GetChapter(NovelId, ChapterCode, ChapterDirection, out ChapterCode);
                if (chapter != null && chapter.Id > 0 && IsRead(_orderService))
                {
                    #region

                    bool   isPreChapterCode  = false;
                    bool   isNextChapterCode = false;
                    string url = GetChapterPager("/chapter/detail", ChapterCode, out isPreChapterCode, out isNextChapterCode);

                    #endregion

                    #region 推荐阅读

                    //推荐阅读 - 轮循广告
                    int adClassId           = RecSection.BookChapterDetail.Ad;
                    IEnumerable <AD> adList = GetADList(adClassId, novel.Id, 3);

                    #endregion

                    //阅读记录
                    ReadLog(currentUser.UserName, chapter.NovelId, chapter.Id, chapter.ChapterCode);

                    //最近阅读日志
                    RecentReadContext.Save(novel, chapter.ChapterName, ChapterCode, RouteChannelId, currentUser.UserId);

                    //是否收藏
                    bool isMark = _bookmarkService.Exists(NovelId, currentUser.UserName);

                    //漫画目录
                    IEnumerable <ExtendChapterView> extendChapterList = GetExtendChapterList(novel);

                    // 千字价格
                    int chapterWordSizeFee = GetChapterWordSizeFee(novel.ChapterWordSizeFee);
                    //正文中插入用户信息
                    string encryptInfo = string.IsNullOrEmpty(currentUser.UserName) ? null : string.Concat("16", ";", currentUser.UserName.Substring(1));

                    ChapterDetailView detailView = new ChapterDetailView()
                    {
                        Novel                    = new SimpleResponse <Novel>(true, novel),
                        Chapter                  = new SimpleResponse <Chapter>(true, chapter),
                        ChapterFee               = GetFee(chapter.WordSize, chapterWordSizeFee),
                        ChapterContent           = StringHelper.ConvertAndSignTxt((novel.ContentType == (int)Constants.Novel.ContentType.小说) ? FileHelper.ReadFile(FileHelper.MergePath("\\", new string[] { novel.FilePath, chapter.FileName }), chapter.ChapterName) : "", Constants.SecurityKey.userAESId.ToLower(), encryptInfo),
                        IsPreChapterCode         = isPreChapterCode,
                        IsNextChapterCode        = isNextChapterCode,
                        PreChapterUrl            = ChapterContext.GetUrl(url, NovelId, ChapterCode, Constants.Novel.ChapterDirection.pre, channelId: RouteChannelId),
                        NextChapterUrl           = ChapterContext.GetUrl(url, NovelId, ChapterCode, Constants.Novel.ChapterDirection.next, channelId: RouteChannelId),
                        AdList                   = new SimpleResponse <IEnumerable <AD> >(!adList.IsNullOrEmpty <AD>(), adList),
                        IsMark                   = isMark,
                        ExtendChapterList        = new SimpleResponse <IEnumerable <ExtendChapterView> >(!extendChapterList.IsNullOrEmpty <ExtendChapterView>(), extendChapterList),
                        ChapterAudioUrl          = GetAudioUrl(novel.ContentType, chapter.FileName),
                        HitUrl                   = GetHitUrl(),
                        ShowQrCodeMinChapterCode = StringHelper.ToInt(UrlParameterHelper.GetParams("qrdx"))
                    };

                    if (novel.ContentType == (int)Constants.Novel.ContentType.漫画)
                    {
                        return(View("/views/cartoonchapter/detail.cshtml", detailView));
                    }
                    else if (novel.ContentType == (int)Constants.Novel.ContentType.听书)
                    {
                        return(View("/views/audiochapter/detail.cshtml", detailView));
                    }
                    else
                    {
                        return(View(detailView));
                    }
                }
                else
                {
                    if (novel.FeeType == (int)Constants.Novel.FeeType.chapter || novel.FeeType == (int)Constants.Novel.FeeType.novelchapter)
                    {
                        return(Redirect(ChapterContext.GetUrl("/preorder/chapter", NovelId, ChapterCode, channelId: RouteChannelId)));
                    }
                    else if (novel.FeeType == (int)Constants.Novel.FeeType.novel)
                    {
                        return(Redirect(ChapterContext.GetUrl("/preorder/novel", NovelId, ChapterCode, channelId: RouteChannelId)));
                    }
                }
            }

            return(Redirect(DataContext.GetErrorUrl(ErrorMessage.小说不存在, channelId: RouteChannelId)));
        }
Exemplo n.º 40
0
        public override Boolean RemoveUUID(IEnumerable<ObjectUUID> myObjectUUIDs)
        {
            if (!myObjectUUIDs.IsNullOrEmpty())
            {
                foreach (var aUUID in myObjectUUIDs)
                {
                    _ObjectUUIDs.Remove(aUUID);
                }

                return true;
            }

            return false;
        }
Exemplo n.º 41
0
        public IEnumerable <EventCustomerScreeningAggregate> Parse()
        {
            var eventCustomerAggregates = new List <EventCustomerScreeningAggregate>();

            var directoryPath = GetFolderPathfor(_microalbuminResultOutputPath);

            if (string.IsNullOrEmpty(directoryPath) && string.IsNullOrEmpty(directoryPath))
            {
                return(null);
            }

            List <string> pdfFiles = null;

            if (!string.IsNullOrEmpty(directoryPath))
            {
                pdfFiles = GetPdfFiles(directoryPath);
            }

            var eventList = DirectoryOperationsHelper.GetDirectories(directoryPath);

            if (eventList != null && eventList.Any())
            {
                _logger.Info("Number of Events : " + eventList.Count());

                foreach (var events in eventList)
                {
                    long   customerId   = 0;
                    long   eventId      = 0;
                    string errorMessage = string.Empty;

                    if (!long.TryParse(events, out eventId))
                    {
                        _logger.Info("Event Id not found  : " + events);
                        continue;
                    }

                    List <string> pdfResults  = null;
                    var           eventFolder = Path.Combine(directoryPath, events);
                    if (!string.IsNullOrEmpty(eventFolder))
                    {
                        pdfResults = GetPdfFiles(eventFolder);

                        if (pdfResults != null && pdfResults.Any())
                        {
                            _logger.Info("Number of Files to Parse : " + pdfFiles.Count() + " Event Id is :" + events);

                            foreach (var filePath in pdfResults)
                            {
                                var fileNameWithExtention = Path.GetFileName(filePath);
                                if (!string.IsNullOrEmpty(fileNameWithExtention))
                                {
                                    fileNameWithExtention = fileNameWithExtention.ToLower();
                                }

                                var fileName = Path.GetFileNameWithoutExtension(filePath);
                                if (!string.IsNullOrEmpty(fileName))
                                {
                                    fileName = fileName.ToLower();
                                }

                                _logger.Info("=============== Parsing Started for file: " + fileName + " =================");

                                TestType testTypeId;
                                string   testName = "";
                                try
                                {
                                    var temp           = fileName.Split('_');
                                    var memberIdString = temp[0];
                                    testName = Convert.ToString(temp[1]);

                                    testTypeId = ((TestType)Enum.Parse(typeof(TestType), testName));

                                    IEnumerable <long> customerIds = _customerRepository.GetCustomerIdByInsuranceId(memberIdString);

                                    if (!customerIds.IsNullOrEmpty())
                                    {
                                        errorMessage = "Invalid member Id:  " + memberIdString + " File Path" + filePath;
                                        _logger.Info(errorMessage);
                                        continue;
                                    }

                                    var eventCustomers = _eventCustomerRepository.GetbyEventId(eventId);

                                    eventCustomers = eventCustomers.Where(x => customerIds.Contains(x.CustomerId) && x.AppointmentId.HasValue);

                                    if (eventCustomers.IsNullOrEmpty())
                                    {
                                        errorMessage = "customer has not been booked for event with member Id: " + memberIdString + " EventId : " + eventId;
                                        _logger.Info(errorMessage);
                                        continue;
                                    }
                                    if (eventCustomers.Count() > 1)
                                    {
                                        errorMessage = "more than one customer has been booked for event with member Id: " + memberIdString + " EventId : " + eventId;
                                        _logger.Info(errorMessage);
                                        continue;
                                    }
                                    customerId = eventCustomers.First().CustomerId;
                                }
                                catch (Exception)
                                {
                                    errorMessage = "File name is not in correct format. ";
                                    _logger.Error(errorMessage);
                                    continue;
                                }

                                var isTestPurchased = _testResultService.IsTestPurchasedByCustomer(eventId, customerId, (long)testTypeId);
                                if (!isTestPurchased)
                                {
                                    errorMessage = string.Format("Customer Id :" + customerId + " Test: " + testName + " not purchased ");
                                    _logger.Info(errorMessage);
                                    continue;
                                }

                                try
                                {
                                    string folderToSavePdf = _mediaRepository.GetResultMediaFileLocation(customerId, eventId).PhysicalPath;
                                    var    resultMedia     = GetMediaFromPdfFile(filePath, folderToSavePdf, testTypeId);

                                    MovedParsedFile(filePath, eventId);

                                    //if (resultMedia != null)
                                    //{
                                    //    TestResult testResult = new DiabeticRetinopathyTestResult { ResultImage = resultMedia };

                                    //    _resultParserHelper.AddTestResulttoEventCustomerAggregate(eventCustomerAggregates, eventId, customerId, testResult);
                                    //    _resultParserHelper.AddResultArchiveLog(string.Empty, TestType.DiabeticRetinopathy, customerId, MedicalEquipmentTag.Vatica);

                                    //    _logger.Info(string.Concat("\nParsing succeeded for Customer Id: ", customerId, "\n"));
                                    //}
                                }
                                catch (Exception ex)
                                {
                                    errorMessage = " System Failure! Message: " + ex.Message + "\n\t" + ex.StackTrace;
                                    _logger.Error(errorMessage);

                                    // _resultParserHelper.AddResultArchiveLog(ex.Message, TestType.DiabeticRetinopathy, customerId, MedicalEquipmentTag.Vatica, false);
                                }
                            }
                        }
                    }
                }
            }
            return(eventCustomerAggregates);
        }
Exemplo n.º 42
0
        private static void ValidateReferences(IEnumerable<Reference> refs)
        {
            if (refs.IsNullOrEmpty())
            {
                throw new Exception("Got no references.");
            }

            var errorMessages = new List<string>();

            foreach (var reference in refs)
            {
                ICollection<string> errors;
                if (!ReferenceValidator.Validate(reference, out errors))
                {
                    errorMessages.Add("Row {0}: {1}".Fill(reference.RowNum, errors.SemicolonSeparated()));
                }
            }

            if(errorMessages.Any())
            {
                throw new Exception("Invalid records data found:\n" + errorMessages.JoinWith("\n"));
            }
        }
 public void Test_ListOfInts(IEnumerable <int> data, bool expect)
 {
     Assert.Equal(expect, data.IsNullOrEmpty());
 }
Exemplo n.º 44
0
        //检查库存信息
        private static void CheckStock(IEnumerable<ProductColor> lstProductColor, DataRow drNew)
        {
            if (!lstProductColor.IsNullOrEmpty())
            {
                var settings = new JsonSerializerSettings();

                string result = JsonConvert.SerializeObject(lstProductColor, Formatting.Indented, settings);
                //需要注意的是,如果返回的是一个集合,那么还要在它的上面再封装一个类。否则客户端收到会出错的。
                //转回为对象
                //var pcList = JsonConvert.DeserializeObject<List<ProductColor>>(result);

                drNew["SKU"] = result;
                drNew["库存"] = lstProductColor.Sum(productColor => productColor.AvlNumForColor);
                drNew["售完"] = 0;
            }
            else
            {
                drNew["售完"] = 1;
                drNew["库存"] = 0;
            }
        }
Exemplo n.º 45
0
        private bool TryGetAllItems(out IEnumerable<Stream> results)
        {
            string cacheKey = "aditi:gis:arm:data:stream-all";
            if (!cache.TryGet(cacheKey, out results))
            {
                CommonService<StreamModel, Stream> service = new CommonService<StreamModel, Stream>();
                results = service.GetList();
                if (results.IsNullOrEmpty())
                {
                    results = null;
                    return false;
                }

                cache.Set(cacheKey, results);
            }

            return true;
        }
        public void PollForParsingCustomerActivityTypeUpload()
        {
            try
            {
                var today = DateTime.Now;
                if (_settings.IsDevEnvironment || today.TimeOfDay > new TimeSpan(4, 0, 0))
                {
                    _logger.Info("Entering CustomerActivityTypeUpload parse polling agent @:" + today);

                    var customerActivityTypeFilesForParsing = _customerActivityTypeUploadRepository.GetFilesToParse();

                    if (customerActivityTypeFilesForParsing.IsNullOrEmpty())
                    {
                        _logger.Info("No file found for parsing");
                        return;
                    }

                    _logger.Info("No. of files to Parse:" + customerActivityTypeFilesForParsing.Count());

                    var parseFileIds  = customerActivityTypeFilesForParsing.Select(x => x.FileId);
                    var uploadedFiles = _fileRepository.GetByIds(parseFileIds);
                    var filesLocation = _mediaRepository.GetCustomerActivityTypeUploadMediaFileLocation();

                    foreach (var customerActivityTypeUploadDomain in customerActivityTypeFilesForParsing)
                    {
                        var failedRecords = new List <CustomerActivityTypeUploadLogViewModel>();
                        try
                        {
                            customerActivityTypeUploadDomain.ParseStartTime = DateTime.Now;
                            var file = uploadedFiles.FirstOrDefault(x => x.Id == customerActivityTypeUploadDomain.FileId);
                            if (file == null)
                            {
                                UpdateParsingStatus(customerActivityTypeUploadDomain, (long)CallUploadStatus.FileNotFound);
                                _logger.Info("Parsing Failed: FileNotFound CustomerActivityTypeUpload Id: " + customerActivityTypeUploadDomain.Id);
                                continue;
                            }

                            var filePhysicalLocation = filesLocation.PhysicalPath + file.Path;

                            if (!System.IO.File.Exists(filePhysicalLocation))
                            {
                                UpdateParsingStatus(customerActivityTypeUploadDomain, (long)CallUploadStatus.FileNotFound);
                                _logger.Info("Parsing Failed, FileNotFound: File: " + file.Path);
                                continue;
                            }

                            var fInfo = new FileInfo(filePhysicalLocation);
                            if (fInfo.Extension != ".csv")
                            {
                                UpdateParsingStatus(customerActivityTypeUploadDomain, (long)CallUploadStatus.InvalidFileFormat);
                                _logger.Info("Parsing Failed: InvalidFileFormat File: " + file.Path);
                                continue;
                            }

                            _logger.Error("Parsing started for File: " + file.Path);

                            UpdateParsingStatus(customerActivityTypeUploadDomain, (long)CallUploadStatus.Parsing, false);

                            var customerEligibleUploadTable = _csvReader.ReadWithTextQualifier(filePhysicalLocation);
                            var recordsInFile = customerEligibleUploadTable.Rows.Count;

                            var totalPages = recordsInFile / PageSize + (recordsInFile % PageSize != 0 ? 1 : 0);
                            _logger.Info("Total no. of Pages: " + totalPages + " , Total Records: " + recordsInFile);
                            var pageNumber = 1;

                            while (pageNumber <= totalPages)
                            {
                                try
                                {
                                    IEnumerable <CustomerActivityTypeUploadLogViewModel> tempParsedRecords = null;
                                    var query = customerEligibleUploadTable.AsEnumerable();
                                    _logger.Info("Parsing For Page Number: " + pageNumber);
                                    var rows = query.Skip(PageSize * (pageNumber - 1)).Take(PageSize);
                                    pageNumber++;

                                    tempParsedRecords = ParseDataTable(rows, failedRecords);

                                    if (tempParsedRecords.IsNullOrEmpty())
                                    {
                                        continue;
                                    }

                                    UpdateActivityType(tempParsedRecords, failedRecords, file.UploadedBy.Id);
                                }
                                catch (Exception ex)
                                {
                                    _logger.Info(string.Format("Parsing failed for Page: {0} File name: {1}", pageNumber, file.Path));
                                    _logger.Error("ExceptionMessage: " + ex.Message + "\n\tStackTrace: " + ex.StackTrace);
                                    continue;
                                }
                            }
                            customerActivityTypeUploadDomain.SuccessfullUploadCount = recordsInFile - failedRecords.Count();
                            customerActivityTypeUploadDomain.ParseEndTime           = DateTime.Now;
                            customerActivityTypeUploadDomain.StatusId = (long)CallUploadStatus.Parsed;

                            UpdateCustomerActivityTypeUploadDetail(customerActivityTypeUploadDomain, failedRecords, filePhysicalLocation);
                            _logger.Error("Parse Succeeded : File name: " + file.Path);
                        }
                        catch (Exception ex)
                        {
                            var fileDomain = uploadedFiles.FirstOrDefault(x => x.Id == customerActivityTypeUploadDomain.FileId);

                            if (fileDomain != null)
                            {
                                _logger.Error("Failed to parse File , File name: " + fileDomain.Path);
                                var filePhysicalLocation = filesLocation.PhysicalPath + fileDomain.Path;
                                customerActivityTypeUploadDomain.StatusId = (long)CallUploadStatus.ParseFailed;
                                UpdateCustomerActivityTypeUploadDetail(customerActivityTypeUploadDomain, failedRecords, filePhysicalLocation);
                            }
                            else
                            {
                                _logger.Error("Record does not exist in file table");
                            }

                            _logger.Error("ExceptionMessage: " + ex.Message + "\n\tStackTrace: " + ex.StackTrace);
                            continue;
                        }
                    }
                }
                else
                {
                    _logger.Info(string.Format("CustomerActivityTypeUpload Parser can not be invoked as time of day is {0}", today.TimeOfDay));
                }
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("Exception occurred during execution of CustomerActivityTypeUploadPollingAgent \nException Message: {0}\n\tStackTrace:{1}", ex.Message, ex.StackTrace));
                return;
            }
        }
Exemplo n.º 47
0
    public IEnumerable<int> IndexesOf(IEnumerable<string> keyNames)
    {
        Assert.IsTrue(!keyNames.IsNullOrEmpty());
        Assert.IsTrue(!keyNames.HasDuplication());
        Assert.IsTrue(keyNames.All(x => columnInfo.ContainsKey(x)), "Has unknown keyName in \n" + keyNames.ToStringList(","));

        return keyNames.Select(x => columnInfo.IndexOf(x));
    }
Exemplo n.º 48
0
 /// <summary>
 ///     Gets Or Adds a PropertyValue with the given label and collection.
 /// </summary>
 /// <param name="label"> </param>
 /// <param name="collections"> </param>
 /// <returns> </returns>
 public override PropertyValue GetPropertyValue(string label, IEnumerable<string> collections = null) {
     var result = _propertyValues.FirstOrDefault(each => each.Label == label);
     if (result == null) {
         _propertyValues.Add(result = new PropertyValue(this, label, collections.IsNullOrEmpty() ? null : collections));
     }
     return result;
 }
        /// <summary>
        /// Select from DOM using index. First non-class/tag/id selector will result in this being passed off to GetMatches
        /// </summary>
        /// <param name="document"></param>
        /// <returns></returns>
        public IEnumerable<IDomObject> Select(IDomDocument document, IEnumerable<IDomObject> context)
        {
            if (Selectors == null )
            {
                throw new ArgumentException("No selectors provided.");
            }
            if (Selectors.Count == 0)
            {
                yield break;
            }
            Document = document;
            IEnumerable<IDomObject> lastResult = null;
            HashSet<IDomObject> output = new HashSet<IDomObject>();
            IEnumerable<IDomObject> selectionSource = context;

            // Disable the index if there is no context (e.g. disconnected elements)
            bool useIndex = context.IsNullOrEmpty() || !context.First().IsDisconnected;

            // Copy the list because it may change during the process
            ActiveSelectors = new List<Selector>(Selectors);

            for (activeSelectorId = 0; activeSelectorId < ActiveSelectors.Count; activeSelectorId++)
            {
                var selector = ActiveSelectors[activeSelectorId];
                CombinatorType combinatorType = selector.CombinatorType;
                SelectorType selectorType = selector.SelectorType;
                TraversalType traversalType = selector.TraversalType;

                // Determine what kind of combining method we will use with previous selection results

                if (activeSelectorId != 0)
                {
                    switch (combinatorType)
                    {
                        case CombinatorType.Cumulative:
                            // do nothing
                            break;
                        case CombinatorType.Root:
                            selectionSource = context;
                            if (lastResult != null)
                            {
                                output.AddRange(lastResult);
                                lastResult = null;
                            }
                            break;
                        case CombinatorType.Chained:
                            selectionSource = lastResult;
                            lastResult = null;
                            break;
                        // default (chained): leave lastresult alone
                    }
                }

                HashSet<IDomObject> tempResult = null;
                IEnumerable<IDomObject> interimResult = null;

                string key = "";
                if (useIndex && !selector.NoIndex)
                {

            #if DEBUG_PATH

                    if (type.HasFlag(SelectorType.Attribute))
                    {
                        key = "!" + selector.AttributeName;
                        type &= ~SelectorType.Attribute;
                        if (selector.AttributeValue != null)
                        {
                            InsertAttributeValueSelector(selector);
                        }
                    }
                    else if (type.HasFlag(SelectorType.Tag))
                    {
                        key = "+"+selector.Tag;
                        type &= ~SelectorType.Tag;
                    }
                    else if (type.HasFlag(SelectorType.ID))
                    {
                        key = "#" + selector.ID;
                        type &= ~SelectorType.ID;
                    }
                    else if (type.HasFlag(SelectorType.Class))
                    {
                        key = "." + selector.Class;
                        type &= ~SelectorType.Class;
                    }

            #else
                    if (selectorType.HasFlag(SelectorType.Attribute))
                    {
                        key = "!" + (char)DomData.TokenID(selector.AttributeName);
                        selectorType &= ~SelectorType.Attribute;
                        if (selector.AttributeValue != null)
                        {
                            InsertAttributeValueSelector(selector);
                        }
                    }
                    else if (selectorType.HasFlag(SelectorType.Tag))
                    {
                        key = "+" + (char)DomData.TokenID(selector.Tag, true);
                        selectorType &= ~SelectorType.Tag;
                    }
                    else if (selectorType.HasFlag(SelectorType.ID))
                    {
                        key = "#" + (char)DomData.TokenID(selector.ID);
                        selectorType &= ~SelectorType.ID;
                    }
                    else if (selectorType.HasFlag(SelectorType.Class))
                    {
                        key = "." + (char)DomData.TokenID(selector.Class);
                        selectorType &= ~SelectorType.Class;
                    }
            #endif
                }

                // If part of the selector was indexed, key will not be empty. Return initial set from the
                // index. If any selectors remain after this they will be searched the hard way.

                if (key != String.Empty)
                {
                    int depth = 0;
                    bool descendants = true;

                    switch (traversalType)
                    {
                        case TraversalType.Child:
                            depth = selector.ChildDepth; ;
                            descendants = false;
                            break;
                        case TraversalType.Filter:
                            depth = 0;
                            descendants = false;
                            break;
                        case TraversalType.Descendent:
                            depth = 1;
                            descendants = true;
                            break;
                    }

                    if (selectionSource == null)
                    {
                        interimResult = document.QueryIndex(key + DomData.indexSeparator, depth, descendants);
                    }
                    else
                    {
                        interimResult = new HashSet<IDomObject>();
                        foreach (IDomObject obj in selectionSource)
                        {
                            ((HashSet<IDomObject>)interimResult)
                                .AddRange(document.QueryIndex(key + DomData.indexSeparator + obj.Path,
                                    depth, descendants));
                        }
                    }
                }
                else if (selectorType.HasFlag(SelectorType.Elements))
                {
                    selectorType &= ~SelectorType.Elements;
                    HashSet<IDomObject> source = new HashSet<IDomObject>(selectionSource);
                    interimResult = new HashSet<IDomObject>();

                    foreach (IDomObject obj in selectionSource)
                    {
                        key = DomData.indexSeparator + obj.Path;
                        HashSet<IDomObject> srcKeys = new HashSet<IDomObject>(document.QueryIndex(key));
                        foreach (IDomObject match in selector.SelectElements)
                        {
                            if (srcKeys.Contains(match))
                            {
                                ((HashSet<IDomObject>)interimResult).Add(match);
                            }
                        }
                    }
                }
                // TODO - GetMatch should work if passed with no selectors (returning nothing), now it returns everything
                // 12/10/11 - this todo is not verified, much has changed since it was written. TODO confirm this and
                // fix if needed. If having the conversation with self again, remove comments and forget it. This is
                // an example of why comments can do more harm than good.

                if ((selectorType & ~(SelectorType.SubSelectorNot | SelectorType.SubSelectorHas)) != 0)
                {
                    IEnumerable<IDomObject> finalSelectWithin =
                        interimResult
                        ?? (combinatorType == CombinatorType.Chained ? lastResult : null)
                        ?? selectionSource
                        ?? document.ChildElements;

                    // if there are no temporary results (b/c there was no indexed selector) then use the whole set
                    interimResult = GetMatches(finalSelectWithin, selector);

                }

                // Deal with subselectors: has() and not() test for the presence of a selector within the children of
                // an element. This is essentially similar to the manual selection above.

                if (selectorType.HasFlag(SelectorType.SubSelectorHas)
                    || selectorType.HasFlag(SelectorType.SubSelectorNot))
                {
                    bool isHasSelector = selectorType.HasFlag(SelectorType.SubSelectorHas);

                    IEnumerable<IDomObject> subSelectWithin = interimResult
                        ?? (combinatorType == CombinatorType.Chained ? lastResult : null)
                        ?? selectionSource;

                    // subselects are a filter. start a new interim result.

                    HashSet<IDomObject> filteredResults = new HashSet<IDomObject>();

                    foreach (IDomObject obj in subSelectWithin)
                    {
                        bool match = true;
                        foreach (var sub in selector.SubSelectors)
                        {
                            List<IDomObject> listOfOne = new List<IDomObject>();
                            listOfOne.Add(obj);

                            bool has = !sub.Select(document, listOfOne).IsNullOrEmpty();

                            match &= isHasSelector == has;
                        }
                        if (match)
                        {
                            filteredResults.Add(obj);
                        }
                    }
                    interimResult = filteredResults;
                }
                tempResult = new HashSet<IDomObject>();
                if (lastResult != null)
                {
                    tempResult.AddRange(lastResult);
                }
                if (interimResult != null)
                {
                    tempResult.AddRange(interimResult);
                }
                lastResult = tempResult;
            }

            if (lastResult != null)
            {
                output.AddRange(lastResult);
            }

            if (output.IsNullOrEmpty())
            {
                yield break;
            }
            else
            {
                // Selectors always return in DOM order. Selections may end up in a different order but
                // we always sort here.

                foreach (IDomObject item in output.OrderBy(item => item.Path, StringComparer.Ordinal))
                {
                    yield return item;
                }
            }
            ActiveSelectors.Clear();
        }
 public void Test_ListOfStrings(IEnumerable <string> data, bool expect)
 {
     Assert.Equal(expect, data.IsNullOrEmpty());
 }
Exemplo n.º 51
0
        public override bool RemoveUUID(IEnumerable<ObjectUUID> myObjectUUIDs)
        {
            if (!myObjectUUIDs.IsNullOrEmpty())
            {
                weightedSet.RemoveWhere(item => myObjectUUIDs.Contains(item.ObjectUUID));
                return false;
            }

            return false;
        }
Exemplo n.º 52
0
        /// <summary>
        /// Execute send emails
        /// </summary>
        /// <param name="sendInfos">Email send infos</param>
        /// <returns>Return the email send results</returns>
        internal static async Task <List <EmailSendResult> > ExecuteSendAsync(IEnumerable <EmailSendInfo> sendInfos)
        {
            if (sendInfos.IsNullOrEmpty())
            {
                return(new List <EmailSendResult>(0));
            }
            if (EmailEngine == null)
            {
                throw new EZNEWException("No mail delivery execution engine is configured");
            }

            Dictionary <string, List <EmailSendInfo> > emailInfoGroups = new Dictionary <string, List <EmailSendInfo> >();
            Dictionary <string, EmailAccount>          accounts        = new Dictionary <string, EmailAccount>();

            #region Gets email account

            foreach (var sendInfo in sendInfos)
            {
                var account = GetAccount(sendInfo);
                if (account == null)
                {
                    continue;
                }
                string accountKey = account.IdentityKey;
                if (UseSameEmailAccount)
                {
                    emailInfoGroups[accountKey] = sendInfos.ToList();
                    accounts[accountKey]        = account;
                    break;
                }
                if (accounts.ContainsKey(accountKey))
                {
                    emailInfoGroups[accountKey].Add(sendInfo);
                }
                else
                {
                    emailInfoGroups.Add(accountKey, new List <EmailSendInfo>()
                    {
                        sendInfo
                    });
                    accounts.Add(accountKey, account);
                }
            }

            #endregion

            #region Execute send

            //Single email account
            if (emailInfoGroups.Count == 1)
            {
                var firstGroup = emailInfoGroups.First();
                var account    = accounts[firstGroup.Key];
                return(await EmailEngine.SendAsync(account, firstGroup.Value.ToArray()));
            }

            //Multiple email account
            var emailTasks = new Task <List <EmailSendResult> > [emailInfoGroups.Count];
            var groupIndex = 0;
            foreach (var optionGroup in emailInfoGroups)
            {
                var account = accounts[optionGroup.Key];
                emailTasks[groupIndex] = EmailEngine.SendAsync(account, optionGroup.Value.ToArray());
            }
            var sendResults = (await Task.WhenAll(emailTasks).ConfigureAwait(false)).SelectMany(c => c);

            #endregion

            //callback
            ThreadPool.QueueUserWorkItem(s =>
            {
                EmailSentCallback?.Invoke(sendResults);
            });
            return(sendResults.ToList());
        }
Exemplo n.º 53
0
 internal static string SelectedColumns(IEnumerable <string> selection, string tableName)
 {
     return(selection.IsNullOrEmpty() ? SelectAll(tableName) : Fields(selection));
 }
Exemplo n.º 54
0
        static SendMessageResult GetEmailOptions(MessageTemplate messageTemplate, MessageInfo message, string emailCategory, IEnumerable <string> emails, bool asynchronously, out SendEmailOptions sendEmailOptions)
        {
            sendEmailOptions = null;
            if (messageTemplate == null)
            {
                throw new ArgumentNullException(nameof(MessageTemplate));
            }
            if (message == null)
            {
                throw new ArgumentNullException(nameof(MessageInfo));
            }
            if (string.IsNullOrWhiteSpace(messageTemplate.Title))
            {
                throw new Exception("The message template title is null or empty");
            }
            if (string.IsNullOrWhiteSpace(messageTemplate.Content))
            {
                throw new Exception("The message template content is null or empty");
            }
            if (emails.IsNullOrEmpty())
            {
                throw new Exception("The emails is null or empty");
            }
            var parameterDict = message.Parameters?.ObjectToStringDcitionary();
            Dictionary <string, string> templateParameters = GetTemplateParameters(parameterDict);

            //title
            var titleResolveResult = ResolveTemplate(messageTemplate.Title, templateParameters);

            if (!titleResolveResult.Item1 || string.IsNullOrWhiteSpace(titleResolveResult.Item3))
            {
                if (!string.IsNullOrWhiteSpace(titleResolveResult.Item2))
                {
                    return(SendMessageResult.NoParameter($"Not set '{titleResolveResult.Item2}' value in the email title template"));
                }
                return(SendMessageResult.MessageIsNullOrEmpty($"The email title is null or empty"));
            }

            //content
            var contentResolveResult = ResolveTemplate(messageTemplate.Content, templateParameters);

            if (!contentResolveResult.Item1 || string.IsNullOrWhiteSpace(contentResolveResult.Item3))
            {
                if (!string.IsNullOrWhiteSpace(contentResolveResult.Item2))
                {
                    return(SendMessageResult.NoParameter($"Not set '{contentResolveResult.Item2}' value in the email body template"));
                }
                return(SendMessageResult.MessageIsNullOrEmpty($"The email body is null or empty"));
            }

            //Send email
            sendEmailOptions = new SendEmailOptions()
            {
                Category       = emailCategory,
                Content        = contentResolveResult.Item3,
                Subject        = titleResolveResult.Item3,
                Asynchronously = asynchronously,
                Emails         = emails
            };
            sendEmailOptions.AddWorkId(message.WorkId);
            sendEmailOptions.AddTemplateMessageId(message.Id);
            return(SendMessageResult.SendSuccess());
        }
Exemplo n.º 55
0
        private bool TryGetItemEmployees(long id, out IEnumerable<Employee> results)
        {
            string cacheKey = "aditi:gis:arm:data:stream-" + id.ToString() + "-employee";
            if (!cache.TryGet(cacheKey, out results))
            {
                JoinTableRepository<EmployeeModel, StreamModel> repository = new JoinTableRepository<EmployeeModel, StreamModel>();
                IEnumerable<EmployeeModel> employees = repository.GetLeft(id);
                results = AutoMapper.MapCollection<EmployeeModel, Employee>(employees);
                if (results.IsNullOrEmpty())
                {
                    results = null;
                    return false;
                }

                cache.Set(cacheKey, results, InMemoryCache.OneDay);
            }

            return true;
        }
Exemplo n.º 56
0
 internal static string Conditions(IEnumerable <string> where)
 {
     return(where.IsNullOrEmpty() ? string.Empty : "WHERE {0}".FormatWith(string.Join("", where)));
 }
Exemplo n.º 57
0
        private IEnumerable<GraphDBType> GetTypes(DBContext myDBContext, IEnumerable<String> myTypes)
        {
            #region GetTypeToDump

            IEnumerable<GraphDBType> typesToDump;
            if (myTypes.IsNullOrEmpty())
            {
                typesToDump = myDBContext.DBTypeManager.GetAllTypes(false);
            }
            else
            {
                var typesToDumpHash = new HashSet<GraphDBType>();
                foreach (var stringType in myTypes)
                {
                    var type = myDBContext.DBTypeManager.GetTypeByName(stringType);
                    if (type == null)
                    {
                        throw new GraphDBException(new Errors.Error_TypeDoesNotExist(stringType));
                    }

                    //typesToDumpHash.UnionWith(myDBContext.DBTypeManager.GetAllParentTypes(type, true, false));
                    AddTypeAndAttributesRecursivly(myDBContext, type, ref typesToDumpHash);

                }
                typesToDump = typesToDumpHash;
            }

            #endregion

            return typesToDump;
        }
Exemplo n.º 58
0
 public bool IsNullOrEmptyTests(IEnumerable a)
 {
     return(a.IsNullOrEmpty());
 }
Exemplo n.º 59
0
 internal static string GroupBy(IEnumerable <string> grouping)
 {
     return(grouping.IsNullOrEmpty() ? string.Empty : "GROUP BY {0}".FormatWith(Fields(grouping)));
 }
Exemplo n.º 60
0
        public void IsNullOrEmpty_IEnumerable_True_IfNull()
        {
            IEnumerable <int> arr = null;

            arr.IsNullOrEmpty().Should().BeTrue();
        }