Example #1
1
        private IEnumerable<XElement> AddDirectoryAsync(DirectoryInfo dir, string collectionId, ref int count, int fnumber,
            BackgroundWorker worker)
        {
            List<XElement> addedElements = new List<XElement>();
            // добавление коллекции
            string subCollectionId;
            List<XElement> ae = this.cass.AddCollection(dir.Name, collectionId, out subCollectionId).ToList();
            if (ae.Count > 0) addedElements.AddRange(ae);

            count++;
            foreach (FileInfo f in dir.GetFiles())
            {
                if (worker.CancellationPending) break;
                if (f.Name != "Thumbs.db")
                    addedElements.AddRange(this.cass.AddFile(f, subCollectionId));
                count++;
                worker.ReportProgress(100 * count / fnumber);
            }
            foreach (DirectoryInfo d in dir.GetDirectories())
            {
                if (worker.CancellationPending) break;
                addedElements.AddRange(AddDirectoryAsync(d, subCollectionId, ref count, fnumber, worker));
            }
            return addedElements;
        }
Example #2
0
        /// <summary>
        /// Gets all matches for a given requested route
        /// Overridden to handle greedy capturing
        /// </summary>
        /// <param name="segments">Requested route segments</param>
        /// <param name="currentIndex">Current index in the route segments</param>
        /// <param name="capturedParameters">Currently captured parameters</param>
        /// <param name="context">Current Nancy context</param>
        /// <returns>A collection of <see cref="MatchResult"/> objects</returns>
        public override IEnumerable<MatchResult> GetMatches(string[] segments, int currentIndex, IDictionary<string, object> capturedParameters, NancyContext context)
        {
            var fullGreedy = this.GetFullGreedy(segments, currentIndex, capturedParameters);
            if (!this.Children.Any())
            {
                return fullGreedy;
            }

            var sb = new StringBuilder(segments[currentIndex]);
            var results = new List<MatchResult>();
            currentIndex++;

            while (!this.NoMoreSegments(segments, currentIndex - 1))
            {
                var currentSegment = segments[currentIndex];

                TrieNode matchingChild;
                if (this.Children.TryGetValue(currentSegment, out matchingChild))
                {
                    var parameters = new Dictionary<string, object>(capturedParameters);
                    parameters[this.parameterName] = sb.ToString();
                    results.AddRange(matchingChild.GetMatches(segments, currentIndex, parameters, context));
                }

                sb.AppendFormat("/{0}", currentSegment);
                currentIndex++;
            }

            if (!results.Any())
            {
                results.AddRange(fullGreedy);
            }

            return results;
        }
        private byte[] GetLengthBytes()
        {
            var payloadLengthBytes = new List<byte>(9);

            if (PayloadLength > ushort.MaxValue)
            {
                payloadLengthBytes.Add(127);
                byte[] lengthBytes = BitConverter.GetBytes(PayloadLength);
                if (BitConverter.IsLittleEndian)
                    Array.Reverse(lengthBytes);
                payloadLengthBytes.AddRange(lengthBytes);
            }
            else if (PayloadLength > 125)
            {
                payloadLengthBytes.Add(126);
                byte[] lengthBytes = BitConverter.GetBytes((UInt16) PayloadLength);
                if (BitConverter.IsLittleEndian)
                    Array.Reverse(lengthBytes);
                payloadLengthBytes.AddRange(lengthBytes);
            }
            else
            {
                payloadLengthBytes.Add((byte) PayloadLength);
            }

            payloadLengthBytes[0] += (byte) (IsMasked ? 128 : 0);

            return payloadLengthBytes.ToArray();
        }
Example #4
0
 public IList<JToken> ToList()
 {
     var retval = new List<JToken>();
     retval.AddRange(Events.Values);
     retval.AddRange(Tours.Values);
     return retval;
 }
Example #5
0
        protected virtual ExitCode ChangeSetting(IClientSettings clientSettings, SettingsLocation location, ChangeType changeType)
        {
            // Don't want to save defaults for options that apply directly to this command
            List<string> settingsToSkip = new List<string>();
            settingsToSkip.AddRange(StandardOptions.List);
            settingsToSkip.AddRange(StandardOptions.Add);
            settingsToSkip.AddRange(StandardOptions.Remove);

            foreach (var setting in this.Arguments.Options)
            {
                if (settingsToSkip.Contains(setting.Key, StringComparer.OrdinalIgnoreCase)) { continue; }
                bool success = false;
                switch (changeType)
                {
                    case ChangeType.Add:
                        this.Loggers[LoggerType.Status].Write(XTaskStrings.DefaultsSavingProgress, setting.Key);
                        success = clientSettings.SaveSetting(location, setting.Key, setting.Value);
                        break;
                    case ChangeType.Remove:
                        this.Loggers[LoggerType.Status].Write(XTaskStrings.DefaultsRemovingProgress, setting.Key);
                        success = clientSettings.RemoveSetting(location, setting.Key);
                        break;
                }

                this.Loggers[LoggerType.Status].WriteLine(success ? XTaskStrings.Succeeded : XTaskStrings.Failed);
            }

            return ExitCode.Success;
        }
Example #6
0
        // Return a list of folders that need to be on the %PATH%
        public virtual List<string> GetPathFolders(IEnvironment environment)
        {
            // Add the msbuild path and git path to the %PATH% so more tools are available
            var toolsPaths = new List<string> {
                environment.DeploymentToolsPath, // Add /site/deployments/tools to the path to allow users to drop tools in there
                environment.ScriptPath,
                Path.GetDirectoryName(ResolveMSBuildPath()),
                Path.GetDirectoryName(ResolveGitPath()),
                Path.GetDirectoryName(ResolveVsTestPath()),
                Path.GetDirectoryName(ResolveSQLCmdPath()),
                Path.GetDirectoryName(ResolveFSharpCPath())
            };

            toolsPaths.AddRange(ResolveGitToolPaths());
            toolsPaths.AddRange(ResolveNodeNpmPaths());
            toolsPaths.Add(ResolveNpmGlobalPrefix());

            toolsPaths.AddRange(new[]
            {
                ResolveBowerPath(),
                ResolveGruntPath(),
                ResolveGulpPath()
            }.Where(p => !String.IsNullOrEmpty(p)).Select(Path.GetDirectoryName));

            return toolsPaths;
        }
        public static NamespaceDeclarationSyntax AddUsingDirectives(
            this NamespaceDeclarationSyntax namespaceDeclaration,
            IList<UsingDirectiveSyntax> usingDirectives,
            bool placeSystemNamespaceFirst,
            params SyntaxAnnotation[] annotations)
        {
            if (!usingDirectives.Any())
            {
                return namespaceDeclaration;
            }

            var specialCaseSystem = placeSystemNamespaceFirst;
            var comparer = specialCaseSystem
                ? UsingsAndExternAliasesDirectiveComparer.SystemFirstInstance
                : UsingsAndExternAliasesDirectiveComparer.NormalInstance;

            var usings = new List<UsingDirectiveSyntax>();
            usings.AddRange(namespaceDeclaration.Usings);
            usings.AddRange(usingDirectives);

            if (namespaceDeclaration.Usings.IsSorted(comparer))
            {
                usings.Sort(comparer);
            }

            usings = usings.Select(u => u.WithAdditionalAnnotations(annotations)).ToList();
            var newNamespace = namespaceDeclaration.WithUsings(SyntaxFactory.List(usings));

            return newNamespace;
        }
 public ActionResult Bonds()
 {
     List<Asset> assets = new List<Asset>();
     assets.AddRange(repository.GetUserAssets(UserId, AssetType.DomesticBond));
     assets.AddRange(repository.GetUserAssets(UserId, AssetType.InternationalBond));
     return View(assets);
 }
        /// <summary>
        /// This is invoked when the collection changes.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Collections.Specialized.NotifyCollectionChangedEventArgs"/> instance containing the event data.</param>
        /// <remarks>
        /// This method must be public because the <see cref="IWeakEventListener"/> is used.
        /// </remarks>
        public void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            Log.Debug("Automatically tracking change '{0}' of collection", e.Action);

            var undoList = new List<CollectionChangeUndo>();
            var collection = (IList)sender;

            switch (e.Action)
            {
                case NotifyCollectionChangedAction.Add:
                    undoList.AddRange(e.NewItems.Cast<object>().Select((item, i) => new CollectionChangeUndo(collection, CollectionChangeType.Add, -1, e.NewStartingIndex + i, null, item, Tag)));
                    break;

                case NotifyCollectionChangedAction.Remove:
                    undoList.AddRange(e.OldItems.Cast<object>().Select((item, i) => new CollectionChangeUndo(collection, CollectionChangeType.Remove, e.OldStartingIndex + i, -1, item, null, Tag)));
                    break;

                case NotifyCollectionChangedAction.Replace:
                    undoList.Add(new CollectionChangeUndo(collection, CollectionChangeType.Replace, e.OldStartingIndex, e.NewStartingIndex, e.OldItems[0], e.NewItems[0], Tag));
                    break;

#if NET
                case NotifyCollectionChangedAction.Move:
                    undoList.Add(new CollectionChangeUndo(collection, CollectionChangeType.Move, e.OldStartingIndex, e.NewStartingIndex, e.NewItems[0], e.NewItems[0], Tag));
                    break;
#endif
            }

            foreach (var operation in undoList)
            {
                MementoService.Add(operation);
            }

            Log.Debug("Automatically tracked change '{0}' of collection", e.Action);
        }
Example #10
0
        public static CodeGenFile[] Generate(ICodeGeneratorDataProvider provider, string directory, ICodeGenerator[] codeGenerators)
        {
            directory = GetSafeDir(directory);
            CleanDir(directory);

            var generatedFiles = new List<CodeGenFile>();

            foreach (var generator in codeGenerators.OfType<IPoolCodeGenerator>()) {
                var files = generator.Generate(provider.poolNames);
                generatedFiles.AddRange(files);
                writeFiles(directory, files);
            }

            foreach (var generator in codeGenerators.OfType<IComponentCodeGenerator>()) {
                var files = generator.Generate(provider.componentInfos);
                generatedFiles.AddRange(files);
                writeFiles(directory, files);
            }

            foreach (var generator in codeGenerators.OfType<IBlueprintsCodeGenerator>()) {
                var files = generator.Generate(provider.blueprintNames);
                generatedFiles.AddRange(files);
                writeFiles(directory, files);
            }

            return generatedFiles.ToArray();
        }
        private IEnumerable<SignatureHelpParameter> GetDelegateTypeParameters(IMethodSymbol invokeMethod, SemanticModel semanticModel, int position, CancellationToken cancellationToken)
        {
            const string TargetName = "target";

            var parts = new List<SymbolDisplayPart>();
            parts.AddRange(invokeMethod.ReturnType.ToMinimalDisplayParts(semanticModel, position));
            parts.Add(Space());
            parts.Add(Punctuation(SyntaxKind.OpenParenToken));

            var first = true;
            foreach (var parameter in invokeMethod.Parameters)
            {
                if (!first)
                {
                    parts.Add(Punctuation(SyntaxKind.CommaToken));
                    parts.Add(Space());
                }

                first = false;
                parts.AddRange(parameter.Type.ToMinimalDisplayParts(semanticModel, position));
            }

            parts.Add(Punctuation(SyntaxKind.CloseParenToken));
            parts.Add(Space());
            parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.ParameterName, null, TargetName));

            yield return new SignatureHelpParameter(
                TargetName,
                isOptional: false,
                documentationFactory: null,
                displayParts: parts);
        }
Example #12
0
			/// <summary>
			/// Initializes a new instance of the <see cref="Subrule"/> class.
			/// </summary>
			/// <param name="id">The id.</param>
			/// <param name="desc">The description.</param>
			/// <param name="morpher">The morpher.</param>
			/// <param name="headLhs">The head LHS.</param>
			/// <param name="nonHeadLhs">The non-head LHS.</param>
			/// <param name="rhs">The RHS.</param>
			/// <param name="alphaVars">The alpha variables.</param>
			public Subrule(string id, string desc, Morpher morpher, IEnumerable<PhoneticPattern> headLhs,
				IEnumerable<PhoneticPattern> nonHeadLhs, IEnumerable<MorphologicalOutput> rhs, AlphaVariables alphaVars)
				: base (id, desc, morpher)
			{
				m_alphaVars = alphaVars;

				List<PhoneticPattern> lhs = new List<PhoneticPattern>();
				lhs.AddRange(headLhs);
				lhs.AddRange(nonHeadLhs);

				m_transform = new MorphologicalTransform(lhs, rhs, MorphologicalTransform.RedupMorphType.IMPLICIT);

				// the LHS template is generated by simply concatenating all of the
				// LHS partitions; it matches the entire word, so we check for both the
				// left and right margins.
				m_headLhsTemp = new PhoneticPattern();
				m_headLhsTemp.Add(new MarginContext(Direction.LEFT));
				int partition = 0;
				foreach (PhoneticPattern pat in headLhs)
					m_headLhsTemp.AddPartition(pat, partition++);
				m_headLhsTemp.Add(new MarginContext(Direction.RIGHT));

				m_firstNonHeadPartition = partition;
				m_nonHeadLhsTemp = new PhoneticPattern();
				m_nonHeadLhsTemp.Add(new MarginContext(Direction.LEFT));
				foreach (PhoneticPattern pat in nonHeadLhs)
					m_nonHeadLhsTemp.AddPartition(pat, partition++);
				m_nonHeadLhsTemp.Add(new MarginContext(Direction.RIGHT));
			}
Example #13
0
        public List<Tag> BrowseTags()
        {
            //Cursor = Cursors.WaitCursor;
            if (sc == null || !sc.IsConnected()) { this.Connect(); }
            //check if the server is already connected, if not skip the execution
            if (!(sc == null))
            {
                if (sc.IsConnected())
                {
                    //build the tags query
                    var query = new TagQueryParams { PageSize = 100 };
                    var allTags = new List<Tag>();
                    List<Tag> tmp;
                    // return only string tags
                    query.Criteria.TagnameMask = "*";
                    query.Criteria.DataType = Proficy.Historian.ClientAccess.API.Tag.NativeDataType.Float;

                    //execute the query and populate the list datatype
                    while (sc.ITags.Query(ref query, out tmp))
                        allTags.AddRange(tmp);
                    allTags.AddRange(tmp);

                    //populate the combo box
                    //cboTags.DataSource = allTags;
                    //cboTags.DisplayMember = "Name";
                    //cboTags.ValueMember = "Name";

                    return allTags;
                }
            }
            return null;

            //Cursor = Cursors.Default;

        }
 private MethodInfo[] GetAllActionMethodsFromSelector()
 {
     List<MethodInfo> allValidMethods = new List<MethodInfo>();
     allValidMethods.AddRange(_selector.AliasedMethods);
     allValidMethods.AddRange(_selector.NonAliasedMethods.SelectMany(g => g));
     return allValidMethods.ToArray();
 }
Example #15
0
    private static string MakeTestName(string path)
    {
      var rx = new Regex(@"test-(\d+)");
      var tests = new List<string>();
      tests.AddRange(Directory.GetDirectories(path).Select(Path.GetFileNameWithoutExtension));
      tests.AddRange(Directory.GetFiles(path, "*.test").Select(Path.GetFileNameWithoutExtension));
      tests.Sort();
      int num = 0;
      for (int i = tests.Count - 1; i >= 0; i--)
      {
        var testName = tests[i];
        var m = rx.Match(testName);
        if (m.Success)
        {
          num = int.Parse(m.Groups[1].Value) + 1;
          break;
        }
      }

      for (;; num++)
      {
        var fileName = "test-" + num.ToString("0000");
        if (!File.Exists(Path.Combine(path, fileName + ".test")))
          return fileName;
      }
    }
Example #16
0
		public override byte[] GetData()
		{
			var data = new List<byte>();
			data.AddRange(NsBinaryWriter.WriteString(Cpu));
			data.AddRange(NsBinaryWriter.WriteString(Os));
			return data.ToArray();
		}
		/// <summary>
		/// Do the validation.
		/// </summary>
		protected void DoValidate()
		{
			currentResults = new List<ValidationResult> ();
			currentResults.AddRange (new ValidateRaycastColliders ().Validate ());
			currentResults.AddRange (new ValidateLayers ().Validate ());
			currentResults.AddRange (new ValidateRigidbodies ().Validate ());
		}
 static void Main()
 {
     Student[] arrStudentsTest = { new Student("Sonya", "Markova", 3), new Student("Sotir", "Galabov", 2), new Student("Svilen", "Belev", 2),
                                 new Student("Petar","Peshev", 5),new Student("Ivaylo","Drajev", 3),new Student("Krasi","Smilkov", 4),
                                 new Student("Yana","Mileva", 3),new Student("Vito","Zagorski", 1),new Student("Valeri","Timev", 5),
                                 new Student("Rumen","Vlahov", 6),};
     List<Student> studentsTest = arrStudentsTest.ToList();
     foreach (var student in studentsTest.OrderBy(s => s.Grade))
     {
         Console.WriteLine("Student: {0},\tGrade: {1}", student, student.Grade);
     }
     Worker[] arrWorkerTest = { new Worker("Angel", "Velev", 500, 8), new Worker("Lazar", "Penev", 230, 4), new Worker("Georgi", "Kostov", 340, 7),
                              new Worker("Vasil", "Vasilev", 600, 10), new Worker("Teo", "Simeonov", 550, 8), new Worker("Jivko", "Jelev", 380, 7),
                             new Worker("Daniel", "Hristov", 150, 5), new Worker("Mihail", "Ivanov", 480, 8), new Worker("Kamen", "Kamburov", 420, 8),
                             new Worker("Vesela", "Ganeva", 100, 2)};
     List<Worker> workerTest = arrWorkerTest.ToList();
     foreach (var worker in workerTest.OrderByDescending(w => w.MoneyPerHour()))
     {
         Console.WriteLine("Worker: {0},\tMoney Per Hour: {1:0.00}", worker.ToString(), worker.MoneyPerHour());
     }
     List<Human> all = new List<Human>();
     all.AddRange(workerTest);
     all.AddRange(studentsTest);
     foreach (var human in all.OrderBy(i => i.FirstName).ThenBy(i => i.LastName))
     {
         Console.WriteLine(human);
     }
 }
        public static List<Def> GetResearchRequirements( this RecipeDef recipeDef )
        {
            var researchDefs = new List< Def >();

            if( recipeDef.researchPrerequisite != null )
            {
                // Basic requirement
                researchDefs.Add( recipeDef.researchPrerequisite );

                // Advanced requirement
                var advancedResearchDefs = ResearchController.AdvancedResearch.Where( a => (
                    ( a.IsRecipeToggle )&&
                    ( !a.HideDefs )&&
                    ( a.recipeDefs.Contains( recipeDef ) )
                ) ).ToList();

                if( !advancedResearchDefs.NullOrEmpty() )
                {
                    foreach( var a in advancedResearchDefs )
                    {
                        researchDefs.Add( a );
                    }
                }

            }

            // Get list of things recipe is used on
            var thingsOn = new List< ThingDef >();
            var recipeThings = DefDatabase< ThingDef >.AllDefsListForReading.Where( t => (
                ( t.recipes != null )&&
                ( !t.IsLockedOut() )&&
                ( t.recipes.Contains( recipeDef ) )
            ) ).ToList();

            if( !recipeThings.NullOrEmpty() )
            {
                thingsOn.AddRange( recipeThings );
            }

            // Add those linked via the recipe
            if( !recipeDef.recipeUsers.NullOrEmpty() )
            {
                thingsOn.AddRange( recipeDef.recipeUsers );
            }

            // Make sure they all have hard requirements
            if(
                ( !thingsOn.NullOrEmpty() )&&
                ( thingsOn.All( t => t.HasResearchRequirement() ) )
            )
            {
                foreach( var t in thingsOn )
                {
                    researchDefs.AddRange( t.GetResearchRequirements() );
                }
            }

            // Return the list of research required
            return researchDefs;
        }
        public List<TestRunResults> RemoveUnmatchedRunInfoTests(TestRunResults[] results, TestRunInfo[] infos)
        {
            var tests = new List<TestItem>();
            tests.AddRange(_cache.Failed);
            tests.AddRange(_cache.Ignored);

            var removed = new List<TestRunResults>();
            infos
                .Where(i => results.Count(x => i.Assembly.Equals(x.Assembly)) == 0).ToList()
                .ForEach(i =>
                    {
                        tests.Where(x => x.Key.Equals(i.Assembly) &&
                                   (!i.OnlyRunSpcifiedTestsFor(x.Value.Runner) || i.GetTestsFor(x.Value.Runner).Count(t => t.Equals(x.Value.Name)) > 0))
                            .GroupBy(x => x.Value.Runner).ToList()
                            .ForEach(x => 
                                {
                                    removed.Add(new TestRunResults(
                                        i.Project.Key,
                                        i.Assembly,
                                        i.OnlyRunSpcifiedTestsFor(TestRunner.Any),
                                        x.Key,
                                        x.Select(t => new TestResult(
                                            t.Value.Runner,
                                            TestRunStatus.Passed,
                                            t.Value.Name,
                                            t.Value.Message,
                                            t.Value.StackTrace,
                                            t.Value.TimeSpent.TotalMilliseconds).SetDisplayName(t.Value.DisplayName)).ToArray()));
                                });
                    });
            return removed;
        }
 /// <summary>
 /// Выполнить скрипт
 /// </summary>
 /// <param name="text">Текст скрипта</param>
 public static void ExecuteScript(string text)
 {
     foreach (string block in text.Split('/'))
     {
         List<string> commands = new List<string>();
         string lower = block.ToLower();
         int posPackage = lower.IndexOf("package");
         int posProcedure = lower.IndexOf("procedure");
         int posDeclare = lower.IndexOf("declare");
         int posBegin = lower.IndexOf("begin");
         int posStart = posDeclare >= 0 ? posDeclare : posBegin;
         if (posPackage >= 0 || posProcedure >= 0)
             posStart = lower.LastIndexOf("create", posPackage >= 0 ? posPackage : posProcedure);
         if (posStart >= 0)
         {
             if (posStart > 0)
                 commands.AddRange(block.Substring(0, posStart - 1).Split(';'));
             commands.Add(block.Substring(posStart));
         }
         else
             commands.AddRange(block.Split(';'));
         foreach (string command in commands)
         {
             string commandText = command.Trim();
             if (string.IsNullOrEmpty(commandText)) continue;
             ExecuteBlock(commandText);
         }
     }
 }
 public static List<char> InvalidChars()
 {
     var invalidChars = new List<char>();
     invalidChars.AddRange(Path.GetInvalidFileNameChars());
     invalidChars.AddRange(Path.GetInvalidPathChars());
     return invalidChars;
 }
        internal static List<FilePathViewIndex> GetOpenedFiles(int view = 0)
        {
            var result = new List<FilePathViewIndex>();

            int filesCount;
            ClikeStringArray cStrArray;
            int ind;

            if (view == 0 || view == 1)
            {
                filesCount = (int)Win32.SendMessage(PluginBase.nppData._nppHandle, NppMsg.NPPM_GETNBOPENFILES, 0, 1);
                using (cStrArray = new ClikeStringArray(filesCount, Win32.MAX_PATH))
                {
                    ind = 0;
                    if (Win32.SendMessage(PluginBase.nppData._nppHandle, NppMsg.NPPM_GETOPENFILENAMESPRIMARY, cStrArray.NativePointer, filesCount) != IntPtr.Zero)
                        if (cStrArray.ManagedStringsUnicode.Count > 1 || !Utils.IsFileNew(cStrArray.ManagedStringsUnicode[0]))
                            result.AddRange(cStrArray.ManagedStringsUnicode.Select(str => new FilePathViewIndex(str, 0, ind++)));
                }
            }

            if (view == 0 || view == 2)
            {
                filesCount = (int)Win32.SendMessage(PluginBase.nppData._nppHandle, NppMsg.NPPM_GETNBOPENFILES, 0, 2);
                using (cStrArray = new ClikeStringArray(filesCount, Win32.MAX_PATH))
                {
                    ind = 0;
                    if (Win32.SendMessage(PluginBase.nppData._nppHandle, NppMsg.NPPM_GETOPENFILENAMESSECOND, cStrArray.NativePointer, filesCount) != IntPtr.Zero)
                        if (cStrArray.ManagedStringsUnicode.Count > 1 || !Utils.IsFileNew(cStrArray.ManagedStringsUnicode[0]))
                            result.AddRange(cStrArray.ManagedStringsUnicode.Select(str => new FilePathViewIndex(str, 1, ind++)));
                }
            }

            return result;
        }
Example #24
0
        /// <summary>
        /// Returns all type implementing the specified interface in all loaded assemblies
        /// </summary>
        /// <param name="expectedInterface"></param>
        /// <param name="assembly"></param>
        /// <param name="checkReferencedAssemblies">Check referenced assemblies also</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">when <paramref name="assembly"/> is null</exception>
        public static IList<Type> ThatImplement(Type expectedInterface, Assembly assembly, bool checkReferencedAssemblies)
        {
            if (assembly == null) throw new ArgumentNullException("assembly");

            var results = new List<Type>();

            var assemblies = new List<AssemblyName> {assembly.GetName()};

            if( checkReferencedAssemblies ) assemblies.AddRange(assembly.GetReferencedAssemblies());

            foreach( var referencedAssembly in assemblies )
            {
                // Catch loader exceptions for referenced assemblies
                var loadedAssembly = Assembly.Load(referencedAssembly);

                if( loadedAssembly == assembly)
                {
                    results.AddRange(ThatImplement(expectedInterface, loadedAssembly));
                }
                else
                {
                    try
                    {
                        results.AddRange(ThatImplement(expectedInterface, loadedAssembly));
                    }
                    catch (ReflectionTypeLoadException)
                    {
                        continue;
                    }
                }
            }

            return results;
        }
Example #25
0
        public SnapShotStatData GenerateStatisticData(int beginStaTime, int endStaTime, OtherSubSysInterface subSysInterface, int snapshotId)
        {
            StaSimulationCarrier carrier = new StaSimulationCarrier();
            SnapShotStatData data = new SnapShotStatData();
            data.SnapShotName = SimulationTools.GenerateSnapshotName(snapshotId);
            data.DlRsrpFailList.AddRange(this.DlRsrpFailUserList);
            data.UlRsrpFailList.AddRange(this.UlRsrpFailUserList);
            List<StatSimuCarrierResult> carrierResList = carrier.Statistic(beginStaTime, endStaTime, this.m_SimulationCarrierList, subSysInterface);
            data.StatSimuSiteResultList = new StaSimulationSite().Statistic(carrierResList, this.m_SimulationCarrierList);

            foreach (SimulationCarrier carrier2 in this.m_SimulationCarrierList)
            {
                this.SelectUsers(carrier2.OffLineUserList, data.OffLineList);
                List<ISimulationUser> waitUserList = new List<ISimulationUser>();
                waitUserList.AddRange(carrier2.DlDataWaitUserList);
                waitUserList.AddRange(carrier2.DlVoiceWaitUserList);
                waitUserList.AddRange(carrier2.UlDataWaitUserList);
                waitUserList.AddRange(carrier2.UlVoiceWaitUserList);
                temp = carrier2.count;
                this.ClassifyWaitUsers(waitUserList, data);
                data.SatisfiedList.AddRange(this.ToISimuUser(carrier2.UlVoiceServiceUserList));
                data.SatisfiedList.AddRange(this.ToISimuUser(carrier2.UlDataServiceUserList));
                data.SatisfiedList.AddRange(this.ToISimuUser(carrier2.DlVoiceServiceUserList));
                data.SatisfiedList.AddRange(this.ToISimuUser(carrier2.DlDataServiceUserList));
                data.DlRsSinrFailList.AddRange(this.ToISimuUser(carrier2.FailUserList));
                data.UlRsSinrFailList.AddRange(this.ToISimuUser(carrier2.UlRsSinrFailUserList));
            }
            
            data.WholeNetDLInstantaneousThroughput = this.m_WholeNetDLThroughput;
            data.WholeNetULInstantaneousThroughput = this.m_WholeNetULThroughput;
            return data;
        }
        public List<MaterialCost> GetMaterialCost(string hwso, string swso, string evalno)
        {
            List<MaterialCost> data = new List<MaterialCost>();
            if (hwso.Trim() != "")
            {
                List<MaterialCost> hwMCost = ComputeMaterialCost("CAPHWConnection",hwso.Trim());
                data.AddRange(hwMCost);
            }
            if (swso.Trim() != "")
            {
                List<MaterialCost> swMCost = ComputeMaterialCost("CAPSWConnection", swso.Trim());
                data.AddRange(swMCost);
            }

            if (evalno.Trim() != "")
            {
                string[] evalnos = evalno.Split(',');
                foreach (string e in evalnos)
                {
                    string nSoNum = Regex.Replace(e, "[^0-9]", "");
                    if (nSoNum.Trim() != "")
                    {
                        string connection = GetConnectionString(nSoNum.Trim());
                        if (connection.Trim() != "")
                        {
                            List<MaterialCost> eMCost = ComputeMaterialCost("CAPSWConnection", nSoNum.Trim());
                            data.AddRange(eMCost);
                        }
                    }
                }
            }
            return data;
        }
Example #27
0
		public List<string> GetAllFilePathsAsList()
		{
			var list = new List<string> { Csproj, AssemblyInfo };
			list.AddRange(Icons);
			list.AddRange(SourceCodeFiles);
			return list;
		}
Example #28
0
        protected static byte[] ConvertOptionFieldToByte(ushort optionType, byte[] value, bool reverseByteOrder, Action<Exception> ActionOnException)
        {
            Contract.Requires<ArgumentNullException>(value != null, "value cannot be null");
            Contract.Requires<ArgumentException>(value.Length > 0 || optionType == 0, "Only for optionType == 0 value.Lenght can be == 0");
            Contract.Requires<IndexOutOfRangeException>(value.Length <= UInt16.MaxValue, "value.Lenght > UInt16.MaxValue");
            
            List<byte> ret = new List<byte>();

            try
            {
                int remainderLength = (AlignmentBoundary - value.Length % AlignmentBoundary) % AlignmentBoundary;
                ret.AddRange(BitConverter.GetBytes(optionType.ReverseByteOrder(reverseByteOrder)));
                ret.AddRange(BitConverter.GetBytes(((UInt16)value.Length).ReverseByteOrder(reverseByteOrder)));
                if (value.Length > 0)
                {
                    ret.AddRange(value);
                    for (int i = 0; i < remainderLength; i++)
                    {
                        ret.Add(0);
                    }
                }
            }
            catch (Exception exc)
            {
                if (ActionOnException != null)
                    ActionOnException(exc);
            }

            return ret.ToArray();
        }
Example #29
0
    static List<int> QuickSort(List<int> list)
    {
        if (list.Count <= 1)
        {
            return list;
        }

        List<int> min = new List<int>();
        List<int> max = new List<int>();
        int pilor = list[0];
        for (int i = 1; i < list.Count; i++)
        {
            if (list[i] <= pilor)
            {
                min.Add(list[i]);
            }
            else
            {
                max.Add(list[i]);
            }
        }

        List<int> result = new List<int>();
        result.AddRange(QuickSort(min));
        result.Add(pilor);
        result.AddRange(QuickSort(max));
        return result;
    }
Example #30
0
 public int copy_int(int state, int size, string name)
 {
     byte[] s;
     if (size < 2)
     {
         s = new byte[1];
         s[0] = (byte)state;
     }
     else
     {
         s = BitConverter.GetBytes(size == 1 ? (byte)state : (ushort)state);
     }
     name += ": ";
     var nameBytes = new UTF8Encoding().GetBytes(name);
     var list = new List<byte>();
     list.AddRange(nameBytes);
     list.AddRange(s);
     list.AddRange(new byte[] { (byte)'\n' });
     func(buf, list.ToArray(), (uint)list.ToArray().Length);
     if (size < 2)
     {
         return s[0];
     }
     else
     {
         return BitConverter.ToUInt16(s, 0);
     }
 }