public void ConnectControlViewModel_AddNewServer_ResourceRepositoryReturnExistingServers_False() { //------------Setup for test-------------------------- var mainViewModel = new Mock<IMainViewModel>(); var connectControlSingleton = new Mock<IConnectControlSingleton>(); var env1 = new TestEnvironmentModel(new Mock<IEventAggregator>().Object, Guid.NewGuid(), CreateConnection(true, false).Object, new Mock<IResourceRepository>().Object, false); var env2 = new TestEnvironmentModel(new Mock<IEventAggregator>().Object, Guid.NewGuid(), CreateConnection(true, false).Object, new Mock<IResourceRepository>().Object, false); var connectControlEnvironments = new ObservableCollection<IConnectControlEnvironment>(); var controEnv1 = new Mock<IConnectControlEnvironment>(); var controEnv2 = new Mock<IConnectControlEnvironment>(); controEnv1.Setup(c => c.EnvironmentModel).Returns(env1); controEnv2.Setup(c => c.EnvironmentModel).Returns(env2); controEnv1.Setup(c => c.IsConnected).Returns(true); connectControlEnvironments.Add(controEnv2.Object); connectControlEnvironments.Add(controEnv1.Object); connectControlSingleton.Setup(c => c.Servers).Returns(connectControlEnvironments); var environmentRepository = new Mock<IEnvironmentRepository>(); ICollection<IEnvironmentModel> environments = new Collection<IEnvironmentModel> { env1 }; environmentRepository.Setup(e => e.All()).Returns(environments); var viewModel = new ConnectControlViewModel(mainViewModel.Object, environmentRepository.Object, e => { }, connectControlSingleton.Object, "TEST : ", false); //------------Execution------------------------------- int serverIndex; var didAddNew = viewModel.AddNewServer(out serverIndex, i => { }); //------------Assert---------------------------------- Assert.IsNotNull(viewModel); Assert.IsFalse(didAddNew); }
public Game(String XMLContent) { collection = new Collection (XMLContent); collectionStatus = new CollectionStatus(collection.getTotal()); currentArtefact = null; artefactJustCollected = false; }
/// <summary> /// Initializes a new instance of the <see cref="HelpPageApiModel"/> class. /// </summary> public HelpPageApiModel() { UriParameters = new Collection<ParameterDescription>(); SampleRequests = new Dictionary<MediaTypeHeaderValue, object>(); SampleResponses = new Dictionary<MediaTypeHeaderValue, object>(); ErrorMessages = new Collection<string>(); }
public void AddBindingParameters( ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters) { }
public void Table_Should_Contain_GroupFooter() { ICSharpCode.Reports.Core.BaseTableItem table = CreateContainer(); //GroupFooter var c = new Collection<ICSharpCode.Reports.Core.GroupFooter>(table.Items.OfType<ICSharpCode.Reports.Core.GroupFooter>().ToList()); Assert.That(c.Count,Is.GreaterThanOrEqualTo(1)); }
/// <summary> /// Validates a Entity /// </summary> /// <exception cref="ValidationException"></exception> public Tuple<bool, ICollection<ValidationResult>> TryValidateEntity(object instance) { var context = new ValidationContext(instance); var result = new Collection<ValidationResult>(); var success = Validator.TryValidateObject(instance, context, result); return new Tuple<bool, ICollection<ValidationResult>>(success, result); }
protected void Page_Load(object sender, EventArgs e) { Collection<KeyValuePair<string, string>> list = new Collection<KeyValuePair<string, string>>(); list.Add(new KeyValuePair<string, string>("@transaction_master_id", this.Request["TranId"])); DirectSalesInvoiceReport.AddParameterToCollection(list); DirectSalesInvoiceReport.AddParameterToCollection(list); }
private static void ClearStates(Collection<System.Activities.Statements.State> states) { foreach (System.Activities.Statements.State state in states) { ClearState(state); } }
public void SubjectBuffersDisconnected(IWpfTextView textView, ConnectionReason reason, Collection<ITextBuffer> subjectBuffers) { foreach (var buffer in subjectBuffers) { foreach (var document in buffer.GetRelatedDocuments()) { buffer.GetWorkspace().CloseDocument(document.Id); } } }
public void CompileTest() { var messages = new Collection<Tuple<string, int>> { new Tuple<string, int>("aaaaa", 200), new Tuple<string, int>("bbbbb", 200), new Tuple<string, int>("ccccc", 200), new Tuple<string, int>("ddddd", 200), new Tuple<string, int>("eeeee", 700), new Tuple<string, int>("fffff", 5000), new Tuple<string, int>("ggggg", 10000), new Tuple<string, int>("hhhhh", 100) }; //using (var compiler = new ReentrantTask<string, bool>(500, Execute)) //{ // foreach (var message in messages) // { // Thread.Sleep(message.Item2); // compiler.StartNew(message.Item1); // } //} Assert.Inconclusive(); }
/// <summary> /// Initializes a new instance of the <see cref="HelpPageApiModel"/> class. /// </summary> public HelpPageApiModel() { SampleRequests = new Dictionary<MediaTypeHeaderValue, object>(); SampleResponses = new Dictionary<MediaTypeHeaderValue, object>(); ErrorMessages = new Collection<string>(); ErrorCodes = new Collection<HelpPageErrorCode>(); }
private Collection<string> GetSelectedValues() { string selectedValues = this.selectedValuesHidden.Value; //Check if something was selected. if (string.IsNullOrWhiteSpace(selectedValues)) { return new Collection<string>(); } //Create a collection object to store the IDs. Collection<string> values = new Collection<string>(); //Iterate through each value in the selected values //and determine if each value is a number. foreach (string value in selectedValues.Split(',')) { //Parse the value to integer. int val = Conversion.TryCastInteger(value); if (val > 0) { values.Add(value); } } return values; }
public void SubjectBuffersConnected(IWpfTextView textView, ConnectionReason reason, Collection<ITextBuffer> subjectBuffers) { if (reason != ConnectionReason.TextViewLifetime) return; instants.Add (textView, new InstantVisualStudio (textView, this.documentService)); }
public void environmentTypes_Serialisation() { environmentType environmentType1; using (FileStream xmlStream = File.OpenRead(environmentXmlFile)) { environmentType1 = SerialiserFactory.GetXmlSerialiser<environmentType>().Deserialise(xmlStream); } Assert.AreEqual(environmentType1.sessionToken, "2e5dd3ca282fc8ddb3d08dcacc407e8a", true, "Session token does not match."); environmentType environmentType2; using (FileStream xmlStream = File.OpenRead(environmentXmlFile)) { environmentType2 = SerialiserFactory.GetXmlSerialiser<environmentType>().Deserialise(xmlStream); } Assert.AreEqual(environmentType2.sessionToken, "2e5dd3ca282fc8ddb3d08dcacc407e8a", true, "Session token does not match."); ICollection<environmentType> environmentTypes = new Collection<environmentType> { environmentType1, environmentType2 }; string xmlString = SerialiserFactory.GetXmlSerialiser<Collection<environmentType>>(new XmlRootAttribute("environments")).Serialise((Collection<environmentType>)environmentTypes); System.Console.WriteLine(xmlString); environmentTypes = SerialiserFactory.GetXmlSerialiser<Collection<environmentType>>(new XmlRootAttribute("environments")).Deserialise(xmlString); System.Console.WriteLine("Number deserialised is " + environmentTypes.Count); }
public static IDictionary<string, string> Execute(object job, string configuration, Action<string> logAction) { ActivityConfiguration activityConfiguration = Utils.GetActivityConfiguration(configuration); IDotNetActivity activityImplementation = job as IDotNetActivity; Ensure.IsNotNull(job, "job", string.Format( CultureInfo.InvariantCulture, "The type {0} in does not implement IDotNetActivity. Check the configuration and try again.", job == null ? "<null>" : job.GetType().FullName)); ActivityLogger logger = new ActivityLogger(logAction); Collection<LinkedService> linkedServices = new Collection<LinkedService>(); Collection<Table> tables = new Collection<Table>(); PopulateCollections(activityConfiguration.Inputs, linkedServices, tables); PopulateCollections(activityConfiguration.Outputs, linkedServices, tables); Activity activity = null; if(activityConfiguration.Pipeline != null && activityConfiguration.Pipeline.Properties != null && activityConfiguration.Pipeline.Properties.Activities != null) { activity = activityConfiguration.Pipeline.Properties.Activities.FirstOrDefault(); } return activityImplementation.Execute( linkedServices, tables, activity, logger); }
public void GetFilesToRename_WithValidFiles_ReturnsFileMetaDatasForMatchingFiles() { // Assert var fileNames = new List<string> { @".\Resources\2013_05_10_00_00_00.pdf", @"Resources\2014_06_10_15_10_58.pdf", @"Resources\2013_05_01.pdf" }; var pdfInfos = new Collection<PdfInfo> { new PdfInfo("My Bank", @"C:\Temp", "mybank.com", @"\d{1,2}(?:st|nd|rd|th)\s[A-Z,a-z]{3}\s20\d{2}\sto\s(?<day>\d{1,2})(?:st|nd|rd|th)\s(?<month>[A-Z,a-z]{3})\s(?<year>20\d{2})"), new PdfInfo("Bank2 Credit Card", @"C:\Temp", "67904567", @"Statement:\s\d{1,2}\s[A-Z,a-z]+?\sto\s(?<day>\d{1,2})\s(?<month>[A-Z,a-z]{3})[a-z]*\s(?<year>20\d{2})") }; // Act List<FileMetaData> filesToRename = PdfParser.GetFilesToRename(fileNames, pdfInfos).ToList(); // Assert Assert.That(filesToRename.Count, Is.EqualTo(2), "filesToRename.Count"); Assert.That(filesToRename[0].OldPath, Is.EqualTo(@".\Resources\2013_05_10_00_00_00.pdf"), "filesToRename[0].OldPath"); Assert.That(filesToRename[0].NewPath, Is.EqualTo(@"C:\Temp\My Bank 2013_05_10.pdf"), "filesToRename[0].NewPath"); Assert.That(filesToRename[0].Date, Is.EqualTo(new DateTime(2013, 5, 10)), "filesToRename[0].Date"); }
/// <summary> /// Constructor /// </summary> internal SmbServerContext() { this.shareList = new Dictionary<string, SmbServerShare>(); this.globalCapabilities = (Capabilities)0x00; this.isUpdateContext = true; this.connectionList = new Collection<SmbServerConnection>(); }
public static long PostTransaction(string catalog, long transactionMasterId, DateTime valueDate, int officeId, int userId, long loginId, int storeId, string partyCode, int priceTypeId, string referenceNumber, string statementReference, Collection<StockDetail> details, Collection<Attachment> attachments) { string detail = StockMasterDetailHelper.CreateStockMasterDetailParameter(details); string attachment = AttachmentHelper.CreateAttachmentModelParameter(attachments); string sql = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM transactions.post_purchase_return(@TransactionMasterId::bigint, @OfficeId::integer, @UserId::integer, @LoginId::bigint, @ValueDate::date, @StoreId::integer, @PartyCode::national character varying(12), @PriceTypeId::integer, @ReferenceNumber::national character varying(24), @StatementReference::text, ARRAY[{0}], ARRAY[{1}]);", detail, attachment); using (NpgsqlCommand command = new NpgsqlCommand(sql)) { command.Parameters.AddWithValue("@TransactionMasterId", transactionMasterId); command.Parameters.AddWithValue("@OfficeId", officeId); command.Parameters.AddWithValue("@UserId", userId); command.Parameters.AddWithValue("@LoginId", loginId); command.Parameters.AddWithValue("@ValueDate", valueDate); command.Parameters.AddWithValue("@StoreId", storeId); command.Parameters.AddWithValue("@PartyCode", partyCode); command.Parameters.AddWithValue("@PriceTypeId", priceTypeId); command.Parameters.AddWithValue("@ReferenceNumber", referenceNumber); command.Parameters.AddWithValue("@StatementReference", statementReference); command.Parameters.AddRange(StockMasterDetailHelper.AddStockMasterDetailParameter(details).ToArray()); command.Parameters.AddRange(AttachmentHelper.AddAttachmentParameter(attachments).ToArray()); long tranId = Conversion.TryCastLong(DbOperation.GetScalarValue(catalog, command)); return tranId; } }
protected override void ProcessRecord() { ProviderInfo provider = null; Collection<string> resolvedProviderPathFromPSPath; try { if (base.Context.EngineSessionState.IsProviderLoaded(base.Context.ProviderNames.FileSystem)) { resolvedProviderPathFromPSPath = base.SessionState.Path.GetResolvedProviderPathFromPSPath(this._path, out provider); } else { resolvedProviderPathFromPSPath = new Collection<string> { this._path }; } } catch (ItemNotFoundException) { FileNotFoundException exception = new FileNotFoundException(StringUtil.Format(Modules.ModuleNotFound, this._path)); ErrorRecord errorRecord = new ErrorRecord(exception, "Modules_ModuleNotFound", ErrorCategory.ResourceUnavailable, this._path); base.WriteError(errorRecord); return; } if (!provider.NameEquals(base.Context.ProviderNames.FileSystem)) { throw InterpreterError.NewInterpreterException(this._path, typeof(RuntimeException), null, "FileOpenError", ParserStrings.FileOpenError, new object[] { provider.FullName }); } if ((resolvedProviderPathFromPSPath != null) && (resolvedProviderPathFromPSPath.Count >= 1)) { if (resolvedProviderPathFromPSPath.Count > 1) { throw InterpreterError.NewInterpreterException(resolvedProviderPathFromPSPath, typeof(RuntimeException), null, "AmbiguousPath", ParserStrings.AmbiguousPath, new object[0]); } string path = resolvedProviderPathFromPSPath[0]; ExternalScriptInfo scriptInfo = null; if (System.IO.Path.GetExtension(path).Equals(".psd1", StringComparison.OrdinalIgnoreCase)) { string str5; scriptInfo = base.GetScriptInfoForFile(path, out str5, false); PSModuleInfo sendToPipeline = base.LoadModuleManifest(scriptInfo, ModuleCmdletBase.ManifestProcessingFlags.WriteWarnings | ModuleCmdletBase.ManifestProcessingFlags.WriteErrors, null, null); if (sendToPipeline != null) { base.WriteObject(sendToPipeline); } } else { InvalidOperationException exception3 = new InvalidOperationException(StringUtil.Format(Modules.InvalidModuleManifestPath, path)); ErrorRecord record3 = new ErrorRecord(exception3, "Modules_InvalidModuleManifestPath", ErrorCategory.InvalidArgument, this._path); base.ThrowTerminatingError(record3); } } else { FileNotFoundException exception2 = new FileNotFoundException(StringUtil.Format(Modules.ModuleNotFound, this._path)); ErrorRecord record2 = new ErrorRecord(exception2, "Modules_ModuleNotFound", ErrorCategory.ResourceUnavailable, this._path); base.WriteError(record2); } }
public Options(params string[] args) { Port = DefaultPort; AssemblyPaths = new Collection<string>(); options = new OptionSet { { "p|port=", "the {PORT} the server should listen on (default=" + DefaultPort + ").", (int v) => Port = v }, { "a|assembly=", "an assembly to search for step definition methods.", v => AssemblyPaths.Add(v) }, { "h|?|help", "show this message and exit.", v => ShowHelp = v != null } }; options.Parse(args); }
public static void AddGeometries(WpfHexView hexView, Collection<VSTF.TextBounds> textBounds, bool isLineGeometry, bool clipToViewport, Thickness padding, double minWidth, ref PathGeometry geo, ref bool createOutlinedPath) { foreach (var bounds in textBounds) { double left = bounds.Left - padding.Left; double right = bounds.Right + padding.Right; double top, bottom; if (isLineGeometry) { top = bounds.Top - padding.Top; bottom = bounds.Bottom + padding.Bottom; } else { top = bounds.TextTop - padding.Top; bottom = bounds.TextBottom + padding.Bottom; } if (right - left < minWidth) right = left + minWidth; if (clipToViewport) { left = Math.Max(left, hexView.ViewportLeft); right = Math.Min(right, hexView.ViewportRight); } if (right <= left || bottom <= top) continue; const double MAX_HEIGHT = 1000000; const double MAX_WIDTH = 1000000; double width = Math.Min(right - left, MAX_WIDTH); double height = Math.Min(bottom - top, MAX_HEIGHT); if (geo == null) geo = new PathGeometry { FillRule = FillRule.Nonzero }; else createOutlinedPath = true; geo.AddGeometry(new RectangleGeometry(new Rect(left, top, width, height))); } }
public Usuario() { Asistencias = new Collection<Asistencia>(); Tareas = new Collection<Tareas>(); Visitas = new Collection<Visita>(); }
public static Collection<MixERP.Net.Common.Models.Core.Menu> GetMenuCollection(int parentMenuId, short level) { Collection<MixERP.Net.Common.Models.Core.Menu> collection = new Collection<Common.Models.Core.Menu>(); int userId = MixERP.Net.BusinessLayer.Helpers.SessionHelper.GetUserId(); int officeId = MixERP.Net.BusinessLayer.Helpers.SessionHelper.GetOfficeId(); string culture = MixERP.Net.BusinessLayer.Helpers.SessionHelper.GetCulture().TwoLetterISOLanguageName; using (DataTable table = MixERP.Net.DatabaseLayer.Core.Menu.GetMenuTable(parentMenuId, level, userId, officeId, culture)) { if (table == null) { return null; } foreach (DataRow row in table.Rows) { MixERP.Net.Common.Models.Core.Menu model = new Common.Models.Core.Menu(); model.MenuId = Conversion.TryCastInteger(row["menu_id"]); model.MenuText = Conversion.TryCastString(row["menu_text"]); model.Url = Conversion.ResolveUrl(Conversion.TryCastString(row["url"])); model.MenuCode = Conversion.TryCastString(row["menu_code"]); model.Level = Conversion.TryCastInteger(row["level"]); model.ParentMenuId = Conversion.TryCastInteger(row["parent_menu_id"]); collection.Add(model); } } return collection; }
public string CreatureSpawns() { if (!_stuffing.Objects.Any(wowObject => wowObject.Value.Type == ObjectType.Unit)) return string.Empty; var units = _stuffing.Objects.Where(x => x.Value.Type == ObjectType.Unit); const string tableName = "creature"; ICollection<Tuple<uint, uint>> keys = new Collection<Tuple<uint, uint>>(); var rows = new List<QueryBuilder.SQLInsertRow>(); foreach (var unit in units) { var row = new QueryBuilder.SQLInsertRow(); var creature = unit.Value; if (Settings.AreaFilters.Length > 0) if (!(creature.Area.ToString(CultureInfo.InvariantCulture).MatchesFilters(Settings.AreaFilters))) continue; // If our unit got any of the folowing updated fields set, // it's probably a temporary spawn UpdateField uf; creature.UpdateFields.TryGetValue(UpdateFields.GetUpdateField(UnitField.UNIT_FIELD_SUMMONEDBY), out uf); creature.UpdateFields.TryGetValue(UpdateFields.GetUpdateField(UnitField.UNIT_CREATED_BY_SPELL), out uf); creature.UpdateFields.TryGetValue(UpdateFields.GetUpdateField(UnitField.UNIT_FIELD_CREATEDBY), out uf); var temporarySpawn = (uf != null && uf.Int32Value != 0); row.CommentOut = temporarySpawn; // If map is Eastern Kingdoms, Kalimdor, Outland, Northrend or Ebon Hold use a lower respawn time // TODO: Rank and if npc is needed for quest kill should change spawntime as well var spawnTimeSecs = (unit.Value.Map == 0 || unit.Value.Map == 1 || unit.Value.Map == 530 || unit.Value.Map == 571 || unit.Value.Map == 609) ? 120 : 7200; var movementType = 0; // TODO: Find a way to check if our unit got random movement var spawnDist = (movementType == 1) ? 5 : 0; row.AddValue("guid", unit.Key.GetLow()); row.AddValue("id", unit.Key.GetEntry()); row.AddValue("map", creature.Map); row.AddValue("spawnMask", 1); row.AddValue("phaseMask", creature.PhaseMask); row.AddValue("position_x", creature.Movement.Position.X); row.AddValue("position_y", creature.Movement.Position.Y); row.AddValue("position_z", creature.Movement.Position.Z); row.AddValue("orientation", creature.Movement.Orientation); row.AddValue("spawntimesecs", spawnTimeSecs); row.AddValue("spawndist", spawnDist); row.AddValue("MovementType", movementType); row.Comment = StoreGetters.GetName(StoreNameType.Unit, (int) unit.Key.GetEntry(), false); row.Comment += " (Area: " + StoreGetters.GetName(StoreNameType.Area, creature.Area, false) + ")"; if (temporarySpawn) row.Comment += " - !!! might be temporary spawn !!!"; rows.Add(row); keys.Add(new Tuple<uint, uint>((uint) unit.Key.GetLow(), unit.Key.GetEntry())); } return new QueryBuilder.SQLInsert(tableName, keys, new[] { "guid", "id" }, rows).Build(); }
public TaskList() { PartitionKey = string.Empty; RowKey = string.Empty; Notes = new Collection<Note>(); Share = new Collection<User>(); }
internal override Collection<CommandParameterInternal> BindParameters(Collection<CommandParameterInternal> arguments) { Collection<CommandParameterInternal> collection = new Collection<CommandParameterInternal>(); foreach (CommandParameterInternal internal2 in arguments) { if (!internal2.ParameterNameSpecified) { collection.Add(internal2); } else { MergedCompiledCommandParameter parameter = base.BindableParameters.GetMatchingParameter(internal2.ParameterName, false, true, new InvocationInfo(base.InvocationInfo.MyCommand, internal2.ParameterExtent)); if (parameter != null) { if (base.BoundParameters.ContainsKey(parameter.Parameter.Name)) { ParameterBindingException exception = new ParameterBindingException(ErrorCategory.InvalidArgument, base.InvocationInfo, base.GetParameterErrorExtent(internal2), internal2.ParameterName, null, null, "ParameterBinderStrings", "ParameterAlreadyBound", new object[0]); throw exception; } this.BindParameter(int.MaxValue, internal2, parameter, ParameterBindingFlags.ShouldCoerceType); } else if (internal2.ParameterName.Equals("-%", StringComparison.Ordinal)) { base.DefaultParameterBinder.CommandLineParameters.SetImplicitUsingParameters(internal2.ArgumentValue); } else { collection.Add(internal2); } } } return collection; }
public CalculateBolingerBand(Collection<StockData> UpperBolinger, Collection<StockData> LowerBolinger, Collection<DataClass> priceList , Collection<StockData> movingAvrage) { this.UpperBolinger = UpperBolinger; this.LowerBolinger = LowerBolinger; this.priceList = priceList; this.movingAvrage = movingAvrage; }
private void ExploreRouteControllers(IDictionary<string, HttpControllerDescriptor> controllerMappings, IHttpRoute route, Collection<ApiDescription> apiDescriptions) { string routeTemplate = route.RouteTemplate; object controllerVariableValue; if (_controllerVariableRegex.IsMatch(routeTemplate)) { // unbound controller variable, {controller} foreach (KeyValuePair<string, HttpControllerDescriptor> controllerMapping in controllerMappings) { controllerVariableValue = controllerMapping.Key; HttpControllerDescriptor controllerDescriptor = controllerMapping.Value; if (DefaultExplorer.ShouldExploreController(controllerVariableValue.ToString(), controllerDescriptor, route)) { // expand {controller} variable string expandedRouteTemplate = _controllerVariableRegex.Replace(routeTemplate, controllerVariableValue.ToString()); ExploreRouteActions(route, expandedRouteTemplate, controllerDescriptor, apiDescriptions); } } } else { // bound controller variable, {controller = "controllerName"} if (route.Defaults.TryGetValue(ControllerVariableName, out controllerVariableValue)) { HttpControllerDescriptor controllerDescriptor; if (controllerMappings.TryGetValue(controllerVariableValue.ToString(), out controllerDescriptor) && DefaultExplorer.ShouldExploreController(controllerVariableValue.ToString(), controllerDescriptor, route)) { ExploreRouteActions(route, routeTemplate, controllerDescriptor, apiDescriptions); } } } }
public static Collection<KeyValuePair<string, string>> GetParameters(string reportPath) { if(!File.Exists(reportPath)) { return null; } Collection<KeyValuePair<string, string>> parameterCollection = new Collection<KeyValuePair<string, string>>(); XmlNodeList dataSources = XmlHelper.GetNodes(reportPath, "//DataSource"); foreach(XmlNode datasource in dataSources) { foreach(XmlNode parameters in datasource.ChildNodes) { if(parameters.Name.Equals("Parameters")) { foreach(XmlNode parameter in parameters.ChildNodes) { if(parameter.Attributes != null && !KeyExists(parameter.Attributes["Name"].Value, parameterCollection)) { parameterCollection.Add(new KeyValuePair<string, string>(parameter.Attributes["Name"].Value, parameter.Attributes["Type"].Value)); } } } } } return parameterCollection; }
/// <summary> /// Default constructur /// </summary> public ObjectCommentRepository() { _comments = new Collection<CommentEntity>(); Random rand = new Random(); for (long i = 1; i < Repository.UserPostRepositoryInstance.GetCount(); i++) { // random count of comments for post for (int j = 1; j < rand.Next(1, 100); j++) { if (Repository.UserPostRepositoryInstance.IsExists(i)) { CommentEntity comment = new CommentEntity(); comment.Id = identityIdCounter++; comment.CreatedUTC = DateTime.Now; comment.PostId = i; comment.UserId = Repository.UserPostRepositoryInstance.Get(i).AuthorUserId; comment.Message = ""; for (int k = 0; k < rand.Next(1, 10); k++) comment.Message += "Nice post!"; _comments.Add(comment); } } } }
public async Task RemoveAsync(string ID) { await Collection.DeleteOneAsync(o => o.ID == ID); }
public override void GetParentRealUIds(Collection <Guid> realUIds) { base.GetParentRealUIds(realUIds); realUIds.Add(new Guid("ad82f63a-76f8-43cc-8117-4ba46b040bc8")); }
public Categoria() { Produtos = new Collection <Produto>(); }
public EnumTypeModelDescription() { Values = new Collection <EnumValueDescription>(); }
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable <string> parameterNames, SampleDirection sampleDirection, out Collection <MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection <MediaTypeFormatter> newFormatters = new Collection <MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return(type); }
public ParameterDescription() { Annotations = new Collection<ParameterAnnotation>(); }
public static ICollection <TokenSet> GetTokens(this string expression) { var tokens = new Collection <TokenSet>(); if (expression.IsNullOrWhiteSpace()) { return(tokens); } var cleanMatch = expression.EnclosedMatch(); if (cleanMatch.Success) { var match = cleanMatch.Groups[1].Value; if (!HasOrphanedOpenParenthesis(match)) { expression = match; } } if (expression.IsImpliedBoolean()) { return(tokens); } var blocks = expression.Split(new[] { ' ' }); var openGroups = 0; var startExpression = 0; var currentTokens = new TokenSet(); var processingString = false; for (int i = 0; i < blocks.Length; i++) { if (blocks[i].IsStringStart()) { processingString = true; } var netEnclosed = blocks[i].Count(c => c == '(') - blocks[i].Count(c => c == ')'); openGroups += netEnclosed; if (openGroups == 0) { if (!processingString && blocks[i].IsOperation()) { var expression1 = startExpression; if (currentTokens.Left.IsNullOrWhiteSpace()) { var i1 = i; Func <string, int, bool> leftPredicate = (x, j) => j >= expression1 && j < i1; currentTokens.Left = blocks.Where(leftPredicate).Join(" "); currentTokens.Operation = blocks[i]; startExpression = i + 1; if (blocks[i].IsCombinationOperation()) { currentTokens.Right = blocks.Where((x, j) => j > i).Join(" "); tokens.Add(currentTokens); return(tokens); } } else { var i2 = i; Func <string, int, bool> rightPredicate = (x, j) => j >= expression1 && j < i2; currentTokens.Right = blocks.Where(rightPredicate).Join(" "); tokens.Add(currentTokens); startExpression = i + 1; currentTokens = new TokenSet(); if (blocks[i].IsCombinationOperation()) { tokens.Add(new TokenSet { Operation = blocks[i].ToLowerInvariant() }); } } } } if (blocks[i].IsStringEnd()) { processingString = false; } } var remainingToken = blocks.Where((x, j) => j >= startExpression).Join(" "); if (!currentTokens.Left.IsNullOrWhiteSpace()) { currentTokens.Right = remainingToken; tokens.Add(currentTokens); } else if (remainingToken.IsEnclosed()) { currentTokens.Left = remainingToken; tokens.Add(currentTokens); } else if (tokens.Count > 0) { currentTokens.Left = remainingToken; tokens.Add(currentTokens); } return(tokens); }
/// <summary> /// Paste items from clipboard into the designer. /// </summary> public void Paste() { bool pasted = false; string combinedXaml = Clipboard.GetText(TextDataFormat.Xaml); IEnumerable<string> xamls = combinedXaml.Split(_delimeter); xamls = xamls.Where(xaml => xaml != ""); DesignItem parent = _context.Services.Selection.PrimarySelection; DesignItem child = _context.Services.Selection.PrimarySelection; XamlDesignItem rootItem = _context.RootItem as XamlDesignItem; var pastedItems = new Collection<DesignItem>(); foreach(var xaml in xamls) { var obj = XamlParser.ParseSnippet(rootItem.XamlObject, xaml, _settings); if(obj!=null) { DesignItem item = _context._componentService.RegisterXamlComponentRecursive(obj); if (item != null) pastedItems.Add(item); } } if (pastedItems.Count != 0) { var changeGroup = _context.OpenGroup("Paste " + pastedItems.Count + " elements", pastedItems); while (parent != null && pasted == false) { if (parent.ContentProperty != null) { if (parent.ContentProperty.IsCollection) { if (CollectionSupport.CanCollectionAdd(parent.ContentProperty.ReturnType, pastedItems.Select(item => item.Component)) && parent.GetBehavior<IPlacementBehavior>()!=null) { AddInParent(parent, pastedItems); pasted = true; } } else if (pastedItems.Count == 1 && parent.ContentProperty.Value == null && parent.ContentProperty.ValueOnInstance == null && parent.View is ContentControl) { AddInParent(parent, pastedItems); pasted = true; } if(!pasted) parent=parent.Parent; } else { parent = parent.Parent; } } while (pasted == false) { if (child.ContentProperty != null) { if (child.ContentProperty.IsCollection) { foreach (var col in child.ContentProperty.CollectionElements) { if (col.ContentProperty != null && col.ContentProperty.IsCollection) { if (CollectionSupport.CanCollectionAdd(col.ContentProperty.ReturnType, pastedItems.Select(item => item.Component))) { pasted = true; } } } break; } else if (child.ContentProperty.Value != null) { child = child.ContentProperty.Value; } else if (pastedItems.Count == 1) { child.ContentProperty.SetValue(pastedItems.First().Component); pasted = true; break; } else break; } else break; } foreach (var pastedItem in pastedItems) { _context._componentService.RaiseComponentRegisteredAndAddedToContainer(pastedItem); } changeGroup.Commit(); } }
public new HtmlThElement WithAttributes(Collection <HtmlAttribute> attributes) => (HtmlThElement)base.WithAttributes(attributes);
public void GetKnownCustomDataTypes(Collection <Type> customDataTypes) { }
/// <summary> /// When the user clicks on a source point we will need to trabnslate that location to the nearest point on the network /// </summary> /// <param name="userPoint"></param> /// <param name="tolerence"></param> /// <param name="growValue"></param> /// <param name="theLayer"></param> /// <returns></returns> public IntersectionPackage TranslateToPointOnLine(Coordinate userPoint, double tolerence, double growValue, VectorLayer theLayer) { try { // How much should we increase the search area by until we reach tolerence. double GROWVALUE = growValue; // Record how many features are in the bounding box int featureCount = 0; // The features that are withinthe boundbox of GROWVALUE of UserPoints. Collection<IGeometry> geometrysInTolerence = null; IGeometry clickPointAsNts = null; while ((featureCount == 0) && (GROWVALUE < tolerence)) { // Take the point where the user clicked. Grow it by a set a given amount. We use the boundry // box to find all lines within a given tolerence. clickPointAsNts = _geomFactory.CreatePoint(userPoint); var clickPointBoundry = new Envelope(userPoint); clickPointBoundry = clickPointBoundry.Grow(GROWVALUE); var originalLayer = theLayer; originalLayer.DataSource.Open(); geometrysInTolerence = originalLayer.DataSource.GetGeometriesInView(clickPointBoundry); GROWVALUE *= 2; if (geometrysInTolerence != null) featureCount = geometrysInTolerence.Count; } // If there are any geometries in the boundry box then we loop around them them. We are looking for the cloest point so // we can **try** to perform a snap operation. NOTE: This entire procedure is a bit flawed. if (geometrysInTolerence == null) return null; if (geometrysInTolerence.Count > 0) { double closestDistance = double.MaxValue; Coordinate intersectionPointAsNts = null; ILineString closestToThisLine = null; foreach (IGeometry geometryInTolerence in geometrysInTolerence) { var nearestPoints = NetTopologySuite.Operation.Distance.DistanceOp.NearestPoints(clickPointAsNts, geometryInTolerence); if (nearestPoints == null) return null; // We get two points back. The point where we clicked and the point of intersection (?????) on the line). If // we calculate the distance between the two we can var p1 = nearestPoints[0]; var p2 = nearestPoints[1]; var lDistance = p1.Distance(p2); if (lDistance < closestDistance) { closestDistance = lDistance; intersectionPointAsNts = p2; closestToThisLine = (ILineString)geometryInTolerence; } } // Getting Here would mean that we now know the line we if (closestDistance < double.MaxValue) { var theDeliveryPackage = new IntersectionPackage((IPoint)clickPointAsNts, _geomFactory.CreatePoint(intersectionPointAsNts), closestToThisLine); return theDeliveryPackage; } } else return null; return null; } catch (Exception e1) { System.Diagnostics.Debug.WriteLine(e1.ToString()); return null; } }
public new HtmlThElement WithChildren(Collection <HtmlElement> children) => (HtmlThElement)base.WithChildren(children);
public void AzureServiceExtensionTest() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); const string rdpPath = @".\WebRole2.rdp"; try { Collection <ExtensionImageContext> resultExtensions = vmPowershellCmdlets.GetAzureServiceAvailableExtension(); foreach (var extension in resultExtensions) { if (extension.ExtensionName == "RDP") { _extensionName = extension.ExtensionName; _providerNamespace = extension.ProviderNameSpace; _version = extension.Version; break; } } vmPowershellCmdlets.NewAzureService(_serviceName, _serviceName, locationName); Console.WriteLine("service, {0}, is created.", _serviceName); vmPowershellCmdlets.NewAzureDeployment(_serviceName, _packagePath.FullName, _configPath.FullName, DeploymentSlotType.Production, DeploymentLabel, DeploymentName, false, false); DeploymentInfoContext result = vmPowershellCmdlets.GetAzureDeployment(_serviceName, DeploymentSlotType.Production); pass = Utilities.PrintAndCompareDeployment(result, _serviceName, DeploymentName, DeploymentLabel, DeploymentSlotType.Production, null, 2); Console.WriteLine("successfully deployed the package"); vmPowershellCmdlets.SetAzureServiceExtension( serviceName: _serviceName, extensionName: _extensionName, providerNamespace: _providerNamespace, publicConfig: PublicConfig, privateConfig: PrivateConfig, version: _version ); ExtensionContext resultExtensionContext = vmPowershellCmdlets.GetAzureServiceExtension(_serviceName)[0]; Utilities.PrintContext(resultExtensionContext); VerifyExtensionContext(resultExtensionContext, "AllRoles", _extensionName, _providerNamespace, _version); RemoteDesktopExtensionContext resultContext = vmPowershellCmdlets.GetAzureServiceRemoteDesktopExtension(_serviceName)[0]; Utilities.PrintContext(resultContext); VerifyRDP(_serviceName, rdpPath); vmPowershellCmdlets.RemoveAzureServiceExtension( serviceName: _serviceName, extensionName: _extensionName, providerNamespace: _providerNamespace, uninstall: true); try { vmPowershellCmdlets.GetAzureRemoteDesktopFile("WebRole1_IN_0", _serviceName, rdpPath, false); Assert.Fail("Succeeded, but extected to fail!"); } catch (Exception e) { if (e is AssertFailedException) { throw; } Console.WriteLine("Failed to get RDP file as expected"); } vmPowershellCmdlets.RemoveAzureDeployment(_serviceName, DeploymentSlotType.Production, true); pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureDeployment, _serviceName, DeploymentSlotType.Production); } catch (Exception e) { Console.WriteLine("Exception occurred: {0}", e); throw; } }
public Task RemoveAsync(DomainId appId, DomainId contentId) { var documentId = DomainId.Combine(appId, contentId).ToString(); return Collection.DeleteOneAsync(x => x.DocumentId == documentId); }
public override void GetParentRealUIds(Collection <Guid> realUIds) { base.GetParentRealUIds(realUIds); realUIds.Add(new Guid("b7e597e8-d428-4a4d-8319-9dc14978d900")); }
public ApplicationUser() { Followers = new Collection <Following>(); Followees = new Collection <Following>(); UserNotifications = new Collection <UserNotification>(); }
public UriTemplateMatch Match(Uri baseAddress, Uri uri) { if (baseAddress == null || uri == null) { return(null); } if (baseAddress.GetLeftPart(UriPartial.Authority) != uri.GetLeftPart(UriPartial.Authority)) { return(null); } var baseUriSegments = baseAddress.Segments.Select(RemoveTrailingSlash); var candidateSegments = new List <string>(uri.Segments.Select(RemoveTrailingSlash)); foreach (var baseUriSegment in baseUriSegments) { if (baseUriSegment == candidateSegments[0]) { candidateSegments.RemoveAt(0); } } if (candidateSegments.Count > 0 && candidateSegments[0] == string.Empty) { candidateSegments.RemoveAt(0); } if (candidateSegments.Count != _segments.Count) { return(null); } var boundVariables = new NameValueCollection(_pathSegmentVariables.Count); for (var i = 0; i < _segments.Count; i++) { var segment = candidateSegments[i]; var candidateSegment = new { Text = segment, ProposedSegment = _segments[i] }; candidateSegments[i] = candidateSegment.Text; switch (candidateSegment.ProposedSegment.Type) { case SegmentType.Literal when string.Compare(candidateSegment.ProposedSegment.Text, segment, StringComparison.OrdinalIgnoreCase) != 0: return(null); case SegmentType.Wildcard: throw new NotImplementedException("Not finished wildcards implementation yet"); case SegmentType.Variable: boundVariables.Add(candidateSegment.ProposedSegment.Text, Uri.UnescapeDataString(candidateSegment.Text)); break; } } var queryStringVariables = new NameValueCollection(); var uriQuery = ParseQueryStringSegments(uri.Query).ToList(); var requestUriQuerySegments = ParseQueryStringSegments(uriQuery); var queryParams = new Collection <string>(); foreach (var templateQuerySegment in _queryStringSegments.Values) { var requestUriHasQueryStringKey = requestUriQuerySegments.ContainsKey(templateQuerySegment.Key); switch (templateQuerySegment.Type) { case SegmentType.Literal: if (requestUriHasQueryStringKey == false || QuerySegmentValueIsDifferent(requestUriQuerySegments, templateQuerySegment)) { return(null); } break; case SegmentType.Variable when requestUriHasQueryStringKey: queryStringVariables[templateQuerySegment.Value] = requestUriQuerySegments[templateQuerySegment.Key].Value; break; } queryParams.Add(templateQuerySegment.Key); } return(new UriTemplateMatch { BaseUri = baseAddress, Data = 0, PathSegmentVariables = boundVariables, QueryString = uriQuery, QueryParameters = queryParams, QueryStringVariables = queryStringVariables, RelativePathSegments = new Collection <string>(candidateSegments), RequestUri = uri, Template = this, WildcardPathSegments = new Collection <string>() }); }
public override void GetParentRealUIds(Collection <Guid> realUIds) { base.GetParentRealUIds(realUIds); realUIds.Add(new Guid("0bc5d826-8e8f-48cd-b087-30b33d133120")); }
public async Task RemoveRangeAsync(IEnumerable <string> listItem) { await Collection.DeleteManyAsync(o => listItem.Contains(o.ID)); }
public override void GetParentRealUIds(Collection <Guid> realUIds) { base.GetParentRealUIds(realUIds); realUIds.Add(new Guid("66bb5f4d-9a35-4ffa-80c6-0587b0525470")); }
public ComplexTypeModelDescription() { Properties = new Collection <ParameterDescription>(); }
public void RemoveRange(IEnumerable <string> listItem) { Collection.DeleteMany(o => listItem.Contains(o.ID)); }
public async Task AddRangeAsync(IEnumerable <T> listItem) { await Collection.InsertManyAsync(listItem); }
public async Task <T> GetByIDAsync(string ID) { var data = await Collection.FindAsync(o => o.ID == ID); return(data?.SingleOrDefault()); }
public async Task <IEnumerable <T> > GetAllAsync() { var data = await Collection.FindAsync(o => !string.IsNullOrEmpty(o.ID)); return(data?.ToList()); }
public void Remove(string ID) { Collection.DeleteOne(o => o.ID == ID); }
public void AddRange(IEnumerable <T> listItem) { Collection.InsertMany(listItem); }
public T GetByID(string ID) { var data = Collection.Find(o => o.ID == ID).SingleOrDefault(); return(data ?? null); }
private static void Main(string[] args) { var cmd = new Process { StartInfo = { FileName = "cmd", RedirectStandardInput = true, RedirectStandardOutput = true, CreateNoWindow = true, UseShellExecute = false } }; cmd.Start(); cmd.StandardInput.WriteLine("chcp 65001"); cmd.StandardInput.Flush(); cmd.StandardInput.Close(); Console.OutputEncoding = Encoding.UTF8; var files = new[] { // @"G:\Escape from Tarkov\EscapeFromTarkov_Data\Managed\Assembly-CSharp.dll", @"G:\Escape from Tarkov\EscapeFromTarkov_Data\Managed\Assembly-CSharp.dll.ORG", }; foreach (var dll in files) { var file = new FileInfo(dll); Console.WriteLine("Loaded {0}", file.FullName.Quote()); var _Module = ModuleDefinition.ReadModule(dll); TypeDefinition beClass = null; MethodDefinition beMethod = null; try { foreach (var _class in _Module.GetTypes()) { if (_class.IsPublic || !_class.IsSealed) { continue; } if (!_class.HasProperties || _class.Properties.Count != 1) { continue; } if (!_class.HasFields || _class.Fields.Count != 2) { continue; } if (!_class.HasMethods) { continue; } foreach (var method in _class.Methods) { if (method.ReturnType.ToString() == "System.Collections.IEnumerator") { beMethod = method; break; } } if (beMethod is null) { continue; } beClass = _class; break; } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } if (beClass is null) { var cc = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine("[WARNING]"); Console.WriteLine("BattlEye class or method was not found! If your game directly closes after launch you know why!"); Console.WriteLine("[WARNING]"); Console.ForegroundColor = cc; Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } else { var beName = string.Format("{0}::{1} ({2}::{3})", beClass.Name, beMethod.Name, beClass.Name.ToUnicode(), beMethod.Name.ToUnicode()); Console.WriteLine("Found BattlEye as {0}", beName); // Console.ReadKey(); var inst = new Collection <Instruction>(); // print call MethodInfo writeLineMethod = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }); var sentence = string.Concat("BattlEye check called. Bypassing..."); inst.Add(Instruction.Create(OpCodes.Ldstr, sentence)); var writeLine = _Module.Import(writeLineMethod); inst.Add(Instruction.Create(OpCodes.Call, writeLine)); // set success inst.Add(Instruction.Create(OpCodes.Ldarg_0)); inst.Add(Instruction.Create(OpCodes.Ldc_I4_1)); var _com_mod = ModuleDefinition.ReadModule(@"G:\Escape from Tarkov\EscapeFromTarkov_Data\Managed\Comfort.Unity.dll"); var coms = _com_mod.GetTypes(); var abs_op = coms.First(t => t.Name == "AbstractOperation"); var succ_type = _Module.Import(abs_op.Properties.First(p => p.Name == "Succeed").SetMethod); inst.Add(Instruction.Create(OpCodes.Callvirt, succ_type)); // reutrn empty IEnumerator var obj_type = _Module.Import(typeof(object)); var obj_type_get_enu = _Module.Import(typeof(Array).GetMethod("GetEnumerator")); inst.Add(Instruction.Create(OpCodes.Ldc_I4_0)); inst.Add(Instruction.Create(OpCodes.Newarr, obj_type)); inst.Add(Instruction.Create(OpCodes.Call, obj_type_get_enu)); inst.Add(Instruction.Create(OpCodes.Ret)); beMethod.Body.Instructions.Clear(); foreach (var _ins in inst) { beMethod.Body.Instructions.Add(_ins); } Console.WriteLine("Patched BattlEye!"); // Console.ReadKey(); var sFN = file.SplitFileName(); var sF = file.Directory.CombineFile(sFN.Key + ".noBE" + sFN.Value); Console.WriteLine("Saving as {0}!", sF.FullName.Quote()); _Module.Write(sF.FullName); } } Console.ReadKey(); }
public IEnumerable <T> GetAll() { return(Collection.Find(o => !string.IsNullOrEmpty(o.ID))?.ToList()); }