/// <summary> /// Deserialize JSON into a FHIR DeviceRequest /// </summary> public static void DeserializeJson(this DeviceRequest current, ref Utf8JsonReader reader, JsonSerializerOptions options) { string propertyName; while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) { return; } if (reader.TokenType == JsonTokenType.PropertyName) { propertyName = reader.GetString(); if (Hl7.Fhir.Serialization.FhirSerializerOptions.Debug) { Console.WriteLine($"DeviceRequest >>> DeviceRequest.{propertyName}, depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } reader.Read(); current.DeserializeJsonProperty(ref reader, options, propertyName); } } throw new JsonException($"DeviceRequest: invalid state! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); }
protected void SaveOrderInfo(bool update = false) { DeviceOrderInfo info = new DeviceOrderInfo(); info.OrderDate = orderDate; info.CreateTime = DateTimeNow; if (deviceOrderData.orderDetailList.Count > 0) { info.ProjectNumber = deviceOrderData.orderDetailList.First().ProjectNumber; } var user = this.AccountService.GetUser(this.LoginInfo.LoginName); if (user != null) { info.OrderPerson = user.Name; } info.OrderState = (int)EnumOrderStateInfo.AddState; if (update) { DeviceRequest request = new DeviceRequest(); request.ProjectNumber = info.ProjectNumber; if (this.IDKLManagerService.GetDeviceOrderInfoList(request).Count() > 0) { this.IDKLManagerService.DeleteDeviceOrderInfo(info.ProjectNumber); } } this.IDKLManagerService.AddDeviceOrderInfo(info); }
public async Task <IActionResult> RequestAccess(String deviceKey, String hostName) { try { if (_context.DeviceRequest.Any(dr => dr.DeviceKey == deviceKey)) { return(NoContent()); } DeviceRequest request = new DeviceRequest(); request.DeviceKey = deviceKey; request.HostName = hostName; request.ApprovedDevice = null; _context.DeviceRequest.Add(request); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { /* * if (!DeviceExists(id)) * { * return NotFound(); * } * else * { * throw; * } */ throw; } return(NoContent()); }
public async Task <ProgressResponse> StartCircuits(Device device, IEnumerable <string> circuitIds, int durationMinutes, Action <ProgressResponse> handleUpdates = null, Action onReconnect = null, bool silentMode = false) { try { //prepare request var deviceRequest = new DeviceRequest(device); deviceRequest.AddCircuits(circuitIds); var request = new StartCircuitsRequest(deviceRequest); request.Body.DurationMinutes = durationMinutes; //send request/get response var response = await this.DoRequest <StartCircuitsRequest, ProgressResponse>(request, onReconnect : onReconnect, silentMode : silentMode); //after-response tasks ServiceContainer.InvalidateCache(); this.RegisterForProgressUpdates(response, handleUpdates); return(response); } catch (Exception e) { LogUtility.LogException(e); } return(null); }
public async static Task <DeviceRequest> DownloadDeviceConfig(string apiUrl) { DeviceRequest result = null; using (var client = new HttpClient()) { try { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = await client.GetAsync(apiUrl); response.EnsureSuccessStatusCode(); var stringResult = await response.Content.ReadAsStringAsync(); result = JsonConvert.DeserializeObject <DeviceRequest>(stringResult); } catch (HttpRequestException) { } } return(result); }
byte[] VendorRequestIn(DeviceRequest request, ushort value, ushort index, ushort length) { byte requestType = WinUSBDevice.ControlRecipientDevice | WinUSBDevice.ControlTypeVendor; return(Device.ControlTransferIn(requestType, (byte)request, value, index, length)); }
public async Task <DeviceResponse> UpdateDeviceOfUserAsync(Guid userId, int deviceId, DeviceRequest deviceRequest) { var uri = new Uri($"{AccountUrl}/users/{userId}/devices/{deviceId}"); try { var requestJson = JsonConvert.SerializeObject(deviceRequest); var content = new StringContent(requestJson, Encoding.UTF8, "application/json"); var response = await _client.PatchAsync(uri, content).ConfigureAwait(false); if (response.IsSuccessStatusCode) { var deviceResponseJson = await response.Content.ReadAsStringAsync().ConfigureAwait(false); var deviceResponse = JsonConvert.DeserializeObject <DeviceResponse>(deviceResponseJson); return(await Task.FromResult(deviceResponse).ConfigureAwait(false)); } } catch (Exception e) { Debug.WriteLine(e.Message); } return(null); }
private void userButton1_Click(object sender, EventArgs e) { var praseRegularCode = ""; if (comboBox1.SelectedItem != null) { praseRegularCode = comboBox1.SelectedItem.ToString(); } try { DeviceRequest = new DeviceRequest { Name = textBox1.Text, Description = textBox2.Text, Address = textBox3.Text, Length = ushort.Parse(textBox4.Text), CaptureInterval = int.Parse(textBox6.Text), PraseRegularCode = praseRegularCode }; } catch (Exception ex) { MessageBox.Show("数据填入失败!" + ex.Message); return; } DialogResult = DialogResult.OK; }
public ActionResult Submit(int id, FormCollection collection, DeviceRequest request) { var orderInfo = this.IDKLManagerService.GetDeviceOrderInfo(id); orderInfo.OrderState = (int)EnumOrderStateInfo.OrderSucceed; var orderData = this.IDKLManagerService.GetDeviceOrderDetaislList(id); string t1 = collection["orderDetail.RealityOrderNumber"]; int s = int.Parse(t1); orderData.RealityOrderNumber = s; if (orderData.RealityOrderNumber <= orderData.OrderNumber) { try { this.IDKLManagerService.AddDeviceOrderDetail(orderData); } catch (Exception ex) { return(Back(ex.Message)); } } else { return(Back("实际数不能大于预约数")); } try { this.IDKLManagerService.UpdateDeviceOrderInfo(orderInfo); } catch (Exception ex) { return(Back(ex.Message)); } return(this.RefreshParent()); }
public IActionResult SaveDevice(DeviceRequest request) { try { using (TeamsDbEntities entities = new TeamsDbEntities()) { UserDevice devices = entities.UserDevices.FirstOrDefault(p => p.NotificationKey == request.NotificationKey); if (devices == default) { entities.UserDevices.Add(new UserDevice { NotificationKey = request.NotificationKey, UserID = request.UserID, CreateDate = DateTime.Now }); entities.SaveChanges(); } else { devices.UserID = request.UserID; devices.CreateDate = DateTime.Now; } } return(Ok(new ResponseBase { Result = "Success" })); } catch (Exception) { return(BadRequest(new ResponseBase { Result = "System Error." })); } }
public ActionResult Indext(DeviceRequest request) { request.OrderState = (int)EnumOrderStateInfo.AddState; var result = this.IDKLManagerService.GetDeviceOrderInfoList(request); return(View(result)); }
/// <summary> /// 일정추가 화면 호출 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SchedulerControl_EditAppointmentFormShowing(object sender, AppointmentFormEventArgs e) { e.Handled = true; if (schedulerControl.ActiveViewType == SchedulerViewType.WorkWeek || schedulerControl.ActiveViewType == SchedulerViewType.Day) //달력이 형태가 주단위일 경우 { if (schedulerControl.SelectedAppointments.Count > 0) //존재하는 일정을 클릭했을 경우 { _selectedDate = schedulerControl.SelectedInterval.Start; DeviceRequest deviceRequest = new DeviceRequest(_userInfo, e.Appointment, uC_DeptCode.EditValue.ToString()); deviceRequest.DataSendEvent += new DeviceRequest.DeviceRequest_EventHandler(GetRequestData); deviceRequest.ShowDialog(); //일정추가 화면 호출 RefreshCalendar(_storeCode, _itemCode); //캘린더 갱신 } else //새 일정을 추가할 경우 { if (DateTime.Now.CompareTo(schedulerControl.ActiveView.SelectedInterval.Start) < 0)//이전시간에는 신청불가 { _selectedDate = schedulerControl.SelectedInterval.Start; DeviceRequest deviceRequest = new DeviceRequest(e.Appointment.LabelId.ToString(), _selectedDate, _itemCode, LUE_ItemList.Text, _storeCode, _userInfo, uC_DeptCode.EditValue.ToString()); deviceRequest.DataSendEvent += new DeviceRequest.DeviceRequest_EventHandler(GetRequestData); deviceRequest.ShowDialog(); //일정추가 화면 호출 RefreshCalendar(_storeCode, _itemCode); //캘린더 갱신 } else { XtraMessageBox.Show("현시간 이전에는 새 일정을 추가할 수 없습니다.", "안내", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } } } }
private bool UpdateDevice() { var newDeviceName = DeviceNameTextField.Text; if (newDeviceName == _device.Name) { return(true); } var userId = CrossSettings.Current.GetValueOrDefault("LoggedInUser_id", Guid.Empty); if (userId == Guid.Empty) { return(false); } var deviceRequest = new DeviceRequest { Name = newDeviceName }; var res = AccountService.Current.UpdateDeviceOfUserAsync(userId, DeviceId, deviceRequest).Result; if (res == null) { return(false); } return(true); }
private readonly SimpleHybirdLock dictLock; // dict词典的数据锁 #endregion #region JSON Object private void ParseFromRequest(byte[] data, DeviceRequest request) { foreach (var regular in request.RegularNodes) { var value = regular.GetValue(data, ByteTransform); jsonLock.Enter(); if (regular.RegularCode != RegularNodeTypeItem.StringAscii.Code && regular.RegularCode != RegularNodeTypeItem.StringUnicode.Code && regular.RegularCode != RegularNodeTypeItem.StringUtf8.Code && regular.TypeLength > 1) { // 数组 JObjectData[regular.Name] = new JArray(value); } else { // 单个的值 JObjectData[regular.Name] = new JValue(value); } jsonLock.Leave(); SetDictValue(regular.Name, value); WriteCustomerData?.Invoke(this, regular.Name); } }
public async Task SaveEventEquals_Ok() { var deviceId = new Guid(); var deviceEvent = new DeviceEventRequest { Name = "start_app", Date = DateTimeOffset.Now }; var deviceEvents = new List <DeviceEventRequest> { deviceEvent }; var device = new DeviceRequest { Id = deviceId, DeviceEvents = deviceEvents, Name = "somename", Os = "someOs", Version = "later" }; await statisticService.Save(device); eventRepositoryMock.Verify(x => x.Add(It.Is <DeviceEvent>(c => c.DeviceId == deviceId)), Times.Once); }
public async Task <ProgressResponse> TestStations(Device device, IEnumerable <string> stationIds, int durationMinutes, Action <ProgressResponse> handleUpdates = null, Action onReconnect = null, bool silentMode = false) { try { //create & configure request var deviceRequest = new DeviceRequest(device); deviceRequest.AddStations(stationIds); //send request/get response var request = new TestStationsRequest(deviceRequest); var response = await this.DoRequest <TestStationsRequest, ProgressResponse>(request, onReconnect : onReconnect, silentMode : silentMode); //clear cache & other maintenance ServiceContainer.InvalidateCache(); this.RegisterForProgressUpdates(response, handleUpdates); return(response); } catch (Exception e) { LogUtility.LogException(e); } return(null); }
public FormRequest(DeviceRequest deviceRequest, string[] regularsArray) { InitializeComponent(); DeviceRequest = deviceRequest ?? new DeviceRequest(); Icon = Util.GetWinformICon(); RegularsArray = regularsArray; }
/// <summary> /// Invokes the specified device request. /// </summary> /// <param name="deviceId"></param> /// <param name="request"></param> /// <returns></returns> public async Task <DevicePayload> InvokeRequestAsync(string deviceId, DeviceRequest request) { // no JSON formatting to save as much space as possible var payload = JsonConvert.SerializeObject(request, Formatting.None, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, ContractResolver = new CamelCasePropertyNamesContractResolver() }); var result = default(InvocationResult); await m_TelemetryService.IncrementCounterAsync("direct_method", new string[] { }); result = await m_TelemetryService.StartTimerAsync(() => m_DeviceCommunicationAdapter.InvokeCommandAsync(deviceId, payload), "direct_method", new string[] { }); m_TelemetryService.Dispose(); try { return(JsonConvert.DeserializeObject <DevicePayload>(result.Content, new DeviceResponseConverter())); } catch (JsonReaderException ex) { throw new InvalidResultException(ErrorCodes.InvalidResult, ErrorMessages.GetInvalidResultMessage(), ex); } catch (JsonSerializationException ex) { throw new InvalidResultException(ErrorCodes.InvalidResult, ErrorMessages.GetInvalidResultMessage(), ex); } }
public IActionResult RegisterDevice([FromBody] DeviceRequest request) { if (request == null || string.IsNullOrWhiteSpace(request.Token) || !AdamantUtilities.IsValidAdamantAddress(request.Address)) { return(BadRequest()); } // Drop previous registration, if exist var prevDevice = _context.Devices.FirstOrDefault(d => d.Token == request.Token); if (prevDevice != null) { _context.Devices.Remove(prevDevice); } // Add new device var device = new Device { Address = request.Address, Token = request.Token, RegistrationDate = DateTime.Now }; _context.Devices.Add(device); // Save changes _context.SaveChanges(); return(Ok()); }
private ActionResult <CollectionResponse <Device> > QueryImpl(DeviceRequest request) { // Limit maximum of items to prevent exploits: const int maxItems = 100; request.PageSize = Math.Min(maxItems, request.PageSize); var q = _devices.AsQueryable(); if (!string.IsNullOrEmpty(request.Id)) { q = q.Where(d => d.Id == request.Id); } if (!string.IsNullOrEmpty(request.Airport)) { q = q.Where(d => d.Airport == request.Airport); } if (!string.IsNullOrEmpty(request.Terminal)) { q = q.Where(d => d.Terminal == request.Terminal); } if (!string.IsNullOrEmpty(request.Type)) { q = q.Where(d => d.Type == request.Type); } return(new CollectionResponse <Device>(request, q)); }
public async Task UpdateDesiredAsync(float desiredTemperature, SensorDataType sensorDataType) { var builder = new UriBuilder(_roomDevicesApiEndpoint); builder.AppendToPath("Devices"); var uri = builder.ToString(); string methodName; string deviceId; switch (sensorDataType) { case SensorDataType.Temperature: methodName = "SetDesiredTemperature"; deviceId = _thermostatDeviceId; break; case SensorDataType.Light: methodName = "SetDesiredAmbientLight"; deviceId = _lightDeviceId; break; default: throw new NotSupportedException(sensorDataType.ToString()); } var request = new DeviceRequest { DeviceId = deviceId, MethodName = methodName, Value = desiredTemperature.ToString(CultureInfo.InvariantCulture) }; await _requestService.PostAsync(uri, request, _authenticationService.AuthenticatedUser.Token); }
// ReSharper disable PossibleMultipleEnumeration public async Task RunAsync(IRestContext context) { ISystemApi systemApi = context.Factory.CreateSystemApi(); IEnumerable <DeviceResponse> devices = await systemApi.GetDevicesAsync(new SqlQuery()); await DeleteAnyDevices(devices, systemApi); IUserApi userApi = context.Factory.CreateUserApi(); DeviceRequest device = new DeviceRequest { uuid = "1", model = "model", platform = "windows", version = "1.0" }; bool ok = await userApi.SetDeviceAsync(device); Console.WriteLine("SetDeviceAsync(): success={0}", ok); SqlQuery query = new SqlQuery { filter = "platform=\"windows\"", fields = "*" }; devices = await systemApi.GetDevicesAsync(query); Console.WriteLine("GetDevicesAsync(): {0}", context.ContentSerializer.Serialize(devices.Single())); await DeleteAnyDevices(devices, systemApi); }
public async Task <ResponseBase> SaveDevice(DeviceRequest device) { string responseString = await CallAsync(SaveDeviceServiceName, JsonConvert.SerializeObject(device), MethodTypeEnum.POST, _state.userState.Token); ResponseBase response = JsonConvert.DeserializeObject <ResponseBase>(responseString); return(response); }
public ActionResult <CollectionResponse <Device> > Search([ModelBinder(typeof(PathModelBinder <DeviceRequest>))] DeviceRequest request) { if (request == null) { throw new ArgumentNullException(nameof(request)); } return(QueryImpl(request)); }
public DeviceRequest GetFakeDeviceRequest(String deviceKey) { DeviceRequest deviceRequest = A.New <DeviceRequest>(); deviceRequest.DeviceKey = deviceKey; return(deviceRequest); }
public IActionResult CurrentEffectOutputDevice(DeviceRequest deviceRequest) { if (!audioPlayer.UpdateEffectOutputDevice(deviceRequest.Device)) { return(BadRequest()); } return(Ok()); }
public async Task <bool> ExecuteAsync(DeviceRequest request) { var serializer = SerializerFactory.CreateSerializerFromType(request.Command); var device = DeviceFactory.CreateDeviceFromType(request.Command); var data = serializer.Serialize(request.Data); var result = await device.ExecuteAsync(data); return(result); }
public IActionResult CurrentVoiceInputDevice(DeviceRequest deviceRequest) { if (!microphoneHandler.UpdateVoiceInputDevice(deviceRequest.Device)) { return(BadRequest()); } return(Ok()); }
public async Task SaveDevice_NotExisted_CallAdd() { DeviceRequest device = GetDevice(notExistId); await statisticService.Save(device); deviceRepositoryMock.Verify(x => x.Add(It.IsAny <Device>()), Times.Once); deviceRepositoryMock.Verify(x => x.Update(It.IsAny <Device>()), Times.Never); }
/// <summary> /// Gets the value of the resource asynchronously /// </summary> /// <param name="deviceId">Device Id</param> /// <param name="resourcePath">Resource path.</param> /// <returns>Async consumer with string</returns> /// <exception cref="ArgumentNullException"> /// If <paramref name="deviceId"/> is <see langword="null"/>. /// <br/>-or-<br/> /// If <paramref name="resourcePath"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// If <paramref name="deviceId"/> is a blank or empty string. /// <br/>-or-<br/> /// If <paramref name="resourcePath"/> is a blank or empty string. /// </exception> /// <exception cref="CloudApiException"> /// If an error occurred while communicating with the server or if the server responsed with an error. /// </exception> public async Task <AsyncConsumer <string> > GetResourceValueAsync(string deviceId, string resourcePath) { ThrowIfNullOrEmpty(deviceId, nameof(deviceId)); ThrowIfNullOrEmpty(resourcePath, nameof(resourcePath)); var deviceRequest = new DeviceRequest(Method: HttpMethod.Get.Method, Uri: AddLeadingSlash(resourcePath)); return(await CreateAsyncRequestAsync(deviceId, deviceRequest).ConfigureAwait(false)); }
void VendorRequestOut(DeviceRequest request, ushort value, ushort index, byte[] data) { byte requestType = WinUSBDevice.ControlRecipientDevice | WinUSBDevice.ControlTypeVendor; Device.ControlTransferOut(requestType, (byte)request, value, index, data); }
byte GetByte(DeviceRequest request) { byte[] data = VendorRequestIn(request, 0, 0, 1); return data[0]; }
byte[] VendorRequestIn(DeviceRequest request, ushort value, ushort index, ushort length) { byte requestType = WinUSBDevice.ControlRecipientDevice | WinUSBDevice.ControlTypeVendor; return Device.ControlTransferIn(requestType, (byte)request, value, index, length); }
public async Task<bool> SubscribeForPushNotificationAsync(string pushtoken, string deviceUid) { var result = false; var settings = new CreateSubscriptionsRequest () { DeviceRequest = new DeviceRequest () { Platform = Platform.ios, Udid = deviceUid }, PushToken = new PushToken () { ClientIdentificationSequence = pushtoken, #if DEBUG Environment = Quickblox.Sdk.Modules.NotificationModule.Models.Environment.development #else Environment = Quickblox.Sdk.Modules.NotificationModule.Models.Environment.production #endif }, Name = NotificationChannelType.apns }; var createSubscribtionResponse = await client.NotificationClient.CreateSubscriptionsAsync (settings); if (await HandleResponse (createSubscribtionResponse, HttpStatusCode.Created)) { result = true; } return result; } }
UInt16 GetU16(DeviceRequest request) { byte[] data = VendorRequestIn(request, 0, 0, 2); return BitConverter.ToUInt16(data, 0); }
bool GetLed(DeviceRequest request) { return GetByte(request) != 0; }
void SetLed(DeviceRequest request, bool value) { VendorRequestOut(request, (ushort)(value ? 1 : 0), 0, null); }