public bool SendContact(string sessionKey, Shared.Dto.Contact contact) { var dbContext = DbContextFactory.GetContext(); var sessionService = new SessionService(); var user = sessionService.GetUser(sessionKey); if (user == null) return false; User recipient; try { recipient = dbContext.Users.Single(u => u.Id == contact.ReceiverId); } catch (Exception) { return false; } var newContact = new Contact { PublicKey = contact.PublicKey, Name = contact.Name, Sender = user, Recipient = recipient }; dbContext.Add(newContact); dbContext.SaveChanges(); var userService = new PushService(); userService.Push(recipient, "Recieved new contact!"); return true; }
protected async override Task<ProcessResult> OnPolling( Shared.Jobs.PollerJobParameters parameters, string workingFolder) { string pathToFile = await DownloadBlob(parameters.TenantId, parameters.JobId, parameters.FileName, workingFolder); Logger.DebugFormat("Downloaded file {0} to be converted to pdf", pathToFile); var converter = Converters.FirstOrDefault(c => c.CanConvert(pathToFile)); if (converter == null) { Logger.InfoFormat("No converter for extension {0}", Path.GetExtension(pathToFile)); return ProcessResult.Ok; } string outFile = Path.Combine(workingFolder, Guid.NewGuid() + ".pdf"); if (!converter.Convert(pathToFile, outFile)) { Logger.ErrorFormat("Error converting file {0} to pdf", pathToFile); return ProcessResult.Fail; } await AddFormatToDocumentFromFile( parameters.TenantId, parameters.JobId, new DocumentFormat(DocumentFormats.Pdf), outFile, new Dictionary<string, object>()); return ProcessResult.Ok; }
public Shared.Types.BooleanResult AuthenticateUser(Shared.Types.SessionProperties properties) { Shared.Types.UserInformation userInfo = properties.GetTrackedSingle<Shared.Types.UserInformation>(); m_logger.DebugFormat("Authenticate: {0}", userInfo.Username); UserEntry entry = GetUserEntry(userInfo.Username); if (entry != null) { m_logger.DebugFormat("Retrieved info for user {0} from MySQL. Password uses {1}.", entry.Name, entry.HashAlg.ToString()); bool passwordOk = entry.VerifyPassword(userInfo.Password); if (passwordOk) { m_logger.DebugFormat("Authentication successful for {0}", userInfo.Username); return new Shared.Types.BooleanResult() { Success = true, Message = "Success." }; } else { m_logger.DebugFormat("Authentication failed for {0}", userInfo.Username); return new Shared.Types.BooleanResult() { Success = false, Message = "Invalid username or password." }; } } else { m_logger.DebugFormat("Authentication failed for {0}", userInfo.Username); return new Shared.Types.BooleanResult() { Success = false, Message = "Invalid username or password." }; } }
protected override void triggerInternal(Shared lastState, Shared currentState) { if (CommonData.isRaceStarted) { if (pushDataInFront == null || pushDataBehind == null) { clearState(); } if (CommonData.isNewLap) { if (CommonData.racingSameCarInFront) { pushDataInFront.Add(new PushData(currentState.LapTimePrevious, currentState.TimeDeltaFront)); } else { pushDataInFront.Clear(); } if (CommonData.racingSameCarBehind) { pushDataBehind.Add(new PushData(currentState.LapTimePrevious, currentState.TimeDeltaBehind)); } else { pushDataBehind.Clear(); } } if (currentState.NumberOfLaps == -1 && !playedNearEndTimePush && currentState.SessionTimeRemaining < 4 * 60 && currentState.SessionTimeRemaining > 2 * 60) { // estimate the number of remaining laps - be optimistic... int numLapsLeft = (int)Math.Ceiling((double)currentState.SessionTimeRemaining / (double)currentState.LapTimeBest); playedNearEndTimePush = checkGaps(currentState, numLapsLeft); } else if (currentState.NumberOfLaps > 0 && currentState.NumberOfLaps - currentState.CompletedLaps <= 4 && !playedNearEndLapsPush) { playedNearEndLapsPush = checkGaps(currentState, currentState.NumberOfLaps - currentState.CompletedLaps); } else if (currentState.PitWindowStatus == (int)Constant.PitWindow.Completed && lastState.PitWindowStatus == (int)Constant.PitWindow.StopInProgress) { drivingOutOfPits = true; } else if (drivingOutOfPits && currentState.ControlType == (int)Constant.Control.Player && lastState.ControlType == (int)Constant.Control.AI) { drivingOutOfPits = false; // we've just been handed control back after a pitstop if (currentState.TimeDeltaFront > 3 && currentState.TimeDeltaBehind > 4) { // we've exited into clean air audioPlayer.queueClip(folderPushExitingPits, 0, this); } else if (currentState.TimeDeltaBehind <= 4) { // we've exited the pits but there's traffic behind audioPlayer.queueClip(folderTrafficBehindExitingPits, 0, this); } } } }
/// <summary> /// This should read in a Type byte and create an instance of the correct type /// Each event type should include a custom 'Execute' method that handles it /// </summary> protected override IEvent CreateEvent(Shared.InamStream stream) { int ID = stream.ReadInt32(); BrainEventType type = (BrainEventType)stream.ReadByte(); if (type == BrainEventType.System) { } else if (type == BrainEventType.Sight) { return new BrainSightEvent(this, stream, this.entity); } else if (type == BrainEventType.Touch) { return new BrainTouchEvent(this, stream, this.entity); } else if (type == BrainEventType.Hear) { } else if (type == BrainEventType.Taste) { } // bad return null; }
public Shared.Types.BooleanResult AuthenticatedUserGateway(Shared.Types.SessionProperties properties) { UserInformation userInfo = properties.GetTrackedSingle<UserInformation>(); try { using (MySqlUserDataSource dataSource = new MySqlUserDataSource()) { List<GroupGatewayRule> rules = GroupRuleLoader.GetGatewayRules(); foreach (GroupGatewayRule rule in rules) { m_logger.DebugFormat("Checking rule: {0}", rule.ToString()); if (rule.RuleMatch(dataSource.IsMemberOfGroup(userInfo.Username, rule.Group))) { m_logger.DebugFormat("Rule is a match, adding to {0}", rule.LocalGroup); userInfo.Groups.Add(new GroupInformation { Name = rule.LocalGroup }); } else { m_logger.DebugFormat("Rule is not a match"); } } } } catch (Exception e) { m_logger.ErrorFormat("Unexpected error: {0}", e); throw; } // Always return success return new Shared.Types.BooleanResult { Success = true }; }
public void Broadcast(Shared.InamStream stream, byte type) { foreach (IEntity entity in this.Senses[type]) { entity.EventManager.Enqueue(stream); } }
void IUIWidget.OnOperationChange(Shared.Core.Operation operation) { string lineOne = null; if (!string.IsNullOrWhiteSpace(_expressionLineOne)) { lineOne = operation != null ? operation.ToString(_expressionLineOne) : "(n/A)"; } string lineTwo = null; if (!string.IsNullOrWhiteSpace(_expressionLineTwo)) { lineTwo = operation != null ? operation.ToString(_expressionLineTwo) : "(n/A)"; } string lineThree = null; if (!string.IsNullOrWhiteSpace(_expressionLineThree)) { lineThree = operation != null ? operation.ToString(_expressionLineThree) : "(n/A)"; } LineOne.Inlines.Clear(); LineTwo.Inlines.Clear(); LineThree.Inlines.Clear(); LineOne.Inlines.Add(Helper.Execute(lineOne)); LineTwo.Inlines.Add(Helper.Execute(lineTwo)); LineThree.Inlines.Add(Helper.Execute(lineThree)); }
public void ToString_returns_a_string_representation_of_the_object() { var shared = new Shared<object>(); const string expected = "Shared<System.Object>"; Assert.AreEqual(expected, shared.ToString()); }
protected override IEvent CreateEvent(Shared.InamStream stream) { //int ID = stream.ReadInt32(); // there is no ID here, as we are just choosing the correct sense to send this to byte type = stream.ReadByte(); // bad return null; }
public void NavigateToMainView(Shared.ViewModels.MainViewModel.SubView? subView) { if (!subView.HasValue || subView.Value == Shared.ViewModels.MainViewModel.SubView.Auction) { Navigate(typeof(AuctionView)); return; } throw new NotImplementedException(); }
public IHttpActionResult AddContact([FromUri]string sessionKey, Shared.Dto.Contact contact) { var contactService = new ContactService(); if (contactService.SendContact(sessionKey, contact)) { return Ok(); } return Unauthorized(); }
public void Constructor_when_given_a_value_instantiates_with_it() { var value = new object(); var shared = new Shared<object>(value); var actual = shared.Value; Assert.AreEqual(value, actual); }
public override SkillResults Prepare(World.MabiCreature creature, World.MabiSkill skill, Shared.Network.MabiPacket packet, uint castTime) { creature.StopMove(); WorldManager.Instance.Broadcast(new MabiPacket(Op.Effect, creature.Id).PutInt(Effect.SkillInit).PutString("thunder").PutShort((ushort)skill.Id), SendTargets.Range, creature); Send.SkillPrepare(creature.Client, creature, skill.Id, castTime); return SkillResults.Okay; }
public void trigger(Shared lastState, Shared currentState) { // don't trigger events if someone else is driving the car (or it's a replay). No way to tell the difference between // watching an AI 'live' and the AI being in control of your car for starts / pitstops if (!CommonData.isNew && currentState.ControlType != (int)Constant.Control.Remote && currentState.ControlType != (int)Constant.Control.Replay) { triggerInternal(lastState, currentState); } }
public Shared.Types.BooleanResult AuthenticatedUserGateway(Shared.Types.SessionProperties properties) { UserInformation userInfo = properties.GetTrackedSingle<UserInformation>(); try { using (MySqlUserDataSource dataSource = new MySqlUserDataSource()) { List<GroupGatewayRule> rules = GroupRuleLoader.GetGatewayRules(); foreach (GroupGatewayRule rule in rules) { m_logger.DebugFormat("Checking rule: {0}", rule.ToString()); if (rule.RuleMatch(dataSource.IsMemberOfGroup(userInfo.Username, rule.Group))) { m_logger.DebugFormat("Rule is a match, adding to {0}", rule.LocalGroup); userInfo.Groups.Add(new GroupInformation { Name = rule.LocalGroup }); } else { m_logger.DebugFormat("Rule is not a match"); } } } } catch(MySqlException e) { bool preventLogon = Settings.Store.PreventLogonOnServerError; if( preventLogon ) { m_logger.DebugFormat("Encountered MySQL server error, and preventing logon: {0}", e.Message); return new BooleanResult { Success = false, Message = string.Format("Preventing logon due to server error: {0}", e.Message) }; } else { m_logger.DebugFormat("Encoutered MySQL server error, but returning success anyway. Error: {0}", e.Message); return new BooleanResult { Success = true, Message = string.Format("Encountered server error: {0}", e.Message) }; } } catch (Exception e) { m_logger.ErrorFormat("Unexpected error: {0}", e); throw; } // Always return success return new Shared.Types.BooleanResult { Success = true }; }
private Shared.Results.TestResult getResult(double duration, Shared.Results.TestState state, string name, string message, string stackLines) { var result = new Shared.Results.TestResult("XUnit", _currentAssembly, "", duration * 1000, name, state, message); if (stackLines != null) { var lines = stackLines.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); foreach (var line in lines) result.AddStackLine(new Shared.Results.StackLine(line)); } return result; }
public void CompressFiles(string destinationDirectory, string archiveName, Shared.Enums.pdFileCompressor type, string pwd, params string[] files) { switch (type) { case Shared.Enums.pdFileCompressor.SEVEN_ZIP: this.CompressFiles_7z(destinationDirectory, archiveName, pwd, files); break; case Shared.Enums.pdFileCompressor.ZIP: this.CompressFiles_zip(destinationDirectory, archiveName, pwd, files); break; } }
void IUIWidget.OnOperationChange(Shared.Core.Operation operation) { string lineOne = operation != null ? operation.ToString(SettingsManager.Instance.GetSetting("OperationWidget", "LineOne").GetString()) : "(n/A)"; string lineTwo = operation != null ? operation.ToString(SettingsManager.Instance.GetSetting("OperationWidget", "LineTwo").GetString()) : "(n/A)"; string lineThree = operation != null ? operation.ToString(SettingsManager.Instance.GetSetting("OperationWidget", "LineThree").GetString()) : "(n/A)"; LineOne.Inlines.Clear(); LineOne.Inlines.Add(Helper.Traverse(lineOne)); LineTwo.Inlines.Clear(); LineTwo.Inlines.Add(Helper.Traverse(lineTwo)); LineThree.Inlines.Clear(); LineThree.Inlines.Add(Helper.Traverse(lineThree)); }
public ThreadedRecorder(Shared.CameraCollection cameras, IVideoWriter writer) { cameras_ = cameras; frameQueue_ = new List<FrameSet>(); readyFrames_ = new List<Bitmap>(); writer_ = writer; foreach (Shared.IMocapRecorder rec in cameras) { rec.OnFrame += rec_OnFrame; } }
private void CytologyIcd9EntryPage_Return(object sender, Shared.PageNavigationReturnEventArgs e) { switch (e.PageNavigationDirectionEnum) { case Shared.PageNavigationDirectionEnum.Next: this.ShowCytologyClinicalHistoryPage(); break; case Shared.PageNavigationDirectionEnum.Back: this.ShowCytologyIcd9CodingPage(); break; } }
public Shared.Types.BooleanResult AuthenticateUser(Shared.Types.SessionProperties properties) { Shared.Types.UserInformation userInfo = properties.GetTrackedSingle<Shared.Types.UserInformation>(); m_logger.DebugFormat("Authenticate: {0}", userInfo.Username); UserEntry entry = null; try { using (MySqlUserDataSource dataSource = new MySqlUserDataSource()) { entry = dataSource.GetUserEntry(userInfo.Username); } } catch (MySqlException ex) { if (ex.Number == 1042) m_logger.ErrorFormat("Unable to connect to host: {0}", Settings.Store.Host); else { m_logger.ErrorFormat("{0}", ex); throw; } } catch (Exception e) { m_logger.ErrorFormat("Unexpected error: {0}", e); throw; } if (entry != null) { m_logger.DebugFormat("Retrieved info for user {0} from MySQL. Password uses {1}.", entry.Name, entry.HashAlg.ToString()); bool passwordOk = entry.VerifyPassword(userInfo.Password); if (passwordOk) { m_logger.DebugFormat("Authentication successful for {0}", userInfo.Username); return new Shared.Types.BooleanResult() { Success = true, Message = "Success." }; } else { m_logger.DebugFormat("Authentication failed for {0}", userInfo.Username); return new Shared.Types.BooleanResult() { Success = false, Message = "Invalid username or password." }; } } else { m_logger.DebugFormat("Authentication failed for {0}", userInfo.Username); return new Shared.Types.BooleanResult() { Success = false, Message = "Invalid username or password." }; } }
public PropertyQueryInfoViewModel(Shared.PropertyQueryInfoViewModel baseViewModel, bool use = false) { Id = baseViewModel.Id; WebServiceName = baseViewModel.WebServiceName; QueryId = baseViewModel.QueryId; OriginalTitle = baseViewModel.OriginalTitle; Title = baseViewModel.Title; Type = baseViewModel.Type; Period = baseViewModel.Period; Use = use; }
private void Listener_OnTemperatureDataReceived(object sender, Shared.TemperatureData e) { if (e.IsValid) { DispatcherHelper.CheckBeginInvokeOnUI(() => { Messenger.Default.Send(new DataReceivedMessage()); Temperature = e.Temperature.ToString(CultureInfo.InvariantCulture); LastDateTimeReceived = e.Timestamp.ToLocalTime().ToString("HH:mm:ss dd-MM-yyyy"); FanStatus = e.FanStatus == Shared.FanStatus.On ? "on" : "off"; }); } }
void IUIWidget.OnOperationChange(Shared.Core.Operation operation) { string lineOne = FormatLine(_expressionLineOne, operation); string lineTwo = FormatLine(_expressionLineTwo, operation); string lineThree = FormatLine(_expressionLineThree, operation); LineOne.Inlines.Clear(); LineTwo.Inlines.Clear(); LineThree.Inlines.Clear(); LineOne.Inlines.Add(Helper.Execute(lineOne)); LineTwo.Inlines.Add(Helper.Execute(lineTwo)); LineThree.Inlines.Add(Helper.Execute(lineThree)); }
protected override IEvent CreateEvent(Shared.InamStream stream) { int ID = stream.ReadInt32(); TileEngineEventTypes type = (TileEngineEventTypes)stream.ReadByte(); if (type == TileEngineEventTypes.Tile) { return new TileEvent(this, stream); } // bad return null; }
public DatabasePersister( IConfigurationStore configurationStore, ICommandFactory commandFactory, IContextFactory contextFactory, ILogManager logManager, Shared.Interfaces.IMapper mapper) { _commandFactory = commandFactory; _contextFactory = contextFactory; _log = logManager.GetLogger(GetType()); _mapper = mapper; _configNotifier = configurationStore.Register("/urchin/server/persister/repository", SetRepositoryName, "Urchin"); }
public void AskQuestions(string title, Shared.Models.Question question, Action<int> completed) { App.CurrentActivity.RunOnUiThread(() => new AlertDialog.Builder(App.CurrentActivity) .SetTitle(question.Text) .SetItems(question.Answers.Select(a => a.Text).ToArray(), (sender, args) => { if (completed != null) completed(args.Which); }) .SetNegativeButton("Cancel", delegate { }) .Create() .Show()); }
public ReceiveDataViewModel(Shared.Model.Server server) { this._server = server; this.GroupItemsCommand = new RelayCommand<object>(this.OnGroupItems); this.Suggestions = new ObservableCollection<SuggestionItemGroup>(); this.StartServerCommand = new RelayCommand(this.StartServer); this.MenuItems.Insert(0, new MenuItemViewModel("Auswertung") { SubItems = { new MenuItemViewModel("Drucken") { Command =new RelayCommand(this.OnPrintAnalysis), }, //new MenuItemViewModel("Daten an Clients senden") //{ // Command =new RelayCommand(this.OnSendAnalysisToClients), //}, }, }); this.MenuItems.Insert(0, new MenuItemViewModel("Server") { SubItems = { (this._stopServer = new MenuItemViewModel("Server anhalten") { IsCheckable=true, Command = new RelayCommand(this.OnStopServer), }), }, }); this.MenuItems.Insert(0, new MenuItemViewModel("Datei") { SubItems = { new MenuItemViewModel("Daten Exportieren") { Command =new RelayCommand(this.OnExportData), }, new MenuItemViewModel("Daten Importieren") { Command =new RelayCommand(this.OnImportData), }, }, }); }
public void Publish(Shared.Interfaces.IApplicationEvent applicationEvent) { var factory = new ConnectionFactory(); IConnection conn = factory.CreateConnection(); //uses defaults using (IModel channel = conn.CreateModel()) { channel.ExchangeDeclare("CustomerUpdate", ExchangeType.Direct); channel.QueueDeclare("MyMSDNSampleQueue", false, false, false, null); channel.QueueBind("MyMSDNSampleQueue", "CustomerUpdate", "", null); IBasicProperties props = channel.CreateBasicProperties(); string json = JsonConvert.SerializeObject(applicationEvent, Formatting.None); byte[] messageBodyBytes = System.Text.Encoding.UTF8.GetBytes(json); channel.BasicPublish("CustomerUpdate", "", props, messageBodyBytes); } }
private DataTable GetLookups() { return(Shared.GetLookup(this.Context.ClientID, this.Context.Connection)); }
public void AddOrder_CorrectAttributes_Success(int _clientId) { int _key = 0; string _country = "Poland"; string _city = "Gdynia"; string _street = "Rzemieslnicza"; int _ZIPCode = 30445; int _buildingNumber = 12; string _apartmentNumber = "1a"; var testSessionToken = SessionRepository.StartNewSession(_clientId); DatabaseQueryProcessor.Erase(); Shared.FillTheDatabase(); var testOrderEntry = new OrderEntryDto { key = 0, name = "Lavazza", quantity = 1, price = 15 }; var testOrderEntries = new OrderEntryDto[1]; testOrderEntries[0] = testOrderEntry; var testAddress = new AddressDto { key = _key, country = _country, city = _city, street = _street, ZIPCode = _ZIPCode, buildingNumber = _buildingNumber, apartmentNumber = _apartmentNumber }; var addOrderCommand = new AddOrderCommand { sessionToken = testSessionToken, orderEntries = testOrderEntries, totalPrice = "15.00", address = testAddress }; var addressId = DatabaseQueryProcessor.GetAddress(_clientId, _country, _city, _street, _ZIPCode, _buildingNumber, _apartmentNumber); var handler = new AddOrderCommandHandler(); var result = (SuccessInfoDto)handler.Handle(addOrderCommand); var expectedOrder = DatabaseQueryProcessor.GetTheMostRecentOrder(_clientId); SessionRepository.RemoveSession(testSessionToken); DatabaseQueryProcessor.Erase(); Assert.IsTrue(result.isSuccess); }
public void Should_return_module_type_by_id() { using (var context = new WeapsyDbContext(_contextOptions)) { var repository = new ModuleTypeRepository(DbContextShared.CreateNewContextFactory(context), Shared.CreateNewMapper()); var moduleType = repository.GetById(_moduleTypeId1); Assert.NotNull(moduleType); } }
public void GetAddressBook_CorrectAttributes_Success(int _clientId) { DatabaseQueryProcessor.Erase(); Shared.FillTheDatabase(); var firstAddress = new AddressDto { key = 0, country = "Poland", city = "Gdynia", street = "Rzemieslnicza", ZIPCode = 30445, buildingNumber = 12, apartmentNumber = "1a" }; var secondAddress = new AddressDto { key = 0, country = "Poland", city = "Warsaw", street = "Grodzka", ZIPCode = 25487, buildingNumber = 23, apartmentNumber = "" }; var testAddresses = new AddressDto[2]; testAddresses[0] = firstAddress; testAddresses[1] = secondAddress; var expectedAddressBook = new AddressBookDto { isSuccess = true, addresses = testAddresses }; var testSessionToken = SessionRepository.StartNewSession(_clientId); var getAddressBookQuery = new GetAddressBookQuery { sessionToken = testSessionToken, }; var handler = new GetAddressBookQueryHandler(); var addressBook = (AddressBookDto)handler.Handle(getAddressBookQuery); DatabaseQueryProcessor.Erase(); SessionRepository.RemoveSession(testSessionToken); Assert.AreEqual(expectedAddressBook.addresses.Length, addressBook.addresses.Length); Assert.AreEqual(expectedAddressBook.addresses[0].country, addressBook.addresses[0].country); Assert.AreEqual(expectedAddressBook.addresses[0].city, addressBook.addresses[0].city); Assert.AreEqual(expectedAddressBook.addresses[0].street, addressBook.addresses[0].street); Assert.AreEqual(expectedAddressBook.addresses[0].ZIPCode, addressBook.addresses[0].ZIPCode); Assert.AreEqual(expectedAddressBook.addresses[0].buildingNumber, addressBook.addresses[0].buildingNumber); Assert.AreEqual(expectedAddressBook.addresses[0].apartmentNumber, addressBook.addresses[0].apartmentNumber); Assert.AreEqual(expectedAddressBook.addresses[1].country, addressBook.addresses[1].country); Assert.AreEqual(expectedAddressBook.addresses[1].city, addressBook.addresses[1].city); Assert.AreEqual(expectedAddressBook.addresses[1].street, addressBook.addresses[1].street); Assert.AreEqual(expectedAddressBook.addresses[1].ZIPCode, addressBook.addresses[1].ZIPCode); Assert.AreEqual(expectedAddressBook.addresses[1].buildingNumber, addressBook.addresses[1].buildingNumber); Assert.AreEqual(expectedAddressBook.addresses[1].apartmentNumber, addressBook.addresses[1].apartmentNumber); }
public async Task Test03() { var usersResponse = await(await Client.GetAsync($"/api/users")).Content.ReadAsAsync <GetResponse <User> >(); int adminId = usersResponse.Result.FirstOrDefault().Id; // Prepare a well formed entity var dtoForSave = new RoleForSave { Name = "Sales Manager", Name2 = "مدير المبيعات", Code = "SM", IsPublic = false, Permissions = new List <PermissionForSave> { new PermissionForSave { View = "users", Action = "Read" }, new PermissionForSave { View = "measurement-units", Action = "Update" } }, Members = new List <RoleMembershipForSave> { new RoleMembershipForSave { UserId = adminId, Memo = "So Good" } } }; var dtoForSave2 = new RoleForSave { Name = "Chief of Staff", Name2 = "مدير المكتب", Code = "CS", IsPublic = false, Permissions = new List <PermissionForSave> { new PermissionForSave { View = "agents", Action = "Update" } }, Members = new List <RoleMembershipForSave> { } }; // Save it var dtosForSave = new List <RoleForSave> { dtoForSave, dtoForSave2 }; var response = await Client.PostAsJsonAsync($"{Url}?expand=Permissions,Members/User", dtosForSave); // Assert that the response status code is a happy 200 OK Output.WriteLine(await response.Content.ReadAsStringAsync()); Assert.Equal(HttpStatusCode.OK, response.StatusCode); // Assert that the response is well-formed singleton var responseData = await response.Content.ReadAsAsync <EntitiesResponse <Role> >(); Assert.Collection(responseData.Result, e => Assert.NotEqual(0, e.Id), e => Assert.NotEqual(0, e.Id)); // Assert that the result matches the saved entity Assert.Equal("Role", responseData.CollectionName); var responseDto = responseData.Result.FirstOrDefault(); Assert.Equal(dtoForSave.Name, responseDto.Name); Assert.Equal(dtoForSave.Name2, responseDto.Name2); Assert.Equal(dtoForSave.Code, responseDto.Code); Assert.Equal(dtoForSave.IsPublic, responseDto.IsPublic); Assert.Collection(responseDto.Permissions, p => { Assert.Equal(dtoForSave.Permissions[0].Action, p.Action); Assert.Equal(dtoForSave.Permissions[0].View, p.View); Assert.NotEqual(0, p.Id); }, p => { Assert.Equal(dtoForSave.Permissions[1].Action, p.Action); Assert.Equal(dtoForSave.Permissions[1].View, p.View); Assert.NotEqual(0, p.Id); } ); Assert.Collection(responseDto.Members, m => { Assert.Equal(dtoForSave.Members[0].UserId, m.UserId); Assert.Equal(dtoForSave.Members[0].Memo, m.Memo); Assert.NotEqual(0, m.Id); } ); // Get the second result var responseDto2 = responseData.Result.LastOrDefault(); Assert.Equal(dtoForSave2.Name, responseDto2.Name); Assert.Equal(dtoForSave2.Name2, responseDto2.Name2); Assert.Equal(dtoForSave2.Code, responseDto2.Code); Assert.Equal(dtoForSave2.IsPublic, responseDto2.IsPublic); Assert.Collection(responseDto2.Permissions, p => { Assert.Equal(dtoForSave2.Permissions[0].Action, p.Action); Assert.Equal(dtoForSave2.Permissions[0].View, p.View); Assert.NotEqual(0, p.Id); } ); Assert.Empty(responseDto2.Members); Shared.Set("Role_SalesManager", responseDto); Shared.Set("Role_ChiefOfStaff", responseDto2); }
public async Task Test05() { // Prepare a well formed entity var dtoForSave = new RelationForSave { Name = "John Wick", Name2 = "جون ويك", Code = "JW", TaxIdentificationNumber = "13345", IsRelated = false }; var dtoForSave2 = new RelationForSave { Name = "Jason Bourne", Name2 = "جيسن بورن", Code = "JB", TaxIdentificationNumber = "13346", IsRelated = false }; // Save it var dtosForSave = new List <RelationForSave> { dtoForSave, dtoForSave2 }; var response = await Client.PostAsJsonAsync(Url, dtosForSave); // Assert that the response status code is a happy 200 OK Output.WriteLine(await response.Content.ReadAsStringAsync()); Assert.Equal(HttpStatusCode.OK, response.StatusCode); // Assert that the response is well-formed singleton of Contract var responseData = await response.Content.ReadAsAsync <EntitiesResponse <Relation> >(); Assert.Collection(responseData.Result, e => Assert.NotEqual(0, e.Id), e => Assert.NotEqual(0, e.Id)); // Assert that the result matches the saved entity Assert.Equal("Contract", responseData.CollectionName); // Retreve the entity from the entities var responseDto = responseData.Result.FirstOrDefault(); Assert.Equal(dtoForSave.Name, responseDto.Name); Assert.Equal(dtoForSave.Name2, responseDto.Name2); Assert.Equal(dtoForSave.Name3, responseDto.Name3); Assert.Equal(dtoForSave.Code, responseDto.Code); Assert.Equal(dtoForSave.TaxIdentificationNumber, responseDto.TaxIdentificationNumber); var responseDto2 = responseData.Result.LastOrDefault(); Assert.Equal(dtoForSave2.Name, responseDto2.Name); Assert.Equal(dtoForSave2.Name2, responseDto2.Name2); Assert.Equal(dtoForSave2.Name3, responseDto2.Name3); Assert.Equal(dtoForSave2.Code, responseDto2.Code); Assert.Equal(dtoForSave2.TaxIdentificationNumber, responseDto2.TaxIdentificationNumber); Shared.Set("Contract_JohnWick", responseDto); Shared.Set("Contract_JasonBourne", responseDto2); }
public void Should_return_all_moduleTypes() { using (var context = new WeapsyDbContext(_contextOptions)) { var repository = new ModuleTypeRepository(Shared.CreateNewContextFactory(context), Shared.CreateNewMapper()); var moduleTypes = repository.GetAll(); Assert.AreEqual(2, moduleTypes.Count); } }
public void Should_update_moduleType() { const string newModuleTypeTitle = "New Title 1"; var moduleTypeToUpdate = ModuleTypeFactory.ModuleType(_moduleTypeId1, "Name 1", newModuleTypeTitle, "Description 1"); using (var context = new WeapsyDbContext(_contextOptions)) { var repository = new ModuleTypeRepository(DbContextShared.CreateNewContextFactory(context), Shared.CreateNewMapper()); repository.Update(moduleTypeToUpdate); } using (var context = new WeapsyDbContext(_contextOptions)) { var repository = new ModuleTypeRepository(DbContextShared.CreateNewContextFactory(context), Shared.CreateNewMapper()); var updatedModuleType = repository.GetById(_moduleTypeId1); Assert.AreEqual(newModuleTypeTitle, updatedModuleType.Title); } }
/// <summary> /// Converts the detections expressed in the Tiny Yolo 416x416 space back to the original /// image space. /// </summary> /// <param name="detections">The set of detections in Tiny Yolo 416x416 space.</param> /// <param name="sharedImage">The original image.</param> /// <returns>The detections converted to the original image space.</returns> private List <TinyYoloV2Detection> ConvertBoundingBoxesToImageSpace(List <TinyYoloV2Detection> detections, Shared <Image> sharedImage) { var inputImage = sharedImage.Resource; var inputWidth = sharedImage.Resource.Width; var inputHeight = sharedImage.Resource.Height; var squareSize = Math.Min(inputWidth, inputHeight); var scaleFactor = squareSize / 416.0f; return(detections.Select(detection => { if (inputWidth > inputHeight) { return new TinyYoloV2Detection() { BoundingBox = new System.Drawing.RectangleF( (inputWidth - squareSize) / 2 + detection.BoundingBox.X * scaleFactor, detection.BoundingBox.Y * scaleFactor, detection.BoundingBox.Width * scaleFactor, detection.BoundingBox.Height * scaleFactor), Label = detection.Label, Confidence = detection.Confidence, }; } else { return new TinyYoloV2Detection() { BoundingBox = new System.Drawing.RectangleF( detection.BoundingBox.X * scaleFactor, (inputHeight - squareSize) / 2 + detection.BoundingBox.Y * scaleFactor, detection.BoundingBox.Width * scaleFactor, detection.BoundingBox.Height * scaleFactor), Label = detection.Label, Confidence = detection.Confidence, }; } }).ToList()); }
public bool UpdateSectionInfo(string SEC_DIRECTION, decimal SEC_WIDTH, decimal SEC_LENGTH, bool houses, bool publics, bool commerial, bool gardens, bool indisterial, bool rest_house, bool unpaved_True, string unpaved_length, string unpaved_Width, bool mid_island_True, string mid_island_width, bool sideisland_True, string sideisland_width, bool side_Curb_True, string side_Curb_width, bool LIGHTING_True, string LIGHTING_LOC, bool brdg_TUNEL_true, string brdg_tunel_type, bool ag_mid_island_True, bool ag_sid_island_True, bool ag_sec_island_true, bool drinage_mh_true, string drinage_mh_count, bool drinage_cb_true, string drinage_cb_count, bool sewage_mh_true, string sewage_mh_count, bool Elect_mh_true, string Elect_mh_count, bool stc_mh_true, string stc_mh_count, bool water_valve_true, string waterMhCount, bool intersectOpenIsland, bool intersectTrafficLight, int SEC_order, int sectionID, bool drilling_stc, bool drilling_elec, bool drilling_water, bool drilling_sewage, string drilling_stc_length, string drilling_elec_length, string drilling_water_length, string drilling_sewage_length, bool is_r4, bool is_r3, DateTime?r4Date, DateTime?r3Date, string drainCBFair, string drainCbPoor, string drainMhFair, string drainMhPoor, string elecMhFair, string elecMhPoor, string stcMhFair, string stcMhPoor, string sewageMhFair, string sewageMhPoor, string waterMhFair, string waterMhPoor, bool midIslandGood, bool midIslandFair, bool midIslandPoor, bool sideCurbGood, bool sideCurbFair, bool sideCurbPoor, bool propertyConflict, string megacomCount, string mobyCount, string uniPoleCount, string lightingControlsCount, bool multilevel, bool sideIslandGood, bool sideIslandFair, bool sideIslandPoor, bool markers, bool paints, bool ceramics, bool pavedbyMunic, string pavedbyMunicDetails, bool ownedByMunic, string ownedByMunicDetails, bool hasPedestrainBridges, int pedestBridgeType, string pedestBridgesCount, bool sectionBorderOther, string sectionBorderDetails, DateTime?surveyDate, string lightGoodCount, string lightFairCount, string lightPoorCount, string guideSignsCount, int userID, string user) { // string lightCount, bool lightingIsGood, bool lightFair, bool lightPoor, string user, if (multilevel) { string sqlBridgeTunnels = string.Format("select bridge_id from bridges where section_id={0} union select tunnel_id from tunnels where section_id={0} ", sectionID); DataTable dt = db.ExecuteQuery(sqlBridgeTunnels); if (dt.Rows.Count == 0) { throw new Exception("هذا المقطع متعدد المستويات، يرجى إدخال بيانات الجسور أو بيانات الأنفاق الموجودة فيه"); } } SEC_DIRECTION = (SEC_DIRECTION == "0") ? "NULL" : string.Format("'{0}'", SEC_DIRECTION); LIGHTING_LOC = string.IsNullOrEmpty(LIGHTING_LOC) ? "NULL" : string.Format("'{0}'", LIGHTING_LOC.Replace("'", "''")); brdg_tunel_type = string.IsNullOrEmpty(brdg_tunel_type) ? "NULL" : string.Format("'{0}'", brdg_tunel_type.Replace("'", "''")); pavedbyMunicDetails = string.IsNullOrEmpty(pavedbyMunicDetails) ? "NULL" : string.Format("'{0}'", pavedbyMunicDetails.Replace("'", "''")); ownedByMunicDetails = string.IsNullOrEmpty(ownedByMunicDetails) ? "NULL" : string.Format("'{0}'", ownedByMunicDetails.Replace("'", "''")); sectionBorderDetails = string.IsNullOrEmpty(sectionBorderDetails) ? "NULL" : string.Format("'{0}'", sectionBorderDetails.Replace("'", "''")); string unpavedLengthPart = unpaved_True ? decimal.Parse(unpaved_length).ToString("0.00") : "NULL"; string unpavedWidthPart = unpaved_True ? decimal.Parse(unpaved_Width).ToString("0.00") : "NULL"; string drainageCbCount = drinage_cb_true ? int.Parse(drinage_cb_count).ToString() : "NULL"; string drainageMhCount = drinage_mh_true ? int.Parse(drinage_mh_count).ToString() : "NULL"; string sewageMhCount = sewage_mh_true ? int.Parse(sewage_mh_count).ToString() : "NULL"; string ElectMhCount = Elect_mh_true ? int.Parse(Elect_mh_count).ToString() : "NULL"; string stcMhCcount = stc_mh_true ? int.Parse(stc_mh_count).ToString() : "NULL"; string waterValveCount = water_valve_true ? int.Parse(waterMhCount).ToString() : "NULL"; string drainageCbFairPart = string.IsNullOrEmpty(drainCBFair) ? "NULL" : int.Parse(drainCBFair).ToString(); string drainageMhFairPart = string.IsNullOrEmpty(drainMhFair) ? "NULL" : int.Parse(drainMhFair).ToString(); string sewageMhFairPart = string.IsNullOrEmpty(sewageMhFair) ? "NULL" : int.Parse(sewageMhFair).ToString(); string ElectMhFairPart = string.IsNullOrEmpty(elecMhFair) ? "NULL" : int.Parse(elecMhFair).ToString(); string stcMhFairPart = string.IsNullOrEmpty(stcMhFair) ? "NULL" : int.Parse(stcMhFair).ToString(); string waterValveFairPart = string.IsNullOrEmpty(waterMhFair) ? "NULL" : int.Parse(waterMhFair).ToString(); string drainageCbPoorPart = string.IsNullOrEmpty(drainCbPoor) ? "NULL" : int.Parse(drainCbPoor).ToString(); string drainageMhPoorPart = string.IsNullOrEmpty(drainMhPoor) ? "NULL" : int.Parse(drainMhPoor).ToString(); string sewageMhPoorPart = string.IsNullOrEmpty(sewageMhPoor) ? "NULL" : int.Parse(sewageMhPoor).ToString(); string ElectMhPoorPart = string.IsNullOrEmpty(elecMhPoor) ? "NULL" : int.Parse(elecMhPoor).ToString(); string stcMhPoorPart = string.IsNullOrEmpty(stcMhPoor) ? "NULL" : int.Parse(stcMhPoor).ToString(); string waterValvePoorPart = string.IsNullOrEmpty(waterMhPoor) ? "NULL" : int.Parse(waterMhPoor).ToString(); string midIslandWidth = mid_island_True ? decimal.Parse(mid_island_width).ToString("0.00") : "NULL"; string sidIslandWidth = sideisland_True ? decimal.Parse(sideisland_width).ToString("0.00") : "NULL"; string sideCurbWidth = side_Curb_True ? decimal.Parse(side_Curb_width).ToString("0.00") : "NULL"; string drillingStcLen = drilling_stc ? decimal.Parse(drilling_stc_length).ToString("0.00") : "NULL"; string drillingWaterLen = drilling_water ? decimal.Parse(drilling_water_length).ToString("0.00") : "NULL"; string drillingElecLen = drilling_elec ? decimal.Parse(drilling_elec_length).ToString("0.00") : "NULL"; string drillingSewageLen = drilling_sewage ? decimal.Parse(drilling_sewage_length).ToString("0.00") : "NULL"; //string R4datePart = is_r4 ? string.Format("'{0}'", Shared.FormatDateArEgDMY(r4Date)) : "NULL"; string R4datePart = is_r4 ? string.Format("'{0}'", ((DateTime)r4Date).ToString("dd/MM/yyyy")) : "NULL"; string R3datePart = is_r3 ? string.Format("'{0}'", ((DateTime)r3Date).ToString("dd/MM/yyyy")) : "NULL"; string surveyDatePart = surveyDate != null?string.Format("'{0}'", ((DateTime)surveyDate).ToString("dd/MM/yyyy")) : "NULL"; //string noPermitsTillDatePart = is_r3 ? string.Format("'{0}'", ((DateTime)r3Date).AddMonths(6).ToString("dd/MM/yyyy")) : "NULL"; string noPermitsTillDatePart = ""; if (is_r3 && is_r4) { DateTime?date = (r3Date > r4Date) ? r3Date : r4Date; noPermitsTillDatePart = string.Format("'{0}'", ((DateTime)date).AddMonths(6).ToString("dd/MM/yyyy")); } if (is_r3) { noPermitsTillDatePart = string.Format("'{0}'", ((DateTime)r3Date).AddMonths(6).ToString("dd/MM/yyyy")); } else if (is_r4) { noPermitsTillDatePart = string.Format("'{0}'", ((DateTime)r4Date).AddMonths(6).ToString("dd/MM/yyyy")); } else { noPermitsTillDatePart = "NULL"; } //string lightCountPart = string.IsNullOrEmpty(lightCount) ? "NULL" : int.Parse(lightCount).ToString(); string lightGoodCountPart = string.IsNullOrEmpty(lightGoodCount) ? "NULL" : int.Parse(lightGoodCount).ToString(); string lightFairCountPart = string.IsNullOrEmpty(lightFairCount) ? "NULL" : int.Parse(lightFairCount).ToString(); string lightPoorCountPart = string.IsNullOrEmpty(lightPoorCount) ? "NULL" : int.Parse(lightPoorCount).ToString(); string megacomPart = string.IsNullOrEmpty(megacomCount) ? "NULL" : int.Parse(megacomCount).ToString(); string mobyPart = string.IsNullOrEmpty(mobyCount) ? "NULL" : int.Parse(mobyCount).ToString(); string unipolePart = string.IsNullOrEmpty(uniPoleCount) ? "NULL" : int.Parse(uniPoleCount).ToString(); string lightControlsPart = string.IsNullOrEmpty(lightingControlsCount) ? "NULL" : int.Parse(lightingControlsCount).ToString(); string bridgeTypePart = (pedestBridgeType == 0) ? "NULL" : pedestBridgeType.ToString(); string bridgesCountPart = string.IsNullOrEmpty(pedestBridgesCount) ? "NULL" : pedestBridgesCount.ToString(); string guideSignsCountPart = string.IsNullOrEmpty(guideSignsCount) ? "NULL" : int.Parse(guideSignsCount).ToString(); // LIGHTING_COUNT={72}, lightCountPart , LIGHTING_GOOD='{73}', LIGHT_FAIR='{87}', LIGHT_POOR='{88}', Shared.Bool2YN(lightingIsGood), Shared.Bool2YN(lightFair), Shared.Bool2YN(lightPoor), string sql = string.Format("UPDATE SECTION_DETAILS SET SEC_DIRECTION={0}, SEC_order={1}, SEC_LENGTH={2}, SEC_WIDTH={3}, houses='{4}', publics='{5}', commerial='{6}', " + " gardens='{7}', indisterial='{8}', rest_house='{9}', unpaved_true='{10}', unpaved_length={11}, unpaved_width={12}, MID_island_true='{13}', " + " MID_island_WIDTH={14}, SIDEisland_true='{15}', SIDEisland_WIDTH={16}, side_curb_true='{17}', SIDE_curb_WIDTH={18}, LIGHTING_true='{19}', LIGHTING_LOC={20}, " + " brdg_TUNEL_true='{21}', brdg_tunel_type={22}, ag_mid_island_true='{23}', ag_sid_island_true='{24}', ag_sec_island_true='{25}', " + " drinage_mh_true='{26}', drinage_mh_count={27}, drinage_cb_true='{28}', drinage_cb_count={29}, sewage_mh_true='{30}', sewage_mh_count={31}, " + " Elect_mh_true='{32}', Elect_mh_count={33}, stc_mh_true='{34}', stc_mh_count={35}, water_valve_true='{36}', water_valve_count={37}, " + " INTERSECTION_OPEN_ISLAND='{38}', INTERSECTION_TRAFFIC_LIGHT='{39}', DRILLINGS_STC='{41}', DRILLINGS_STC_LENGTH={42}, DRILLINGS_ELEC='{43}', " + " DRILLINGS_ELEC_LENGTH={44}, DRILLINGS_WATER='{45}', DRILLINGS_WATER_LENGTH={46}, DRILLINGS_SEWAGE='{47}', DRILLINGS_SEWAG_LENGTH={48}, IS_R4='{49}', IS_R3='{50}', " + " R4_DATE={51}, R3_DATE={52}, NO_PERMIT_TILL_DATE={53}, DRAIN_CB_FAIR={54}, DRAIN_CB_POOR={55}, DRAIN_MH_FAIR={56}, DRAIN_MH_POOR={57}, " + " ELEC_MH_FAIR={58}, ELEC_MH_POOR={59}, STC_MH_FAIR={60}, STC_MH_POOR={61}, SEWAGE_MH_FAIR={62}, SEWAGE_MH_POOR={63}, WATER_MH_FAIR={64}, WATER_MH_POOR={65}, " + " MID_ISLAND_GOOD='{66}', MID_ISLAND_FAIR='{67}', MID_ISLAND_POOR='{68}', SIDE_CURB_GOOD='{69}', SIDE_CURB_FAIR='{70}', " + " SIDE_CURB_POOR='{71}', LIGHTING_PROPERTY_CONFLICT='{72}', MEGACOM_COUNT={73}, MOBY_COUNT={74}, UNIPOLE_COUNT={75}, LIGHTING_CONTROLS_COUNT={76}, MULTILEVEL='{77}', " + " SID_ISLAND_GOOD='{78}', SID_ISLAND_FAIR='{79}', SID_ISLAND_POOR='{80}', PAVED_BY_MUNIC='{81}', NOT_PAVED_BY_DETAILS={82}, " + " OWNED_BY_MUNIC='{83}', OWNED_DETAILS={84}, PAV_MARKERS_TRUE='{85}', MARKER_CERAMIC='{86}', MARKER_PAINT='{87}', PEDESTRIAN='{88}', " + " PEDESTRIAN_BRIDGE_TYPE={89}, PEDESTRIAN_COUNT={90}, SECTION_BORDER_OTHER='{91}', OTHER_BORDER_DETAILS={92}, SURVEY_DATE={93}, GUIDE_SIGNS_COUNT={94}, " + " DONE_BY={95}, LIGHT_GOOD_COUNT={96}, LIGHT_FAIR_COUNT={97}, LIGHT_POOR_COUNT={98} WHERE SECTION_ID={40} ", SEC_DIRECTION, SEC_order, SEC_LENGTH, SEC_WIDTH, Shared.Bool2YN(houses), Shared.Bool2YN(publics), Shared.Bool2YN(commerial), Shared.Bool2YN(gardens), Shared.Bool2YN(indisterial), Shared.Bool2YN(rest_house), Shared.Bool2YN(unpaved_True), unpaved_length, unpaved_Width, Shared.Bool2YN(mid_island_True), midIslandWidth, Shared.Bool2YN(sideisland_True), sidIslandWidth, Shared.Bool2YN(side_Curb_True), sideCurbWidth, Shared.Bool2YN(LIGHTING_True), LIGHTING_LOC, Shared.Bool2YN(brdg_TUNEL_true), brdg_tunel_type, Shared.Bool2YN(ag_mid_island_True), Shared.Bool2YN(ag_sid_island_True), Shared.Bool2YN(ag_sec_island_true), Shared.Bool2YN(drinage_mh_true), drainageMhCount, Shared.Bool2YN(drinage_cb_true), drainageCbCount, Shared.Bool2YN(sewage_mh_true), sewageMhCount, Shared.Bool2YN(Elect_mh_true), ElectMhCount, Shared.Bool2YN(stc_mh_true), stcMhCcount, Shared.Bool2YN(water_valve_true), waterValveCount, Shared.Bool2YN(intersectOpenIsland), Shared.Bool2YN(intersectTrafficLight), sectionID, Shared.Bool2YN(drilling_stc), drillingStcLen, Shared.Bool2YN(drilling_elec), drillingElecLen, Shared.Bool2YN(drilling_water), drillingWaterLen, Shared.Bool2YN(drilling_sewage), drillingSewageLen, Shared.Bool2YN(is_r4), Shared.Bool2YN(is_r3), R4datePart, R3datePart, noPermitsTillDatePart, drainageCbFairPart, drainageCbPoorPart, drainageMhFairPart, drainageCbPoorPart, ElectMhFairPart, ElectMhPoorPart, stcMhFairPart, stcMhPoorPart, sewageMhFairPart, sewageMhPoorPart, waterValveFairPart, waterValvePoorPart, Shared.Bool2YN(midIslandGood), Shared.Bool2YN(midIslandFair), Shared.Bool2YN(midIslandPoor), Shared.Bool2YN(sideCurbGood), Shared.Bool2YN(sideCurbFair), Shared.Bool2YN(sideCurbPoor), Shared.Bool2YN(propertyConflict), megacomPart, mobyPart, unipolePart, lightControlsPart, Shared.Bool2YN(multilevel), Shared.Bool2YN(sideIslandGood), Shared.Bool2YN(sideIslandFair), Shared.Bool2YN(sideIslandPoor), Shared.Bool2YN(pavedbyMunic), pavedbyMunicDetails, Shared.Bool2YN(ownedByMunic), ownedByMunicDetails, Shared.Bool2YN(markers), Shared.Bool2YN(ceramics), Shared.Bool2YN(paints), Shared.Bool2YN(hasPedestrainBridges), bridgeTypePart, bridgesCountPart, Shared.Bool2YN(sectionBorderOther), sectionBorderDetails, surveyDatePart, guideSignsCountPart, userID, lightGoodCountPart, lightFairCountPart, lightPoorCountPart); int rows = db.ExecuteNonQuery(sql); sql = string.Format("update SECTIONS set SEC_DIRECTION={0}, SEC_ORDER={1}, SEC_LENGTH={2}, SEC_WIDTH={3} WHERE SECTION_ID={4} ", SEC_DIRECTION, SEC_order, SEC_LENGTH, SEC_WIDTH, sectionID); rows += db.ExecuteNonQuery(sql); Shared.SaveLogfile("SECTIONs", sectionID.ToString(), "Update Info", user); return(rows > 0); }
public Dictionary <string, object> Post([FromBody] Dictionary <string, object> data) { var response = new Dictionary <string, object>(); try { // Handle the request type if (data.ContainsKey("type")) { switch (data["type"].ToString()) { // GET case "get": // Retrieve locations var locations = new Dictionary <string, Dictionary <string, object> >(); // Have them be a dictionary keyed by UID foreach (var location in Database.GetDictionaries(@"SELECT * FROM Locations WHERE DATEADD(hour, hours, time) > CURRENT_TIMESTAMP")) { locations.Add((string)location["uid"], location); } response.Add("locations", locations); break; // ADD case "add": // Verify the user's token if (data.ContainsKey("token")) { dynamic payload = Shared.VerifyAndGetPayload(response, data); if (payload != null) { string uid = payload.user_id; dynamic dataObj = data["data"]; string lat = dataObj.lat; string lon = dataObj.lon; int hours = dataObj.hours; // Replace location and return its database-given ID response.Add("success", Database.ExecuteScalar(@" DELETE FROM Locations WHERE uid=@uid INSERT INTO Locations (uid, lat, lon, time, hours) VALUES (@uid, @lat, @lon, CURRENT_TIMESTAMP, @hours) SELECT 1", new Dictionary <string, object>() { { "@uid", uid }, { "@lat", lat }, { "@lon", lon }, { "@hours", hours } })); // Send out broadcast var options = new PusherOptions(); options.Encrypted = true; var pusher = new Pusher("316078", "c367bd18dea7e8eaee28", "36dbabfa4496f090bece", options); var result = pusher.Trigger("main", "broadcast", new { uid = uid }); } } // See if we were able to authenticate if (!response.ContainsKey("success")) { response.Add("error", "Unable to verify user token"); } break; // REMOVE case "remove": // Verify the user's token if (data.ContainsKey("token")) { dynamic payload = Shared.VerifyAndGetPayload(response, data); if (payload != null) { string uid = payload.user_id; // Remove user's location response.Add("success", Database.ExecuteNonQuery("DELETE FROM Locations WHERE uid=@uid", new Dictionary <string, object>() { { "@uid", uid } })); // Send out broadcast var options = new PusherOptions(); options.Encrypted = true; var pusher = new Pusher("316078", "c367bd18dea7e8eaee28", "36dbabfa4496f090bece", options); var result = pusher.Trigger("main", "broadcast", new { uid = uid }); } } // See if we were able to authenticate if (!response.ContainsKey("success")) { response.Add("error", "Unable to verify user token"); } break; } } } catch (Exception e) { response.Add("error", e.Message); } return(response); }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); check = Shared.Get(); Shared.Clean(); CheckListBLL BLL = new CheckListBLL(); chaves = BLL.ListaChaves(); //int count = 0; if (chaves != null) { foreach (Chave p in chaves) { if (p.Area.Equals(check.Area) && !p.Area.Equals("2")) { chavesA.Add(p); } if (p.Area.Equals("2")) { chavesA.Add(p); } } //PARAMETROS PARA OS INTENS LayoutParams lp = new LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); LayoutParams lpL = new LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent); lp.Height = 120; //LAYOUT PRINCIPAL QUE IRÀ DENTRO DO SCROLL LinearLayout layout = new LinearLayout(this); layout.Orientation = Orientation.Vertical; layout.LayoutParameters = lpL; //SCROLL DE ROLAGEM ScrollView scroll = new ScrollView(this); scroll.LayoutParameters = lpL; this.SetContentView(scroll); scroll.AddView(layout); TextView lblChaves = new TextView(this); lblChaves.Text = "Confira as Chaves!!!! =)"; lblChaves.SetTextSize(Android.Util.ComplexUnitType.Sp, 30); //ADICIONAR TUDO AO LAYOUT layout.AddView(lblChaves, lp); Button botao = new Button(this); botao.Text = "CONCLUIR"; if (chavesA != null) { foreach (Chave a in chavesA) { Switch s = new Switch(this); s.Text = a.Nome; //try { s.Id = Convert.ToInt32(a.Id); } catch { } s.SetTextSize(Android.Util.ComplexUnitType.Sp, 30); switches.Add(s); } } //for (int i = 0; i < 60; i++) //{ // Switch s = new Switch(this); // s.Text = "Texto do Switch..: " + i; // s.SetTextSize(Android.Util.ComplexUnitType.Sp, 30); // switches.Add(s); //} foreach (var s in switches) { layout.AddView(s, lp); } layout.AddView(botao, lp); botao.Click += delegate { Aguarde.MostraAguarde(true, this); var task = Task.Factory.StartNew(() => { certo = Cadastrar(); }); task.ContinueWith( t => { if (certo) { Toast.MakeText(this, "CHECKLIST FINALIZADO", ToastLength.Long).Show(); this.FinishAffinity(); } else { Toast.MakeText(this, "VERIFIQUE OS CAMPOS OBRIGATÓRIOS", ToastLength.Long).Show(); } Aguarde.MostraAguarde(false, this); }, TaskScheduler.FromCurrentSynchronizationContext()); // }; } }
public void RegisterEncryptionKey(string dbName, SymmetricKey key) { Shared.SetValue("encryptionKey", "", dbName, key); }
public void Should_return_null_if_module_type_is_deleted() { using (var context = new WeapsyDbContext(_contextOptions)) { var repository = new ModuleTypeRepository(Shared.CreateNewContextFactory(context), Shared.CreateNewMapper()); var moduleType = repository.GetById(_deletedModuleTypeId); Assert.Null(moduleType); } }
// c'tor public TexturePickerUpdateObj(InGame parent, ref Shared shared) : base(parent, ref shared) { } // end of TexturePickerUpdateObj c'tor
public void Should_save_new_moduleType() { var newModuleType = ModuleTypeFactory.ModuleType(Guid.NewGuid(), "Name 3", "Title 3", "Description 3"); using (var context = new WeapsyDbContext(_contextOptions)) { var repository = new ModuleTypeRepository(Shared.CreateNewContextFactory(context), Shared.CreateNewMapper()); repository.Create(newModuleType); } using (var context = new WeapsyDbContext(_contextOptions)) { var repository = new ModuleTypeRepository(Shared.CreateNewContextFactory(context), Shared.CreateNewMapper()); var moduleType = repository.GetById(newModuleType.Id); Assert.NotNull(moduleType); } }
public static void Decrypt(object sender, EventArgs e) { var tsi = sender as ToolStripMenuItem; var name = (tsi.Tag.ToString() == "normal") ? "3DS" : tsi.Tag.ToString(); FileStream openFile; FileStream saveFile = null; if ((Types)tsi.Tag != Types.NSW_XCI && (Types)tsi.Tag != Types.NSW_NCA) { if (!Shared.PrepareFiles("Open an encrypted " + name + " file...", "Save your decrypted file...", ".dec", out openFile, out saveFile)) { return; } } else { var ofd = new OpenFileDialog { Title = "Open an encrypted " + name + " file...", Filter = "All Files (*.*)|*.*" }; if (ofd.ShowDialog() == DialogResult.OK) { openFile = File.Open(ofd.FileName, FileMode.Open, FileAccess.ReadWrite); } else { return; } } bool show = true; try { using (var openBr = new BinaryReaderX(openFile)) { switch (tsi.Tag) { case Types.BlowFishCBC: using (var outFs = new BinaryWriterX(saveFile)) { var key = InputBox.Show("Input decryption key:", "Decrypt Blowfish"); if (key == String.Empty) { throw new Exception("Key can't be empty!"); } var bf = new BlowFish(key); outFs.Write(bf.Decrypt_CBC(openBr.ReadAllBytes())); } break; case Types.BlowFishECB: using (var outFs = new BinaryWriterX(saveFile)) { var key = InputBox.Show("Input decryption key:", "Decrypt Blowfish"); if (key == String.Empty) { throw new Exception("Key can't be empty!"); } var bf = new BlowFish(key); outFs.Write(bf.Decrypt_ECB(openBr.ReadAllBytes())); } break; case Types.MTMobile: using (var outFs = new BinaryWriterX(saveFile)) { var key1 = InputBox.Show("Input 1st decryption key:", "Decrypt MTMobile"); var key2 = InputBox.Show("Input 2nd decryption key:", "Decrypt MTMobile"); if (key1 == String.Empty || key2 == String.Empty) { throw new Exception("Keys can't be empty!"); } outFs.Write(MTFramework.Decrypt(openBr.BaseStream, key1, key2)); } break; case Types.Normal: using (var outFs = new BinaryWriterX(saveFile)) { var engine = new AesEngine(); openBr.BaseStream.CopyTo(outFs.BaseStream); openBr.BaseStream.Position = 0; outFs.BaseStream.Position = 0; engine.DecryptGameNCSD(openBr.BaseStream, outFs.BaseStream); } break; case Types.CIA_shallow: using (var outFs = new BinaryWriterX(saveFile)) { var engine = new AesEngine(); openBr.BaseStream.CopyTo(outFs.BaseStream); openBr.BaseStream.Position = 0; outFs.BaseStream.Position = 0; engine.DecryptCIA(openBr.BaseStream, outFs.BaseStream, true); } break; case Types.CIA_deep: using (var outFs = new BinaryWriterX(saveFile)) { var engine = new AesEngine(); openBr.BaseStream.CopyTo(outFs.BaseStream); openBr.BaseStream.Position = 0; outFs.BaseStream.Position = 0; engine.DecryptCIA(openBr.BaseStream, outFs.BaseStream, false); } break; case Types.NCCH: using (var outFs = new BinaryWriterX(saveFile)) { var engine = new AesEngine(); openBr.BaseStream.CopyTo(outFs.BaseStream); openBr.BaseStream.Position = 0; outFs.BaseStream.Position = 0; engine.DecryptNCCH(openBr.BaseStream, outFs.BaseStream); } break; /*case Types.BOSS: * outFs.Write(engine.DecryptBOSS(openBr.ReadBytes((int)openBr.BaseStream.Length))); * break;*/ case Types.NSW_XCI: openBr.BaseStream.Position = 0; var xci_header_key = InputBox.Show("Input XCI Header Key:", "Decrypt XCI").Hexlify(); Switch.DecryptXCI(openBr.BaseStream, xci_header_key); MessageBox.Show("XCI Header and all NCA's were decrypted successfully!", "Decryption Success", MessageBoxButtons.OK); show = false; break; case Types.NSW_NCA: openBr.BaseStream.Position = 0; Switch.DecryptNCA(openBr.BaseStream, 0); MessageBox.Show("NCA was decrypted successfully!", "Decryption Success", MessageBoxButtons.OK); show = false; break; } } if (show) { MessageBox.Show($"Successfully decrypted {Path.GetFileName(openFile.Name)}.", tsi?.Text, MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception ex) { MessageBox.Show(ex.ToString(), tsi?.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); File.Delete(saveFile.Name); } }
// internal methods private void AddMenu(NesMenuCollection menuCollection, Dictionary <string, string> originalGames, NesApplication.CopyMode copyMode, HashSet <ApplicationFileInfo> localGameSet = null, GamesTreeStats stats = null) { if (stats == null) { stats = new GamesTreeStats(); } if (!stats.allMenus.Contains(menuCollection)) { stats.allMenus.Add(menuCollection); } int menuIndex = stats.allMenus.IndexOf(menuCollection); string targetDirectory = string.Format("{0:D3}", menuIndex); foreach (var element in menuCollection) { if (element is NesApplication) { var game = element as NesApplication; // still use temp directory for game genie games try { if (game is ISupportsGameGenie && File.Exists(game.GameGeniePath)) { string tempPath = Path.Combine(tempDirectory, game.Desktop.Code); Shared.EnsureEmptyDirectory(tempPath); NesApplication gameCopy = game.CopyTo(tempDirectory); (gameCopy as ISupportsGameGenie).ApplyGameGenie(); game = gameCopy; } } catch (GameGenieFormatException ex) { Debug.WriteLine(string.Format(Resources.GameGenieFormatError, ex.Code, game.Name)); } catch (GameGenieNotFoundException ex) { Debug.WriteLine(string.Format(Resources.GameGenieNotFound, ex.Code, game.Name)); } long gameSize = game.Size(); Debug.WriteLine(string.Format("Processing {0} ('{1}'), size: {2}KB", game.Code, game.Name, gameSize / 1024)); gameSize = game.CopyTo(targetDirectory, localGameSet, copyMode); stats.TotalSize += gameSize; stats.TransferSize += gameSize; stats.TotalGames++; // legacy if (game.IsOriginalGame) { originalGames[game.Code] = $"{menuIndex:D3}"; } } if (element is NesMenuFolder) { var folder = element as NesMenuFolder; if (folder.Name == Resources.FolderNameTrashBin) { continue; // skip recycle bin! } if (!stats.allMenus.Contains(folder.ChildMenuCollection)) { stats.allMenus.Add(folder.ChildMenuCollection); AddMenu(folder.ChildMenuCollection, originalGames, copyMode, localGameSet, stats); } folder.ChildIndex = stats.allMenus.IndexOf(folder.ChildMenuCollection); long folderSize = folder.CopyTo(targetDirectory, localGameSet); stats.TotalSize += folderSize; stats.TransferSize += folderSize; Debug.WriteLine(string.Format("Processed folder {0} ('{1}'), size: {2}KB", folder.Code, folder.Name, folderSize / 1024)); } } }
/// <inheritdoc/> public override void Dispose(Shared <DepthImage> destination) => destination?.Dispose();
public bool Insert(string SURVEYOR_NAME, DateTime?SURVEYOR_WORK_STARTDATE, DateTime?SURVEYOR_WORK_ENDDATE, string SURVEYOR_PHONE_NO, bool SUSPENDED) { SURVEYOR_NAME = SURVEYOR_NAME.Replace("'", "''"); SURVEYOR_PHONE_NO = string.IsNullOrEmpty(SURVEYOR_PHONE_NO) ? "NULL" : string.Format("'{0}'", SURVEYOR_PHONE_NO.Replace("'", "''")); string workEndDate = (SURVEYOR_WORK_ENDDATE == null) ? (SUSPENDED ? string.Format("to_date('{0}', 'DD/MM/YYYY')", DateTime.Today.ToString("dd/MM/yyyy")) : "NULL") : string.Format("to_date('{0}', 'DD/MM/YYYY')", ((DateTime)SURVEYOR_WORK_ENDDATE).ToString("dd/MM/yyyy")); string sql = string.Format("INSERT INTO SURVEYORS (SURVEYOR_NO, SURVEYOR_NAME, SURVEYOR_WORK_STARTDATE, SURVEYOR_WORK_ENDDATE, SURVEYOR_PHONE_NO, SUSPENDED) " + " VALUES (SEQ_SURVEYORS.nextval, '{0}', to_date('{1}', 'DD/MM/YYYY'), {2}, {3}, {4}) ", SURVEYOR_NAME, ((DateTime)SURVEYOR_WORK_STARTDATE).ToString("dd/MM/yyyy"), workEndDate, SURVEYOR_PHONE_NO, Shared.Bool2Int(SUSPENDED)); int rows = db.ExecuteNonQuery(sql); return(rows > 0); }
public bool Update(string SURVEYOR_NAME, DateTime?SURVEYOR_WORK_STARTDATE, DateTime?SURVEYOR_WORK_ENDDATE, string SURVEYOR_PHONE_NO, int SURVEYOR_NO, bool SUSPENDED) { SURVEYOR_NAME = SURVEYOR_NAME.Replace("'", "''"); SURVEYOR_PHONE_NO = string.IsNullOrEmpty(SURVEYOR_PHONE_NO) ? "NULL" : string.Format("'{0}'", SURVEYOR_PHONE_NO.Replace("'", "''")); //string workEndDate = (SURVEYOR_WORK_ENDDATE == null) ? "NULL" : string.Format("to_date('{0}', 'DD/MM/YYYY')", ((DateTime)SURVEYOR_WORK_ENDDATE).ToString("dd/MM/yyyy")); string workEndDate = (SURVEYOR_WORK_ENDDATE == null) ? (SUSPENDED ? string.Format("to_date('{0}', 'DD/MM/YYYY')", DateTime.Today.ToString("dd/MM/yyyy")) : "NULL") : string.Format("to_date('{0}', 'DD/MM/YYYY')", ((DateTime)SURVEYOR_WORK_ENDDATE).ToString("dd/MM/yyyy")); string sql = string.Format("UPDATE SURVEYORS SET SURVEYOR_NAME='{0}', SURVEYOR_WORK_STARTDATE=to_date('{1}', 'DD/MM/YYYY'), SURVEYOR_WORK_ENDDATE={2}, " + " SURVEYOR_PHONE_NO={3}, SUSPENDED={5} WHERE SURVEYOR_NO={4} ", SURVEYOR_NAME, ((DateTime)SURVEYOR_WORK_STARTDATE).ToString("dd/MM/yyyy"), workEndDate, SURVEYOR_PHONE_NO, SURVEYOR_NO, Shared.Bool2Int(SUSPENDED)); int rows = db.ExecuteNonQuery(sql); return(rows > 0); }