private static Map InitializeMapGoogle(GoogleMapType mt) { Map map = new Map(); GoogleRequest req; ITileSource tileSource; TileLayer tileLayer; if (mt == (GoogleMapType.GoogleSatellite | GoogleMapType.GoogleLabels)) { req = new GoogleRequest(GoogleMapType.GoogleSatellite); tileSource = new GoogleTileSource(req); tileLayer = new TileLayer(tileSource, "TileLayer - " + GoogleMapType.GoogleSatellite); map.Layers.Add(tileLayer); req = new GoogleRequest(GoogleMapType.GoogleLabels); tileSource = new GoogleTileSource(req); mt = GoogleMapType.GoogleLabels; } else { req = new GoogleRequest(mt); tileSource = new GoogleTileSource(req); } tileLayer = new TileLayer(tileSource, "TileLayer - " + mt); map.Layers.Add(tileLayer); map.ZoomToBox(tileLayer.Envelope); return(map); }
public static SharpMap.Map InitializeGoogleMap(GoogleMapType mt) { SharpMap.Map map = new SharpMap.Map(); GoogleRequest req; ITileSource tileSource; TileAsyncLayer tileLayer; if (mt == (GoogleMapType.GoogleSatellite | GoogleMapType.GoogleLabels)) { req = new GoogleRequest(GoogleMapType.GoogleSatellite); tileSource = new GoogleTileSource(req); tileLayer = new TileAsyncLayer(tileSource, "TileLayer - " + GoogleMapType.GoogleSatellite); map.Layers.Add(tileLayer); req = new GoogleRequest(GoogleMapType.GoogleLabels); tileSource = new GoogleTileSource(req); mt = GoogleMapType.GoogleLabels; } else { req = new GoogleRequest(mt); tileSource = new GoogleTileSource(req); } tileLayer = new TileAsyncLayer(tileSource, "TileLayer - " + mt); map.BackgroundLayer.Add(tileLayer); map.ZoomToBox(tileLayer.Envelope); return(map); }
public async Task <IHttpActionResult> GoogleAsync([FromBody] GoogleRequest request) { User user; user = await UnitOfWork.GetUserRepository().SelectFirstOrDefaultAsync(r => r.Email == request.Email); if (user == null) { Registration registration = await _registrationService.RegisterAsync(registrationType : RegistrationType.Google, email : request.Email, firstName : request.FirstName, lastName : request.LastName, birthDt : request.BirthDay, gender : request.Gender); user = registration.User; } else if (user.Registration.Type.Equals(RegistrationType.Email)) { throw new ActionCannotBeExecutedException(ExceptionMessages.WrongRegistrationType); } if (!user.GoogleToken.Equals(request.GoogleToken)) { user.GoogleToken = request.GoogleToken; } (string accessToken, System.Guid guid, User user)result = await _loginService.LoginAsync(LoginType.Google, request.Email); LoginResposne response = new LoginResposne { AccessToken = result.accessToken, RefreshToken = result.guid, Role = result.user.Role }; await UnitOfWork.SaveChangesAsync(); return(Ok(response)); }
/// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='request'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <object> PostAsync(this ISmartHome operations, GoogleRequest request, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PostWithHttpMessagesAsync(request, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
async Task <IActionResult> QUERY(GoogleRequest request) { //https://developers.google.com/actions/smarthome/create#actiondevicesquery var payload = request.inputs.First().payload as PayLoads.DevicesQueryInputPayload; var response = new GoogleResponse <PayLoads.DeviceQueryPayload>(request); return(Ok(response)); }
private IActionResult ResponseForFacebook(GoogleRequest data1) { _logger.LogInformation("facebook"); var attachments = data1?.OriginalDetectIntentRequest?.Payload?.Data?.Message?.Attachments; if (attachments != null && attachments.Any(x => x.Type.Equals("image", _stringcompare))) { _logger.LogInformation("pic is sent, creating"); var entity = new Litter { UserId = data1.OriginalDetectIntentRequest.Payload.Data.Sender.Id, ImageUrl = attachments.First().Payload.Url }; _context.Litters.Add(entity); _context.SaveChanges(); return(ResponseShareLocation()); } else if (data1?.OriginalDetectIntentRequest?.Payload?.Data?.Postback?.Payload != null && data1.OriginalDetectIntentRequest.Payload.Data.Postback.Payload.Contains("LOCATION", _stringcompare)) { _logger.LogInformation("Location is sent, updating "); var coords = data1?.OriginalDetectIntentRequest?.Payload?.Data?.Postback?.Data; if (coords == null) { return(BadRequest()); } var userId = data1.OriginalDetectIntentRequest.Payload.Data.Sender.Id; var litters = _context.Litters //litters without lat/long/num saved .Where(x => x.UserId == userId && x.CigarettesNum <= 0) .OrderByDescending(x => x.CreatedAt) .ToArray(); var litter = litters.FirstOrDefault(); //newest one if (litter != null) { _context.Litters.RemoveRange(litters.Skip(1)); litter.CigarettesNum = 1; litter.Lat = coords.Long; litter.Long = coords.Lat; _context.Litters.Update(litter); _context.SaveChanges(); return(ResponseThankYou(userId)); } } return(ResponseUploadPhoto()); }
public async Task Should_Response_Correct_Content_From_Google() { var request = new GoogleRequest(); var result = await _httpClient.SendAndGetResponseAsync(request); Assert.NotNull(result); Assert.True(result.Length > 0); }
async Task <IActionResult> SYNC(GoogleRequest request) { //https://developers.google.com/actions/smarthome/create#actiondevicessync var response = new GoogleResponse <PayLoads.DevicesSyncPayLoad>(request); var UserId = GetUserId(); var GoogleUser = DataContext.GoogleUsers.FirstOrDefault(o => o.UserId == UserId); if (GoogleUser == null) { GoogleUser = new SmartDevices.Devices.GoogleUser { GoogleUserId = Guid.NewGuid(), UserId = UserId, ActivationDate = DateTime.UtcNow, Active = true }; await DataContext.GoogleUsers.AddAsync(GoogleUser); } else { if (GoogleUser.Active == false) { GoogleUser.Active = true; GoogleUser.ActivationDate = DateTime.UtcNow; } } await DataContext.SaveChangesAsync(); response.payload = new PayLoads.DevicesSyncPayLoad { agentUserId = UserId }; var UserDevices = await DataContext.Devices.Where(o => o.UserId == UserId).ToListAsync(); var googleDevices = from e in UserDevices select new ST.SmartDevices.Google.DeviceSYNC { id = e.DeviceId.ToString(), name = new DeviceName { name = e.Name, nicknames = e.NickNames.Select(o => o.NickName)?.ToArray() }, roomHint = e.Piece.Name, traits = e.Traits.Select(o => o.DeviceTraitId)?.ToArray(), type = e.DeviceType?.DeviceTypeId, willReportState = willReportState(e) }; response.payload.devices = googleDevices?.ToArray(); response.payload.agentUserId = UserId; return(Ok(response)); }
public ActionResult Fallback(GoogleRequest result) { var speech = "Sorry, I had an issue with completing your request. Please try again later."; WebhookResponse jsonData = new WebhookResponse { fulfillmentText = speech, // This is what is said back to the user source = "DialogFlow API", }; string str = ser.Serialize(jsonData); return(Json(jsonData, JsonRequestBehavior.AllowGet)); }
// Intents - Different function for each intent public ActionResult IntentNameHere(GoogleRequest result) { var speech = "This string here is what will be said by Google back to the user"; WebhookResponse jsonData = new WebhookResponse { fulfillmentText = speech, // This is what is said back to the user source = "Diagflow API", }; string str = ser.Serialize(jsonData); return(Json(jsonData, JsonRequestBehavior.AllowGet)); }
async Task <IActionResult> EXECUTE(GoogleRequest request) { //https://developers.google.com/actions/smarthome/create#actiondevicesexecute var userId = GetUserId(); var userChannel = SmartHubContext.Clients.User(userId); if (userChannel != null) { await userChannel.NewGoogleAction(Guid.Empty, ""); } var response = new GoogleResponse <PayLoads.DeviceExecuteResponsePayload>(request); return(Ok(response)); }
private IActionResult HandleChatbotRequest(GoogleRequest data1) { var source = data1.OriginalDetectIntentRequest.Source; if (source.Equals("facebook", _stringcompare)) { return(ResponseForFacebook(data1)); } else if (source.Equals("google", _stringcompare)) { return(ResponseForGoogleAssistant()); } else { throw new NotImplementedException("that source is not implemented"); } }
public ContentResult Post([FromBody] GoogleRequest value) { var query = value.queryResult.queryText; var sessionId = value.session; var intent = value.queryResult.intent; _client.SendBotMessage(query, sessionId).Wait(); var replies = _client.ReadBotMessages(sessionId).Result; //TODO: This pulls the last message sent by the bot. Could break for multiple messages sent var reply = replies.LastOrDefault(); var response = new GoogleResponse(reply); var json = Newtonsoft.Json.JsonConvert.SerializeObject(response); var res = json.ToString(); return(Content(json.ToString(), "application/json")); }
static string CreateRequestPayload(string audioPayload, string lang = "en-US") { //Create the Google request JSON GoogleRequest request = new GoogleRequest { audio = new GoogleRequest_Audio { content = audioPayload }, config = new GoogleRequest_Config { enableWordTimeOffsets = false, encoding = "SPEEX_WITH_HEADER_BYTE", languageCode = lang, sampleRateHertz = 16000 } }; //Convert to JSON return(JsonConvert.SerializeObject(request)); }
public async Task <IActionResult> Post(GoogleRequest request) { debug("post"); switch (request.inputs.First()?.intent) { case action.devices.SYNC: return(await SYNC(request)); case action.devices.QUERY: return(await QUERY(request)); case action.devices.EXECUTE: return(await EXECUTE(request)); case action.devices.DISCONNECT: return(await DISCONNECT(request)); default: return(NotFound()); } }
public static string GoogleRequestTitle(GoogleRequest gr) { switch (gr) { case GoogleRequest.None: return("<none>"); case GoogleRequest.UserInfo: return("User Info"); case GoogleRequest.GMail_Messages: return("GMail - Messages"); case GoogleRequest.GMail_Message_Details: return("GMail - Message Details"); case GoogleRequest.GMail_Labels: return("GMail - Labels"); case GoogleRequest.GMail_Threads: return("GMail - Threads"); case GoogleRequest.GMail_History: return("GMail - History"); case GoogleRequest.GMail_Drafts: return("GMail - Drafts"); } return("<unknown>"); }
public ActionResult Index(GoogleRequest result) { try { // Grab intent and run function relative to intent to send back data to Google var intent = result.queryResult.intent.displayName; switch (intent) { case "IntentNameHere": return(IntentNameHere(result)); // function name doesnt have to be same as Intent name default: // Diagflow should throw an error before even reaching this, but it it breaks somehow, run Fallback to say error found return(Fallback(result)); } } catch (Exception e) { // Return a fallback if there is an exception return(Fallback(result)); } }
private async Task ProcessOrderEventAsync(Order order, bool add) { try { //settings per store var store = await _storeService.GetStoreByIdAsync(order.StoreId) ?? await _storeContext.GetCurrentStoreAsync(); var googleAnalyticsSettings = await _settingService.LoadSettingAsync <GoogleAnalyticsSettings>(store.Id); var request = new GoogleRequest { AccountCode = googleAnalyticsSettings.GoogleId, Culture = "en-US", HostName = new Uri(_webHelper.GetThisPageUrl(false)).Host, PageTitle = add ? "AddTransaction" : "CancelTransaction" }; var orderId = order.CustomOrderNumber; var orderShipping = googleAnalyticsSettings.IncludingTax ? order.OrderShippingInclTax : order.OrderShippingExclTax; var orderTax = order.OrderTax; var orderTotal = order.OrderTotal; if (!add) { orderShipping = -orderShipping; orderTax = -orderTax; orderTotal = -orderTotal; } var billingAddress = await _addressService.GetAddressByIdAsync(order.BillingAddressId); var trans = new Transaction(FixIllegalJavaScriptChars(orderId), FixIllegalJavaScriptChars(billingAddress.City), await _countryService.GetCountryByAddressAsync(billingAddress) is Country country ? FixIllegalJavaScriptChars(country.Name) : string.Empty, await _stateProvinceService.GetStateProvinceByAddressAsync(billingAddress) is StateProvince stateProvince ? FixIllegalJavaScriptChars(stateProvince.Name) : string.Empty, store.Name, orderShipping, orderTax, orderTotal); foreach (var item in await _orderService.GetOrderItemsAsync(order.Id)) { var product = await _productService.GetProductByIdAsync(item.ProductId); //get category var category = (await _categoryService.GetCategoryByIdAsync((await _categoryService.GetProductCategoriesByProductIdAsync(product.Id)).FirstOrDefault()?.CategoryId ?? 0))?.Name; var unitPrice = googleAnalyticsSettings.IncludingTax ? item.UnitPriceInclTax : item.UnitPriceExclTax; var qty = item.Quantity; if (!add) { qty = -qty; } var sku = await _productService.FormatSkuAsync(product, item.AttributesXml); if (string.IsNullOrEmpty(sku)) { sku = product.Id.ToString(); } var productItem = new TransactionItem(FixIllegalJavaScriptChars(orderId), FixIllegalJavaScriptChars(sku), FixIllegalJavaScriptChars(product.Name), unitPrice, qty, FixIllegalJavaScriptChars(category)); trans.Items.Add(productItem); } await request.SendRequest(trans, _httpClientFactory.CreateClient(NopHttpDefaults.DefaultHttpClient)); } catch (Exception ex) { await _logger.InsertLogAsync(LogLevel.Error, "Google Analytics. Error canceling transaction from server side", ex.ToString()); } }
async Task <IActionResult> DISCONNECT(GoogleRequest request) { //https://developers.google.com/actions/smarthome/create#actiondevicesdisconnect return(new JsonResult(new { })); }
public GoogleResponse InvokeGoogleService(GoogleRequest request) { GoogleResponse response = new GoogleResponse(); response.Message = "This is a test"; var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = new ClientSecrets { ClientId = "929463394906-lkrivbdgl8k2j4r8e5sm9rk8rcejli21.apps.googleusercontent.com", ClientSecret = "QgSCXEro5F1SdDXGODd0q5EZ" }, Scopes = new[] { CalendarService.Scope.Calendar }, DataStore = new FileDataStore("Drive.Api.Auth.Store") }); var token = new TokenResponse { AccessToken = request.User.AccessToken, RefreshToken = request.User.RefreshToken }; var credential = new UserCredential(flow, Environment.UserName, token); var service = new CalendarService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "ASP.NET MVC Sample" }); var newEvent = new Google.Apis.Calendar.v3.Data.Event() { Summary = "Google I/O 2015", Location = "800 Howard St., San Francisco, CA 94103", Description = "A chance to hear more about Google's developer products.", Start = new EventDateTime() { DateTime = DateTime.Parse("2018-03-01T09:00:00-07:00"), TimeZone = "America/Chicago", }, End = new EventDateTime() { DateTime = DateTime.Parse("2018-03-01T11:00:00-07:00"), TimeZone = "America/Chicago", }, //Recurrence = new string[] { "RRULE:FREQ=DAILY;COUNT=2" }, Attendees = new EventAttendee[] { new EventAttendee() { Email = "*****@*****.**" }, new EventAttendee() { Email = "*****@*****.**" }, }, Reminders = new Google.Apis.Calendar.v3.Data.Event.RemindersData() { UseDefault = false, Overrides = new EventReminder[] { new EventReminder() { Method = "email", Minutes = 24 * 60 }, new EventReminder() { Method = "sms", Minutes = 10 }, } }, Transparency = "transparent" }; EventsResource.InsertRequest apiRequest = service.Events.Insert(newEvent, "primary"); Google.Apis.Calendar.v3.Data.Event createdEvent = apiRequest.Execute(); response.Message = "Google Calendar Event Added: URL = " + createdEvent.HtmlLink; return(response); }
/// <param name='request'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse <object> > PostWithHttpMessagesAsync(GoogleRequest request, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (request == null) { throw new ValidationException(ValidationRules.CannotBeNull, "request"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("request", request); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Post", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "SmartHome/fulfillment").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (request != null) { _requestContent = SafeJsonConvert.SerializeObject(request, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse <object>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject <object>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public static string GoogleRequestBaseUrl(GoogleRequest gr, out string sUriResource, string UserId, string id) { sUriResource = ""; switch (gr) { case GoogleRequest.UserInfo: sUriResource = "/oauth2/v1/userinfo"; return("https://www.googleapis.com"); case GoogleRequest.GMail_Messages: if (UserId.Length == 0) { return(""); } sUriResource = "/" + UserId + "/messages"; return("https://www.googleapis.com/gmail/v1/users"); case GoogleRequest.GMail_Message_Details: if (UserId.Length == 0) { return(""); } if (id.Length == 0) { return(""); } sUriResource = "/" + UserId + "/messages/" + id; return("https://www.googleapis.com/gmail/v1/users"); case GoogleRequest.GMail_Labels: if (UserId.Length == 0) { return(""); } sUriResource = "/" + UserId + "/labels"; return("https://www.googleapis.com/gmail/v1/users"); case GoogleRequest.GMail_Threads: if (UserId.Length == 0) { return(""); } sUriResource = "/" + UserId + "/threads"; return("https://www.googleapis.com/gmail/v1/users"); case GoogleRequest.GMail_History: if (UserId.Length == 0) { return(""); } sUriResource = "/" + UserId + "/history"; return("https://www.googleapis.com/gmail/v1/users"); case GoogleRequest.GMail_Drafts: if (UserId.Length == 0) { return(""); } sUriResource = "/" + UserId + "/drafts"; return("https://www.googleapis.com/gmail/v1/users"); } return(""); }
private void DoLoad(TreeLbItem ti, string sContent, string sID, string sDetails, bool bSaveJSon) { string sErr = ""; RscJSonItem jsonRoot = null; /* * jsonRoot = new RscJSonItem(); * jsonRoot.ID = response.ResponseUri.ToString(); * jsonRoot.Name = "IRestResponse<Object>"; * jsonRoot.AddProperty( "Response Status", response.ResponseStatus.ToString() ); * jsonRoot.AddProperty( "Response Uri", response.ResponseUri.ToString() ); * jsonRoot.AddProperty( "Content Length", response.ContentLength.ToString() ); */ jsonRoot = RscJSon.FromResponseContetn(jsonRoot, sContent, out sErr, sID, sDetails); if (sErr.Length > 0) { LogError(sErr); } if (jsonRoot != null) { // // // string sErrorCode = ""; if (jsonRoot.ChildCount > 0) { if (jsonRoot.GetChild(0).Name == "error") { //For example: Required Scope not specified while LogOn!!! sErrorCode = jsonRoot.GetChildPropertyValue(0, "code"); string sErrorMessage = jsonRoot.GetChildPropertyValue(0, "message"); LogError("Error response:\ncode: " + sErrorCode + "\nmessage: " + sErrorMessage); } } // // // //Show Error JSon!!! //if( sErrorCode.Length == 0 ) { //Try to load result as is... GoogleRequest gr = GoogleUtils.GoogleRequestFromUrl(jsonRoot.ID); switch (gr) { case GoogleRequest.UserInfo: case GoogleRequest.GMail_Messages: case GoogleRequest.GMail_Message_Details: case GoogleRequest.GMail_Labels: case GoogleRequest.GMail_Threads: case GoogleRequest.GMail_History: case GoogleRequest.GMail_Drafts: { ti.SetResponse(jsonRoot); RscStore store = new RscStore(); if (gr == GoogleRequest.UserInfo) { string sUserID = jsonRoot.GetPropertyValue("id"); if (m_sUserIDlast.Length == 0 || m_sUserIDlast != sUserID) { if (sUserID.Length > 0) { m_sUserIDlast = sUserID; store.WriteTextFile(csSecretsFolder + "\\" + "UserIDlast.txt", m_sUserIDlast, true); AddRootContainers(); } } } string sPath = ""; string sFn = ""; if (m_sUserIDlast.Length > 0) { sPath = csSecretsFolder + "\\" + m_sUserIDlast; sFn = Uri2FileName(jsonRoot.ID); } if (bSaveJSon) { if (m_sUserIDlast.Length > 0) { store.CreateFolderPath(sPath); store.WriteTextFile(sPath + "\\" + sFn + ".json", sContent, true); m_btnCleanUp.Visibility = Rsc.Visible; } } if (sErr.Length == 0) { if (sFn.Length > 0) { if (bSaveJSon) { m_AppFrame.StatusText = "Downloaded to " + sPath + "\\" + sFn + ".json"; } else { m_AppFrame.StatusText = "Loaded from " + sPath + "\\" + sFn + ".json"; } } else { if (bSaveJSon) { m_AppFrame.StatusText = "Downloaded..."; } else { m_AppFrame.StatusText = "Loaded..."; } } } break; } default: { //Unexpected... LogError(jsonRoot.ToDecoratedString()); break; } } } } }
override public void Expand() { if (Expanded) { return; } if (!HasResponse) { base.Expand(); return; } PreInserts(); if (m_jsonResponse.ID.Length > 0) { TreeLbItem ti = new TreeLbItem(Holder, this); ti.DetailsOnly = "RscJSonItem.ID" + ": " + m_jsonResponse.ID; ti.DetailsBackColor = Colors.Gray; ti.DetailsForeColor = Colors.Black; Insert(ti); } if (m_jsonResponse.Description.Length > 0) { TreeLbItem ti = new TreeLbItem(Holder, this); ti.DetailsOnly = "RscJSonItem.Description" + ": " + m_jsonResponse.Description; ti.DetailsBackColor = Colors.Gray; ti.DetailsForeColor = Colors.Black; Insert(ti); } if (m_jsonParameters != null) { //Response properties inherited from parent to get this response... for (int i = 0; i < m_jsonParameters.PropertyCount; i++) { RscJSonItemProperty oProp = m_jsonParameters.GetProperty(i); TreeLbItem ti = new TreeLbItem(Holder, this); ti.DetailsOnly = oProp.Name + ": " + oProp.Value(false); ti.DetailsBackColor = Colors.White; ti.DetailsForeColor = Colors.Black; Insert(ti); } } for (int i = 0; i < m_jsonResponse.PropertyCount; i++) { RscJSonItemProperty oProp = m_jsonResponse.GetProperty(i); TreeLbItem ti = new TreeLbItem(Holder, this); ti.DetailsOnly = oProp.Name + ": " + oProp.Value(false); Insert(ti); } GoogleRequest grParent = GoogleRequest.None; if (Parent != null) { if (((TreeLbItem)Parent).Response != null) { grParent = GoogleUtils.GoogleRequestFromUrl(((TreeLbItem)Parent).Response.ID); } } for (int i = 0; i < m_jsonResponse.ChildCount; i++) { RscJSonItem oChild = m_jsonResponse.GetChild(i); TreeLbItem ti = new TreeLbItem(Holder, this); /* * if( m_jsonResponse.Name != "error" ) * { */ switch (grParent) { case GoogleRequest.GMail_Messages: { if (m_jsonResponse.Name == "messages") { //Downloadable, but with parameters... ti.gr = GoogleRequest.GMail_Message_Details; ti.m_jsonParameters = oChild; } else { ti.m_jsonResponse = oChild; } break; } default: { //Allowe to expand item... ti.m_jsonResponse = oChild; break; } } /* * } * else * { * ti.m_jsonResponse = oChild; * } */ Insert(ti); } base.Expand(); }
private void ProcessOrderEvent(Order order, bool add) { try { //settings per store var store = _storeService.GetStoreById(order.StoreId) ?? _storeContext.CurrentStore; var googleAnalyticsSettings = _settingService.LoadSetting <GoogleAnalyticsSettings>(store.Id); var request = new GoogleRequest { AccountCode = googleAnalyticsSettings.GoogleId, Culture = "en-US", HostName = new Uri(_webHelper.GetThisPageUrl(false)).Host, PageTitle = add ? "AddTransaction" : "CancelTransaction" }; var orderId = order.CustomOrderNumber; var orderShipping = googleAnalyticsSettings.IncludingTax ? order.OrderShippingInclTax : order.OrderShippingExclTax; var orderTax = order.OrderTax; var orderTotal = order.OrderTotal; if (!add) { orderShipping = -orderShipping; orderTax = -orderTax; orderTotal = -orderTotal; } var trans = new Transaction(FixIllegalJavaScriptChars(orderId), order.BillingAddress == null ? "" : FixIllegalJavaScriptChars(order.BillingAddress.City), order.BillingAddress == null || order.BillingAddress.Country == null ? "" : FixIllegalJavaScriptChars(order.BillingAddress.Country.Name), order.BillingAddress == null || order.BillingAddress.StateProvince == null ? "" : FixIllegalJavaScriptChars(order.BillingAddress.StateProvince.Name), store.Name, orderShipping, orderTax, orderTotal); foreach (var item in order.OrderItems) { //get category var category = _categoryService.GetProductCategoriesByProductId(item.ProductId).FirstOrDefault()?.Category?.Name; var unitPrice = googleAnalyticsSettings.IncludingTax ? item.UnitPriceInclTax : item.UnitPriceExclTax; var qty = item.Quantity; if (!add) { qty = -qty; } var sku = _productService.FormatSku(item.Product, item.AttributesXml); if (String.IsNullOrEmpty(sku)) { sku = item.Product.Id.ToString(); } var product = new TransactionItem(FixIllegalJavaScriptChars(orderId), FixIllegalJavaScriptChars(sku), FixIllegalJavaScriptChars(item.Product.Name), unitPrice, qty, FixIllegalJavaScriptChars(category)); trans.Items.Add(product); } request.SendRequest(trans, _httpClientFactory.CreateClient(NopHttpDefaults.DefaultHttpClient)); } catch (Exception ex) { _logger.InsertLog(LogLevel.Error, "Google Analytics. Error canceling transaction from server side", ex.ToString()); } }
static void Main(string[] args) { /* var jsonString="{\"responseId\": \"f46297bb-ca55-4efa-8a0d-6d7ad59f2787\","+ * "\"queryResult\": {\"queryText\": \"Привет привет\",\"action\": \"google\","+ * "\"parameters\": {},\"allRequiredParamsPresent\": true, \"fulfillmentMessages\": ["+ * "{\"text\": {\"text\": [\"\"]}}],\"intent\": {"+ * "\"name\": \"projects/inventory-6d37b/agent/intents/95d5c853-aab6-4310-a12b-2801b4bbde65\","+ * "\"displayName\": \"hello\"},\"intentDetectionConfidence\": 0.75,"+ * "\"languageCode\": \"ru\"},\"originalDetectIntentRequest\": {"+ * "\"payload\": {}},"+ * "\"session\": \"projects/inventory-6d37b/agent/sessions/3dd0a0da-ae9d-dd8b-8948-c93b9c0401e4\"}"; */ var json = "{\"responseId\":\"639d66f8-6232-4d86-873b-8881c84a3f4d\",\"queryResult\":{\"queryText\":\"Привет привет\",\"action\":\"google\",\"parameters\":{},\"allRequiredParamsPresent\":true,\"fulfillmentMessages\":[{\"text\":{\"text\":[\"\"]}}],\"intent\":{\"name\":\"projects/inventory-6d37b/agent/intents/95d5c853-aab6-4310-a12b-2801b4bbde65\",\"displayName\":\"hello\"},\"intentDetectionConfidence\":0.75,\"languageCode\":\"ru\"},\"originalDetectIntentRequest\":{\"payload\":{}},\"session\":\"projects/inventory-6d37b/agent/sessions/3dd0a0da-ae9d-dd8b-8948-c93b9c0401e4\"}"; var req = GoogleRequest.FromJson(json); dynamic data = JObject.Parse(json); var reqText = data.queryResult.queryText.Value; var queryBegin = "\",\"queryResult\":{\"queryText\":\""; var queryEnd = "\",\"action\":\"google\","; var queryStartPosition = json.IndexOf(queryBegin) + queryBegin.Length; var queryEndPosition = json.IndexOf(queryEnd); if (json.Contains(queryBegin) && json.Contains(queryEnd)) { var queryText = json.Substring(queryStartPosition, queryEndPosition - queryStartPosition); var canExit = false; var session = new UserSession(); Console.WriteLine("Учёт-Бот на месте, дайте команду"); session.ProcessInput("add кот"); session.ProcessInput("добавить кот"); session.ProcessInput("add 2 кота"); session.ProcessInput("Учёт материалов добавить таблетка аспирин"); session.ProcessInput("добавить таблетка аспирин"); session.ProcessInput("добавить таблетка аспирин"); session.ProcessInput("add 3 таблетки аспирина"); session.ProcessInput("add 5 ампул адреналина"); session.ProcessInput("add 50 миллиграммов глюкозы"); session.ProcessInput("add грамм глюкозы"); session.ProcessInput("add 3 грамма глюкозы"); session.ProcessInput("add ампула адреналина"); session.ProcessInput("добавить 3 ампулы адреналина"); session.ProcessInput("add 500 миллилитров физраствора"); session.ProcessInput("add 150 миллилитров физраствора"); session.ProcessInput("добавить 3 машины"); session.ProcessInput("add 15 машин"); session.ProcessInput("add dog"); session.ProcessInput("add 4 dogs"); session.ProcessInput("add 100 граммов золота"); session.ProcessInput("add 100 грамм золота"); session.ProcessInput("add 5 килограмм золота"); session.ProcessInput("add 4 килограмма золота"); session.ProcessInput("добавить 50 метров кабеля"); session.ProcessInput("add 150 сантиметров кабеля"); session.ProcessInput("add 5000 миллиметров кабеля"); session.ProcessInput("добавить таблетка амоксиклава по 1000 мг"); session.ProcessInput("add 3 таблетки амоксиклава по 1000 мг"); session.ProcessInput("добавить автомат АК-47"); session.ProcessInput("добавить 10 штук автомат АК-47"); session.ProcessInput("добавить автомат АК-74"); Console.WriteLine(session.ProcessInput("list").TextResponse); } else { Console.WriteLine("команда не распознана"); }; }
private void ProcessOrderEvent(Order order, bool add) { //ensure the plugin is installed and active var plugin = _widgetService.LoadWidgetBySystemName("Widgets.GoogleAnalytics") as GoogleAnalyticsPlugin; if (plugin == null || !plugin.IsWidgetActive(_widgetSettings) || !plugin.PluginDescriptor.Installed) { return; } try { var store = _storeService.GetStoreById(order.StoreId) ?? _storeContext.CurrentStore; //settings per store var googleAnalyticsSettings = _settingService.LoadSetting <GoogleAnalyticsSettings>(store.Id); if (!googleAnalyticsSettings.EnableEcommerce) { return; } var request = new GoogleRequest { AccountCode = googleAnalyticsSettings.GoogleId, Culture = "en-US", HostName = new Uri(_webHelper.GetThisPageUrl(false)).Host, PageTitle = add ? "AddTransaction" : "CancelTransaction" }; var orderId = order.Id.ToString(); //pass custom order number? order.CustomOrderNumber var orderShipping = googleAnalyticsSettings.IncludingTax ? order.OrderShippingInclTax : order.OrderShippingExclTax; var orderTax = order.OrderTax; var orderTotal = order.OrderTotal; if (!add) { orderShipping = -orderShipping; orderTax = -orderTax; orderTotal = -orderTotal; } var trans = new Transaction(orderId, order.BillingAddress == null ? "" : FixIllegalJavaScriptChars(order.BillingAddress.City), order.BillingAddress == null || order.BillingAddress.Country == null ? "" : FixIllegalJavaScriptChars(order.BillingAddress.Country.Name), order.BillingAddress == null || order.BillingAddress.StateProvince == null ? "" : FixIllegalJavaScriptChars(order.BillingAddress.StateProvince.Name), store.Name, orderShipping, orderTax, orderTotal); foreach (var item in order.OrderItems) { //get category var category = ""; var defaultProductCategory = _categoryService.GetProductCategoriesByProductId(item.ProductId).FirstOrDefault(); if (defaultProductCategory != null) { category = defaultProductCategory.Category.Name; } var unitPrice = googleAnalyticsSettings.IncludingTax ? item.UnitPriceInclTax : item.UnitPriceExclTax; var qty = item.Quantity; if (!add) { qty = -qty; } var product = new TransactionItem(FixIllegalJavaScriptChars(orderId), FixIllegalJavaScriptChars(item.Product.FormatSku(item.AttributesXml, _productAttributeParser)), FixIllegalJavaScriptChars(item.Product.Name), unitPrice, qty, FixIllegalJavaScriptChars(category)); trans.Items.Add(product); } request.SendRequest(trans); } catch (Exception ex) { _logger.InsertLog(LogLevel.Error, "Google Analytics. Error canceling transaction from server side", ex.ToString()); } }
/// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='request'> /// </param> public static object Post(this ISmartHome operations, GoogleRequest request) { return(Task.Factory.StartNew(s => ((ISmartHome)s).PostAsync(request), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult()); }