public SingleModelResponse <Event> SaveEvent(EventViewModel evnt) { string saveUrl = EventUri + "SaveEvent"; List <EventRoute> newRoutes = new List <EventRoute>(); foreach (EventRouteViewModel evntRoute in evnt.EventRoutes) { EventRoute route = new EventRoute(DateTime.Now.ToString()); route.Title = evntRoute.Title; route.Description = evntRoute.Description; route.RouteID = evntRoute.RouteId; route.Distance = evntRoute.Distance; route.EventID = evnt.EventId; newRoutes.Add(route); } var newEvent = new Event { UserID = evnt.UserID, Date = evnt.Date, ClubID = evnt.ClubId, Time = evnt.Time, Timezone = evnt.Timezone, EventDateTime = evnt.EventDateTime, DateCreated = DateTime.Now.ToString(), Description = evnt.Description, Location = evnt.Location, Title = evnt.Title, EventRoute = newRoutes }; var createdEvent = PostContent(saveUrl, newEvent); return(createdEvent); }
//add addEvent public Event AddEvent(Event evnt) { Event newEvent = new Event(); newEvent.Title = evnt.Title; newEvent.Description = evnt.Description; newEvent.Date = evnt.Date; newEvent.Time = evnt.Time; newEvent.Location = evnt.Location; newEvent.UserID = evnt.UserID; newEvent.ClubID = evnt.ClubID; newEvent.DateCreated = evnt.DateCreated; foreach (EventRoute evntRoute in evnt.EventRoute) { EventRoute route = new EventRoute(); route.Title = evntRoute.Title; route.Description = evnt.Description; route.RouteID = evntRoute.RouteID; route.DateAdded = evntRoute.DateAdded; route.Distance = evntRoute.Distance; newEvent.EventRoute.Add(route); } DbContext.Event.Add(newEvent); DbContext.SaveChanges(); return(newEvent); }
protected void RequireStateTransitionDelay(string transition, StateEventArg arg = null) { EventRoute.SendEvent(EventSendType.OneTime, new SystemStateTransitionEvent() { transition = transition, eventArg = arg }); }
public async Task EventRoutes_Lifecycle() { // arrange DigitalTwinsClient client = GetClient(); // Ensure unique eventRouteId and endpointName string eventRouteId = $"someEventRouteId-{GetRandom()}"; string filter = "$eventType = 'DigitalTwinTelemetryMessages' or $eventType = 'DigitalTwinLifecycleNotification'"; var eventRoute = new EventRoute(EndpointName) { Filter = filter }; // Test CreateEventRoute Response createEventRouteResponse = await client.CreateEventRouteAsync(eventRouteId, eventRoute).ConfigureAwait(false); createEventRouteResponse.Status.Should().Be((int)HttpStatusCode.NoContent); // Test GetEventRoute EventRoute getEventRouteResult = await client.GetEventRouteAsync(eventRouteId); eventRoute.EndpointName.Should().Be(getEventRouteResult.EndpointName); eventRoute.Filter.Should().Be(getEventRouteResult.Filter); eventRouteId.Should().Be(getEventRouteResult.Id); // Test GetEventRoutes var eventRoutesListOptions = new EventRoutesListOptions(); AsyncPageable <EventRoute> eventRouteList = client.GetEventRoutesAsync(eventRoutesListOptions); bool eventRouteFoundInList = false; await foreach (EventRoute eventRouteListEntry in eventRouteList) { if (StringComparer.Ordinal.Equals(eventRouteListEntry.Id, eventRouteId)) { eventRouteFoundInList = true; eventRoute.EndpointName.Should().Be(getEventRouteResult.EndpointName); eventRoute.Filter.Should().Be(getEventRouteResult.Filter); break; } } eventRouteFoundInList.Should().BeTrue("Newly created event route should have been present when listing all event routes"); // Test DeleteEventRoute Response deleteEventRouteResponse = await client.DeleteEventRouteAsync(eventRouteId).ConfigureAwait(false); deleteEventRouteResponse.Status.Should().Be((int)HttpStatusCode.NoContent); // Verify event route was deleted by trying to get it again // act Func <Task> act = async() => await client.GetEventRouteAsync(eventRouteId).ConfigureAwait(false); // assert act.Should().Throw <RequestFailedException>() .And.Status.Should().Be((int)HttpStatusCode.NotFound); }
public EventRouteRegistrationEventArgs(EventRoute eventRoute) : base() { if (eventRoute == null) { throw new ArgumentNullException("eventRoute"); } this._eventRoute = eventRoute; }
private void CreateNewEventRoute(int routeId, int eventId, string routeDetails) { EventRoute route = new EventRoute(); route.RouteId = routeId; route.EventId = eventId; route.Details = routeDetails; _context.EventRoutes.Add(route); _context.SaveChanges(); }
private async Task <EventRoute> CreateEventRoute(DigitalTwinsClient client, string eventRouteId) { string filter = "type = 'Microsoft.DigitalTwins.Twin.Create' OR type = 'microsoft.iot.telemetry'"; var eventRoute = new EventRoute(EndpointName, filter); // Create an event route. Response createEventRouteResponse = await client.CreateEventRouteAsync(eventRouteId, eventRoute).ConfigureAwait(false); createEventRouteResponse.Status.Should().Be((int)HttpStatusCode.NoContent); return(eventRoute); }
public void EventRoutes_MalformedEventRouteFilter_ThrowsBadRequestException() { // arrange DigitalTwinsClient client = GetClient(); // Ensure unique eventRouteId and endpointName string eventRouteId = $"someEventRouteId-{GetRandom()}"; string filter = "this is not a valid filter string"; var eventRoute = new EventRoute(EndpointName, filter); // Test CreateEventRoute Func <Task> act = async() => await client.CreateEventRouteAsync(eventRouteId, eventRoute).ConfigureAwait(false); act.Should().Throw <RequestFailedException>() .And.Status.Should().Be((int)HttpStatusCode.BadRequest); }
public async Task CreateRouteAsync(RequestContext context) { var client = new DigitalTwinsClient(new Uri($"https://{context.Host}"), new DefaultAzureCredential()); EventRoute route = null; try { route = await client.GetEventRouteAsync(RouteId); } catch (RequestFailedException e) when(e.Status == 404) { } if (route == null) { _log.LogInformation($"Creating route for {context.InstanceName}"); await client.CreateEventRouteAsync(RouteId, new EventRoute(EndpointId) { Filter = "true" }); } }
/// <summary> /// Creates event route for digital Twin /// </summary> public async Task CreateEventRoute() { PrintHeader("CREATE EVENT ROUTE"); try { #region Snippet:DigitalTwinsSampleCreateEventRoute string eventFilter = "$eventType = 'DigitalTwinTelemetryMessages' or $eventType = 'DigitalTwinLifecycleNotification'"; var eventRoute = new EventRoute(eventhubEndpointName, eventFilter); await client.CreateEventRouteAsync(_eventRouteId, eventRoute); Console.WriteLine($"Created event route '{_eventRouteId}'."); #endregion Snippet:DigitalTwinsSampleCreateEventRoute } catch (Exception ex) { FatalError($"CreateEventRoute: Failed to create event route due to: {ex.Message}"); } }
// Add a preopportunity handler for the logical parent incase of templated element. internal static void AddParentPreOpportunityHandler(DependencyObject o, EventRoute route, RoutedEventArgs args) { // If the logical parent is different from visual parent then add handler on behalf of the // parent into the route. This is to cover the templated elements, where event could be // handled by one of the child visual element but we should consider it as if event is handled by // parent element ( logical parent). DependencyObject visualParent = null; if (o is Visual || o is Visual3D) { visualParent = UIElementHelper.GetUIParent(o); } DependencyObject logicalParent = SynchronizedInputHelper.GetUIParentCore(o); if (logicalParent != null && logicalParent != visualParent) { UIElement e = logicalParent as UIElement; if (e != null) { e.AddSynchronizedInputPreOpportunityHandler(route, args); } else { ContentElement ce = logicalParent as ContentElement; if (ce != null) { ce.AddSynchronizedInputPreOpportunityHandler(route, args); } else { UIElement3D e3D = logicalParent as UIElement3D; if (e3D != null) { e3D.AddSynchronizedInputPreOpportunityHandler(route, args); } } } } }
/// <summary> /// Creates event route for digital Twin /// </summary> public async Task CreateEventRoute() { PrintHeader("CREATE EVENT ROUTE"); try { #region Snippet:DigitalTwinSampleCreateEventRoute string eventFilter = "$eventType = 'DigitalTwinTelemetryMessages' or $eventType = 'DigitalTwinLifecycleNotification'"; var eventRoute = new EventRoute(_eventhubEndpointName) { Filter = eventFilter }; Response createEventRouteResponse = await DigitalTwinsClient.CreateEventRouteAsync(_eventRouteId, eventRoute).ConfigureAwait(false); #endregion Snippet:DigitalTwinSampleCreateEventRoute Console.WriteLine($"Created event route: {_eventRouteId} Response status: {createEventRouteResponse.Status}"); } catch (Exception ex) { FatalError($"CreateEventRoute: Failed to create event route due to: {ex.Message}"); } }
public Event UpdateEvent(Event evnt) { IEnumerable <EventRoute> evntRoutes = GetEventRoutes(evnt.EventId); Event newEvent = GetEventByID(evnt.EventId); newEvent.Title = evnt.Title; newEvent.Description = evnt.Description; newEvent.Date = evnt.Date; newEvent.Time = evnt.Time; newEvent.Location = evnt.Location; newEvent.DateModified = evnt.DateModified; //DeleteEventRoutes(evntRoutes); foreach (EventRoute route in evntRoutes) { DbContext.Entry(route).State = EntityState.Deleted; } DbContext.SaveChanges(); newEvent.EventRoute = new List <EventRoute>(); foreach (EventRoute evntRoute in evnt.EventRoute) { EventRoute route = new EventRoute(); route.DateAdded = evntRoute.DateAdded; route.Title = evntRoute.Title; route.Description = evnt.Description; route.RouteID = evntRoute.RouteID; route.Distance = evntRoute.Distance; newEvent.EventRoute.Add(route); } DbContext.Event.Update(newEvent); DbContext.SaveChanges(); return(newEvent); }
public SingleModelResponse <Event> UpdateEvent(EventViewModel evnt) { string saveUrl = EventUri + "Update/EditEvent"; List <EventRoute> newRoutes = new List <EventRoute>(); char numLet = 'A'; foreach (EventRouteViewModel evntRoute in evnt.EventRoutes) { EventRoute route = new EventRoute(DateTime.Now.ToString()); route.Title = evnt.Title + ' ' + numLet; numLet++; route.Description = evnt.Description; route.Distance = evntRoute.Distance; route.RouteID = evntRoute.RouteId; route.EventID = evnt.EventId; newRoutes.Add(route); } var newEvent = new Event { EventId = evnt.EventId, Date = evnt.Date, Time = evnt.Time, Description = evnt.Description, DateCreated = evnt.DateCreated, Timezone = evnt.Timezone, EventDateTime = evnt.EventDateTime, DateModified = DateTime.Now.ToString(), Location = evnt.Location, Title = evnt.Title, EventRoute = newRoutes }; var updatedEvent = PutContent(saveUrl, newEvent); return(updatedEvent); }
private static void CheckParameters(EventRoute route, RadRoutedEventArgs args) { if (route == null) { throw new ArgumentNullException("route"); } if (args == null) { throw new ArgumentNullException("args"); } if (args.Source == null) { throw new ArgumentException(SR.Get(SRID.SourceNotSet, new object[0])); } if (args.RoutedEvent != route.RoutedEvent) { throw new ArgumentException(SR.Get(SRID.MismatchedRoutedEvent, new object[0])); } }
public static void RaiseEvent(DependencyObject element, RadRoutedEventArgs args) { if (args == null) { throw new ArgumentNullException("args"); } EventRoute route = new EventRoute(args.RoutedEvent); args.Source = element; BuildRoute(element, route, args); route.InvokeHandlers(element, args); args.Source = args.OriginalSource; route.Clear(); }
private static void CheckParameters(DependencyObject element, EventRoute route, RadRoutedEventArgs e) { if (element == null) { throw new ArgumentNullException("element"); } if (route == null) { throw new ArgumentNullException("route"); } if (e == null) { throw new ArgumentNullException("e"); } }
//------------------------------------------------------------------- // // Internal Methods // //-------------------------------------------------------------------- #region Internal Methods /// <summary> /// Allows FrameworkElement to augment the EventRoute. /// </summary> internal override bool BuildRouteCore(EventRoute route, RoutedEventArgs args) { // Do not add intermediate ContentElements to the route, // because they were added by embedded viewer. return BuildRouteCoreHelper(route, args, false); }
public EventRoutePreRegistrationEventArgs(EventRoute eventRoute) : base(eventRoute) { }
private void AddToEventRouteImpl(EventRoute route, RoutedEventArgs args) { // // add class listeners then instance listeners. // Hashtable store = _classEventHandlersStore; RoutedEvent evt = args._routedEvent; for (int repeat = 0; repeat < 2; repeat++) { if (store != null) { ArrayList eventListeners = (ArrayList)store[evt]; // Add all listeners for this UIElement if (eventListeners != null) { for (int i = 0, count = eventListeners.Count; i < count; i++) { RoutedEventHandlerInfo eventListener = (RoutedEventHandlerInfo)eventListeners[i]; route.Add(this, eventListener._handler, eventListener._handledEventsToo); } } } store = _instanceEventHandlersStore; } }
private void Add_OnClick(object sender, EventRoute e) { }
private static void AddToEventRoute(DependencyObject element, EventRoute route, RadRoutedEventArgs e) { CheckParameters(element, route, e); DependencyObjectType dependencyType = element.GetDependencyObjectType(); if (dependencyType == null) { dependencyType = DependencyObjectType.FromSystemTypeInternal(element.GetType()); element.SetDependencyObjectType(dependencyType); } for (RoutedEventHandlerInfoList list = GlobalEventManager.GetDTypedClassListeners(dependencyType, e.RoutedEvent); list != null; list = list.Next) { for (int i = 0; i < list.Handlers.Length; i++) { route.Add(element, list.Handlers[i].Handler, list.Handlers[i].InvokeHandledEventsToo); } } EventHandlersStore eventHandlersStore = GetEventHandlersStore(element); if (eventHandlersStore != null) { List<RoutedEventHandlerInfo> list2 = eventHandlersStore[e.RoutedEvent]; if (list2 != null) { for (int j = 0; j < list2.Count; j++) { RoutedEventHandlerInfo info = list2[j]; route.Add(element, info.Handler, info.InvokeHandledEventsToo); } } } }
/// <summary> /// Add the event handlers for this element to the route. /// </summary> // REFACTOR -- do we need this to be public? public void AddToEventRoute(EventRoute route, RoutedEventArgs args) { VerifyAccess(); if (route == null || args == null) { throw new ArgumentNullException(); } AddToEventRouteImpl(route, args); }
private void Cancel_OnClick(object sender, EventRoute e) { }
/// <summary> /// Adds or replaces an event route. /// Status codes: /// 200 (OK): Success. /// 400 (Bad Request): The request is invalid. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='id'> /// The id for an event route. The id is unique within event routes and case /// sensitive. /// </param> /// <param name='eventRoute'> /// The event route data /// </param> public static void Add(this IEventRoutesOperations operations, string id, EventRoute eventRoute = default(EventRoute)) { operations.AddAsync(id, eventRoute).GetAwaiter().GetResult(); }
/// <summary> /// Adds or replaces an event route. /// Status codes: /// 200 (OK): Success. /// 400 (Bad Request): The request is invalid. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='id'> /// The id for an event route. The id is unique within event routes and case /// sensitive. /// </param> /// <param name='eventRoute'> /// The event route data /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task AddAsync(this IEventRoutesOperations operations, string id, EventRoute eventRoute = default(EventRoute), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.AddWithHttpMessagesAsync(id, eventRoute, null, cancellationToken).ConfigureAwait(false)).Dispose(); }
public MFTestResults UIElement_AddToEventRouteTest4() { MFTestResults testResult = MFTestResults.Pass; rEvents = new RoutedEvent[] { Buttons.ButtonDownEvent, Buttons.ButtonUpEvent, Buttons.PreviewButtonDownEvent, Buttons.PreviewButtonUpEvent}; handledEventsToo = false; //addToEvtRoute = true; Log.Comment("Setting Both Event Counters to zero (0)"); _btnEventCntr = 0; _fcsEventCntr = 0; Log.Comment("Adding all ButtonDownEvents to the EventRoute"); btnEvent = true; fcsEvent = false; for (int i = 0; i < rEvents.Length; i++) { eRoute = new EventRoute(rEvents[i]); mainWindow.Dispatcher.Invoke(new TimeSpan(0, 0, 5), new DispatcherOperationCallback(AddToHandler), eRoute); } Log.Comment("Raising the Events and Verifying"); for (int i = 0; i < rEvents.Length; i++) { ButtonEventArgs bea = new ButtonEventArgs(null, null, DateTime.Now, Hardware.Button.AppDefined1); bea.RoutedEvent = rEvents[i]; mainWindow.Dispatcher.Invoke(new TimeSpan(0, 0, 5), new DispatcherOperationCallback(RaiseEvent), bea); } Log.Comment("This currently fails, getting one additional button event than expected, investigating"); if (_btnEventCntr != rEvents.Length) { Log.Comment("Expected ButtonEvents = '" + rEvents.Length + "' but got '" + _btnEventCntr + "'"); testResult = MFTestResults.Skip; } Log.Comment("Adding all FocuseChangedEvents to the EventRoute"); btnEvent = false; fcsEvent = true; rEvents = new RoutedEvent[] { Buttons.GotFocusEvent, Buttons.LostFocusEvent }; for (int i = 0; i < rEvents.Length; i++) { eRoute = new EventRoute(rEvents[i]); mainWindow.Dispatcher.Invoke(new TimeSpan(0, 0, 5), new DispatcherOperationCallback(AddToHandler), eRoute); } Log.Comment("Raising the Events and Verifying"); for (int i = 0; i < rEvents.Length; i++) { FocusChangedEventArgs fcea = new FocusChangedEventArgs(null, DateTime.Now, mainWindow, mainWindow); fcea.RoutedEvent = rEvents[i]; Application.Current.Dispatcher.Invoke(new TimeSpan(0, 0, 5), new DispatcherOperationCallback(RaiseEvent), fcea); } if (_fcsEventCntr != rEvents.Length) { Log.Comment("Expected FocusChangedEvent = '" + rEvents.Length + "' but got '" + _fcsEventCntr + "'"); testResult = MFTestResults.Fail; } return testResult; }
public async Task PublishTelemetry_Lifecycle() { // Setup // Create a DigitalTwinsClient instance. DigitalTwinsClient client = GetClient(); string wifiComponentName = "wifiAccessPoint"; string wifiModelId = await GetUniqueModelIdAsync(client, TestAssetDefaults.WifiModelIdPrefix).ConfigureAwait(false); string roomWithWifiModelId = await GetUniqueModelIdAsync(client, TestAssetDefaults.RoomWithWifiModelIdPrefix).ConfigureAwait(false); string roomWithWifiTwinId = await GetUniqueTwinIdAsync(client, TestAssetDefaults.RoomWithWifiTwinIdPrefix).ConfigureAwait(false); string eventRouteId = $"someEventRouteId-{GetRandom()}"; try { // Create an event route for the digital twins client. EventRoute eventRoute = await CreateEventRoute(client, eventRouteId).ConfigureAwait(false); // Create the models needed for the digital twin. await CreateModelsAndTwins(client, wifiModelId, roomWithWifiModelId, wifiComponentName, roomWithWifiTwinId).ConfigureAwait(false); // Act - Test publishing telemetry to a digital twin. var telemetryOptions = new PublishTelemetryOptions() { TimeStamp = default }; Response publishTelemetryResponse = await client.PublishTelemetryAsync(roomWithWifiTwinId, Recording.Random.NewGuid().ToString(), "{\"Telemetry1\": 5}", telemetryOptions).ConfigureAwait(false); // Assert publishTelemetryResponse.Status.Should().Be((int)HttpStatusCode.NoContent); // Act - Test publishing telemetry to a component in a digital twin. var componentTelemetryOptions = new PublishComponentTelemetryOptions() { TimeStamp = default }; var telemetryPayload = new Dictionary <string, int> { { "ComponentTelemetry1", 9 } }; Response publishComponentTelemetryResponse = await client .PublishComponentTelemetryAsync(roomWithWifiTwinId, wifiComponentName, Recording.Random.NewGuid().ToString(), JsonSerializer.Serialize(telemetryPayload), componentTelemetryOptions) .ConfigureAwait(false); // Assert publishComponentTelemetryResponse.Status.Should().Be((int)HttpStatusCode.NoContent); } catch (Exception ex) { Assert.Fail($"Failure in executing a step in the test case: {ex.Message}."); } finally { // clean up try { if (!string.IsNullOrWhiteSpace(eventRouteId)) { await client.DeleteEventRouteAsync(eventRouteId).ConfigureAwait(false); } if (!string.IsNullOrWhiteSpace(roomWithWifiTwinId)) { await client.DeleteDigitalTwinAsync(roomWithWifiTwinId).ConfigureAwait(false); } if (!string.IsNullOrWhiteSpace(roomWithWifiModelId)) { await client.DeleteModelAsync(roomWithWifiModelId).ConfigureAwait(false); } if (!string.IsNullOrWhiteSpace(wifiModelId)) { await client.DeleteModelAsync(wifiModelId).ConfigureAwait(false); } } catch (Exception ex) { Assert.Fail($"Test clean up failed: {ex.Message}"); } } }
//------------------------------------------------------------------- // // Internal Methods // //------------------------------------------------------------------- #region Internal Methods /// <summary> /// Allows FrameworkElement to augment the EventRoute. /// </summary> internal override bool BuildRouteCore(EventRoute route, RoutedEventArgs args) { // If FlowDocumentPageViewer is used as embedded viewer (in FlowDocumentReader), // it is not part of logical tree, so default logic in FE to re-add logical // tree from branched node does not work here. // But before FlowDocumentPageViewer is added to the event route, logical // ancestors up to Document need to be added to the route. Otherwise // content will not have a chance to react to events first. // This breaks navigation cursor management logic, because TextEditor attached // to FlowDocumentPageViewer handles those events first. DependencyObject document = this.Document as DependencyObject; if (document != null && LogicalTreeHelper.GetParent(document) != this) { DependencyObject branchNode = route.PeekBranchNode() as DependencyObject; if (branchNode != null && DocumentViewerHelper.IsLogicalDescendent(branchNode, document)) { // Add intermediate ContentElements to the route. FrameworkElement.AddIntermediateElementsToRoute( LogicalTreeHelper.GetParent(document), route, args, LogicalTreeHelper.GetParent(branchNode)); } } return base.BuildRouteCore(route, args); }
// If the routed event type matches one the element listening on then add handler to the event route. internal static void AddHandlerToRoute(DependencyObject o, EventRoute route, RoutedEventHandler eventHandler, bool handledToo) { // Add a synchronized input handler to the route. route.Add(o, eventHandler, handledToo); }
/// <summary> /// Adds or replaces an event route. /// Status codes: /// 200 (OK): Success. /// 400 (Bad Request): The request is invalid. /// </summary> /// <param name='id'> /// The id for an event route. The id is unique within event routes and case /// sensitive. /// </param> /// <param name='eventRoute'> /// The event route data /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse> AddWithHttpMessagesAsync(string id, EventRoute eventRoute = default(EventRoute), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (id == null) { throw new ValidationException(ValidationRules.CannotBeNull, "id"); } if (eventRoute != null) { eventRoute.Validate(); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("id", id); tracingParameters.Add("eventRoute", eventRoute); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Add", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "eventroutes/{id}").ToString(); _url = _url.Replace("{id}", System.Uri.EscapeDataString(id)); List <string> _queryParameters = new List <string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } 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 (eventRoute != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(eventRoute, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await 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 != 204) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } 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 AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// Raise the events specified by /// <see cref="RoutedEventArgs.RoutedEvent"/> /// </summary> /// <remarks> /// This method is a shorthand for /// This method walks up the visual tree, calling /// <see cref="UIElement.BuildRouteCore"/> /// on every <see cref="UIElement"/> <para/> /// <para/> /// /// NOTE: The RoutedEvent in RoutedEventArgs /// and EventRoute must be matched /// /// Once the route is built, it calls InvokeHandlers() /// </remarks> /// <param name="args"> /// <see cref="RoutedEventArgs"/> for the event to /// be raised /// </param> public void RaiseEvent(RoutedEventArgs args) { // Verify Context Access VerifyAccess(); if (args == null) { throw new ArgumentNullException(); } EventRoute route = new EventRoute(args._routedEvent); // Set Source args.Source = this; // direct. if (args._routedEvent._routingStrategy == RoutingStrategy.Direct) { this.AddToEventRouteImpl(route, args); } else { int cElements = 0; UIElement uiElement = this; do { // Protect against infinite loops by limiting the number of elements // that we will process. if (cElements++ > MAX_ELEMENTS_IN_ROUTE) { throw new InvalidOperationException(/*SR.Get(SRID.TreeLoop) */); } uiElement.AddToEventRouteImpl(route, args); uiElement = uiElement._parent; } while (uiElement != null); } route.InvokeHandlers(this, args); // Reset Source to OriginalSource args.Source = args.OriginalSource; }
/// <summary> /// When RenderScope is FlowDocumentView, events can bypass our nested ScrollViewer. /// We want to make sure that ScrollViewer-- and any other elements in our style-- /// always gets a `crack at mouse events. /// </summary> internal override void AddToEventRouteCore(EventRoute route, RoutedEventArgs args) { base.AddToEventRouteCore(route, args); // Walk up the tree from the RenderScope to this, adding each element to the route Visual visual = this.RenderScope; while (visual != this && visual != null) { if (visual is UIElement) { ((UIElement)visual).AddToEventRoute(route, args); } visual = VisualTreeHelper.GetParent(visual) as Visual; } }
private static void BuildRoute(DependencyObject element, EventRoute route, RadRoutedEventArgs args) { CheckParameters(route, args); if (args.RoutedEvent.RoutingStrategy == RoutingStrategy.Direct) { RadRoutedEventHelper.AddToEventRoute(element, route, args); } else { int nestLevel = 0; while (element != null) { if (nestLevel++ > 0x1000) { throw new InvalidOperationException(SR.Get(SRID.TreeLoop)); } object source = null; if (source != null) { route.AddSource(source); } if (element != null) { RadRoutedEventHelper.AddToEventRoute(element, route, args); element = FindParent(element as FrameworkElement); } if (element == args.Source) { route.AddSource(element); } } } }