Ejemplo n.º 1
0
        public void InsertSortTest()
        {
            // Random elements
            var sorter = new InsertionSort<int>();
            sorter.Sort(shuffledList);
            var temp = shuffledList.ToArray();
            Array.Sort(temp);
            CollectionAssert.AreEqual(temp, shuffledList);

            //one element
            var collection = new[] {0};
            sorter.Sort(collection);
            temp = collection.ToArray();
            Array.Sort(temp);
            CollectionAssert.AreEqual(temp, collection);

            //zero elements
            collection = new int[0];
            sorter.Sort(collection);
            temp = collection.ToArray();
            Array.Sort(temp);
            CollectionAssert.AreEqual(temp, collection);

            //null elements
            collection = null;
            sorter.Sort(collection);
            CollectionAssert.AreEqual(null, collection);
        }
        public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
        {
            var standardValues = new[] { NullLifetimeManagerDisplay }
                .Union(LifetimeManagerTypes.Select(x => x.Name))
                .Union(new[] {DesignResources.RegistrationLifetimeCustom});

            return new StandardValuesCollection(standardValues.ToArray());
        }
Ejemplo n.º 3
0
        public void Set(object target, object value, params object[] index)
        {
            IEnumerable<object> args = new[] { value };
            if (index != null) args = args.Union(index);
            if (target != null && !target.GetType().CanAssign(InternalMember.DeclaringType))
                throw new TargetException("Expected {0}".AsFormat(InternalMember.DeclaringType.GetRealClassName()));

            Cache.GetSetter(InternalMember)(target, args.ToArray());
        }
Ejemplo n.º 4
0
        public static Image BinaryToImage(System.Data.Linq.Binary binaryData)
        {
            if (binaryData == null) return null;

            byte[] buffer = binaryData.ToArray();
            MemoryStream memStream = new MemoryStream();
            memStream.Write(buffer, 0, buffer.Length);
            return Image.FromStream(memStream);
        }
Ejemplo n.º 5
0
        public Tree Union(Tree t, Edge e)
        {
            var es = new[] { e };
            es = es.Concat(Edges).ToArray();
            es = es.Concat(t.Edges).ToArray();

            var ns = Nodes.Concat(t.Nodes);

            return new Tree(ns.ToArray(), es.ToArray());
        }
Ejemplo n.º 6
0
        public PvcPipe Pipe(string tag, Func<IEnumerable<PvcStream>, IEnumerable<PvcStream>> plugin)
        {
            IEnumerable<string> tags = new[] { tag };
            if (tag.IndexOf(',') != -1)
            {
                tags = tag.Split(',').ToList().Select(x => x.Trim());
            }

            return this.Pipe(tags.ToArray(), plugin);
        }
        public void CanSortDates()
        {
            var sourceArray = new[] { DateTime.MaxValue, DateTime.MinValue, DateTime.Now };
            var expected = sourceArray.ToArray();
            Array.Sort(expected);
            var sorter = DedicatedSortersFactory.CreateDedicatedSorter<DateTime>();

            sorter.Sort(sourceArray);

            CollectionAssert.AreEqual(expected, sourceArray);
        }
        public void CanSortDoubles()
        {
            var sourceArray = new[] { 10.1, 20.2, 1.343, -4.121, 5.23, 6.5, 11.77, 3443.23 };
            var expected = sourceArray.ToArray();
            Array.Sort(expected);
            var sorter = DedicatedSortersFactory.CreateDedicatedSorter<double>();

            sorter.Sort(sourceArray);

            CollectionAssert.AreEqual(expected, sourceArray);
        }
Ejemplo n.º 9
0
        public void LoadChildNodes(TreeNode node, System.Collections.Generic.IList<TreeNode> nodes)
        {
            tableNodeContainer.BeforeExpand -= tableNodeContainer_BeforeExpand;

            node.Nodes.Clear();
            node.Nodes.AddRange(nodes.ToArray());
            node.Expand();
            ShowReady();

            tableNodeContainer.BeforeExpand += tableNodeContainer_BeforeExpand;
        }
        public void CanSortFloats()
        {
            var sourceArray = new[] { 10.1f, 20.2f, 1.343f, -4.121f, 5.23f, 6.5f, 11.77f, 3443.23f };
            var expected = sourceArray.ToArray();
            Array.Sort(expected);
            var sorter = DedicatedSortersFactory.CreateDedicatedSorter<float>();

            sorter.Sort(sourceArray);

            CollectionAssert.AreEqual(expected, sourceArray);
        }
        public void CanSortIntegers()
        {
            var sourceArray = new[] { 10, 20, 1, -4, 5, 6, 11, 3443 };
            var expected = sourceArray.ToArray();
            Array.Sort(expected);
            var sorter = DedicatedSortersFactory.CreateDedicatedSorter<int>();

            sorter.Sort(sourceArray);

            CollectionAssert.AreEqual(expected, sourceArray);
        }
Ejemplo n.º 12
0
        public void XOR_AllTrue_Multiple()
        {
            // Arrange
            bool result;
            var inputs = new[] { true, true, true };
            IConditionModifier modifier = new XORModifier();

            // Act
            result = modifier.IsConditionMet(true, inputs.ToArray());

            // Assert
            Assert.IsFalse(result);
        }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            var names = new[] { "Bessie", "Vashti", "Frederica", "Nisha", "Kendall", "Magdalena", "Brendon", "Eve", "Manda", "Elvera", "Miquel", "Tyra", "Lucie", "Marvella", "Tracee", "Ramiro", "Irene", "Davina", "Jeromy", "Siu" };
            //1
            Console.WriteLine("Create a list of Persons, each with one of the names");
            foreach (string s in (string[])names.ToArray())
            {
                Console.WriteLine(s);
            }
            //2
            Console.WriteLine("Create the same list then get a subset with only people whose names start with M");
            var mStarts = from s in names.ToList() where s.StartsWith("M") select s;
            foreach (string s in (string[])mStarts.ToArray())
            {
                Console.WriteLine(s);
            }

            //3
            Console.WriteLine("Create the same list then get a list everyone’s names in uppercase ");
            var upper = names.Select(x => x.ToUpper()).ToArray();
            foreach (string s in (string[])upper.ToArray())
            {
                Console.WriteLine(s);
            }
            //4
            Console.WriteLine("Create the same list then get a and array if int with the length of each name");
            foreach (string s in (string[])names.ToArray())
            {
                Console.WriteLine(s + " --> " + s.Length);
            }
            //5
            Console.WriteLine("Create the same list then get a list with only the name shortened to the first three letters ordered by name");
            var strfirst3charorder = names.Select(x => x.Substring(0, 3)).OrderBy(x => x);
            foreach (string s in (string[])strfirst3charorder.ToArray())
            {
                Console.WriteLine(s);
            }
            Console.ReadLine();
        }
 public void Save(string file, System.IO.MemoryStream contents)
 {
     using (System.IO.IsolatedStorage.IsolatedStorageFile isoStorage = GetISOStorage())
     {
         using (var writer = new System.IO.IsolatedStorage.IsolatedStorageFileStream(file, System.IO.FileMode.Create, isoStorage))
         {
             if (contents.CanSeek && contents.Position > 0) contents.Seek(0, SeekOrigin.Begin);
             byte[] data = contents.ToArray();
             writer.Write(data, 0, data.Length);
             writer.Close();
         }
     }
 }
Ejemplo n.º 15
0
        public async Task<bool> Save(string file, System.IO.MemoryStream contents)
        {
            byte[] data = contents.ToArray();

            var folder = ApplicationData.Current.LocalFolder;
            var f = await folder.CreateFileAsync(file, CreationCollisionOption.ReplaceExisting);

            using (var s = await f.OpenStreamForWriteAsync())
            {
                await s.WriteAsync(data, 0, data.Length);
            }
            return true;
        }
Ejemplo n.º 16
0
        private System.Collections.Generic.List<TestPlan> getTestPlansFromProjectsInPipelineByName(
            System.Collections.Generic.List<TestProject> testProjects,
            System.Collections.Generic.List<TestPlan> testPlans,
            string[] testPlanNames,
            bool makeFail,
            bool inputNotSpecified)
        {
            
            GetTLTestPlanCommand cmdlet = new GetTLTestPlanCommand();

            if (inputNotSpecified) {
                cmdlet.InputObject = null;
            } else {
                TestProject[] projectsArray =
                    testProjects.ToArray();
                cmdlet.InputObject = projectsArray;
            }
            cmdlet.TestPlanName = testPlanNames;
            
            TLAddinData.CurrentTestLinkConnection =
                FakeTestLinkFactory.GetTestLinkWithTestPlans(testProjects, testPlans, null, null);
            
            if (inputNotSpecified) {
                TLAddinData.CurrentTestProject = testProjects[0];
            }
            
            if (makeFail) {
                TLAddinData.CurrentTestLinkConnection = null;
            }
            
            TLSrvGetTestPlanCommand command =
                new TLSrvGetTestPlanCommand(cmdlet);
            command.Execute();
            
            System.Collections.Generic.List<TestPlan> resultList =
                new System.Collections.Generic.List<TestPlan>();

            foreach (object tpl in PSTestLib.UnitTestOutput.LastOutput) {

                resultList.Add((TestPlan)tpl);
            }

            return resultList;
            
        }
        private static void VerifyAllExpectedSolutionsWhereLoaded(SolutionsLauncherViewModel viewModel)
        {
            SolutionViewModel[] expected = new[] {
                new SolutionViewModel
                        {
                            FullFilePath = solutionFileName,
                            Priority = 0
                        },
            new SolutionViewModel
                        {
                            FullFilePath = sibllingSolutionFileName,
                            Priority = 0
                        }};

            var expectedArray = expected.ToArray();
            var actualArray = viewModel.SiblingsSolutions.Cast<SolutionViewModel>().ToArray();

            CollectionAssert.AreEquivalent(expectedArray, actualArray);
        }
        public void WhenContactIsSelected_ThenEmailContactCommandIsEnabledAndNotifiesChange()
        {
            var contactsServiceMock = new Mock<IContactsService>();
            var resultMock = new Mock<IAsyncResult>();
            IEnumerable<Contact> contacts = new[] { new Contact { }, new Contact { } };
            contactsServiceMock
                .Setup(svc => svc.GetContactsAsync())
                .Returns(Task.FromResult(contacts));

            var regionManager = new RegionManager();

            var viewModel = new TestContactsViewModel(contactsServiceMock.Object, regionManager, contacts.ToArray());

            var notified = false;
            viewModel.EmailContactCommand.CanExecuteChanged += (s, o) => notified = true;
            Assert.IsFalse(viewModel.EmailContactCommand.CanExecute(null));
            viewModel.Contacts.MoveCurrentToFirst();
            Assert.IsTrue(viewModel.EmailContactCommand.CanExecute(null));
            Assert.IsTrue(notified);
        }
Ejemplo n.º 19
0
		public MatchingContains(bool useCase, bool useContains)
		{
			var tmp = new[] { Matching, MatchingCase, Contains, ContainsCase, NotMatching, NotMatchingCase, NotContains, NotContainsCase }.ToList();

			if (!useCase)
			{
				tmp.Remove(MatchingCase);
				tmp.Remove(ContainsCase);
				tmp.Remove(NotMatchingCase);
				tmp.Remove(NotContainsCase);
			}
			if (!useContains)
			{
				tmp.Remove(Contains);
				tmp.Remove(NotContains);
				tmp.Remove(ContainsCase);
				tmp.Remove(NotContainsCase);
			}

			AvailableValues = tmp.ToArray();
			DefaultValue = Matching;
		}
Ejemplo n.º 20
0
        public Payload GetSharedMedia(string id, bool includeChildren, int startIndex, int requestCount)
        {
            _hierarchy = _hierarchy ?? CreateHierarchy();

            var node = _hierarchy.GetNode(id);

            IEnumerable<AbstractSharedMediaInfo> nodes = new []{node.ToMedia()};
            if (includeChildren)
            {
                nodes = _hierarchy.GetChildren(node).Select(n => n.ToMedia())
                    .Skip(startIndex);
                if (requestCount != 0)
                {
                    nodes = nodes.Take(requestCount);
                }

            }

            var list = nodes.ToArray();

            ApplySortIndexes(list);

            return new Payload(node.Id, node.ParentId, node.Title, 0, list, node.IsContainer);
        }
Ejemplo n.º 21
0
        private static void TestCreateGrammar(IEnumerable<Operator> operators)
        {
            IEnumerable<string> expectedFromSymbols = new[] { "V", "C", "InfGuard", "RegOp2Operands", "OpNode", "OpOrOp0NodeOperands", "OpOrVNodeOperands", "OpOrVNode" };
            expectedFromSymbols = expectedFromSymbols.Concat(operators.GroupBy(op => op.Arity).Select(g => "Op" + g.Key + "Node"))
                .Concat(operators.Where(op => op.Arity > 0).Select(op => op.Name + "Node"));

            expectedFromSymbols = expectedFromSymbols.OrderBy(s => s);

            Random random = RandomMock.Setup(EnumerableExtensions.Repeat(i => i * 0.1, 10));
            IDictionary<Operator, double> operatorAndProbabilityMap = new DictionaryExt<Operator, double>(operators.Select((op, i) => new KeyValuePair<Operator, double>(op, i % 2 + 1)));
            Grammar<Operator> grammar = FormulaTreeGenerator.CreateGrammar(random, operatorAndProbabilityMap, () => 0, 1, false, 0.3, 0.3);
            IEnumerable<string> fromSymbols = grammar.Rules.Select(r => r.From.Name).OrderBy(s => s);
            Assert.AreElementsEqual(expectedFromSymbols.ToArray(), fromSymbols.ToArray());
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Converts a MemoryStream to a string. Makes some assumptions about the content of the stream. 
 /// </summary>
 /// <param name="s"></param>
 /// <returns></returns>
 static String MemoryStreamToString(System.IO.MemoryStream ms)
 {
     byte[] ByteArray = ms.ToArray();
     return System.Text.Encoding.ASCII.GetString(ByteArray);
 }
Ejemplo n.º 23
0
        // ReSharper restore NonLocalizedString
        public static List<string> ConvertPilotFiles(IList<string> inputFiles, IProgressMonitor progress, ProgressStatus status)
        {
            string groupConverterExePath = null;
            var inputFilesPilotConverted = new List<string>();

            for (int index = 0; index < inputFiles.Count; index++)
            {
                string inputFile = inputFiles[index];
                if (!inputFile.EndsWith(BiblioSpecLiteBuilder.EXT_PILOT))
                {
                    inputFilesPilotConverted.Add(inputFile);
                    continue;
                }
                string outputFile = Path.ChangeExtension(inputFile, BiblioSpecLiteBuilder.EXT_PILOT_XML);
                // Avoid re-converting files that have already been converted
                if (File.Exists(outputFile))
                {
                    // Avoid duplication, in case the user accidentally adds both .group and .group.xml files
                    // for the same results
                    if (!inputFiles.Contains(outputFile))
                        inputFilesPilotConverted.Add(outputFile);
                    continue;
                }

                string message = string.Format(Resources.VendorIssueHelper_ConvertPilotFiles_Converting__0__to_xml, Path.GetFileName(inputFile));
                int percent = index * 100 / inputFiles.Count;
                progress.UpdateProgress(status = status.ChangeMessage(message).ChangePercentComplete(percent));

                if (groupConverterExePath == null)
                {
                    var key = Registry.LocalMachine.OpenSubKey(KEY_PROTEIN_PILOT, false);
                    if (key != null)
                    {
                        string proteinPilotCommandWithArgs = (string)key.GetValue(string.Empty);

                        var proteinPilotCommandWithArgsSplit =
                            proteinPilotCommandWithArgs.Split(new[] { "\" \"" }, StringSplitOptions.RemoveEmptyEntries);     // Remove " "%1" // Not L10N
                        string path = Path.GetDirectoryName(proteinPilotCommandWithArgsSplit[0].Trim(new[] { '\\', '\"' })); // Remove preceding "
                        if (path != null)
                        {
                            var groupFileExtractorPath = Path.Combine(path, EXE_GROUP_FILE_EXTRACTOR);
                            if (File.Exists(groupFileExtractorPath))
                            {
                                groupConverterExePath = groupFileExtractorPath;
                            }
                            else
                            {
                                var group2XmlPath = Path.Combine(path, EXE_GROUP2_XML);
                                if (File.Exists(group2XmlPath))
                                {
                                    groupConverterExePath = group2XmlPath;
                                }
                                else
                                {
                                    string errorMessage = string.Format(Resources.VendorIssueHelper_ConvertPilotFiles_Unable_to_find__0__or__1__in_directory__2____Please_reinstall_ProteinPilot_software_to_be_able_to_handle__group_files_,
                                        EXE_GROUP_FILE_EXTRACTOR, EXE_GROUP2_XML, path);
                                    throw new IOException(errorMessage);
                                }
                            }
                        }
                    }

                    if (groupConverterExePath == null)
                    {
                        throw new IOException(Resources.VendorIssueHelper_ConvertPilotFiles_ProteinPilot_software__trial_or_full_version__must_be_installed_to_convert___group__files_to_compatible___group_xml__files_);
                    }
                }

                // run group2xml
                // ReSharper disable NonLocalizedString
                var argv = new[]
                               {
                                   "XML",
                                   "\"" + inputFile + "\"",
                                   "\"" + outputFile + "\""
                               };
                // ReSharper restore NonLocalizedString

                var psi = new ProcessStartInfo(groupConverterExePath)
                              {
                                  CreateNoWindow = true,
                                  UseShellExecute = false,
                                  // Common directory includes the directory separator
                                  WorkingDirectory = Path.GetDirectoryName(groupConverterExePath) ?? string.Empty,
                                  Arguments = string.Join(" ", argv.ToArray()), // Not L10N
                                  RedirectStandardError = true,
                                  RedirectStandardOutput = true,
                              };

                var sbOut = new StringBuilder();
                var proc = new Process {StartInfo = psi};
                proc.Start();

                var reader = new ProcessStreamReader(proc);
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    if (progress.IsCanceled)
                    {
                        proc.Kill();
                        throw new LoadCanceledException(status.Cancel());
                    }

                    sbOut.AppendLine(line);
                }

                while (!proc.WaitForExit(200))
                {
                    if (progress.IsCanceled)
                    {
                        proc.Kill();
                        return inputFilesPilotConverted;
                    }
                }

                if (proc.ExitCode != 0)
                {
                    throw new IOException(TextUtil.LineSeparate(string.Format(Resources.VendorIssueHelper_ConvertPilotFiles_Failure_attempting_to_convert_file__0__to__group_xml_,
                                                        inputFile), string.Empty, sbOut.ToString()));
                }

                inputFilesPilotConverted.Add(outputFile);
            }
            progress.UpdateProgress(status.ChangePercentComplete(100));
            return inputFilesPilotConverted;
        }
Ejemplo n.º 24
0
        private static void ConvertLocalWiffToMzxml(string filePathWiff, int sampleIndex,
            string outputPath, IProgressMonitor monitor)
        {
            var argv = new[]
                           {
                               "--mzXML", // Not L10N
                               "-s" + (sampleIndex + 1), // Not L10N
                               "\"" + filePathWiff + "\"", // Not L10N
                               "\"" + outputPath + "\"", // Not L10N
                           };

            var psi = new ProcessStartInfo(EXE_MZ_WIFF)
            {
                CreateNoWindow = true,
                UseShellExecute = false,
                // Common directory includes the directory separator
                WorkingDirectory = Path.GetDirectoryName(filePathWiff) ?? string.Empty,
                Arguments = string.Join(" ", argv.ToArray()), // Not L10N
                RedirectStandardError = true,
                RedirectStandardOutput = true,
            };

            var sbOut = new StringBuilder();
            var proc = new Process { StartInfo = psi };
            proc.Start();

            var reader = new ProcessStreamReader(proc);
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                if (monitor.IsCanceled)
                {
                    proc.Kill();
                    throw new LoadCanceledException(new ProgressStatus(string.Empty).Cancel());
                }

                sbOut.AppendLine(line);
            }

            while (!proc.WaitForExit(200))
            {
                if (monitor.IsCanceled)
                {
                    proc.Kill();
                    throw new LoadCanceledException(new ProgressStatus(string.Empty).Cancel());
                }
            }

            // Exit code -4 is a compatibility warning but not necessarily an error
            if (proc.ExitCode != 0 && !IsCompatibilityWarning(proc.ExitCode))
            {
                var message = TextUtil.LineSeparate(string.Format(Resources.VendorIssueHelper_ConvertLocalWiffToMzxml_Failure_attempting_to_convert_sample__0__in__1__to_mzXML_to_work_around_a_performance_issue_in_the_AB_Sciex_WiffFileDataReader_library,
                                                                  sampleIndex, filePathWiff),
                                                    string.Empty,
                                                    sbOut.ToString());
                throw new IOException(message);
            }
        }
        public void Can_call_method_with_one_list_of_string_arg()
        {
            try
            {
                var listValue = new[] { "Hello", "World" }.ToList();
                var valueString = string.Join(",", listValue.ToArray());

                var actionInvoke = CreateInvokerWithSimpleController();

                actionInvoke.Invoke(typeof(SimpleController).Name
                    + "://TestWithOneListOfStringArg/" + valueString);

                Assert.That(simpleController.HitoryJoined,
                    Is.EqualTo("TestWithOneListOfStringArg(" + valueString + ")"));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 26
0
        public float[] BvhNodesAsFloatArray(GpuSmitsBVHNode[] nodes)
        {
            return
                nodes.SelectMany(n =>
                {

                    var lc = new GpuBVHNodeU(ref n);
                    var r = lc.v0;
                    var data = new[] { r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7] };
                    return data.ToArray();
                }).ToArray();
        }
Ejemplo n.º 27
0
 private static string ComposeFullMethodName(MethodDefinition method, bool includeParamsToName)
 {
     var @params = method.Parameters.Select(p =>
     {
         if (p.ParameterType.IsArray)
         {
             ArrayType array = (ArrayType)p.ParameterType;
             if (array.Dimensions.Count > 1)
                 return array.ElementType.Name + "Array" + array.Dimensions.Count.ToString();
             else
                 return array.ElementType.Name + "Array";
         }
         else
             return p.ParameterType.Name;
     });
     IEnumerable<string> partsOfName = new[] {method.IsConstructor ? "Ctor" : method.Name};
     if (includeParamsToName)
         partsOfName = partsOfName.Concat(@params);
     return string.Join("_", partsOfName.ToArray());
 }
Ejemplo n.º 28
0
		public override Task<DebugResult> Scopes(int frameId) {

			var scopes = new List<Scope>();

			var frame = _frameHandles.Get(frameId, null);

			if (frame.Index == 0 && _exception != null) {
				scopes.Add(new Scope("Exception", _variableHandles.Create(new ObjectValue[] { _exception })));
			}

			var parameters = new[] { frame.GetThisReference() }.Concat(frame.GetParameters()).Where(x => x != null);
			if (parameters.Any()) {
				scopes.Add(new Scope("Argument", _variableHandles.Create(parameters.ToArray())));
			}

			var locals = frame.GetLocalVariables();
			if (locals.Length > 0) {
				scopes.Add(new Scope("Local", _variableHandles.Create(locals)));
			}

			return Task.FromResult(new DebugResult(new ScopesResponseBody(scopes)));
		}
        public override void Scopes(Response response, dynamic args)
        {
            int frameId = getInt(args, "frameId", 0);
            var frame = _frameHandles.Get(frameId, null);

            var scopes = new List<Scope>();

            if (frame.Index == 0 && _exception != null) {
                scopes.Add(new Scope("Exception", _variableHandles.Create(new ObjectValue[] { _exception })));
            }

            var parameters = new[] { frame.GetThisReference() }.Concat(frame.GetParameters()).Where(x => x != null);
            if (parameters.Any()) {
                scopes.Add(new Scope("Argument", _variableHandles.Create(parameters.ToArray())));
            }

            var locals = frame.GetLocalVariables();
            if (locals.Length > 0) {
                scopes.Add(new Scope("Local", _variableHandles.Create(locals)));
            }

            SendResponse(response, new ScopesResponseBody(scopes));
        }
Ejemplo n.º 30
0
        public IEnumerable<Tag> GetNewTags(Guid subject, Folder parentFolder, bool deepSearch)
        {
            using (var DbManager = GetDbManager())
            {
                if (parentFolder == null || parentFolder.ID == null)
                    throw new ArgumentException("folderId");

                var result = new List<Tag>();

                var monitorFolderIds = new[] {parentFolder.ID}.AsEnumerable();

                var getBaseSqlQuery = new Func<SqlQuery>(() =>
                                                             {
                                                                 var fnResult =
                                                                     Query("files_tag ft")
                                                                         .Select("ft.name",
                                                                                 "ft.flag",
                                                                                 "ft.owner",
                                                                                 "ftl.entry_id",
                                                                                 "ftl.entry_type",
                                                                                 "ftl.tag_count",
                                                                                 "ft.id")
                                                                         .Distinct()
                                                                         .InnerJoin("files_tag_link ftl",
                                                                                    Exp.EqColumns("ft.tenant_id", "ftl.tenant_id") &
                                                                                    Exp.EqColumns("ft.id", "ftl.tag_id"))
                                                                         .Where(Exp.Eq("ft.flag", (int) TagType.New));

                                                                 if (subject != Guid.Empty)
                                                                     fnResult.Where(Exp.Eq("ft.owner", subject));

                                                                 return fnResult;
                                                             });

                var tempTags = Enumerable.Empty<Tag>();

                if (parentFolder.FolderType == FolderType.SHARE)
                {
                    var shareQuery =
                        new Func<SqlQuery>(() => getBaseSqlQuery().InnerJoin("files_security fs",
                                                                             Exp.EqColumns("fs.tenant_id", "ftl.tenant_id") &
                                                                             Exp.EqColumns("fs.entry_id", "ftl.entry_id") &
                                                                             Exp.EqColumns("fs.entry_type", "ftl.entry_type")));

                    var tmpShareFileTags = DbManager.ExecuteList(
                        shareQuery().InnerJoin("files_file f",
                                               !Exp.Eq("f.create_by", subject) &
                                               Exp.EqColumns("f.id", "ftl.entry_id") &
                                               Exp.Eq("ftl.entry_type", FileEntryType.File))
                                    .Select(GetRootFolderType("folder_id")))
                                                    .Where(r => ParseRootFolderType(r[7]) == FolderType.USER).ToList()
                                                    .ConvertAll(r => ToTag(r));
                    tempTags = tempTags.Concat(tmpShareFileTags);


                    var tmpShareFolderTags = DbManager.ExecuteList(
                        shareQuery().InnerJoin("files_folder f",
                                               !Exp.Eq("f.create_by", subject) &
                                               Exp.EqColumns("f.id", "ftl.entry_id") &
                                               Exp.Eq("ftl.entry_type", FileEntryType.Folder))
                                    .Select(GetRootFolderType("parent_id")))
                                                      .Where(r => ParseRootFolderType(r[7]) == FolderType.USER).ToList()
                                                      .ConvertAll(r => ToTag(r));
                    tempTags = tempTags.Concat(tmpShareFolderTags);

                    var tmpShareSboxTags = DbManager.ExecuteList(
                        shareQuery()
                            .InnerJoin("files_thirdparty_id_mapping m",
                                       Exp.EqColumns("m.hash_id", "ftl.entry_id"))
                            .InnerJoin("files_thirdparty_account ac",
                                       Exp.Sql("m.id Like concat('sbox-', ac.id, '%')") &
                                       !Exp.Eq("ac.user_id", subject) &
                                       Exp.Eq("ac.folder_type", FolderType.USER)
                            )
                        ).ConvertAll(r => ToTag(r));

                    tempTags = tempTags.Concat(tmpShareSboxTags);
                }
                else if (parentFolder.FolderType == FolderType.Projects)
                    tempTags = DbManager.ExecuteList(getBaseSqlQuery().InnerJoin("files_bunch_objects fbo",
                                                                                 Exp.EqColumns("fbo.tenant_id", "ftl.tenant_id") &
                                                                                 Exp.EqColumns("fbo.left_node", "ftl.entry_id") &
                                                                                 Exp.Eq("ftl.entry_type", (int) FileEntryType.Folder))
                                                                      .Where(Exp.Eq("fbo.tenant_id", TenantID) & Exp.Like("fbo.right_node", "projects/project/", SqlLike.StartWith)))
                                        .ConvertAll(r => ToTag(r));

                if (tempTags.Any())
                {
                    if (!deepSearch) return tempTags;

                    monitorFolderIds = monitorFolderIds.Concat(tempTags.Where(x => x.EntryType == FileEntryType.Folder).Select(x => x.EntryId));
                    result.AddRange(tempTags);
                }

                var subFoldersSqlQuery = new SqlQuery("files_folder_tree")
                    .Select("folder_id")
                    .Where(Exp.In("parent_id", monitorFolderIds.ToArray()));

                if (!deepSearch)
                    subFoldersSqlQuery.Where(Exp.Eq("level", 1));

                monitorFolderIds = monitorFolderIds.Concat(DbManager.ExecuteList(subFoldersSqlQuery).ConvertAll(x => x[0]));

                var newTagsForFolders = DbManager.ExecuteList(getBaseSqlQuery()
                                                                  .Where(Exp.In("ftl.entry_id", monitorFolderIds.ToArray()) &
                                                                         Exp.Eq("ftl.entry_type", (int) FileEntryType.Folder)))
                                                 .ConvertAll(r => ToTag(r));

                result.AddRange(newTagsForFolders);

                var newTagsForFiles = DbManager.ExecuteList(getBaseSqlQuery()
                                                                .InnerJoin("files_file ff",
                                                                           Exp.EqColumns("ftl.tenant_id", "ff.tenant_id") &
                                                                           Exp.EqColumns("ftl.entry_id", "ff.id"))
                                                                .Where(Exp.In("ff.folder_id", (deepSearch
                                                                                                   ? monitorFolderIds.ToArray()
                                                                                                   : new[] {parentFolder.ID})) &
                                                                       Exp.Eq("ftl.entry_type", (int) FileEntryType.File)))
                                               .ConvertAll(r => ToTag(r));

                result.AddRange(newTagsForFiles);

                if (parentFolder.FolderType == FolderType.USER || parentFolder.FolderType == FolderType.COMMON)
                {
                    var folderType = parentFolder.FolderType;

                    var querySelect = new SqlQuery("files_thirdparty_account")
                        .Select("id")
                        .Where("tenant_id", TenantID)
                        .Where("folder_type", (int) folderType);

                    if (folderType == FolderType.USER)
                        querySelect = querySelect.Where(Exp.Eq("user_id", subject.ToString()));

                    var sboxFolderIds = DbManager.ExecuteList(querySelect).ConvertAll(r => "sbox-" + r[0]);

                    var newTagsForSBox = DbManager.ExecuteList(getBaseSqlQuery()
                                                                   .InnerJoin("files_thirdparty_id_mapping mp", Exp.EqColumns("ftl.entry_id", "mp.hash_id"))
                                                                   .Where(Exp.In("mp.id", sboxFolderIds) &
                                                                          Exp.Eq("ft.owner", subject) &
                                                                          Exp.Eq("ftl.entry_type", (int) FileEntryType.Folder)))
                                                  .ConvertAll(r => ToTag(r));

                    result.AddRange(newTagsForSBox);
                }

                return result;
            }
        }