public void TestMethod1() { // arrange var builder = new FilterBuilder(); builder.AddConstraint("endDate", DateTime.Parse("2010-12-26")); var client = new Mock<IMyAtTaskRestClient>(); client.Setup(x => x.Search(ObjCode.TIMESHEET, builder.Filter)) .Returns(JToken.Parse(Resources.timesheets)); client.Setup(x => x.Search(ObjCode.EXPENSE, It.IsAny<List<string>>())) .Returns(JToken.Parse(Resources.expenses)); /* var mapper = new Mock<IPayrollMapper>(); var expectedPayroll = new Payroll[0]; mapper.Setup(x => x.MapTimesheetsToPayrollReportItem(It.IsAny<JToken>(), It.IsAny<JToken>())) .Returns(expectedPayroll);*/ var gateway = new Gateway(new PayrollMapper(), client.Object); // act Payroll[] result = gateway.GetTimesheetsByFilter(builder); // assert var payrollFive = result.Single(x => x.Lastname == "Five"); Assert.AreEqual(13, payrollFive.TotalMileage); //mapper.Verify(m => m.MapTimesheetsToPayrollReportItem( }
public Factory(Gateway.Event.IMediator eventMediator, ITransition transition, Command.Endpoint.IFactory commandEndpointFactory, Packet.Endpoint.IFactory packetEndpointFactory) { _eventMediator = eventMediator; _transition = transition; _commandEndpointFactory = commandEndpointFactory; _packetEndpointFactory = packetEndpointFactory; }
public PageHandler(string gatewayServerAddress) { shuffUIManager = new ShuffUIManager(); gameDrawer = new GameDrawer(); TimeTracker = new TimeTracker(); var gateway = new Gateway(gatewayServerAddress,false); ClientGameManager = new ClientGameManager(gateway); ClientSiteManager = new ClientSiteManager(gateway); ClientDebugManager = new ClientDebugManager(gateway); ClientChatManager = new ClientChatManager(gateway); ClientInfo = new ClientInformation(); this.GameManager = new GameManager(this); LoginUI = new LoginUI(shuffUIManager, this); HomeUI = new HomeUI(shuffUIManager, this); QuestionUI = new QuestionUI(shuffUIManager, this); /*gateway.On("Area.Lobby.ListCardGames.Response", (data) => { }); gateway.On("Area.Lobby.ListRooms.Response", (data) => { Logger.Log });*/ //ie8 /* { dynamic d2 = (Action<string, ElementEventHandler>)Document.Body.AttachEvent; var m = (Action<string, ElementEventHandler>)d2; m("contextmenu", () => { }); }*/ }
public void GetDistanceTest() { Map map = CreateChaoYang(); DijikstraPathFinder target = new DijikstraPathFinder(map); MapNode source = new CubeIsland() { Id = 0, Name = "ChaoYang-Island7" }; var g1 = new Gateway() { Id = 0, Name = "ChaoYang-G-W" }; var g2 = new Gateway() { Id = 0, Name = "ChaoYang-G-N" }; var g3 = new MeetingRoom { Id = 0, Name = "Tian Tan" }; var g4 = new MeetingRoom { Id = 0, Name = "Wang Fu Jing" }; var g5 = new CubeIsland { Id = 0, Name = "ChaoYang-Island10" }; var g6 = new CubeIsland { Id = 0, Name = "ChaoYang-Island12" }; var g7 = new CubeIsland { Id = 0, Name = "ChaoYang-Island13" }; IList<MapNode> dest = new List<MapNode>() { g1, g2, g3, g4, g4, g5, g6, g7 }; IDictionary<MapNode, double> expected = new Dictionary<MapNode, double>(); expected.Add(g1, 11); expected.Add(g2, 3); expected.Add(g3, 7); expected.Add(g4, 5); IDictionary<MapNode, double> actual = target.GetDistance(source, dest); Assert.AreEqual(expected, actual); }
public OctopusRepository(string connectionString) { _Gateway = new Gateway(connectionString); Job = new JobRepository(_Gateway); Heartbeat = new HeartbeatRepository(_Gateway); }
public Listening(Gateway.Event.IMediator eventMediator, ITransition transition, Packet.Endpoint.IFactory packetEndpointFactory, Context.IListen context) { _eventMediator = eventMediator; _transition = transition; _packetEndpointFactory = packetEndpointFactory; _context = context; }
internal GatewayAcceptor(MessageCenter msgCtr, Gateway gateway, IPEndPoint gatewayAddress) : base(msgCtr, gatewayAddress, SocketDirection.GatewayToClient) { this.gateway = gateway; loadSheddingCounter = CounterStatistic.FindOrCreate(StatisticNames.GATEWAY_LOAD_SHEDDING); gatewayTrafficCounter = CounterStatistic.FindOrCreate(StatisticNames.GATEWAY_RECEIVED); }
internal void SetGateway(Gateway gateway) { this.gateway = gateway; // Only start ClientRefreshTimer if this silo has a gateway. // Need to start the timer in the system target context. scheduler.QueueAction(Start, this.SchedulingContext).Ignore(); }
public static Gateway<Orders> GetOrderGateway() { if (OrderGateway == null) { OrderGateway = new Gateway<Orders>("Api/Ordre/"); } return OrderGateway; }
public static Gateway<Movie> GetMovieGateway() { if (MovieGateway == null) { MovieGateway = new Gateway<Movie>("Api/movie/"); } return MovieGateway; }
public static Gateway<Customer> GetCustomerGateway() { if (CustomerGateway == null) { CustomerGateway = new Gateway<Customer>("Api/Customer/"); } return CustomerGateway; }
public static Gateway<Department> GetDepartmentGateway() { if (DepartmentGateway == null) { DepartmentGateway = new Gateway<Department>("Api/Department/"); } return DepartmentGateway; }
public static Gateway<Comment> GetCommentGateway() { if (CommentGateway == null) { CommentGateway = new Gateway<Comment>("Api/Comment"); } return CommentGateway; }
public static Gateway<Status> GetStatusGateway() { if (StatusGateway == null) { StatusGateway = new Gateway<Status>("Api/Status/"); } return StatusGateway; }
public static Gateway<Project> GetProjectGateway() { if (ProjectGateway == null) { ProjectGateway = new Gateway<Project>("Api/Project/"); } return ProjectGateway; }
public static Gateway<Genres> GetGenreGateway() { if (GenreGateway == null) { GenreGateway = new Gateway<Genres>("Api/Genre/"); } return GenreGateway; }
public GetQuotes(Gateway apiGateway, string apiCall) : base(apiGateway, apiCall) { InitializeComponent(); if (ApiCall.CompareTo("Market/Get Option Expirations") == 0) { label2.Text = "** Only one symbol may be used when fetching option expirations. **"; } }
public void Gateway_Can_Retrieve_Employee() { const string drecksageCode = "9d3c8120a653cebbe040007f01002438"; Employee emp = null; using (Gateway gateway = new Gateway()) { emp = gateway.GetEmployee(drecksageCode); } Assert.AreEqual("Barry Drecksage", emp.Name); }
public void updateServerStatusMethod(string status, Gateway p) { lbServerStatus.Text = status; parafaitPaymentGateway = p; if ("Could not connect".Equals(status)) { MessageBox.Show("Could not connect to server", "Connection error", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
public void GenerateGateways() { JSONNode gateways = root ["gateway"]; for (int i=0; i<gateways.Count; i++) { Gateway gateway = new Gateway(); gateway.dest.id = gateways[i]["id"]; gateway.dest.name = gateways[i]["name"]; gateway.dest.map = gateways[i]["map"]; gateway.SetPosition(rooms[gateways[i]["room"].AsInt].GetRandomPosition()); } }
public GetIntradayStatus(Gateway apiGateway, string apiCall) : base(apiGateway, apiCall) { InitializeComponent(); if (ApiCall.CompareTo("Market/Get Intraday Status") == 0) { label1.Visible = false; txtMonth.Visible = false; label2.Visible = false; txtYear.Visible = false; } }
public void AdditionalPropertiesTest() { Gateway gateway = new Gateway(Environment.Development, "API_KEY", "API_SECRET"); string json = "{\"a\":0,\"b\":{\"c\":{\"d\":0}},\"sig\":\"AekURjhSnDivoHlgEdc0m_jBnI0=\",\"ts\":\"TS\"}"; Response response = new TestResponse(gateway, json); Assert.True(response.IsValidSignature, response.ExpectedSignature); json = "{\"a\":0,\"b\":[0,{\"d\":0}],\"sig\":\"Wd24z5rhDUcm63JqpaaSuUqfy4U=\",\"ts\":\"TS\"}"; response = new TestResponse(gateway, json); Assert.True(response.IsValidSignature, response.ExpectedSignature); }
public void CreateFlatExpenseXml() { var builder = new FilterBuilder(); builder.DateRange("entryDate", new DateTime(2011, 2, 1), new DateTime(2011, 3, 15)); JArray expenses = null; using (Gateway gateway = new Gateway()) { expenses = gateway.Client.Search(ObjCode.EXPENSE, builder.Filter).Value<JArray>("data"); } using (StreamWriter writer = new StreamWriter("expenses.xml")) { writer.Write(expenses.ToString()); } }
public GetTimeAndSales(Gateway apiGateway, string apiCall) : base(apiGateway, apiCall) { InitializeComponent(); if(ApiCall.CompareTo("Market/Get Historical Pricing") == 0) { label3.Visible = false; cmbSession.Visible = false; cmbSession.SelectedItem = null; cmbInterval.Items.Clear(); cmbInterval.Items.Add("daily"); cmbInterval.Items.Add("weekly"); cmbInterval.Items.Add("monthly"); } }
public void CreateTimesheetsXml() { var weekEnding = new DateTime(2010, 12, 26); var builder = new FilterBuilder(); builder .AddConstraint("endDate", weekEnding); JArray timesheets = null; using (var gateway = new Gateway()) { timesheets = gateway.Client.Search(ObjCode.TIMESHEET, builder.Filter).Value<JArray>("data"); } using (StreamWriter writer = new StreamWriter("timesheets.xml")) { writer.Write(timesheets.ToString()); } }
public static void Connect(GatewayControl gw) { gw.Invoke(gw.delegateUpdateServerStatus, "Connecting...", null); Gateway parafaitPaymentGateway = new Gateway(); parafaitPaymentGateway = new Gateway(); if (!parafaitPaymentGateway.InitializeDllMode()) { gw.Invoke(gw.delegateUpdateServerStatus, "Could not connect", null); //throw new Exception("Error initializing Parafait External Gateway: " + parafaitPaymentGateway.LastMessageDetails()); //MessageBox.Show("Error initializing Parafait External Gateway", "Init Gateway"); //MessageBox.Show(parafaitPaymentGateway.LastMessageDetails(), "Init Gateway"); } else { gw.Invoke(gw.delegateUpdateServerStatus, "Connected", parafaitPaymentGateway); } }
public CommandPanel(Gateway apiGateway, string apiCall) : base(apiGateway, apiCall) { InitializeComponent(); //Putting the following in Designer.cs hoses the GUI txtAccountId.Text = CommandPanel.AccountId; if (ApiCall.CompareTo("Account/Get History") == 0) { label3.Visible = true; txtOffset.Visible = true; txtPageSize.Visible = true; } else if (ApiCall.CompareTo("Account/Get Order Status") == 0) { label2.Visible = true; txtOrderId.Visible = true; } }
private static void Main(string[] args) { var connString = "Server = 127.0.0.1; Port = 5432; Database = postgres; User Id = postgres; Password = celfinet; "; var gateway = new Gateway<Cell>(connString); gateway.Insert(new Cell { Name = "NAME", Tech = "TECH", Vendor = "VENDOR" }); var output = gateway.Get(); Console.ReadLine(); }
public void Calculate_User_InChargeDays() { // arrange const string userId = "9d3c8120a653cebbe040007f01002438"; var filter = new FilterBuilder(); filter.DateRange("endDate", new DateTime(2010, 11, 22), new DateTime(2010, 11, 28)); Payroll[] payrollItems = null; // act using (Gateway gateway = new Gateway()) { payrollItems = gateway.GetTimesheetsByFilter(filter); } // assert Payroll payroll = payrollItems.Single(x => x.EmployeeID == userId); Console.WriteLine("in charge = {0}", payroll.InChargeDays); Console.WriteLine("mileage = {0}", payroll.TotalMileage); }
public void printGwInfo(Gateway gtw) { ResourcesManager rm = gameObject.GetComponent<ResourcesManager>(); this.gtw = gtw; player = gameObject.GetComponent<NetworkManager>().getCurrentPlayer(); string owner = gtw.getOwner(); GameObject gateway = GameObject.Find("GatewayLabels"); gateway.transform.FindChild("gw_name").GetComponent<UILabel>().text = gtw.getName(); gateway.transform.FindChild("gw_type").GetComponent<UILabel>().text = gtw.getType(); gateway.transform.FindChild("gw_atk").GetComponent<UILabel>().text = gtw.getAtk().ToString(); gateway.transform.FindChild("gw_def").GetComponent<UILabel>().text = gtw.getDef().ToString(); GameObject slot1 = GameObject.Find("Slot1"); GameObject slot2 = GameObject.Find("Slot2"); GameObject slot3 = GameObject.Find("Slot3"); if (owner.Equals(player)) { if (gtw.getSlot(0) != "" || gtw.getSlot(0) != "null") slot1.GetComponent<SpriteRenderer>().sprite = rm.getSlotImage(gtw.getSlot(0)); else slot1.GetComponent<SpriteRenderer>().sprite = rm.getEmptySlot(); if (gtw.getSlot(1) != "" || gtw.getSlot(0) != "null") slot2.GetComponent<SpriteRenderer>().sprite = rm.getSlotImage(gtw.getSlot(1)); else slot2.GetComponent<SpriteRenderer>().sprite = rm.getEmptySlot(); if (gtw.getSlot(2) != "" || gtw.getSlot(0) != "null") slot3.GetComponent<SpriteRenderer>().sprite = rm.getSlotImage(gtw.getSlot(2)); else slot3.GetComponent<SpriteRenderer>().sprite = rm.getEmptySlot(); } else { slot1.GetComponent<SpriteRenderer>().sprite = rm.getUnknownSlot(); slot2.GetComponent<SpriteRenderer>().sprite = rm.getUnknownSlot(); slot3.GetComponent<SpriteRenderer>().sprite = rm.getUnknownSlot(); } }
public Answer DeleteEventActivity(string activityId) { var answer = Gateway.DeleteActivity(activityId); return(answer); }
public EventRequestingArgs(HttpRequest request, HttpResponse response, Gateway gateway) : base(request, response, gateway) { Cancel = false; }
public ExternalPaymentMethodContext ProcessCallback(Dictionary <string, string> responseData) { try { GatewayMoneybookers.PaymentXmlTransformer <GatewayMoneybookers.VirtualAccountPaymentMethod> paymentTransformer = new GatewayMoneybookers.PaymentXmlTransformer <GatewayMoneybookers.VirtualAccountPaymentMethod>(); GatewayMoneybookers.PaymentResponse paymentResponse = paymentTransformer.TransformResponse(responseData["response"]); string result = String.Format("{0} - {1} - {2} - {3}", paymentResponse.Result, paymentResponse.Status, paymentResponse.Reason, paymentResponse.Return); if (paymentResponse.Result.ToUpperInvariant() != "ACK") { ErrorMessage errorMessage = new ErrorMessage(AspDotNetStorefrontCore.AppLogic.GetString("checkoutpayment.aspx.35", Customer.Current.SkinID, Customer.Current.LocaleSetting)); string redirectUrl = String.Format("{0}shoppingcart.aspx?ErrorMsg={1}", AppLogic.GetStoreHTTPLocation(false), errorMessage.MessageId); return(new ExternalPaymentMethodContext(result, redirectUrl, new Dictionary <string, string>())); } int customerId = Int32.Parse(paymentResponse.SessionId); Customer customer = new Customer(customerId); ShoppingCart cart = new ShoppingCart(customer.SkinID, customer, CartTypeEnum.ShoppingCart, 0, false); Address billingAddress = new Address(); billingAddress.LoadByCustomer(customer.CustomerID, customer.PrimaryBillingAddressID, AddressTypes.Billing); billingAddress.ClearCCInfo(); billingAddress.UpdateDB(); var expectedTransactionId = GenerateTransactionId(cart, cart.Total(true)); var receivedTransactionId = DecryptTransactionId(paymentResponse.TransactionId); if (receivedTransactionId != expectedTransactionId) { ErrorMessage errorMessage = new ErrorMessage(AspDotNetStorefrontCore.AppLogic.GetString("checkoutpayment.aspx.38", Customer.Current.SkinID, Customer.Current.LocaleSetting)); string redirectUrl = String.Format("{0}shoppingcart.aspx?ErrorMsg={1}", AppLogic.GetStoreHTTPLocation(false), errorMessage.MessageId); return(new ExternalPaymentMethodContext(result, redirectUrl, new Dictionary <string, string>())); } int orderNumber = AppLogic.GetNextOrderNumber(); String status = Gateway.MakeOrder(Gateway.ro_GWMONEYBOOKERS, AppLogic.TransactionMode(), cart, orderNumber, String.Empty, String.Empty, String.Empty, String.Empty); if (status != AppLogic.ro_OK) { throw new Exception("Gateway processing error: " + result); } string sql = String.Format("update Orders set AuthorizationResult={0}, PaymentGateway='MoneybookersQuickCheckout', AuthorizationPNREF={1}, TransactionCommand=null, AuthorizedOn=getDate() where OrderNumber={2}", DB.SQuote(paymentResponse.Return), DB.SQuote(String.Format("AUTH={0}|CAPTURE={0}", paymentResponse.TransactionUniqueId)), orderNumber); DB.ExecuteSQL(sql); Gateway.ProcessOrderAsCaptured(orderNumber); return(new ExternalPaymentMethodContext(result, AppLogic.GetStoreHTTPLocation(false) + "orderconfirmation.aspx?ordernumber=" + orderNumber, new Dictionary <string, string>())); } catch (Exception exception) { string result = "Error processing order: " + exception.ToString(); ErrorMessage errorMessage = new ErrorMessage(AspDotNetStorefrontCore.AppLogic.GetString("checkoutpayment.aspx.35", Customer.Current.SkinID, Customer.Current.LocaleSetting)); string redirectUrl = String.Format("{0}shoppingcart.aspx?ErrorMsg={1}", AppLogic.GetStoreHTTPLocation(false), errorMessage.MessageId); return(new ExternalPaymentMethodContext(result, redirectUrl, new Dictionary <string, string>())); } }
public IActionResult ViewEventHistory(string eventId) { var vm = Gateway.CreateEventHistory(eventId); return(View(vm)); }
protected override void OnInit(EventArgs e) { int CustomerID = ThisCustomer.CustomerID; int OrderNumber = CommonLogic.QueryStringUSInt("OrderNumber"); StringBuilder output = new StringBuilder(); if (CustomerID != 0 && OrderNumber != 0) { Order ord = new Order(OrderNumber, ThisCustomer.LocaleSetting); if (ThisCustomer.CustomerID != ord.CustomerID) { Response.Redirect(SE.MakeDriverLink("ordernotfound")); } if (ThisCustomer.ThisCustomerSession["3DSecure.LookupResult"].Length > 0) { DB.ExecuteSQL("update orders set CardinalLookupResult=" + DB.SQuote(ThisCustomer.ThisCustomerSession["3DSecure.LookupResult"]) + " where OrderNumber=" + OrderNumber.ToString()); } ThisCustomer.ThisCustomerSession.Clear(); String ReceiptURL = "receipt.aspx?ordernumber=" + OrderNumber.ToString() + "&customerid=" + CustomerID.ToString(); bool orderexists; using (SqlConnection conn = DB.dbConn()) { conn.Open(); using (IDataReader rs = DB.GetRS("select * from dbo.orders where customerid=" + CustomerID.ToString() + " and ordernumber=" + OrderNumber.ToString(), conn)) { orderexists = rs.Read(); } } if (orderexists) { String PM = AppLogic.CleanPaymentMethod(ord.PaymentMethod); String StoreName = AppLogic.AppConfig("StoreName"); bool UseLiveTransactions = AppLogic.AppConfigBool("UseLiveTransactions"); if (!ord.AlreadyConfirmed) { // check to see if this was an "admin edit order" and if so, cleanup the old order, as it was being replaced by this new order: int EditingOrderNumber = base.EditingOrderImpersonation; if (base.IsInImpersonation && EditingOrderNumber != 0) { Order editedOrder = new Order(EditingOrderNumber, Localization.GetDefaultLocale()); if (!editedOrder.HasBeenEdited && editedOrder.TransactionState == AppLogic.ro_TXStateAuthorized || editedOrder.TransactionState == AppLogic.ro_TXStateCaptured) { editedOrder.EditedOn = System.DateTime.Now; editedOrder.RelatedOrderNumber = OrderNumber; // try void first, or refund if that doesn't work if (Gateway.OrderManagement_DoVoid(editedOrder, Localization.GetDefaultLocale()) != AppLogic.ro_OK) { Gateway.OrderManagement_DoFullRefund(editedOrder, Localization.GetDefaultLocale(), "Order Was Edited, New Order #: " + OrderNumber.ToString()); } } base.AdminImpersonatingCustomer.ThisCustomerSession.ClearVal("IGD_EDITINGORDER"); } DB.ExecuteSQL("update Customer set OrderOptions=NULL, OrderNotes=NULL, FinalizationData=NULL where CustomerID=" + CustomerID.ToString()); AppLogic.SendOrderEMail(ThisCustomer, OrderNumber, false, PM, true, base.EntityHelpers, base.GetParser); } String XmlPackageName = AppLogic.AppConfig("XmlPackage.OrderConfirmationPage"); if (XmlPackageName.Length == 0) { XmlPackageName = "page.orderconfirmation.xml.config"; } if (XmlPackageName.Length != 0) { output.Append(AppLogic.RunXmlPackage(XmlPackageName, base.GetParser, ThisCustomer, SkinID, String.Empty, "OrderNumber=" + OrderNumber.ToString(), true, true)); } if (!ord.AlreadyConfirmed) { if (AppLogic.AppConfigBool("IncludeGoogleTrackingCode")) { Topic GoogleTrackingCode = new Topic("GoogleTrackingCode"); if (GoogleTrackingCode.Contents.Length != 0) { output.Append(GoogleTrackingCode.Contents.Replace("(!ORDERTOTAL!)", Localization.CurrencyStringForGatewayWithoutExchangeRate(ord.Total(true))).Replace("(!ORDERNUMBER!)", OrderNumber.ToString()).Replace("(!CUSTOMERID!)", ThisCustomer.CustomerID.ToString())); } } if (AppLogic.AppConfigBool("IncludeOvertureTrackingCode")) { Topic OvertureTrackingCode = new Topic("OvertureTrackingCode"); if (OvertureTrackingCode.Contents.Length != 0) { output.Append(OvertureTrackingCode.Contents.Replace("(!ORDERTOTAL!)", Localization.CurrencyStringForGatewayWithoutExchangeRate(ord.Total(true))).Replace("(!ORDERNUMBER!)", OrderNumber.ToString()).Replace("(!CUSTOMERID!)", ThisCustomer.CustomerID.ToString())); } } Topic GeneralTrackingCode = new Topic("ConfirmationTracking"); if (GeneralTrackingCode.Contents.Length != 0) { output.Append(GeneralTrackingCode.Contents.Replace("(!ORDERTOTAL!)", Localization.CurrencyStringForGatewayWithoutExchangeRate(ord.Total(true))).Replace("(!ORDERNUMBER!)", OrderNumber.ToString()).Replace("(!CUSTOMERID!)", ThisCustomer.CustomerID.ToString())); } if (AppLogic.AppConfigBool("Google.EcomOrderTrackingEnabled") && AppLogic.AppConfigBool("Google.DeprecatedEcomTokens.Enabled")) { output.Append(MobileGetGoogleEComTrackingV2(ThisCustomer, true)); } } DB.ExecuteSQL("Update Orders set AlreadyConfirmed=1 where OrderNumber=" + OrderNumber.ToString()); } else { output.Append("<div align=\"center\">"); output.Append(""); output.Append(AppLogic.GetString("orderconfirmation.aspx.19", SkinID, ThisCustomer.LocaleSetting)); output.Append(""); output.Append("</div>"); } } else { output.Append("<p><b>Error: Invalid Customer ID or Invalid Order Number</b></p>"); } if (!ThisCustomer.IsRegistered || AppLogic.AppConfigBool("ForceSignoutOnOrderCompletion")) { if (AppLogic.AppConfigBool("SiteDisclaimerRequired")) { Profile.SiteDisclaimerAccepted = string.Empty; } //V3_9 Kill the Authentication ticket. Session.Clear(); Session.Abandon(); FormsAuthentication.SignOut(); ThisCustomer.Logout(); } litOutput.Text = output.ToString(); base.OnInit(e); }
private void Seed() { using (var context = new MusalaContext(ContextOptions)) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); var gateway1 = new Gateway() { Ipv4 = "10.98.87.1", Name = "Gateway 1", }; var gateway2 = new Gateway() { Ipv4 = "10.98.87.1", Name = "Gateway 2", }; List <Gateway> gateways = new List <Gateway>() { gateway1, gateway2, new Gateway { Ipv4 = "34.23.168.1", Name = "Gateway 3" } , new Gateway { Ipv4 = "34.23.4.1", Name = "Gateway 4" }, new Gateway { Ipv4 = "34.23.5.1", Name = "Gateway 5" }, new Gateway { Ipv4 = "34.23.6.1", Name = "Gateway 6" } }; List <Device> peripherals = new List <Device>(); for (int i = 0; i < 10; i++) { peripherals.Add(new Device() { Vendor = $"Device {i+1}", Status = true, DateCreation = DateTime.Now, Gateway = gateway1, }); if (i < 9) { peripherals.Add(new Device() { Vendor = $"Device {i + 11}", Status = true, DateCreation = DateTime.Now, Gateway = gateway2, }); } } context.Gateway.AddRange(gateways); context.Peripheral.AddRange(peripherals); context.SaveChanges(); } }
public virtual Task StartAsync(CancellationToken cancellationToken) { g = new Gateway(); g.Open(); return(Task.CompletedTask); }
/// <summary> /// This method returns the number of items imported /// </summary> /// <param name="text">The contents to be imported.</param> /// <param name="tableName">Only used in cases where more than one import takes place.</param> /// <param name="expectedCount">Number of expected columns in the csv file</param> /// <param name="callback">The method to call to update progress</param> /// <returns></returns> public static int ImportData(string text, string tableName, int expectedCount, ImportProgressCallback callback) { // initial value int savedCount = 0; // locals char[] delimiters = { ',' }; int count = 0; int totalCount = 0; int refreshRate = 5; List <Word> words = null; RawImport rawImport = null; // if the fileExists if (TextHelper.Exists(text)) { // Create a new instance of a 'Gateway' object. Gateway gateway = new Gateway(); // set the textLines List <TextLine> textLines = WordParser.GetTextLines(text.Trim()); // If the textLines collection exists and has one or more items if (ListHelper.HasOneOrMoreItems(textLines)) { // notify the callback to setup the Graph - table name is optional if you have more than one import callback(textLines.Count, "RawImport"); // change the RefreshRate if (textLines.Count > 1000) { // change this to whatever makes since for your app refreshRate = 25; } // set the totalCount totalCount = textLines.Count - 1; // Iterate the collection of TextLine objects foreach (TextLine textLine in textLines) { // Increment the value for count count++; // skip the first row if (count > 1) { // get the list of words words = WordParser.GetWords(textLine.Text, delimiters, true); // if the words collection has exactly the right amount if ((ListHelper.HasOneOrMoreItems(words)) && (words.Count == expectedCount)) { // Create a new instance of a 'RawImport' object. rawImport = new RawImport(); // Load the RawImport with the words SetRawImportProperties(ref rawImport, words); // save the rawImport object bool saved = gateway.SaveRawImport(ref rawImport); // if the value for saved is true if (saved) { // Increment the value for savedCount savedCount++; // refresh every x number of records if (savedCount % refreshRate == 0) { // update the graph (for a large project, you might want to update every 25, 50 or 100 records or so callback(savedCount, tableName); } } } } } } } // return value return(savedCount); }
public IActionResult CreateUpdateEvent(string eventId = null) { var viewModel = Gateway.GetEventViewModel(eventId); return(View("CreateUpdateEvent", viewModel)); }
public override void WriteFiles(Dictionary <string, object> files) { Gateway.WriteGistFiles(GistId, files); ClearGist(); }
/// <summary> /// A tab button was clicked. /// </summary> /// <param name="buttonText"></param> public void OnTabButtonClicked(TabButton tabButton) { // determine action by the button text switch (tabButton.ButtonText) { case "Add": // Set the ActionType this.ActionType = ActionTypeEnum.AddButtonClicked; // If the ParentCustomMethodsEditorForm object exists if (this.HasParentCustomMethodsEditorForm) { // Close the parent form this.ParentCustomMethodsEditorForm.Close(); } // required break; case "Edit": // Select Edit Edit(); // required break; case "Delete": // If the SelectedMethod object exists if ((this.HasSelectedMethod) && (this.HasSelectedTable)) { // Show the user a message string message = "Are you sure you wish to delete this method? This action cannot be undone."; string title = "Confirm Delete"; // Get Dialog Result DialogResult result = MessageBox.Show(message, title, MessageBoxButtons.YesNo, MessageBoxIcon.Question); // if user choose 'Yes' if (result == DialogResult.Yes) { // user confirmed the delete // Create a new instance of a 'Gateway' object. Gateway gateway = new Gateway(); // perform the delete bool deleted = gateway.DeleteMethod(this.selectedMethod.MethodId); // if the value for deleted is true if (deleted) { // load the Methods for the SelectedTable this.SelectedTable.Methods = gateway.LoadMethodsForTable(this.SelectedTable.TableId); // Set the MethodsList MethodsList = this.SelectedTable.Methods; // Just to make sure the caller knows no action is required (should already be set to NoAction value) ActionType = ActionTypeEnum.NoAction; // Erase the SelectedMethod this.SelectedMethod = null; // Make sure the buttons are not enabled with a selected item MethodsListBox_SelectedIndexChanged(this, new EventArgs()); } } } // required break; } }
public async Task <Answer> ResetPassword(string id) { var answer = await Gateway.ResetPassword(id); return(answer); }
public void Any(SGPublishPostExternalVoid request) { request.Value += "> " + Request.Verb + " " + nameof(SGPublishPostExternalVoid); Gateway.Publish(request.ConvertTo <SGSyncPostExternalVoid>()); }
public Answer DeleteAgeRestriction(string restrictionId) { return(Gateway.DeleteAgeRestriction(restrictionId)); }
public object Any(SGSendSyncGetAsyncObjectExternal request) { request.Value += "> " + Request.Verb + " " + nameof(SGSendSyncGetAsyncObjectExternal); return(Gateway.SendAsync <object>(request.ConvertTo <SGSyncGetAsyncObjectExternal>())); }
public object Any(SGSyncPostValidationExternal request) { request.Value += "> " + Request.Verb + " " + typeof(SGSyncPostValidationExternal).Name; return(Gateway.Send(request.ConvertTo <SGSyncPostValidationInternal>())); }
public ServerCenter(Gateway gateway) { Gateway = gateway; mAgents = new ConcurrentDictionary <string, ServerAgent>(); }
public IActionResult UpdateEventActivity(string activityId) { var viewModel = Gateway.GetActivityViewModel(activityId); return(CreateUpdateEventActivity(viewModel)); }
public IActionResult UpdateEventAgeRestriction(string restrictionId) { var viewModel = Gateway.GetAgeRestrictionViewModel(restrictionId); return(CreateUpdateEventAgeRestriction(viewModel)); }
public RouteCenter(Gateway gateway) { Gateway = gateway; Default = new UrlRoute(gateway, "*", string.Empty); }
public object Any(SGSendSyncGetSyncObjectInternal request) { request.Value += "> " + Request.Verb + " " + typeof(SGSendSyncGetSyncObjectInternal).Name; return(Gateway.Send <object>(request.ConvertTo <SGSyncGetSyncObjectInternal>())); }
/// <summary> /// Executes the POST method on the resource. /// </summary> /// <param name="Request">HTTP Request</param> /// <param name="Response">HTTP Response</param> /// <exception cref="HttpException">If an error occurred when processing the method.</exception> public void POST(HttpRequest Request, HttpResponse Response) { Gateway.AssertUserAuthenticated(Request); if (!Request.HasData) { throw new BadRequestException(); } object Obj = Request.DecodeData(); if (!(Obj is Dictionary <string, object> Parameters)) { throw new BadRequestException(); } if (!Parameters.TryGetValue("repair", out Obj) || !(Obj is bool Repair)) { throw new BadRequestException(); } if (!CanStartAnalyzeDB()) { Response.StatusCode = 409; Response.StatusMessage = "Conflict"; Response.ContentType = "text/plain"; Response.Write("Analysis is underway."); return; } string BasePath = Export.FullExportFolder; if (!Directory.Exists(BasePath)) { Directory.CreateDirectory(BasePath); } BasePath += Path.DirectorySeparatorChar; string FullFileName = Path.Combine(BasePath, "DBReport " + DateTime.Now.ToString("yyyy-MM-dd HH_mm_ss")); FullFileName = StartExport.GetUniqueFileName(FullFileName, ".xml"); FileStream fs = null; try { fs = new FileStream(FullFileName, FileMode.Create, FileAccess.Write); DateTime Created = File.GetCreationTime(FullFileName); XmlWriter XmlOutput = XmlWriter.Create(fs, XML.WriterSettings(true, false)); string FileName = FullFileName.Substring(BasePath.Length); Task.Run(() => DoAnalyze(FullFileName, FileName, Created, XmlOutput, fs, Repair)); Response.StatusCode = 200; Response.ContentType = "text/plain"; Response.Write(FileName); Response.SendResponse(); } catch (Exception ex) { if (!(fs is null)) { fs.Dispose(); File.Delete(FullFileName); } Response.SendResponse(ex); } }
private void Page_Load(object sender, System.EventArgs e) { Response.CacheControl = "private"; Response.Expires = -1; Response.AddHeader("pragma", "no-cache"); Response.Cache.SetAllowResponseInBrowserHistory(false); Customer ThisCustomer = ((AspDotNetStorefrontPrincipal)Context.User).ThisCustomer; ThisCustomer.RequireCustomerRecord(); int CustomerID = ThisCustomer.CustomerID; String Payload = ThisCustomer.ThisCustomerSession["Cardinal.Payload"]; String PaRes = CommonLogic.FormCanBeDangerousContent("PaRes"); String TransactionID = ThisCustomer.ThisCustomerSession["Cardinal.TransactionID"]; int OrderNumber = ThisCustomer.ThisCustomerSession.SessionUSInt("Cardinal.OrderNumber"); String ReturnURL = String.Empty; if (ShoppingCart.CartIsEmpty(CustomerID, CartTypeEnum.ShoppingCart)) { ReturnURL = "ShoppingCart.aspx"; } ErrorMessage err; if (ReturnURL.Length == 0) { if (OrderNumber == 0) { err = new ErrorMessage(Server.HtmlEncode(AppLogic.GetString("cardinal_process.aspcs.cs.1", 1, Localization.GetDefaultLocale()))); ReturnURL = "checkoutpayment.aspx?error=1&errormsg=" + err.MessageId; } } if (ReturnURL.Length == 0) { if (Payload.Length == 0 || TransactionID.Length == 0) { err = new ErrorMessage(Server.HtmlEncode(AppLogic.GetString("cardinal_process.aspcs.cs.1", 1, Localization.GetDefaultLocale()))); ReturnURL = "checkoutpayment.aspx?error=1&errormsg=" + err.MessageId; } } String PAResStatus = String.Empty; String SignatureVerification = String.Empty; String ErrorNo = String.Empty; String ErrorDesc = String.Empty; ShoppingCart cart = new ShoppingCart(1, ThisCustomer, CartTypeEnum.ShoppingCart, 0, false); if (ReturnURL.Length == 0) { String CardinalAuthenticateResult = String.Empty; String AuthResult = Cardinal.PreChargeAuthenticate(OrderNumber, PaRes, TransactionID, out PAResStatus, out SignatureVerification, out ErrorNo, out ErrorDesc, out CardinalAuthenticateResult); ThisCustomer.ThisCustomerSession["Cardinal.AuthenticateResult"] = CardinalAuthenticateResult; //===================================================================================== // Determine if the Authentication was Successful or Error // // Please consult the documentation regarding the handling of each response scenario. // // If the Authentication results (PAResStatus) is a Y or A, and the SignatureVerification is Y, then // the Payer Authentication was successful. The Authorization Message should be processed, // and the User taken to a Order Confirmation location. // // If the Authentication results were not successful (PAResStatus = N), or // the ErrorNo was NOT //0// then the Consumer should be redirected, and prompted for another // form of payment. // // If the Authentication results were not successful (PAResStatus = U) and the ErrorNo = //0// // then authorization message should be processed. In this case the merchant will retain // liability for this transaction if it is sent to authorization. // // Note that it is also important that you account for cases when your flow logic can account // for error cases, and the flow can be broken after //N// number of attempts //===================================================================================== // handle success cases: if (((PAResStatus == "Y" || PAResStatus == "A") && SignatureVerification == "Y") || (PAResStatus == "U" && ErrorNo == "0")) { // GET CAVV from authenticate call result: String CAVV = CommonLogic.ExtractToken(ThisCustomer.ThisCustomerSession["Cardinal.AuthenticateResult"], "<Cavv>", "</Cavv>"); String ECI = CommonLogic.ExtractToken(ThisCustomer.ThisCustomerSession["Cardinal.AuthenticateResult"], "<EciFlag>", "</EciFlag>"); String XID = CommonLogic.ExtractToken(ThisCustomer.ThisCustomerSession["Cardinal.AuthenticateResult"], "<Xid>", "</Xid>"); Address UseBillingAddress = new Address(); UseBillingAddress.LoadByCustomer(ThisCustomer.CustomerID, ThisCustomer.PrimaryBillingAddressID, AddressTypes.Billing); String status = Gateway.MakeOrder(String.Empty, AppLogic.TransactionMode(), cart, OrderNumber, CAVV, ECI, XID, String.Empty); if (status != AppLogic.ro_OK) { err = new ErrorMessage(status); ReturnURL = "checkoutpayment.aspx?error=1&errormsg=" + err.MessageId; } else { // store cardinal call results for posterity: DB.ExecuteSQL("update orders set CardinalLookupResult=" + DB.SQuote(ThisCustomer.ThisCustomerSession["Cardinal.LookupResult"]) + ", CardinalAuthenticateResult=" + DB.SQuote(ThisCustomer.ThisCustomerSession["Cardinal.AuthenticateResult"]) + " where OrderNumber=" + OrderNumber.ToString()); ReturnURL = "orderconfirmation.aspx?ordernumber=" + OrderNumber.ToString() + "&paymentmethod=Credit+Card"; } } // handle failure: if (PAResStatus == "N" || ErrorNo != "0") { err = new ErrorMessage(Server.HtmlEncode(AppLogic.GetString("cardinal_process.aspx.3", 1, Localization.GetDefaultLocale()))); ReturnURL = "checkoutpayment.aspx?error=1&errormsg=" + err.MessageId; } // handle failure: if (SignatureVerification == "N" || ErrorNo != "0") { err = new ErrorMessage(Server.HtmlEncode(AppLogic.GetString("cardinal_process.aspx.4", 1, Localization.GetDefaultLocale()))); ReturnURL = "checkoutpayment.aspx?error=1&errormsg=" + err.MessageId; } } if (ReturnURL.Length == 0) { err = new ErrorMessage(Server.HtmlEncode(String.Format(AppLogic.GetString("cardinal_process.aspx.5", 1, Localization.GetDefaultLocale()), ErrorDesc))); ReturnURL = "checkoutpayment.aspx?error=1&errormsg=" + err.MessageId; } ReturnURL = GetSmartOPCReturnURL(ReturnURL, ThisCustomer, cart); ThisCustomer.ThisCustomerSession["Cardinal.LookupResult"] = String.Empty; ThisCustomer.ThisCustomerSession["Cardinal.AuthenticateResult"] = String.Empty; ThisCustomer.ThisCustomerSession["Cardinal.ACSUrl"] = String.Empty; ThisCustomer.ThisCustomerSession["Cardinal.Payload"] = String.Empty; ThisCustomer.ThisCustomerSession["Cardinal.TransactionID"] = String.Empty; ThisCustomer.ThisCustomerSession["Cardinal.OrderNumber"] = String.Empty; ThisCustomer.ThisCustomerSession["Cardinal.LookupResult"] = String.Empty; Response.CacheControl = "private"; Response.Expires = 0; Response.AddHeader("pragma", "no-cache"); Response.Write("<html><head><title>Cardinal Process</title></head><body>"); Response.Write("<script type=\"text/javascript\">\n"); Response.Write("top.location='" + ReturnURL + "';\n"); Response.Write("</SCRIPT>\n"); Response.Write("<div align=\"center\">" + String.Format(AppLogic.GetString("cardinal_process.aspx.6", 1, Localization.GetDefaultLocale()), ReturnURL) + "</div>"); Response.Write("</body></html>"); }
internal void SetGateway(Gateway gateway) { this.gateway = gateway; }
public EventAgentRequestingArgs(HttpRequest request, HttpResponse response, Gateway gateway, Servers.ServerAgent server, Routes.UrlRoute urlRoute) : base(request, response, gateway) { Server = server; UrlRoute = urlRoute; }
static void Main(string[] args) { try { System.Console.ForegroundColor = ConsoleColor.White; System.Console.Out.WriteLine("Welcome to the Internet of Things Gateway server application."); System.Console.Out.WriteLine(new string('-', 79)); System.Console.Out.WriteLine("This server application will help you manage IoT devices and"); System.Console.Out.WriteLine("create dynamic content that you can publish on the Internet."); System.Console.Out.WriteLine("It also provides programming interfaces (API) which allow you"); System.Console.Out.WriteLine("to dynamically and securely interact with the devices and the"); System.Console.Out.WriteLine("content you publish."); Log.Register(new ConsoleEventSink(false)); Log.RegisterExceptionToUnnest(typeof(System.Runtime.InteropServices.ExternalException)); Log.RegisterExceptionToUnnest(typeof(System.Security.Authentication.AuthenticationException)); AppDomain.CurrentDomain.UnhandledException += (sender, e) => { if (e.IsTerminating) { using (StreamWriter w = File.CreateText(Path.Combine(Gateway.AppDataFolder, "UnhandledException.txt"))) { w.Write("Type: "); if (e.ExceptionObject != null) { w.WriteLine(e.ExceptionObject.GetType().FullName); } else { w.WriteLine("null"); } w.Write("Time: "); w.WriteLine(DateTime.Now.ToString()); w.WriteLine(); if (e.ExceptionObject is Exception ex) { w.WriteLine(ex.Message); w.WriteLine(); w.WriteLine(ex.StackTrace); } else { if (e.ExceptionObject != null) { w.WriteLine(e.ExceptionObject.ToString()); } w.WriteLine(); w.WriteLine(Environment.StackTrace); } w.Flush(); } } if (e.ExceptionObject is Exception ex2) { Log.Critical(ex2); } else if (e.ExceptionObject != null) { Log.Critical(e.ExceptionObject.ToString()); } else { Log.Critical("Unexpected null exception thrown."); } }; Gateway.GetDatabaseProvider += GetDatabase; Gateway.GetXmppClientCredentials += GetXmppClientCredentials; Gateway.XmppCredentialsUpdated += XmppCredentialsUpdated; Gateway.RegistrationSuccessful += RegistrationSuccessful; if (!Gateway.Start(true).Result) { System.Console.Out.WriteLine(); System.Console.Out.WriteLine("Gateway being started in another process."); return; } ManualResetEvent Done = new ManualResetEvent(false); System.Console.CancelKeyPress += (sender, e) => Done.Set(); try { SetConsoleCtrlHandler((ControlType) => { switch (ControlType) { case CtrlTypes.CTRL_BREAK_EVENT: case CtrlTypes.CTRL_CLOSE_EVENT: case CtrlTypes.CTRL_C_EVENT: case CtrlTypes.CTRL_SHUTDOWN_EVENT: Done.Set(); break; case CtrlTypes.CTRL_LOGOFF_EVENT: break; } return(true); }, true); } catch (Exception) { Log.Error("Unable to register CTRL-C control handler."); } while (!Done.WaitOne(1000)) { ; } } catch (Exception ex) { Log.Critical(ex); } finally { Gateway.Stop(); Log.Terminate(); } }
public Pluginer(Gateway gateway, Routes.UrlRoute urlRoute) { Gateway = gateway; UrlRoute = urlRoute; }
public object Any(SGSendSyncPostInternal request) { request.Value += "> " + Request.Verb + " " + nameof(SGSendSyncPostInternal); return(Gateway.Send(request.ConvertTo <SGSyncPostInternal>())); }
public IActionResult Index() { var viewModel = Gateway.BuildLanding(); return(View(viewModel)); }
public IActionResult ManageSearch(string searchWords, int page = 0, int perPage = ResultsPerPage) { var viewModel = Gateway.BuildIndex(DisplayPagination.BuildForGateway(page, perPage), searchWords); return(View("Manage", viewModel)); }