private bool CheckInput(ref int port, ref Scheme scheme) { int temp; if(inputUser.Text==string.Empty) { OutputInfo.Text = "User can't be empty"; return false; } if (int.TryParse(inputPort.Text, out temp)) { port = temp; } else { OutputInfo.Text = "Port should to be integer"; MainPage.SplunkService = null; return false; } scheme = Scheme.Https; if (Http.IsChecked == true) { scheme = Scheme.Http; } return true; }
public async Task FetchResultsAsync_WithUnsubmittedReturnData_ReturnsEmptyList() { using (Weee.Tests.Core.Model.DatabaseWrapper wrapper = new Weee.Tests.Core.Model.DatabaseWrapper()) { Organisation organisation = Organisation.CreateSoleTrader("Test Organisation"); Scheme scheme = new Scheme(organisation); Quarter quarter = new Quarter(2099, QuarterType.Q1); DataReturn dataReturn = new DataReturn(scheme, quarter); DataReturnVersion version = new DataReturnVersion(dataReturn); WeeeCollectedAmount amount1 = new WeeeCollectedAmount( WeeeCollectedAmountSourceType.Dcf, ObligationType.B2C, WeeeCategory.LargeHouseholdAppliances, 123.456m); version.WeeeCollectedReturnVersion.AddWeeeCollectedAmount(amount1); wrapper.WeeeContext.DataReturns.Add(dataReturn); await wrapper.WeeeContext.SaveChangesAsync(); // Act FetchSummaryCsvDataAccess dataAccess = new FetchSummaryCsvDataAccess(wrapper.WeeeContext); List<DataReturnSummaryCsvData> results = await dataAccess.FetchResultsAsync(scheme.Id, 2099); // Assert Assert.NotNull(results); Assert.Empty(results); } }
/// <summary> /// Add a nokia layer to the layers collection of the map. /// </summary> /// <param name="layers">The layers collection.</param> /// <param name="type">The basic map type.</param> /// <param name="scheme">The scheme of the map.</param> /// <param name="appId">The application id.</param> /// <param name="token">The token.</param> public static void AddNokiaLayer(this LayerCollection layers, Type type, Scheme scheme, string appId, string token) { // request schema is // http://SERVER-URL/maptile/2.1/TYPE/MAPID/SCHEME/ZOOM/COL/ROW/RESOLUTION/FORMAT?param=value&... string copyrightText = (scheme == Scheme.SatelliteDay) ? "© 2012 DigitalGlobe" : "© 2012 NAVTEQ"; string schemeString = Regex.Replace(scheme.ToString(), "[a-z][A-Z]", m => m.Value[0] + "." + m.Value[1]).ToLower(); string typeString = type.ToString().ToLower(); string caption = (type == Type.StreetTile) ? "Streets" : (type == Type.LabelTile) ? "Labels" : "BaseMap"; layers.Add(new TiledLayer("Nokia_" + type.ToString()) { Caption = caption, IsLabelLayer = type == Type.LabelTile || type == Type.StreetTile, IsBaseMapLayer = type == Type.MapTile || type == Type.BaseTile, TiledProvider = new RemoteTiledProvider { MinZoom = 0, MaxZoom = 20, RequestBuilderDelegate = (x, y, level) => string.Format("http://{0}.maps.nlp.nokia.com/maptile/2.1/{1}/newest/{2}/{3}/{4}/{5}/256/png8?app_id={6}&token={7}", "1234"[(x ^ y) % 4], typeString, schemeString, level, x, y, appId, token) }, Copyright = copyrightText, }); }
public DataReturn(Scheme scheme, Quarter quarter) { Guard.ArgumentNotNull(() => scheme, scheme); Guard.ArgumentNotNull(() => quarter, quarter); Scheme = scheme; Quarter = quarter; }
public void DataReturn_qQuarterNotDefined_ThrowsArugmentNullException() { // Arrange Scheme scheme = new Scheme(Guid.NewGuid()); // Assert Assert.Throws<ArgumentNullException>(() => new DataReturn(scheme, null)); }
public async Task CreateCustomerFile_WithFileID_CreatesFileWithCorrectFileID() { // Arrange UKCompetentAuthority authority = A.Dummy<UKCompetentAuthority>(); Address address = new Address( "1 High Street", null, "Some town", "Some county", "Post code", new Country(Guid.NewGuid(), "UK - England"), "01234 567890", "*****@*****.**"); Contact contact = new Contact("John", "Smith", "Manager"); Organisation organisation = Organisation.CreateSoleTrader("Test organisation"); organisation.AddOrUpdateAddress(AddressType.OrganisationAddress, address); organisation.AddOrUpdateMainContactPerson(contact); Scheme scheme = new Scheme(organisation); scheme.UpdateScheme( "Test scheme", "WEE/AA1111AA/SCH", "WEE00000001", A.Dummy<ObligationType>(), authority); int complianceYear = A.Dummy<int>(); MemberUpload memberUpload = new MemberUpload( A.Dummy<Guid>(), A.Dummy<string>(), A.Dummy<List<MemberUploadError>>(), A.Dummy<decimal>(), complianceYear, scheme, A.Dummy<string>()); memberUpload.Submit(A.Dummy<User>()); List<MemberUpload> memberUploads = new List<MemberUpload>(); memberUploads.Add(memberUpload); InvoiceRun invoiceRun = new InvoiceRun(authority, memberUploads, A.Dummy<User>()); BySchemeCustomerFileGenerator generator = new BySchemeCustomerFileGenerator(); ulong id = 12345; // Act var result = await generator.CreateAsync(id, invoiceRun); CustomerFile customerFile = result.IbisFile; // Assert Assert.Equal((ulong)12345, customerFile.FileID); }
public Task<int> GetNumberOfDataReturnSubmissionsAsync(Scheme scheme, int complianceYear, QuarterType quarter) { return weeeContext.DataReturnVersions .Where(d => d.SubmittedDate.HasValue) .Where(d => d.DataReturn.Scheme.Id == scheme.Id) .Where(d => d.DataReturn.Quarter.Year == complianceYear) .Where(d => d.DataReturn.Quarter.Q == quarter) .CountAsync(); }
private int maxID; // максимальный идентификатор элемента схемы #endregion Fields #region Constructors /// <summary> /// Конструктор /// </summary> public SchemeView() : base() { maxID = 0; ElementList = new List<Element>(); ElementDict = new Dictionary<int, Element>(); ImageDict = new Dictionary<string, Image>(); CnlsFilter = new List<int>(); SchemeParams = new Scheme(ImageDict, CnlsFilter); }
/// <summary> /// Fetches all data returns for the specified scheme and compliance year. /// The current data return version, EEE output return version and EEE output amounts /// will be pre-loaded in the results. /// Results will be returned orderd by quarter type. /// </summary> /// <param name="scheme"></param> /// <param name="complianceYear"></param> /// <returns></returns> public async Task<IEnumerable<DataReturn>> FetchDataReturns(Scheme scheme, int complianceYear) { return await context.DataReturns .Include(dr => dr.CurrentVersion) .Include(dr => dr.CurrentVersion.EeeOutputReturnVersion) .Include(dr => dr.CurrentVersion.EeeOutputReturnVersion.EeeOutputAmounts) .Where(dr => dr.Scheme.Id == scheme.Id) .Where(dr => dr.Quarter.Year == complianceYear) .OrderBy(dr => dr.Quarter.Q) .ToListAsync(); }
public DataReturnUpload(Scheme scheme, string data, List<DataReturnUploadError> errors, string fileName, int? year, int? quarter) { Guard.ArgumentNotNull(() => scheme, scheme); Scheme = scheme; Errors = errors; RawData = new DataReturnUploadRawData() { Data = data }; this.Date = SystemTime.UtcNow; FileName = fileName; ComplianceYear = year; Quarter = quarter; }
private Scheme BuildScheme(string approvalNumber) { var scheme = new Scheme(new Guid("FE4056B3-F892-476E-A4AB-7C111AE1EF14")); scheme.UpdateScheme( "Test scheme", approvalNumber, "1B1S", Domain.Obligation.ObligationType.Both, new Guid("C5D400BE-0CE7-43D7-BD7B-B7936967E500")); return scheme; }
public MemberUpload GenerateMemberUpload(ProcessXmlFile messageXmlFile, List<MemberUploadError> errors, decimal totalCharges, Scheme scheme) { if (errors != null && errors.Any(e => e.ErrorType == UploadErrorType.Schema)) { return new MemberUpload(messageXmlFile.OrganisationId, xmlConverter.XmlToUtf8String(messageXmlFile.Data), errors, totalCharges, null, scheme, messageXmlFile.FileName); } else { var xml = xmlConverter.XmlToUtf8String(messageXmlFile.Data); var deserializedXml = xmlConverter.Deserialize<schemeType>(xmlConverter.Convert(messageXmlFile.Data)); return new MemberUpload(messageXmlFile.OrganisationId, xml, errors, totalCharges, int.Parse(deserializedXml.complianceYear), scheme, messageXmlFile.FileName); } }
public void SetCurrentDataReturnVersion_ThrowsArugmentNullException() { // Arrange Scheme scheme = new Scheme(Guid.NewGuid()); Quarter quarter = new Quarter(2016, QuarterType.Q1); DataReturn dataReturn = new DataReturn(scheme, quarter); // Act Action action = () => dataReturn.SetCurrentVersion(null); // Assert Assert.Throws<ArgumentNullException>(action); }
public async Task HandleAsync_WithFilterSetToApproved_ReturnsSchemesWithStatusOfApproved() { // Arrange IWeeeAuthorization authorization = AuthorizationBuilder.CreateUserWithAllRights(); IMap<Scheme, SchemeData> schemeMap = new SchemeMap(A.Dummy<IMapper>()); Domain.Organisation.Organisation organisation = Domain.Organisation.Organisation.CreateSoleTrader("Test Organisation"); Scheme schemePending = new Scheme(organisation); schemePending.UpdateScheme("Scheme Pending", "WEE/11AAAA11/SCH", "WEE1234567", ObligationType.Both, A.Dummy<UKCompetentAuthority>()); Scheme schemeApproved = new Scheme(organisation); schemeApproved.UpdateScheme("Scheme Approved", "WEE/11AAAA11/SCH", "WEE1234567", ObligationType.Both, A.Dummy<UKCompetentAuthority>()); schemeApproved.SetStatus(SchemeStatus.Approved); Scheme schemeRejected = new Scheme(organisation); schemeRejected.UpdateScheme("Scheme Rejected", "WEE/11AAAA11/SCH", "WEE1234567", ObligationType.Both, A.Dummy<UKCompetentAuthority>()); schemeRejected.SetStatus(SchemeStatus.Rejected); Scheme schemeWithdrawn = new Scheme(organisation); schemeWithdrawn.UpdateScheme("Scheme Withdrawn", "WEE/11AAAA11/SCH", "WEE1234567", ObligationType.Both, A.Dummy<UKCompetentAuthority>()); schemeWithdrawn.SetStatus(SchemeStatus.Approved); schemeWithdrawn.SetStatus(SchemeStatus.Withdrawn); IGetSchemesDataAccess dataAccess = A.Fake<IGetSchemesDataAccess>(); A.CallTo(() => dataAccess.GetSchemes()).Returns( new List<Scheme>() { schemePending, schemeApproved, schemeRejected, schemeWithdrawn }); GetSchemesHandler handler = new GetSchemesHandler( authorization, schemeMap, dataAccess); // Act GetSchemes request = new GetSchemes(GetSchemes.FilterType.Approved); List<SchemeData> results = await handler.HandleAsync(request); // Assert Assert.NotNull(results); Assert.Equal(1, results.Count); Assert.Contains(results, r => r.SchemeName == "Scheme Approved"); }
public void SetCurrentDataReturnVersion_ThrowInvalidOperationException() { // Arrange Scheme scheme = new Scheme(Guid.NewGuid()); Quarter quarter = new Quarter(2016, QuarterType.Q1); DataReturn dataReturn = new DataReturn(scheme, quarter); DataReturnVersion version = new DataReturnVersion(new DataReturn(scheme, quarter)); // Act Action action = () => dataReturn.SetCurrentVersion(version); // Assert Assert.Throws<InvalidOperationException>(action); }
public IEnumerable<ErrorData> Validate(string xmlSchemeApprovalNumber, Scheme scheme) { var result = new List<ErrorData>(); if (xmlSchemeApprovalNumber != scheme.ApprovalNumber) { var errorMessage = string.Format( "The PCS approval number {0} you have provided does not match with the PCS. Review the PCS approval number.", xmlSchemeApprovalNumber); result.Add(new ErrorData(errorMessage, ErrorLevel.Error)); } return result; }
/// <summary> /// Initializes a new instance of the <see cref="FMSAxml"/> class. /// Default constructor, requires all the info. /// </summary> /// <param name="theScheme">The scheme (HTTP/HTTPS).</param> /// <param name="theServer">The IP or DNS name of the web server.</param> /// <param name="thePort">The port.</param> /// <param name="theGrammar">The XML grammar requested from FMSA.</param> /// <param name="theAccount">The account.</param> /// <param name="thePW">The password.</param> /// <param name="timeOut">Milliseconds to wait for FMSA's response. (Default is 100,000 or 100 seconds).</param> /// <param name="dtd">Use DTD validation (Default is False). DO NOT USE WITH FMSA 9!!!!</param> /// <remarks>In this version of fmDotNet we're only going to use fmresultset as the available grammar no matter what is specified in the class constructor parameters</remarks> public FMSAxml(Scheme theScheme, string theServer, int thePort, Grammar theGrammar, string theAccount, string thePW, int timeOut, bool dtd) { Protocol = theScheme; ServerAddress = theServer; Port = thePort; ResponseTimeout = timeOut; DTDValidation = dtd; XmlGrammer = Grammar.fmresultset; FMAccount = theAccount; FMPassword = thePW; BaseUrl = MakeURL(); availableDBs = GetFiles(); }
public async void SchemeDoesExist_SetsSchemeStatus_AndSavesChanges(SchemeStatus status) { var scheme = new Scheme(Guid.NewGuid()); A.CallTo(() => context.Schemes) .Returns(dbContextHelper.GetAsyncEnabledDbSet(new List<Scheme> { scheme })); await SetSchemeStatusHandler().HandleAsync(new SetSchemeStatus(scheme.Id, status)); Assert.Equal(status.ToDomainEnumeration<Domain.Scheme.SchemeStatus>(), context.Schemes.Single().SchemeStatus); A.CallTo(() => context.SaveChangesAsync()).MustHaveHappened(Repeated.Exactly.Once); }
public async Task CreateTransactionFile_WithFileID_CreatesFileWithCorrectFileID() { // Arrange UKCompetentAuthority authority = A.Dummy<UKCompetentAuthority>(); Organisation organisation = Organisation.CreateSoleTrader("Test organisation"); Scheme scheme = new Scheme(organisation); scheme.UpdateScheme( "Test scheme", "WEE/AA1111AA/SCH", "WEE00000001", A.Dummy<ObligationType>(), authority); int complianceYear = A.Dummy<int>(); MemberUpload memberUpload = new MemberUpload( A.Dummy<Guid>(), A.Dummy<string>(), A.Dummy<List<MemberUploadError>>(), 123.45m, complianceYear, scheme, A.Dummy<string>()); memberUpload.Submit(A.Dummy<User>()); List<MemberUpload> memberUploads = new List<MemberUpload>(); memberUploads.Add(memberUpload); InvoiceRun invoiceRun = new InvoiceRun(authority, memberUploads, A.Dummy<User>()); ITransactionReferenceGenerator transactionReferenceGenerator = A.Fake<ITransactionReferenceGenerator>(); A.CallTo(() => transactionReferenceGenerator.GetNextTransactionReferenceAsync()).Returns("WEE800001H"); BySchemeTransactionFileGenerator generator = new BySchemeTransactionFileGenerator( transactionReferenceGenerator); ulong id = 12345; // Act var result = await generator.CreateAsync(id, invoiceRun); TransactionFile transactionFile = result.IbisFile; // Assert Assert.Equal((ulong)12345, transactionFile.FileID); }
public string Route(Scheme scheme, string routeName, params object[] args) { routeName.ThrowIfNull("routeName"); Routing.Route[] routes = _routes.Value.GetRoutes(routeName).ToArray(); if (routes.Length > 1) { throw new ArgumentException(String.Format("More than one route exists with name '{0}'.", routeName), "routeName"); } if (!routes.Any()) { throw new ArgumentException(String.Format("Route with name '{0}' was not found.", routeName), "routeName"); } return Absolute(scheme, routes[0].ResolveRelativeUrl(args)); }
public async void HandleAsync_SchemeExists_MapsStatus() { var schemeId = Guid.NewGuid(); var scheme = new Scheme(schemeId); A.CallTo(() => context.Schemes) .Returns(contextHelper.GetAsyncEnabledDbSet(new List<Scheme> { scheme })); await GetSchemeStatusHandler().HandleAsync(new GetSchemeStatus(schemeId)); A.CallTo(() => mapper.Map(A<Domain.Scheme.SchemeStatus>._)) .MustHaveHappened(Repeated.Exactly.Once); }
public Libpre(Scheme scheme, byte[] parameters) { this.scheme = scheme; // Initialize unmanaged library by having it generate parameters first. // This is required to avoid a weird error where it otherwise would crash // the entire process if initialized with parameters the first time. this.errorId = LibpreWrapper.GenerateParams(out this.parameters, this.scheme); AssertSuccess(); // if we actually received some premade parameters, then use those) if (parameters != null) { LibpreWrapper.DestroyParams(this.parameters); this.parameters = DeserializeParams(parameters); } }
private bool SaveSettings(string user, string password, string host, string port, Scheme scheme) { var vault = new PasswordVault(); foreach (var pwdCredential in vault.RetrieveAll()) { vault.Remove(pwdCredential); } vault.Add(new PasswordCredential(ResourceName, user, password)); var res = vault.FindAllByUserName(user); ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; localSettings.Values["host"] = host; localSettings.Values["scheme"] = scheme.ToString(); localSettings.Values["port"] = port.ToString(); MainPage.SplunkService = null; return true; }
public static ProducerSubmission Create( ObligationType obligationType, string prn, Guid? schemeOrganisationId = null, int? complianceYear = null, ProducerBusiness producerBusiness = null, params string[] brandNames) { Scheme scheme = new Scheme( schemeOrganisationId ?? Guid.Empty); RegisteredProducer registeredProducer = new RegisteredProducer( prn, complianceYear ?? 2016, scheme); MemberUpload memberUpload = new MemberUpload( Guid.NewGuid(), "<xml>SomeData</xml>", new List<MemberUploadError>(), 0, complianceYear ?? 2016, scheme, "File name"); return new ProducerSubmission( registeredProducer, memberUpload, producerBusiness ?? new ProducerBusiness(), new AuthorisedRepresentative("authrep"), DateTime.Now, 0, true, null, "trading name", EEEPlacedOnMarketBandType.Lessthan5TEEEplacedonmarket, SellingTechniqueType.Both, obligationType, AnnualTurnOverBandType.Greaterthanonemillionpounds, brandNames.Select(bn => new BrandName(bn)).ToList(), new List<SICCode>(), new ChargeBandAmount(Guid.NewGuid(), ChargeBand.A, 123), 999); }
public string Absolute(Scheme scheme, string relativeUrl, params object[] args) { relativeUrl.ThrowIfNull("relativeUrl"); string rootRelativePath = _httpRuntime.AppDomainAppVirtualPath.TrimStart('/'); string rootPath = String.Format("{0}/{1}", rootRelativePath.Length > 0 ? "/" + rootRelativePath : "", String.Format(relativeUrl.TrimStart('/'), args)); switch (scheme) { case Scheme.NotSpecified: return rootPath; case Scheme.Http: return new UriBuilder("http", _configuration.HostName, _configuration.GetPort(scheme), rootPath).GetUriWithoutOptionalPort().ToString(); case Scheme.Https: return new UriBuilder("https", _configuration.HostName, _configuration.GetPort(scheme), rootPath).GetUriWithoutOptionalPort().ToString(); default: throw new ArgumentOutOfRangeException("scheme"); } }
public async Task HandleAsync_HappyPath_UpdatesSchemeCallsSaveAndReturnsSuccess() { // Arrange IWeeeAuthorization authorization = AuthorizationBuilder.CreateUserWithAllRights(); IUpdateSchemeInformationDataAccess dataAccess = A.Fake<IUpdateSchemeInformationDataAccess>(); Scheme scheme = new Scheme(A.Dummy<Organisation>()); A.CallTo(() => dataAccess.FetchSchemeAsync(A<Guid>._)).Returns(scheme); UpdateSchemeInformationHandler handler = new UpdateSchemeInformationHandler( authorization, dataAccess); // Act UpdateSchemeInformation request = new UpdateSchemeInformation( A.Dummy<Guid>(), "New scheme name", "WEE/AB8888CD/SCH", "WEE7453956", ObligationType.B2B, new Guid("559B69CE-865C-465F-89ED-D6A58AA8B0B9"), SchemeStatus.Approved); UpdateSchemeInformationResult result = await handler.HandleAsync(request); // Assert Assert.Equal("New scheme name", scheme.SchemeName); Assert.Equal("WEE/AB8888CD/SCH", scheme.ApprovalNumber); Assert.Equal("WEE7453956", scheme.IbisCustomerReference); Assert.Equal(Domain.Obligation.ObligationType.B2B, scheme.ObligationType); Assert.Equal(new Guid("559B69CE-865C-465F-89ED-D6A58AA8B0B9"), scheme.CompetentAuthorityId); Assert.Equal(Domain.Scheme.SchemeStatus.Approved, scheme.SchemeStatus); A.CallTo(() => dataAccess.SaveAsync()).MustHaveHappened(); Assert.NotNull(result); Assert.Equal(UpdateSchemeInformationResult.ResultType.Success, result.Result); }
/// <summary> /// Метод для трассировки /// </summary> /// <returns>Список логов шагов</returns> public static List <StepTracingLog> Trace(Scheme sch, PlacementResult plc, bool isOptimized, out string err) { // обязательно создаём лог действий var log = new List <StepTracingLog>(); // при возникновении критической ошибки её нужно занести в эту переменную и сделать return null err = ""; // формируем список плат, в котором хранится список слоёв (для каждого проводника свой слой ДРП) var boards = new List <List <Matrix <Cell> > >(); // считываем список плат, в каждой плате хранится список проводников (Wire) соединяют всего 2 контакта List <List <Wire> > boardsWiresPositions = plc.BoardsWiresPositions; // запускаем цикл по платам for (int boardNum = 0; boardNum < boardsWiresPositions.Count; boardNum++) { // получаем список проводов, которые необходимо развести на этой плате // элемент списка объект класса Wire, который хранит координаты точки А и Б на ДРП var boardWiresPositions = boardsWiresPositions[boardNum]; // список ДРП текущей платы, в который будет заносится ДРП для каждого провода var boardDRPs = new List <Matrix <Cell> >(); // добавляем этот список в список всех плат boards.Add(boardDRPs); // первым слоем будет являтся ДРП на котором просто отмечены места контактов платы boardDRPs.Add(plc.BoardsDRPs[boardNum]); // запускаем цикл по проводам foreach (var wire in boardWiresPositions) { // ДРП для провода формируем на основе шаблона ДРП, на котором просто отмечены контакты. Оно уже имеет необходимые размеры. var currentDRP = new Matrix <Cell>(plc.BoardsDRPs[boardNum].RowsCount, plc.BoardsDRPs[boardNum].ColsCount); // добавляем это ДРП в список ДРП платы boardDRPs.Add(currentDRP); // заполняем ДРП пустыми ячейками for (int i = 0; i < currentDRP.RowsCount; i++) { for (int j = 0; j < currentDRP.ColsCount; j++) { currentDRP[i, j] = new Cell(); } } // дрп, в котором будут объединены все слои с проводами (для определения гдле занята ячейка - где нет) Matrix <Cell> fullDrp; // получаем из провода стартовую и конечную позицию var startPos = wire.A.PositionContact; var endPos = wire.B.PositionContact; // помечаем буквами стартовую и конечную позицию на текущем слое провода currentDRP[startPos.Row, startPos.Column].State = CellState.PointA; currentDRP[endPos.Row, endPos.Column].State = CellState.PointB; log.Add(new StepTracingLog(boards, $"Начинаем трассировку {boardDRPs.Count - 1}-го проводника в {boardNum + 1} узле")); int currentWeight = 0; // у начальной позиции вес 0 currentDRP[startPos.Row, startPos.Column].Weight = currentWeight; // объединяем все слои fullDrp = ApplicationData.MergeLayersDRPs(boardDRPs); // и получаем незанятых соседей для начальной точки var neighbors = getNeighbors(fullDrp, startPos); // запускаем цикл пока не будет найдено ни одного незанятого соседа или в списке соседей окажется точка Б do { // увеличиваем вес currentWeight++; // запускаем цикл по всем незанятым соседним ячейкам foreach (var neighbor in neighbors) { // распространяем волну currentDRP[neighbor.Row, neighbor.Column].Weight = currentWeight; currentDRP[neighbor.Row, neighbor.Column].State = CellState.Wave; fullDrp[neighbor.Row, neighbor.Column].Weight = currentWeight; fullDrp[neighbor.Row, neighbor.Column].State = CellState.Wave; } if (!isOptimized) { log.Add(new StepTracingLog(boards, $"Распроcтраняем волну с весом {currentWeight} для {boardDRPs.Count - 1}-го проводника в {boardNum+1} узле")); } // и получаем список незанятых соседей для ячеек текущей волны neighbors = getNeighbors(fullDrp, neighbors); } while (neighbors.Count > 0 && !neighbors.Any(x => x.Equals(endPos))); // если незанятых соседей не оказалось, значит трассировка невозможна if (neighbors.Count == 0) { log.Add(new StepTracingLog(boards, $"Невозможно выполнить трассировку {boardDRPs.Count - 1}-го проводника в {boardNum + 1} узле")); // очищаем текущее дрп for (int i = 0; i < currentDRP.RowsCount; i++) { for (int j = 0; j < currentDRP.ColsCount; j++) { if (currentDRP[i, j].State == CellState.Wave) { currentDRP[i, j].State = CellState.Empty; } currentDRP[i, j].Weight = -1; } } currentDRP[startPos.Row, startPos.Column].State = CellState.Contact; currentDRP[endPos.Row, endPos.Column].State = CellState.Contact; continue; } if (isOptimized) { log.Add(new StepTracingLog(boards, $"Волна {boardDRPs.Count - 1}-го проводника достигла точки Б в {boardNum + 1} узле")); } // теперь начинаем обратный крестовый поход от точки Б neighbors = new List <Position>(); neighbors.Add(endPos); Position currentPos = endPos.Clone(); fullDrp = ApplicationData.MergeLayersDRPs(boardDRPs); do { // получаем список волновых соседей neighbors = getNeighborsOnlyWave(fullDrp, currentPos); foreach (var neighbor in neighbors) { // находим в списке соседей первую ячейку с волной необходимого веса if (currentDRP[neighbor.Row, neighbor.Column].Weight == currentWeight) { // помечаем что в этой ячейке будет находится проводник, но какой имеено определим ниже currentDRP[neighbor.Row, neighbor.Column].State = CellState.Wire; fullDrp[neighbor.Row, neighbor.Column].State = CellState.Wire; currentPos = neighbor.Clone(); break; } } // на каждом шаге уменьшаем вес currentWeight--; } while (currentWeight >= 0); // очищаем всё дрп от веса и ячеек с волной for (int i = 0; i < currentDRP.RowsCount; i++) { for (int j = 0; j < currentDRP.ColsCount; j++) { currentDRP[i, j].Weight = -1; if (currentDRP[i, j].State == CellState.Wave) { currentDRP[i, j].State = CellState.Empty; } } } log.Add(new StepTracingLog(boards, $"Волна достигла точки Б. Определяем точки, где будет проходить проводник №{boardDRPs.Count - 1} в {boardNum + 1} узле")); // начинаем долгую и мучительную спец операцию по определению какой формы проводник должен стоять в ячейке // запускаем цикл по всем ячейкам дрп for (int i = 0; i < currentDRP.RowsCount; i++) { for (int j = 0; j < currentDRP.ColsCount; j++) { // объявляем соседей, от них нам нужно будет только состояние Cell leftCell = new Cell(); Cell rightCell = new Cell(); Cell topCell = new Cell(); Cell bottomCell = new Cell(); // блок, который присвоит пустое состояние ячейке, если она находится вне дрп, если находится в дрп, то присвоит нужную позицию if (j > 0) { leftCell = currentDRP[i, j - 1]; } else { leftCell.State = CellState.Empty; } if (j < currentDRP.ColsCount - 1) { rightCell = currentDRP[i, j + 1]; } else { rightCell.State = CellState.Empty; } if (i > 0) { topCell = currentDRP[i - 1, j]; } else { topCell.State = CellState.Empty; } if (i < currentDRP.RowsCount - 1) { bottomCell = currentDRP[i + 1, j]; } else { bottomCell.State = CellState.Empty; } // конец блока var currentCell = currentDRP[i, j]; // если текущая ячейка должна быть каким-то кабелем // определяем значения ячеек вокруг и на основе этих данных узнаём какой имеено должен быть кабель // идущим вертикально или слева вверх или горизонтальным и т.д. if (currentCell.State == CellState.Wire) { // если есть кабель сверху и кабель в ячейке снизу, то в текущей ячейке должен стоять вертикальный проводник if (topCell.isConnectible && bottomCell.isConnectible) { currentDRP[i, j].State = CellState.WireVertical; } else if (leftCell.isConnectible && rightCell.isConnectible) { currentDRP[i, j].State = CellState.WireHorizontal; } else if (topCell.isConnectible && leftCell.isConnectible) { currentDRP[i, j].State = CellState.WireTopLeft; } else if (topCell.isConnectible && rightCell.isConnectible) { currentDRP[i, j].State = CellState.WireTopRight; } else if (bottomCell.isConnectible && leftCell.isConnectible) { currentDRP[i, j].State = CellState.WireBottomLeft; } else if (bottomCell.isConnectible && rightCell.isConnectible) { currentDRP[i, j].State = CellState.WireBottomRight; } } } } // заменяем буквы просто контактами currentDRP[startPos.Row, startPos.Column].State = CellState.Contact; currentDRP[endPos.Row, endPos.Column].State = CellState.Contact; log.Add(new StepTracingLog(boards, $"Построили на базе точек проводник №{boardDRPs.Count - 1} в {boardNum + 1} узле")); } } return(log); }
public AutoRouteCollection CssBundle(Bundle bundle, string routeName, Scheme scheme, string relativePath, IComparer <AssetFile> assetOrder, IAssetConcatenator concatenator, params IAssetTransformer[] transformers) { return(CssBundle(bundle, routeName, scheme, relativePath, assetOrder, concatenator, (IEnumerable <IAssetTransformer>)transformers)); }
public static IIcd Of(string identifier, string code, Scheme scheme, string issuingAgency) { return(new GenericIcd(identifier, code, scheme, issuingAgency)); }
public MainForm() { InitializeComponent(); drugs = new BindingList <Drug>(); schemes = new BindingList <Scheme>(); patients = new BindingList <Patient>(); currentScheme = new Scheme(); currentPatient = new Patient(); currentPatientNotSavedFlag = true; patientBTN.BackgroundImageLayout = ImageLayout.Stretch; { XmlSerializer formatter = new XmlSerializer(typeof(BindingList <Drug>)); try { FileStream fs = new FileStream("drugs.xml", FileMode.OpenOrCreate); drugs = formatter.Deserialize(fs) as BindingList <Drug>; fs.Close(); } catch { MessageBox.Show("Cannot open Drugs File"); } } { XmlSerializer formatter = new XmlSerializer(typeof(BindingList <Scheme>)); try { FileStream fs = new FileStream("schemes.xml", FileMode.OpenOrCreate); schemes = formatter.Deserialize(fs) as BindingList <Scheme>; fs.Close(); } catch { MessageBox.Show("Cannot open Schemes File"); } } { XmlSerializer formatter = new XmlSerializer(typeof(BindingList <Patient>)); try { FileStream fs = new FileStream("patients.xml", FileMode.OpenOrCreate); patients = formatter.Deserialize(fs) as BindingList <Patient>; fs.Close(); } catch { MessageBox.Show("Cannot open Patients File"); } } { drugsDataGridView.DataSource = drugs; drugsDataGridView.Columns["currentDose"].Visible = false; drugsDataGridView.Columns["name"].HeaderText = "Название"; drugsDataGridView.Columns["description"].HeaderText = "Описание"; drugsDataGridView.Columns["calculationMethod"].HeaderText = "Способ расчета"; drugsDataGridView.Columns["dose"].HeaderText = "Дозировка"; schemesDataGridView.DataSource = schemes; schemesDataGridView.Columns["name"].HeaderText = "Название"; schemesDataGridView.Columns["intervalInDays"].HeaderText = "Интервал"; schemesDataGridView.ReadOnly = true; schemesDataGridView.AllowUserToResizeColumns = false; schemeCMBX.DataSource = schemes; schemeCMBX.DisplayMember = "name"; currentPatientSchemeGridView.DataSource = currentScheme.drugsList; currentPatientSchemeGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; currentPatientSchemeGridView.Columns["calculationMethod"].Visible = false; currentPatientSchemeGridView.Columns["currentDose"].DefaultCellStyle.Format = "N2"; } }
public AutoRouteCollection JavaScriptBundle(Bundle bundle, string routeName, Scheme scheme, string relativePath, IAssetConcatenator concatenator, params IAssetTransformer[] transformers) { return(JavaScriptBundle(bundle, routeName, scheme, relativePath, concatenator, (IEnumerable <IAssetTransformer>)transformers)); }
public void Restart(Scheme scheme) { Reset(); Load(scheme); // TODO: reuse objects }
public override Uri Normalize() { return(new Urn(Scheme.ToLowerInvariant() + ':' + NamespaceIdentifier.ToLowerInvariant() + ':' + NamespaceSpecificString)); }
/// <summary> /// Initializes a new instance of the <see cref="Context"/> class with a /// protocol, host, port number, and optional message handler. /// </summary> /// <param name="scheme"> /// The <see cref="Scheme"/> used to communicate with <see cref="Host"/>. /// </param> /// <param name="host"> /// The DNS name of a Splunk server instance. /// </param> /// <param name="port"> /// The port number used to communicate with <see cref="Host"/>. /// </param> /// <param name="timeout"> /// The timeout. /// </param> /// <param name="handler"> /// The <see cref="HttpMessageHandler"/> responsible for processing the HTTP /// response messages. /// </param> /// <param name="disposeHandler"> /// <c>true</c> if the inner handler should be disposed of by Dispose, /// <c>false</c> if you intend to reuse the inner handler. /// </param> /// <exception name="ArgumentException"> /// <paramref name="scheme"/> is invalid, <paramref name="host"/> is /// <c>null</c> or empty, or <paramref name="port"/> is less than zero /// or greater than <c>65535</c>. /// </exception> public Context(Scheme scheme, string host, int port, TimeSpan timeout, HttpMessageHandler handler, bool disposeHandler = true) { Contract.Requires<ArgumentException>(scheme == Scheme.Http || scheme == Scheme.Https); Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(host)); Contract.Requires<ArgumentException>(0 <= port && port <= 65535); this.Scheme = scheme; this.Host = host; this.Port = port; this.httpClient = handler == null ? new HttpClient(new HttpClientHandler { UseCookies = false }) : new HttpClient(handler, disposeHandler); this.httpClient.DefaultRequestHeaders.Add("User-Agent", "splunk-sdk-csharp/2.0"); this.CookieJar = new CookieStore(); if (timeout != default(TimeSpan)) { this.httpClient.Timeout = timeout; } }
private async Task WriteResultsToSql( DateTime utcNow, string connectionString, string tableName, string session, string description, string aspnetCoreVersion, string runtimeVersion, string scenario, Hardware hardware, string hardwareVersion, Benchmarks.ServerJob.OperatingSystem operatingSystem, Scheme scheme, Source source, WebHost webHost, int?kestrelThreadCount, int clientThreads, int connections, int duration, int?pipelineDepth, string path, string method, IDictionary <string, string> headers, string dimension, double value, bool runtimeStore) { string insertCmd = @" INSERT INTO [dbo].[" + tableName + @"] ([DateTime] ,[Session] ,[Description] ,[AspNetCoreVersion] ,[RuntimeVersion] ,[Scenario] ,[Hardware] ,[HardwareVersion] ,[OperatingSystem] ,[Framework] ,[RuntimeStore] ,[Scheme] ,[WebHost] ,[KestrelThreadCount] ,[ClientThreads] ,[Connections] ,[Duration] ,[PipelineDepth] ,[Path] ,[Method] ,[Headers] ,[Dimension] ,[Value]) VALUES (@DateTime ,@Session ,@Description ,@AspNetCoreVersion ,@RuntimeVersion ,@Scenario ,@Hardware ,@HardwareVersion ,@OperatingSystem ,@Framework ,@RuntimeStore ,@Scheme ,@WebHost ,@KestrelThreadCount ,@ClientThreads ,@Connections ,@Duration ,@PipelineDepth ,@Path ,@Method ,@Headers ,@Dimension ,@Value) "; using (var connection = new SqlConnection(connectionString)) { await connection.OpenAsync(); var transaction = connection.BeginTransaction(); try { var command = new SqlCommand(insertCmd, connection, transaction); var p = command.Parameters; p.AddWithValue("@DateTime", utcNow); p.AddWithValue("@Session", session); p.AddWithValue("@Description", description); p.AddWithValue("@AspNetCoreVersion", aspnetCoreVersion); p.AddWithValue("@RuntimeVersion", runtimeVersion); p.AddWithValue("@Scenario", scenario.ToString()); p.AddWithValue("@Hardware", hardware.ToString()); p.AddWithValue("@HardwareVersion", hardwareVersion); p.AddWithValue("@OperatingSystem", operatingSystem.ToString()); p.AddWithValue("@Framework", "Core"); p.AddWithValue("@RuntimeStore", runtimeStore); p.AddWithValue("@Scheme", scheme.ToString().ToLowerInvariant()); p.AddWithValue("@WebHost", webHost.ToString()); p.AddWithValue("@KestrelThreadCount", (object)kestrelThreadCount ?? DBNull.Value); p.AddWithValue("@ClientThreads", clientThreads); p.AddWithValue("@Connections", connections); p.AddWithValue("@Duration", duration); p.AddWithValue("@PipelineDepth", (object)pipelineDepth ?? DBNull.Value); p.AddWithValue("@Path", string.IsNullOrEmpty(path) ? (object)DBNull.Value : path); p.AddWithValue("@Method", method.ToString().ToUpperInvariant()); p.AddWithValue("@Headers", headers.Any() ? JsonConvert.SerializeObject(headers) : (object)DBNull.Value); p.AddWithValue("@Dimension", dimension); p.AddWithValue("@Value", value); await command.ExecuteNonQueryAsync(); transaction.Commit(); } catch { transaction.Rollback(); throw; } finally { transaction.Dispose(); } } }
public void CompleteScheme(Scheme nextBehaviourType, ISchemeModelMarkup nextModel) { CompleteBehaviourInternal(nextBehaviourType, nextModel); }
public async Task Execute_ListOfProducers_ReturnsRecordsInCurrectOrder() { using (DatabaseWrapper db = new DatabaseWrapper()) { // Arrange ModelHelper helper = new ModelHelper(db.Model); Scheme scheme1 = helper.CreateScheme(); scheme1.OrganisationId = new Guid("4EEE5942-01B2-4A4D-855A-34DEE1BBBF26"); scheme1.Organisation.Id = new Guid("4EEE5942-01B2-4A4D-855A-34DEE1BBBF26"); scheme1.SchemeName = "Lamborghini"; scheme1.Organisation.Name = "PCS operator name"; scheme1.Organisation.BusinessAddressId = new Guid("b58e9cb2-b97e-4141-ad32-73c70284fc77"); scheme1.Organisation.Address = helper.CreateOrganisationAddress(); scheme1.Organisation.Address.Id = new Guid("b58e9cb2-b97e-4141-ad32-73c70284fc77"); MemberUpload memberUpload1 = helper.CreateMemberUpload(scheme1); memberUpload1.ComplianceYear = 2016; memberUpload1.IsSubmitted = true; ProducerSubmission producerSubmission1 = helper.CreateProducerAsCompany(memberUpload1, "WEE/99ZZZZ99"); producerSubmission1.Business.Company.Name = "A company name"; ProducerSubmission producerSubmission2 = helper.CreateProducerAsCompany(memberUpload1, "WEE/88ZZZZ88"); producerSubmission2.Business.Company.Name = "B company name"; Scheme scheme2 = helper.CreateScheme(); scheme2.OrganisationId = new Guid("84729d95-3c26-4c37-9730-f25fa2b6dbfc"); scheme2.Organisation.Id = new Guid("84729d95-3c26-4c37-9730-f25fa2b6dbfc"); scheme2.SchemeName = "Aston Martin"; scheme2.Organisation.Name = "PCS operator name 1"; scheme2.Organisation.BusinessAddressId = new Guid("ecdf60fc-1576-43e2-9bb4-e6c9dc9d721d"); scheme2.Organisation.Address = helper.CreateOrganisationAddress(); scheme2.Organisation.Address.Id = new Guid("ecdf60fc-1576-43e2-9bb4-e6c9dc9d721d"); MemberUpload memberUpload2 = helper.CreateMemberUpload(scheme2); memberUpload2.ComplianceYear = 2016; memberUpload2.IsSubmitted = true; ProducerSubmission producerSubmission3 = helper.CreateProducerAsCompany(memberUpload2, "WEE/11ZZZZ11"); producerSubmission3.Business.Company.Name = "C company name"; ProducerSubmission producerSubmission4 = helper.CreateProducerAsCompany(memberUpload2, "WEE/22ZZZZ22"); producerSubmission4.Business.Company.Name = "D company name"; db.Model.SaveChanges(); // Act List <ProducerPublicRegisterCSVData> results = await db.StoredProcedures.SpgProducerPublicRegisterCSVDataByComplianceYear(2016); // Assert Assert.NotNull(results); Assert.True(results.FindIndex(i => i.SchemeName == "Aston Martin" && i.ProducerName == "C company name") < results.FindIndex(i => i.SchemeName == "Aston Martin" && i.ProducerName == "D company name")); Assert.True(results.FindIndex(i => i.SchemeName == "Lamborghini" && i.ProducerName == "A company name") < results.FindIndex(i => i.SchemeName == "Lamborghini" && i.ProducerName == "B company name")); Assert.True(results.FindIndex(i => i.SchemeName == "Aston Martin" && i.ProducerName == "C company name") < results.FindIndex(i => i.SchemeName == "Lamborghini" && i.ProducerName == "B company name")); } }
public async Task Execute_HappyPath_ProducerTypeIsCompany_PerfectAssociationOfSchemeToOrganisationAndReturnsSelectedComplianceYearRecords() { using (DatabaseWrapper db = new DatabaseWrapper()) { // Arrange ModelHelper helper = new ModelHelper(db.Model); Scheme scheme1 = helper.CreateScheme(); scheme1.OrganisationId = new Guid("4EEE5942-01B2-4A4D-855A-34DEE1BBBF26"); scheme1.Organisation.Id = new Guid("4EEE5942-01B2-4A4D-855A-34DEE1BBBF26"); scheme1.SchemeName = "SchemeName"; scheme1.Organisation.Name = "PCS operator name"; scheme1.Organisation.BusinessAddressId = new Guid("b58e9cb2-b97e-4141-ad32-73c70284fc77"); scheme1.Organisation.Address = helper.CreateOrganisationAddress(); scheme1.Organisation.Address.Id = new Guid("b58e9cb2-b97e-4141-ad32-73c70284fc77"); MemberUpload memberUpload1 = helper.CreateMemberUpload(scheme1); memberUpload1.ComplianceYear = 2016; memberUpload1.IsSubmitted = true; ProducerSubmission producerSubmission1 = helper.CreateProducerAsCompany(memberUpload1, "WEE/99ZZZZ99"); producerSubmission1.Business.Company.Contact1.Telephone = "55 5555 5555"; producerSubmission1.Business.Company.Contact1.Email = "*****@*****.**"; Scheme scheme2 = helper.CreateScheme(); scheme2.OrganisationId = new Guid("84729d95-3c26-4c37-9730-f25fa2b6dbfc"); scheme2.Organisation.Id = new Guid("84729d95-3c26-4c37-9730-f25fa2b6dbfc"); scheme2.SchemeName = "A test scheme name"; scheme2.Organisation.Name = "PCS operator name 1"; scheme2.Organisation.BusinessAddressId = new Guid("ecdf60fc-1576-43e2-9bb4-e6c9dc9d721d"); scheme2.Organisation.Address = helper.CreateOrganisationAddress(); scheme2.Organisation.Address.Id = new Guid("ecdf60fc-1576-43e2-9bb4-e6c9dc9d721d"); MemberUpload memberUpload2 = helper.CreateMemberUpload(scheme2); memberUpload2.ComplianceYear = 2017; memberUpload2.IsSubmitted = true; ProducerSubmission producerSubmission2 = helper.CreateProducerAsCompany(memberUpload2, "WEE/11ZZZZ11"); producerSubmission2.Business.Company.Contact1.Telephone = "55 5555 5555"; producerSubmission2.Business.Company.Contact1.Email = "*****@*****.**"; db.Model.SaveChanges(); // Act List <ProducerPublicRegisterCSVData> results = await db.StoredProcedures.SpgProducerPublicRegisterCSVDataByComplianceYear(2016); // Assert Assert.NotNull(results); Assert.True(results.TrueForAll(i => i.ComplianceYear == 2016)); Assert.False(results.Any(i => i.PRN == "WEE/11ZZZZ11" && i.ComplianceYear == 2017)); var result = results.SingleOrDefault(i => i.PRN == "WEE/99ZZZZ99" && i.ComplianceYear == 2016); Assert.NotNull(result); Assert.Equal(result.CSROAAddress1, scheme1.Organisation.Address.Address1); Assert.Equal(result.CSROAPostcode, scheme1.Organisation.Address.Postcode); Assert.Equal(result.SchemeName, scheme1.SchemeName); Assert.Equal(result.SchemeOperator, scheme1.Organisation.Name); Assert.Equal(result.ROATelephone, producerSubmission1.Business.Company.Contact1.Telephone); Assert.Equal(result.ROAEmail, producerSubmission1.Business.Company.Contact1.Email); } }
public async Task <IList <RegisteredProducer> > FetchRegisteredProducersAsync(Scheme scheme, int year) { return(await context .RegisteredProducers .Where(rp => rp.Scheme.Id == scheme.Id) .Where(rp => rp.ComplianceYear == year) .Where(rp => rp.CurrentSubmission != null) .Include(rp => rp.CurrentSubmission) .ToListAsync()); }
public SchemeSelectionView(Scheme schemes) { }
public void Setup(Scheme scheme) { SetupField(scheme.GetFieldData()); }
/// <summary> /// Initializes a new instance of the <see cref="Context"/> class with a /// protocol, host, and port number. /// </summary> /// <param name="scheme"> /// The <see cref="Scheme"/> used to communicate with <see cref="Host"/> /// </param> /// <param name="host"> /// The DNS name of a Splunk server instance. /// </param> /// <param name="port"> /// The port number used to communicate with <see cref="Host"/>. /// </param> /// <param name="timeout"> /// The timeout. /// </param> /// /// ### <exception name="ArgumentException"> /// <paramref name="scheme"/> is invalid, <paramref name="host"/> is /// <c>null</c> or empty, or <paramref name="port"/> is less than zero /// or greater than <c>65535</c>. /// </exception> public Context(Scheme scheme, string host, int port, TimeSpan timeout = default(TimeSpan)) : this(scheme, host, port, timeout, null) { // NOTE: This constructor obviates the need for callers to include a // using for System.Net.Http. }
////////////////////////////////////////////////////////////////////////////// #region Setup public void Load(Scheme scheme) { SetupField(scheme.GetFieldData(), scheme.GetBrickDensity()); SetupPlayers(players, scheme.GetPlayerLocations()); SetupPowerups(scheme.GetPowerupInfo()); }
/// <inheritdoc /> /// <summary> /// </summary> /// <param name="builder"></param> /// <param name="scheme"></param> public void WriteEpilogue(StringBuilder builder, Scheme scheme) { builder.Append(" ]\n}"); }
/// <summary> /// Initializes a new instance of the <see cref="Service"/> class. /// </summary> /// <param name="scheme"> /// The scheme for the new <see cref="Service"/>. /// </param> /// <param name="host"> /// The host for the new <see cref="Service"/>. /// </param> /// <param name="port"> /// The port for the new <see cref="Service"/>. /// </param> /// <param name="ns"> /// The namespace for requests issue by the new <see cref="Service"/>. /// </param> /// /// ### <exception name="ArgumentException"> /// <paramref name="scheme"/> is invalid, <paramref name="host"/> is /// <c>null</c> or empty, or <paramref name="port"/> is less than zero /// or greater than <c>65535</c>. /// </exception> public Service(Scheme scheme, string host, int port, Namespace ns = null) : this(new Context(scheme, host, port), ns) { }
internal void Process(string Id, string From, string To, HttpRequest Request, IEndToEndEncryption E2e, string EndpointReference, int MaxChunkSize, bool Sipub, bool Ibb, bool Socks5, bool Jingle) { HttpAuthenticationScheme[] AuthenticationSchemes; bool Result; try { if (this.server.TryGetResource(Request.Header.Resource, out HttpResource Resource, out string SubPath)) { Request.Resource = Resource; this.server.RequestReceived(Request, From, Resource, SubPath); AuthenticationSchemes = Resource.GetAuthenticationSchemes(Request); if (AuthenticationSchemes != null && AuthenticationSchemes.Length > 0) { foreach (HttpAuthenticationScheme Scheme in AuthenticationSchemes) { if (Scheme.IsAuthenticated(Request, out IUser User)) { Request.User = User; break; } } if (Request.User is null) { List <KeyValuePair <string, string> > Challenges = new List <KeyValuePair <string, string> >(); foreach (HttpAuthenticationScheme Scheme in AuthenticationSchemes) { Challenges.Add(new KeyValuePair <string, string>("WWW-Authenticate", Scheme.GetChallenge())); } this.SendQuickResponse(Request, E2e, EndpointReference, Id, From, To, 401, "Unauthorized", false, MaxChunkSize, Challenges.ToArray()); Request.Dispose(); return; } } Request.SubPath = SubPath; Resource.Validate(Request); if (Request.Header.Expect != null) { if (Request.Header.Expect.Continue100) { if (!Request.HasData) { this.SendQuickResponse(Request, E2e, EndpointReference, Id, From, To, 100, "Continue", false, MaxChunkSize); return; } } else { this.SendQuickResponse(Request, E2e, EndpointReference, Id, From, To, 417, "Expectation Failed", true, MaxChunkSize); Request.Dispose(); return; } } this.ExecuteRequest(E2e, EndpointReference, Id, From, To, MaxChunkSize, Ibb, Socks5, Request, Resource); return; } else { this.server.RequestReceived(Request, From, null, null); this.SendQuickResponse(Request, E2e, EndpointReference, Id, From, To, 404, "Not Found", false, MaxChunkSize); Result = true; } }
private extern static double GetMaturityValue(ref FixedDeposit fd, Scheme policy);
public override async Task <ProcessRuleResult> ProcessAsync(string callerIP, Scheme scheme, string host, int port, string path, string pathAndQuery, NameValueCollection query, NameValueCollection headers, StaticFileProcessor parent) { string portStr = port.ToString(); string pScheme; if (this.SetScheme) { pScheme = (this.Scheme ?? Scheme).ToString(); } else { pScheme = scheme.ToString(); } string pHost; if (this.SetHostName) { pHost = (this.HostName ?? host).ToString(); } else { pHost = host; } string pPath = null; if (this.SetPath) { if (this.UsePathVariable) { // {$Path|^.sdsdd$} string newPath = this.PathAndQuery?.Replace("%PATH%", this.PathAndQuery); Regex regex = new Regex(@"\%[^\%]*\%", RegexOptions.IgnoreCase); MatchCollection matches = regex.Matches(this.PathAndQuery); foreach (Match match in matches) { string innerRegex = match.Value.Trim('%'); var regex2 = new Regex(innerRegex, RegexOptions.IgnoreCase); string innerRegexResult = regex2.Match(pathAndQuery).Value; newPath = newPath?.Replace(match.Value, innerRegexResult); } pPath = newPath; } else { pPath = path; } } else { pPath = path; } string pPort; if (this.SetPort) { pPort = (this.Port ?? port).ToString(); } else { pPort = portStr; } string rProxyURL = pScheme + "://" + pHost + ":" + pPort + pPath; //AddOriginal Headers HttpClient httpClient = ((HttpServer)parent).HttpClient; var items = headers.AllKeys.SelectMany(headers.GetValues, (k, v) => new { key = k, value = v }); string originalHost = null; bool AddXFFor = true; bool AddXFProto = true; bool AddXFHost = true; bool AddXFPort = true; foreach (var item in items) { if (string.Equals(item.key, "Host")) { originalHost = item.value; continue; } // AddHost = false; if (string.Equals(item.key, "X-Forwarded-For")) { AddXFFor = false; } if (string.Equals(item.key, "X-Forwarded-Proto")) { AddXFProto = false; } if (string.Equals(item.key, "X-Forwarded-Host")) { AddXFHost = false; } if (string.Equals(item.key, "X-Forwarded-Port")) { AddXFPort = false; } httpClient.DefaultRequestHeaders.Add(item.key, item.value); } if (originalHost == null) { originalHost = host; } //Add Proxy Headers if (AddXFFor) { httpClient.DefaultRequestHeaders.Add("X-Forwarded-For", callerIP); } if (AddXFProto) { httpClient.DefaultRequestHeaders.Add("X-Forwarded-Proto", pScheme); } if (AddXFHost) { httpClient.DefaultRequestHeaders.Add("X-Forwarded-Host", originalHost); } if (AddXFPort) { httpClient.DefaultRequestHeaders.Add("X-Forwarded-Port", portStr); } HttpResponseMessage resp = await httpClient.GetAsync(rProxyURL); Stream rProxyResult = await resp.Content.ReadAsStreamAsync(); string contentType = null; if (resp.IsSuccessStatusCode) { if (resp.Content.Headers.Contains("Content-Type")) { contentType = resp.Content.Headers.GetValues("Content-Type").FirstOrDefault(); } } if (resp.IsSuccessStatusCode) { return(new ProcessRuleResult() { IsSuccess = true, ActionType = ActionType.ReverseProxy, HttpStreamResult = new HTTPStreamResult(false, null, resp.StatusCode, contentType, rProxyResult, null, false), Message = rProxyURL }); } else { return(new ProcessRuleResult() { IsSuccess = false, ActionType = ActionType.ReverseProxy, SendErrorResponsePage_HttpStatusCode = resp.StatusCode, LogLevel = LogLevel.Warning, Message = rProxyURL + " > " + resp.ReasonPhrase }); } }
private void InstantiateProducerParameters() { TradingName = "Test trading name"; scheme = A.Fake <Scheme>(); MemberUpload = new MemberUpload( A.Dummy <Guid>(), A.Dummy <string>(), A.Dummy <List <MemberUploadError> >(), A.Dummy <decimal>(), A.Dummy <int>(), scheme, A.Dummy <string>(), A.Dummy <string>(), A.Dummy <bool>()); ProducerCharges = new Dictionary <string, ProducerCharge>(); ProducerCharges.Add(TradingName, new ProducerCharge() { ChargeBandAmount = new ChargeBandAmount() }); GeneratedPrns = new Queue <string>(); A.CallTo(() => DataAccess.ComputePrns(A <int> ._)).Returns(GeneratedPrns); BrandNames = Enumerable.Empty <string>().ToArray(); SicCodes = Enumerable.Empty <string>().ToArray(); ProducerBusiness = new producerBusinessType() { correspondentForNotices = new optionalContactDetailsContainerType() { }, Item = new companyType() { registeredOffice = new contactDetailsContainerType() { contactDetails = new contactDetailsType() { address = new addressType() { country = countryType.UKENGLAND } } } } }; AuthorisedRepresentative = null; EEEPlacedOnMarketBandType = eeePlacedOnMarketBandType.Lessthan5TEEEplacedonmarket; SellingTechnique = sellingTechniqueType.Both; ObligationType = obligationTypeType.Both; AnnualTurnoverBandType = annualTurnoverBandType.Greaterthanonemillionpounds; CeaseDate = null; RegistrationNumber = "TestRegistrationNumber"; AnnualTurnover = 10; VatRegistered = false; Status = statusType.I; }
public virtual Task <ProcessRuleResult> ProcessAsync(string callerIP, Scheme scheme, string host, int port, string path, string pathAndQuery, NameValueCollection query, NameValueCollection headers, StaticFileProcessor parent) { return(null); }
public static IIcd Of(string identifier, string code, Scheme scheme) { return(new GenericIcd(identifier, code, scheme, null)); }
/// <summary> /// Initializes a new instance of the <see cref="Context"/> class with a /// protocol, host, and port number. /// </summary> /// <param name="scheme"> /// The <see cref="Scheme"/> used to communicate with <see cref="Host"/> /// </param> /// <param name="host"> /// The DNS name of a Splunk server instance. /// </param> /// <param name="port"> /// The port number used to communicate with <see cref="Host"/>. /// </param> /// <param name="timeout"> /// The timeout. /// </param> /// <exception name="ArgumentException"> /// <paramref name="scheme"/> is invalid, <paramref name="host"/> is /// <c>null</c> or empty, or <paramref name="port"/> is less than zero /// or greater than <c>65535</c>. /// </exception> public Context(Scheme scheme, string host, int port, TimeSpan timeout = default(TimeSpan)) : this(scheme, host, port, timeout, null) { // NOTE: This constructor obviates the need for callers to include a // using for System.Net.Http. }
private void DoChangeScheme(Scheme scheme) { // setup settings lock (thislock) { currentScheme = null; //coDesc.AtomShadingDesc.MoleculeMaterials = refcoDesc.AtomShadingDesc.MoleculeMaterials; //coDesc.BondShadingDesc.MoleculeMaterials = refcoDesc.BondShadingDesc.MoleculeMaterials; // set common values if (scheme.scheme.HandlesAtoms) { uiAtomsGSetGroup.Enabled = true; uiAtomLODControl.SetupValues(scheme.settings.AtomLODRange, scheme.settings.AtomLOD); if (!(uiAtomDDraw.Enabled = scheme.scheme.HandlesBonds)) { coDesc.AtomShadingDesc.Draw = false; } uiAtomDDraw.Checked = coDesc.AtomShadingDesc.Draw; uiAtomFillModeList.SelectedIndex = (int)coDesc.AtomShadingDesc.FillMode; uiAtomSymbolsDraw.Checked = coDesc.AtomShadingDesc.SymbolText; uiAtomSymbolsBlend.Checked = coDesc.AtomShadingDesc.BlendSymbolText; } else { uiAtomsGSetGroup.Enabled = false; } if (scheme.scheme.HandlesBonds) { uiBondsGSetGroup.Enabled = true; uiBondSpacingList.SelectedIndex = (int)coDesc.BondShadingDesc.Spacing; uiBondEndTypeList.SelectedIndex = (int)coDesc.BondShadingDesc.EndType; uiBondLODControl.SetupValues(scheme.settings.BondLODRange, scheme.settings.BondLOD); if (!(uiBondDDraw.Enabled = scheme.scheme.HandlesAtoms)) { coDesc.BondShadingDesc.Draw = false; } uiBondDDraw.Checked = coDesc.BondShadingDesc.Draw; } else { uiBondsGSetGroup.Enabled = false; } // add control if (scheme.sUI != null /* || ((scheme.sUI = scheme.settings.GetSUI()) != null)*/) { //scheme.sUI.SetChangeEvent(new EventHandler(OnSettingsChanged)); scheme.sUI.UpdateValues(); Control control = (Control)scheme.sUI; GroupBox gBox = new GroupBox(); gBox.MaximumSize = gBox.MinimumSize = new Size(panel2.Width, control.Height + 20); control.Dock = DockStyle.Fill; gBox.Text = scheme.scheme.Name; gBox.Controls.Add(control); gBox.Dock = DockStyle.Top; panel2.Controls.Add(gBox); } // TODO: need to get these from elsewhere! OutputSettings outSettings = new OutputSettings(outCaps.Adapter, true, DeviceType.Hardware, Format.Unknown, outCaps.AntiAliasing.MaxSupported, DepthFormat.D16, CreateFlags.HardwareVertexProcessing); schemePreviewControl.Enabled = true; schemePreviewControl.OutSettings = outSettings; coDesc.SchemeSettings = scheme.settings; schemePreviewControl.SetScheme(scheme.scheme, coDesc); currentScheme = scheme; // update effects tab SetRequiredEffects(scheme.settings.GetRequiredEffects()); } }
private static Scheme GetTestScheme() { var scheme = new Scheme(A.Dummy <Guid>()); return(scheme); }
public Libpre(Scheme scheme) : this(scheme, null) { }
public Scheme GetModel(string definition) { var scheme = new Scheme(); using var b = new StringReader(definition); scheme.Version = SchemeVersion.Version3; // Skip over some heading lines b.ReadLine(); b.ReadLine(); b.ReadLine(); b.ReadLine(); scheme.HotSeatTime = GetByte(b); scheme.RetreatTime = GetByte(b); scheme.RetreatTimeRope = GetByte(b); scheme.ShowRoundTime = GetBool(b); scheme.Replays = GetBool(b); scheme.FallDamage = GetByte(b); scheme.ArtilleryMode = GetBool(b); scheme.Stockpiling = GetEnum <Stockpiling>(b); scheme.WormSelect = GetEnum <WormSelect>(b); scheme.SuddenDeathEvent = GetEnum <SuddenDeathEvent>(b); scheme.WaterRiseRate = GetByte(b); scheme.WeaponCrateProb = GetSbyte(b); scheme.HealthCrateProb = GetSbyte(b); scheme.UtilityCrateProb = GetSbyte(b); scheme.HealthCrateEnergy = GetByte(b); scheme.DonorCards = GetBool(b); scheme.ObjectTypes = GetEnum <MapObjectType>(b); scheme.ObjectCount = GetByte(b); scheme.MineDelayRandom = GetBool(b); scheme.MineDelay = GetByte(b); scheme.DudMines = GetBool(b); scheme.ManualWormPlacement = GetBool(b); scheme.WormEnergy = GetByte(b); scheme.TurnTimeInfinite = GetBool(b); scheme.TurnTime = GetByte(b); scheme.RoundTimeMinutes = GetByte(b); scheme.RoundTimeSeconds = GetByte(b); scheme.NumberOfWins = GetByte(b); scheme.Blood = GetBool(b); scheme.AquaSheep = GetBool(b); scheme.SheepHeaven = GetBool(b); scheme.GodWorms = GetBool(b); scheme.IndiLand = GetBool(b); scheme.UpgradeGrenade = GetBool(b); scheme.UpgradeShotgun = GetBool(b); scheme.UpgradeCluster = GetBool(b); scheme.UpgradeLongbow = GetBool(b); scheme.TeamWeapons = GetBool(b); scheme.SuperWeapons = GetBool(b); // Skip over the middle heading b.ReadLine(); b.ReadLine(); b.ReadLine(); b.ReadLine(); b.ReadLine(); b.ReadLine(); b.ReadLine(); foreach (var weaponName in (Weapon[])Enum.GetValues(typeof(Weapon))) { var(ammo, power, delay, prob) = GetWeaponDetails(b); scheme.Weapons[weaponName].Ammo = ammo; scheme.Weapons[weaponName].Power = power; scheme.Weapons[weaponName].Delay = delay; scheme.Weapons[weaponName].Prob = prob; } // Skip over the heading b.ReadLine(); b.ReadLine(); b.ReadLine(); b.ReadLine(); b.ReadLine(); b.ReadLine(); b.ReadLine(); scheme.Extended.ConstantWind = GetBool(b); scheme.Extended.Wind = GetSbyte(b); scheme.Extended.WindBias = GetByte(b); scheme.Extended.Gravity = GetFloat(b); scheme.Extended.Friction = GetFloat(b); scheme.Extended.RopeKnockForce = GetNullableByte(b); scheme.Extended.BloodAmount = GetNullableByte(b); scheme.Extended.RopeUpgrade = GetBool(b); scheme.Extended.GroupPlaceAllies = GetBool(b); scheme.Extended.NoCrateProbability = GetNullableByte(b); scheme.Extended.CrateLimit = GetByte(b); scheme.Extended.SuddenDeathNoWormSelect = GetBool(b); scheme.Extended.SuddenDeathTurnDamage = GetByte(b); scheme.Extended.WormPhasingAlly = GetEnum <WormPhasing>(b); scheme.Extended.WormPhasingEnemy = GetEnum <WormPhasing>(b); scheme.Extended.CircularAim = GetBool(b); scheme.Extended.AntiLockAim = GetBool(b); scheme.Extended.AntiLockPower = GetBool(b); scheme.Extended.WormSelectKeepHotSeat = GetBool(b); scheme.Extended.WormSelectAnytime = GetBool(b); scheme.Extended.BattyRope = GetBool(b); scheme.Extended.RopeRollDrops = GetEnum <RopeRollDrops>(b); scheme.Extended.KeepControlXImpact = GetEnum <XImpactControlLoss>(b); scheme.Extended.KeepControlHeadBump = GetBool(b); scheme.Extended.KeepControlSkim = GetEnum <SkimControlLoss>(b); scheme.Extended.ExplosionFallDamage = GetBool(b); scheme.Extended.ObjectPushByExplosion = GetNullableBool(b); scheme.Extended.UndeterminedCrates = GetNullableBool(b); scheme.Extended.UndeterminedMineFuse = GetNullableBool(b); scheme.Extended.FiringPausesTimer = GetBool(b); scheme.Extended.LoseControlDoesntEndTurn = GetBool(b); scheme.Extended.ShotDoesntEndTurn = GetBool(b); scheme.Extended.ShotDoesntEndTurnAll = GetBool(b); scheme.Extended.DrillImpartsVelocity = GetNullableBool(b); scheme.Extended.GirderRadiusAssist = GetBool(b); scheme.Extended.FlameTurnDecay = GetFloat(b); scheme.Extended.FlameTouchDecay = GetByte(b); scheme.Extended.FlameLimit = GetByte(b); scheme.Extended.ProjectileMaxSpeed = GetByte(b); scheme.Extended.RopeMaxSpeed = GetByte(b); scheme.Extended.JetpackMaxSpeed = GetByte(b); scheme.Extended.GameSpeed = GetByte(b); scheme.Extended.IndianRopeGlitch = GetNullableBool(b); scheme.Extended.HerdDoublingGlitch = GetNullableBool(b); scheme.Extended.JetpackBungeeGlitch = GetBool(b); scheme.Extended.AngleCheatGlitch = GetBool(b); scheme.Extended.GlideGlitch = GetBool(b); scheme.Extended.SkipWalk = GetEnum <SkipWalk>(b); scheme.Extended.Roofing = GetEnum <Roofing>(b); scheme.Extended.FloatingWeaponGlitch = GetBool(b); scheme.Extended.WormBounce = GetFloat(b); scheme.Extended.Viscosity = GetFloat(b); scheme.Extended.ViscosityWorms = GetBool(b); scheme.Extended.RwWind = GetFloat(b); scheme.Extended.RwWindWorms = GetBool(b); scheme.Extended.RwGravityType = GetEnum <RwGravityType>(b); scheme.Extended.RwGravity = GetFloat(b); scheme.Extended.CrateRate = GetByte(b); scheme.Extended.CrateShower = GetBool(b); scheme.Extended.AntiSink = GetBool(b); scheme.Extended.WeaponsDontChange = GetBool(b); scheme.Extended.ExtendedFuse = GetBool(b); scheme.Extended.AutoReaim = GetBool(b); scheme.Extended.TerrainOverlapGlitch = GetNullableBool(b); scheme.Extended.RoundTimeFractional = GetBool(b); scheme.Extended.AutoRetreat = GetBool(b); scheme.Extended.HealthCure = GetEnum <HealthCure>(b); scheme.Extended.KaosMod = GetByte(b); scheme.Extended.SheepHeavenFlags = GetEnum <SheepHeavenFlags>(b); scheme.Extended.ConserveUtilities = GetBool(b); scheme.Extended.ExpediteUtilities = GetBool(b); scheme.Extended.DoubleTimeCount = GetByte(b); return(scheme); }
/// <summary> /// Initializes a new instance of the <see cref="Context"/> class with a /// protocol, host, port number, and optional message handler. /// </summary> /// <param name="scheme"> /// The <see cref="Scheme"/> used to communicate with <see cref="Host"/>. /// </param> /// <param name="host"> /// The DNS name of a Splunk server instance. /// </param> /// <param name="port"> /// The port number used to communicate with <see cref="Host"/>. /// </param> /// <param name="timeout"> /// The timeout. /// </param> /// <param name="handler"> /// The <see cref="HttpMessageHandler"/> responsible for processing the HTTP /// response messages. /// </param> /// <param name="disposeHandler"> /// <c>true</c> if the inner handler should be disposed of by Dispose, /// <c>false</c> if you intend to reuse the inner handler. /// </param> /// /// ### <exception name="ArgumentException"> /// <paramref name="scheme"/> is invalid, <paramref name="host"/> is /// <c>null</c> or empty, or <paramref name="port"/> is less than zero /// or greater than <c>65535</c>. /// </exception> public Context(Scheme scheme, string host, int port, TimeSpan timeout, HttpMessageHandler handler, bool disposeHandler = true) { Contract.Requires<ArgumentException>(scheme == Scheme.Http || scheme == Scheme.Https); Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(host)); Contract.Requires<ArgumentException>(0 <= port && port <= 65535); this.Scheme = scheme; this.Host = host; this.Port = port; this.httpClient = handler == null ? new HttpClient() : new HttpClient(handler, disposeHandler); if (timeout != default(TimeSpan)) { this.httpClient.Timeout = timeout; } }
public override List getAllHandlers(Scheme value) { return(Arrays.asList(new ch.cyberduck.core.local.Application(Application.ExecutablePath))); }
private void ReplaceWithWire(ElementBase element) { var firstPos = new Vector3Int(ConnectionsMaker.GetConnectPosition(true, element).x, ConnectionsMaker.GetConnectPosition(true, element).y, Scheme.GetWiresCount() + 2); var secondPos = new Vector3Int(ConnectionsMaker.GetConnectPosition(false, element).x, ConnectionsMaker.GetConnectPosition(false, element).y, Scheme.GetWiresCount() + 2); var wire = new Wire(firstPos, secondPos, element.angle); Scheme.AddElement(wire); var texture = Resources.Load <Texture2D>("Sprites/HalfWireSprite"); var tile = new Tile { sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.0f, 0.5f), 100, 1, SpriteMeshType.Tight, Vector4.zero ) }; var scale = wire.pivotPosition.x == wire.secondPosition.x ? (Math.Abs(wire.pivotPosition.y - wire.secondPosition.y) + 0.01f) / 2 : (Math.Abs(wire.pivotPosition.x - wire.secondPosition.x) + 0.01f) / 2; var rotation = Quaternion.Euler(0, 0, element.angle); var m = tile.transform; m.SetTRS(Vector3.zero, rotation, new Vector3(scale, 1, 1)); tile.transform = m; tile.name = "Wire"; map.GetComponent <Tilemap>().SetTile(wire.pivotPosition, tile); }
/// <inheritdoc /> /// <summary> /// </summary> /// <param name="builder"></param> /// <param name="scheme"></param> /// <param name="colorIndex1"></param> /// <param name="colorIndex2"></param> public void WriteColor(StringBuilder builder, Scheme scheme, int colorIndex1, int colorIndex2) { builder.Append($" \"{ColorHelpers.ColorToHex(scheme.Colors[colorIndex1])}\",\n"); }