public void LoadShapePositions(string solutionFolder)
        {
            FilePath = Path.Combine(solutionFolder, "DiagramShapePositions.json");

            tracer.Verbose("Loading shape positions from {0}", FilePath);

            // Load shape positions from file
            try
            {
                if (File.Exists(FilePath))
                {
                    var fileContent = File.ReadAllText(FilePath);
                    ShapePositions = JsonConvert.DeserializeObject <Dictionary <Guid, Point> >(fileContent);
                    tracer.Info("Loaded shape positions from {0}", FilePath);
                }
                else
                {
                    tracer.Info("Could not find shape positions file at {0}", FilePath);
                }
            }
            catch (Exception ex)
            {
                tracer.Error(ex, "Cannot load shape positions from {0}.", FilePath);
            }

            // If File not exists or an error ocurred
            if (ShapePositions == null)
            {
                ShapePositions = new Dictionary <Guid, Point>();
            }
        }
Beispiel #2
0
        public bool Initialize(Endpoint endpoint)
        {
            NetworkStream clientStream;
            NetworkStream serverStream;

            try
            {
                m_serverEndpoint   = endpoint;
                clientStream       = m_clientConnection.GetStream();
                m_serverConnection = new TcpClient(endpoint.Hostname, endpoint.Port)
                {
                    NoDelay = true
                };
                serverStream = m_serverConnection.GetStream();
            }
            catch (Exception ex) when(ex is SocketException || ex is InvalidOperationException)
            {
                m_tracer.Error(ex.ToString());
                return(false);
            }

            HandleClientTraffic(clientStream, serverStream);
            HandleServerTraffic(serverStream, clientStream);

            return(true);
        }
        void PublishXaml(string fileName)
        {
            // Make sure we can read it as XML, just to safeguard the client.
            try {
                using (var reader = XmlReader.Create(fileName)) {
                    var xdoc = XDocument.Load(reader);
                    // Strip the x:Class attribute since it doesn't make
                    // sense for the deserialization and might break stuff.
                    var xclass = xdoc.Root.Attribute("{http://schemas.microsoft.com/winfx/2009/xaml}Class");
                    if (xclass != null)
                    {
                        xclass.Remove();
                    }
                    xclass = xdoc.Root.Attribute("{http://schemas.microsoft.com/winfx/2006/xaml}Class");
                    if (xclass != null)
                    {
                        xclass.Remove();
                    }

                    var xml = xdoc.ToString(SaveOptions.DisableFormatting);
                    tracer.Info("!Publishing XAML payload");

                    proxy.Invoke("Xaml", SessionId, xml)
                    .ContinueWith(t =>
                                  tracer.Error(t.Exception.InnerException, "Failed to publish XAML payload."),
                                  CancellationToken.None,
                                  TaskContinuationOptions.OnlyOnFaulted,
                                  TaskScheduler.Default);
                }
            } catch (XmlException) {
                return;
            }
        }
Beispiel #4
0
        internal void ValidateCustomizedSettingsOverriddenByCustomizableState(ValidationContext context)
        {
            try
            {
                if (this.IsCustomizationEnabled)
                {
                    if ((this.IsCustomizable == CustomizationState.False) &&
                        (this.Policy.IsModified == true))
                    {
                        context.LogWarning(
                            string.Format(CultureInfo.CurrentCulture, Properties.Resources.Validate_CustomizedSettingsOverriddenByCustomizableState, this.Name),
                            Properties.Resources.Validate_CustomizedSettingsOverriddenByCustomizableStateCode, this);
                    }
                }
            }
            catch (Exception ex)
            {
                tracer.Error(
                    ex,
                    Resources.ValidationMethodFailed_Error,
                    Reflector <CustomizableElementSchemaBase> .GetMethod(n => n.ValidateCustomizedSettingsOverriddenByCustomizableState(context)).Name);

                throw;
            }
        }
        internal void ValidateNameIsUnique(ValidationContext context)
        {
            try
            {
                IEnumerable <PatternElementSchema> sameNamedElements;
                if (this.View != null)
                {
                    // Get siblings in the owning view
                    sameNamedElements = this.View.AllElements()
                                        .Where(element => element.Name.Equals(this.Name, System.StringComparison.OrdinalIgnoreCase));
                }
                else
                {
                    // Get siblings in the owning element
                    sameNamedElements = this.Owner.AllElements()
                                        .Where(element => element.Name.Equals(this.Name, System.StringComparison.OrdinalIgnoreCase));
                }

                if (sameNamedElements.Count() > 1)
                {
                    context.LogError(
                        string.Format(CultureInfo.CurrentCulture, Resources.Validate_PatternElementNameIsNotUnique, this.Name),
                        Resources.Validate_PatternElementNameIsNotUniqueCode, this);
                }
            }
            catch (Exception ex)
            {
                tracer.Error(
                    ex,
                    Resources.ValidationMethodFailed_Error,
                    Reflector <ExtensionPointSchema> .GetMethod(n => n.ValidateNameIsUnique(context)).Name);

                throw;
            }
        }
Beispiel #6
0
        internal void ValidateCommandIdAndWizardIdIsNotEmpty(ValidationContext context, DragDropSettings settings)
        {
            Guard.NotNull(() => context, context);
            Guard.NotNull(() => settings, settings);

            try
            {
                // Ensure not empty
                if (settings.CommandId == Guid.Empty && settings.WizardId == Guid.Empty)
                {
                    context.LogError(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            Resources.Validate_DragDropSettingsCommandIdAndWizardIdIsNotEmpty,
                            settings.Name),
                        Resources.Validate_DragDropSettingsCommandIdAndWizardIdIsNotEmptyCode, settings.Extends);
                }
            }
            catch (Exception ex)
            {
                tracer.Error(
                    ex,
                    Resources.ValidationMethodFailed_Error,
                    Reflector <DragDropSettingsValidations> .GetMethod(n => n.ValidateCommandIdAndWizardIdIsNotEmpty(null, null)).Name);

                throw;
            }
        }
        async Task HandleConnectionExceptionAsync(Exception exception)
        {
            if (exception is TimeoutException)
            {
                await NotifyErrorAsync(ServerProperties.Resources.ServerPacketListener_NoConnectReceived, exception)
                .ConfigureAwait(continueOnCapturedContext: false);
            }
            else if (exception is MqttConnectionException)
            {
                tracer.Error(exception, ServerProperties.Resources.ServerPacketListener_ConnectionError, clientId ?? "N/A");

                var connectEx = exception as MqttConnectionException;
                var errorAck  = new ConnectAck(connectEx.ReturnCode, existingSession: false);

                try {
                    await channel.SendAsync(errorAck)
                    .ConfigureAwait(continueOnCapturedContext: false);
                } catch (Exception ex) {
                    await NotifyErrorAsync(ex).ConfigureAwait(continueOnCapturedContext: false);
                }
            }
            else
            {
                await NotifyErrorAsync(exception).ConfigureAwait(continueOnCapturedContext: false);
            }
        }
        public override void EndInit()
        {
            base.EndInit();

            this.statusBar = serviceProvider.GetService <SVsStatusbar, IVsStatusbar>();

            //this.DragEnterEvent = GetObservableEvent(typeof(IOnSolutionBuilderDragEnter));
            //this.DragLeaveEvent = GetObservableEvent(typeof(IOnSolutionBuilderDragLeave));
            //this.DropEvent = GetObservableEvent(typeof(IOnSolutionBuilderDrop));

            this.dragEnterEventSubscription = this.DragEnterEvent.Subscribe(this.OnDragEnterEvent);
            this.dragLeaveEventSubscription = this.DragLeaveEvent.Subscribe(this.OnDragLeaveEvent);
            this.dropEventSubscription      = this.DropEvent.Subscribe(this.OnDropEvent);

            if (this.BindingFactory != null)
            {
                try
                {
                    this.Conditions = this.Settings.ConditionSettings.Select(x => this.BindingFactory.CreateBinding <ICondition>(x)).ToArray();
                }
                catch (Exception e)
                {
                    tracer.Error(e, Resources.EventAutomation_FailedToParseConditions, this.Name);
                    if (Microsoft.VisualStudio.ErrorHandler.IsCriticalException(e))
                    {
                        throw;
                    }
                }
            }
        }
Beispiel #9
0
        /// <summary>
        /// Load native symbols and modules (i.e. dac, dbi).
        /// </summary>
        /// <param name="callback">called back for each symbol file loaded</param>
        /// <param name="parameter">callback parameter</param>
        /// <param name="tempDirectory">temp directory unique to this instance of SOS</param>
        /// <param name="moduleFilePath">module path</param>
        /// <param name="address">module base address</param>
        /// <param name="size">module size</param>
        /// <param name="readMemory">read memory callback delegate</param>
        public static void LoadNativeSymbols(SymbolFileCallback callback, IntPtr parameter, string tempDirectory, string moduleFilePath, ulong address, int size, ReadMemoryDelegate readMemory)
        {
            if (IsSymbolStoreEnabled())
            {
                Debug.Assert(s_tracer != null);
                Stream       stream    = new TargetStream(address, size, readMemory);
                KeyTypeFlags flags     = KeyTypeFlags.SymbolKey | KeyTypeFlags.ClrKeys;
                KeyGenerator generator = null;

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    var elfFile = new ELFFile(new StreamAddressSpace(stream), 0, true);
                    generator = new ELFFileKeyGenerator(s_tracer, elfFile, moduleFilePath);
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    var machOFile = new MachOFile(new StreamAddressSpace(stream), 0, true);
                    generator = new MachOFileKeyGenerator(s_tracer, machOFile, moduleFilePath);
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    var peFile = new PEFile(new StreamAddressSpace(stream), true);
                    generator = new PEFileKeyGenerator(s_tracer, peFile, moduleFilePath);
                }
                else
                {
                    return;
                }

                try
                {
                    IEnumerable <SymbolStoreKey> keys = generator.GetKeys(flags);
                    foreach (SymbolStoreKey key in keys)
                    {
                        string moduleFileName = Path.GetFileName(key.FullPathName);
                        s_tracer.Verbose("{0} {1}", key.FullPathName, key.Index);

                        // Don't download the sos binaries that come with the runtime
                        if (moduleFileName != "SOS.NETCore.dll" && !moduleFileName.StartsWith("libsos."))
                        {
                            string downloadFilePath = GetSymbolFile(key, tempDirectory);
                            if (downloadFilePath != null)
                            {
                                s_tracer.Information("{0}: {1}", moduleFileName, downloadFilePath);
                                callback(parameter, moduleFileName, downloadFilePath);
                            }
                        }
                    }
                }
                catch (Exception ex) when(ex is BadInputFormatException || ex is InvalidVirtualAddressException)
                {
                    s_tracer.Error("{0}/{1:X16}: {2}", moduleFilePath, address, ex.Message);
                }
            }
        }
Beispiel #10
0
        /// <summary>
        /// Sets the value of the binding
        /// </summary>
        protected void SetValue(object target, object value)
        {
            var property = TypeDescriptor.GetProperties(target)
                           .Cast <PropertyDescriptor>()
                           .FirstOrDefault(d => d.Name == this.PropertyName);

            if (property != null)
            {
                if (value != null && !property.PropertyType.IsAssignableFrom(value.GetType()))
                {
                    if (property.Converter != null)
                    {
                        if (property.Converter.CanConvertFrom(value.GetType()))
                        {
                            property.SetValue(target, property.Converter.ConvertFrom(value));
                        }
                        else
                        {
                            var message = string.Format(CultureInfo.CurrentCulture,
                                                        Resources.PropertyBinding_PropertyNotCompatible,
                                                        ObjectDumper.ToString(value, 5), target, this.PropertyName, property.PropertyType, property.Converter);

                            tracer.Error(message);
                            throw new ArgumentException(message);
                        }
                    }
                    else
                    {
                        var message = string.Format(CultureInfo.CurrentCulture,
                                                    Resources.PropertyBinding_TracePropertyCustomNotCompatible,
                                                    ObjectDumper.ToString(value, 5), target, this.PropertyName, property.PropertyType);

                        tracer.Error(message);
                        throw new ArgumentException(message);
                    }
                }
                else
                {
                    property.SetValue(target, value);
                }
            }
            else
            {
                var message = string.Format(CultureInfo.CurrentCulture, Resources.PropertyBinding_TracePropertyNotFound, target, this.PropertyName);
                tracer.Error(message);
                throw new ArgumentException(message);
            }
        }
Beispiel #11
0
        public async Task <IMqttChannel <byte[]> > CreateAsync()
        {
            TcpClient tcpClient = new TcpClient();

            try
            {
                Task connectTask = tcpClient.ConnectAsync(_hostAddress, _configuration.Port);
                Task timeoutTask = Task.Delay(TimeSpan.FromSeconds(_configuration.ConnectionTimeoutSecs));
                Task resultTask  = await Task
                                   .WhenAny(connectTask, timeoutTask);

                if (resultTask == timeoutTask)
                {
                    throw new TimeoutException();
                }

                if (resultTask.IsFaulted)
                {
                    ExceptionDispatchInfo.Capture(resultTask.Exception.InnerException).Throw();
                }

                return(new TcpChannel(tcpClient, new PacketBuffer(), _configuration));
            }
            catch (SocketException socketEx)
            {
                string message = ClientProperties.TcpChannelFactory_TcpClient_Failed(_hostAddress, _configuration.Port);

                _tracer.Error(socketEx, message);

                throw new MqttException(message, socketEx);
            }
            catch (TimeoutException timeoutEx)
            {
                try
                {
                    // Just in case the connection is a little late,
                    // dispose the tcpClient. This may throw an exception,
                    // which we should just eat.
                    tcpClient.Dispose();
                }
                catch { }

                string message = ClientProperties.TcpChannelFactory_TcpClient_Failed(_hostAddress, _configuration.Port);

                _tracer.Error(timeoutEx, message);
                throw new MqttException(message, timeoutEx);
            }
        }
Beispiel #12
0
        public void Dispose()
        {
            _cancellationTokenSource.Cancel(false);
            _attachedMessages.Clear();
            _renewalQueue.CompleteAdding();

            try
            {
                _renewalManager.Wait();
                _renewer.Wait();
            }
            catch (Exception ex)
            {
                _tracer.Error(ex, "Renewal producer/consumer finished with failures");
            }
        }
        internal void ValidateArtifactReferences(ValidationContext context, IProductElement element)
        {
            if (this.UriReferenceService == null)
            {
                return;
            }

            try
            {
                var references = SolutionArtifactLinkReference.GetReferenceValues(element);

                foreach (var reference in references)
                {
                    if (this.UriReferenceService.TryResolveUri <IItemContainer>(reference) == null)
                    {
                        context.LogError(
                            string.Format(CultureInfo.InvariantCulture,
                                          Properties.Resources.Validate_ArtifactReferenceNotFound,
                                          element.InstanceName, reference.ToString(), ReflectionExtensions.DisplayName(typeof(SolutionArtifactLinkReference))),
                            Properties.Resources.Validate_ArtifactReferenceNotFoundCode,
                            element as ModelElement);
                    }
                }
            }
            catch (Exception ex)
            {
                tracer.Error(
                    ex,
                    Properties.Resources.ValidationMethodFailed_Error,
                    Reflector <ArtifactReferenceValidation> .GetMethod(n => n.ValidateArtifactReferences(context, element)).Name);

                throw;
            }
        }
Beispiel #14
0
        public static void ActivateSharedGuidanceWorkflow(this IGuidanceManager guidanceManager, IServiceProvider provider, string extensionId)
        {
            Guard.NotNull(() => guidanceManager, guidanceManager);
            Guard.NotNull(() => provider, provider);
            Guard.NotNullOrEmpty(() => extensionId, extensionId);

            var registration = guidanceManager.InstalledGuidanceExtensions.First(e => e.ExtensionId == extensionId);

            if (registration == null)
            {
                tracer.Error(Resources.GuidanceManagerExtensions_ErrorNoRegistration, extensionId);
                return;
            }
            else
            {
                // Ensure at least one instance exists
                var instance = guidanceManager.InstantiatedGuidanceExtensions.FirstOrDefault(e => e.ExtensionId == extensionId);
                if (instance == null)
                {
                    // Create the first instance of the guidance
                    tracer.ShieldUI(() =>
                    {
                        instance = guidanceManager.Instantiate(extensionId, registration.DefaultName);
                    }, Resources.GuidanceManagerExtensions_ErrorGuidanceInstantiationFailed, registration.DefaultName, extensionId);
                }

                // Activate the instance
                if (instance != null)
                {
                    guidanceManager.ActivateGuidanceInstance(provider, instance);
                }
            }
        }
Beispiel #15
0
        internal void ValidateTypeNameNotEmpty(ValidationContext context)
        {
            try
            {
                // Ensure not empty
                if (string.IsNullOrEmpty(this.TypeName))
                {
                    context.LogError(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            Resources.Validate_WizardSettingsTypeIsNotEmpty,
                            this.Name),
                        Resources.Validate_WizardSettingsTypeIsNotEmptyCode, this.Extends);
                }
            }
            catch (Exception ex)
            {
                tracer.Error(
                    ex,
                    Resources.ValidationMethodFailed_Error,
                    Reflector <WizardSettings> .GetMethod(n => n.ValidateTypeNameNotEmpty(context)).Name);

                throw;
            }
        }
Beispiel #16
0
        public static Exception ShieldUI(this ITracer tracer, Action action, string errorMessageFormat, params string[] errorArgs)
        {
            Guard.NotNull(() => tracer, tracer);
            Guard.NotNull(() => action, action);
            Guard.NotNullOrEmpty(() => errorMessageFormat, errorMessageFormat);
            Guard.NotNull(() => errorArgs, errorArgs);

            try
            {
                action();
            }
            catch (Exception ex)
            {
                if (ErrorHandler.IsCriticalException(ex))
                {
                    throw;
                }
                else
                {
                    tracer.Error(ex, errorMessageFormat, errorArgs);

                    ShowExceptionAction(ex, errorMessageFormat, errorArgs);

                    return(ex);
                }
            }

            return(null);
        }
            public bool CanExecute(object parameter)
            {
                var propertyChanged = this.automation as INotifyPropertyChanged;

                try
                {
                    // Prevent re-entrancy on query status
                    if (propertyChanged != null)
                    {
                        propertyChanged.PropertyChanged -= this.OnMenuPropertyChanged;
                    }

                    this.status.QueryStatus(this.menu);
                    parent.IsEnabled = this.menu.Enabled;
                    parent.IsVisible = this.menu.Visible;
                }
                catch (Exception e)
                {
                    tracer.Error(e, Resources.AutomationCommand_QueryStatusFailed);
                    return(false);
                }
                finally
                {
                    // Enable status monitoring again.
                    if (propertyChanged != null)
                    {
                        propertyChanged.PropertyChanged += this.OnMenuPropertyChanged;
                    }
                }

                return(this.menu.Enabled);
            }
Beispiel #18
0
        internal void ValidateNameIsUnique(ValidationContext context)
        {
            try
            {
                IEnumerable <AutomationSettingsSchema> sameNamedElements = this.Owner.AutomationSettings
                                                                           .Where(setting => setting.Name.Equals(this.Name, System.StringComparison.OrdinalIgnoreCase));

                if (sameNamedElements.Count() > 1)
                {
                    // Check if one of the properties is a system property
                    if (sameNamedElements.FirstOrDefault(property => property.IsSystem == true) != null)
                    {
                        context.LogError(
                            string.Format(CultureInfo.CurrentCulture, Properties.Resources.Validate_AutomationSettingsNameSameAsSystem, this.Name),
                            Properties.Resources.Validate_AutomationSettingsNameSameAsSystemCode, this);
                    }
                    else
                    {
                        context.LogError(
                            string.Format(CultureInfo.CurrentCulture, Properties.Resources.Validate_AutomationSettingsNameIsNotUnique, this.Name),
                            Properties.Resources.Validate_AutomationSettingsNameIsNotUniqueCode, this);
                    }
                }
            }
            catch (Exception ex)
            {
                tracer.Error(
                    ex,
                    Resources.ValidationMethodFailed_Error,
                    Reflector <AutomationSettingsSchema> .GetMethod(n => n.ValidateNameIsUnique(context)).Name);

                throw;
            }
        }
Beispiel #19
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }

            if (disposing)
            {
                tracer.Info(Properties.Resources.Mqtt_Disposing, GetType().FullName);

                streamSubscription.Dispose();
                receiver.OnCompleted();

                try {
                    client?.CloseAsync(WebSocketCloseStatus.NormalClosure, "Dispose", CancellationToken.None).Wait();
                    client?.Dispose();
                }
                catch (SocketException socketEx) {
                    tracer.Error(socketEx, Properties.Resources.MqttChannel_DisposeError, socketEx.SocketErrorCode);
                }

                disposed = true;
            }
        }
        protected async override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.SimpleMain);

            //UI Logic
            ConfigureUI();

            Console.WriteLine("Welcome to Raspberry Extensions tests");
            var relay = new IoTRelay(Connectors.GPIO17, Connectors.GPIO27);

            hubContainer       = new RelayHubTest();
            hubContainer.Step += (sender, step) => {
                RunOnUiThread(() => lblLog.Text = $"Step {step}");
            };
            hubContainer.Finished += delegate {
                RunOnUiThread(() => lblLog.Text = $"Finished");
            };

            hubContainer.Configure(relay);
            try {
                await hubContainer.StartAsync(loop : true);
            } catch (Exception ex) {
                tracer.Error(ex);
            }
        }
Beispiel #21
0
        async Task HandleConnectionExceptionAsync(Exception exception)
        {
            if (exception is TimeoutException)
            {
                await NotifyErrorAsync(ServerProperties.ServerPacketListener_NoConnectReceived, exception);
            }
            else if (exception is MqttConnectionException)
            {
                _tracer.Error(exception, ServerProperties.ServerPacketListener_ConnectionError(_clientId ?? "N/A"));

                MqttConnectionException connectEx = exception as MqttConnectionException;
                ConnectAck errorAck = new ConnectAck(connectEx.ReturnCode, existingSession: false);

                try
                {
                    await _channel.SendAsync(errorAck);
                }
                catch (Exception ex)
                {
                    await NotifyErrorAsync(ex);
                }
            }
            else
            {
                await NotifyErrorAsync(exception);
            }
        }
Beispiel #22
0
        public CommandRegistrar([ImportMany] IEnumerable <Lazy <ICommandExtension, ICommandMetadata> > commands)
        {
            commandsByPackage = new Lazy <ConcurrentDictionary <Guid, List <Lazy <ICommandExtension, ICommandMetadata> > > >(
                () =>
            {
                var result = new ConcurrentDictionary <Guid, List <Lazy <ICommandExtension, ICommandMetadata> > >();

                foreach (var groupedCommands in commands.GroupBy(x => x.Metadata.PackageId))
                {
                    try
                    {
                        result
                        .AddOrUpdate(
                            new Guid(groupedCommands.Key),
                            key => new List <Lazy <ICommandExtension, ICommandMetadata> >(groupedCommands),
                            (key, value) =>
                        {
                            value.AddRange(groupedCommands);
                            return(value);
                        });
                    }
                    catch (Exception ex)
                    {
                        tracer.Error(ex, Strings.CommandRegistrar.ErrorImportingCommandForPackage(groupedCommands.Key));
                    }
                }

                return(result);
            });
        }
        internal void ValidateGuidanceReference(ValidationContext context, IProductElement element)
        {
            try
            {
                if (this.GuidanceManager == null)
                {
                    return;
                }

                var reference = element.TryGetReference(ReferenceKindConstants.GuidanceTopic);
                if (!string.IsNullOrEmpty(reference))
                {
                    var uri = GuidanceReference.GetResolvedReferences(element, this.GuidanceManager).FirstOrDefault();
                    if (uri == null)
                    {
                        context.LogError(
                            string.Format(CultureInfo.InvariantCulture,
                                          Properties.Resources.Validate_GuidanceReferenceNotFound,
                                          element.InstanceName, reference, ReflectionExtensions.DisplayName(typeof(GuidanceReference))),
                            Properties.Resources.Validate_GuidanceReferenceNotFoundCode,
                            element as ModelElement);
                    }
                }
            }
            catch (Exception ex)
            {
                tracer.Error(
                    ex,
                    Properties.Resources.ValidationMethodFailed_Error,
                    Reflector <GuidanceReferenceValidation> .GetMethod(n => n.ValidateGuidanceReference(context, element)).Name);

                throw;
            }
        }
        /// <summary>
        /// Builds the URI for the given template based on the containing project VSIX manifest identifier.
        /// </summary>
        internal static Uri BuildUri(IItemContainer selectedItem)
        {
            var manifest      = selectedItem.GetToolkitManifest();
            var owningProject = selectedItem.Traverse(x => x.Parent, item => item.Kind == ItemKind.Project);

            tracer.Info(Properties.Resources.TextTemplateUriEditor_TraceReadingManifest, manifest.GetLogicalPath());

            string vsixId;

            try
            {
                vsixId = Vsix.ReadManifestIdentifier(manifest.PhysicalPath);
            }
            catch (Exception e)
            {
                tracer.Error(e,
                             String.Format(CultureInfo.CurrentCulture, Properties.Resources.TextTemplateUriEditor_TraceReadingManifestFailed, manifest.GetLogicalPath()));
                throw;
            }

            var path = GetLogicalPath(selectedItem).Replace(owningProject.GetLogicalPath(), string.Empty);

            // Use alternative name if IncludeInVSIXAs defined
            var templateItem = (IItem)selectedItem;

            if (IsIncludeInVSIXAs(templateItem))
            {
                path = Path.Combine(Path.GetDirectoryName(path), templateItem.Data.IncludeInVSIXAs);
            }

            return(new Uri(new Uri(TextTemplateUri.UriHostPrefix), new Uri(vsixId + path, UriKind.Relative)));
        }
        internal void ValidateTypeIsNotEmpty(ValidationContext context, CommandSettings settings)
        {
            Guard.NotNull(() => context, context);
            Guard.NotNull(() => settings, settings);

            try
            {
                // Ensure not empty
                if (string.IsNullOrEmpty(settings.TypeId))
                {
                    context.LogError(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            Resources.Validate_CommandSettingsTypeIsNotEmpty,
                            settings.Name),
                        Resources.Validate_CommandSettingsTypeIsNotEmptyCode, settings.Extends);
                }
            }
            catch (Exception ex)
            {
                tracer.Error(
                    ex,
                    Resources.ValidationMethodFailed_Error,
                    Reflector <CommandSettingsValidations> .GetMethod(n => n.ValidateTypeIsNotEmpty(null, null)).Name);

                throw;
            }
        }
Beispiel #26
0
        /// <summary>
        /// Called when validations are needed for the command
        /// </summary>
        /// <param name="context">Validation Context where to add validation errors</param>
        /// <param name="settingsElement">The settings element in the model being validated</param>
        /// <param name="settings">Settings for the command</param>
        public void Validate(Microsoft.VisualStudio.Modeling.Validation.ValidationContext context, IAutomationSettingsSchema settingsElement, ICommandSettings settings)
        {
            try
            {
                Guard.NotNull(() => settings, settings);

                var templateValidator = new TemplateValidator(settings.Name,
                                                              new UnfoldVsTemplateCommand.UnfoldVsTemplateSettings
                {
                    SanitizeName         = settings.GetPropertyValue <bool>(Reflector <UnfoldVsTemplateCommand> .GetPropertyName(u => u.SanitizeName)),
                    SyncName             = settings.GetPropertyValue <bool>(Reflector <UnfoldVsTemplateCommand> .GetPropertyName(u => u.SyncName)),
                    TemplateAuthoringUri = settings.GetPropertyValue <string>(Reflector <UnfoldVsTemplateCommand> .GetPropertyName(u => u.TemplateAuthoringUri)),
                    TemplateUri          = settings.GetPropertyValue <string>(Reflector <UnfoldVsTemplateCommand> .GetPropertyName(u => u.TemplateUri)),
                    SettingsElement      = settingsElement,
                    OwnerElement         = settings.Owner,
                }, context, ((ModelElement)settings).Store);
                templateValidator.ValidateCommandSettings(tracer);
            }
            catch (Exception ex)
            {
                tracer.Error(
                    ex,
                    Resources.ValidationMethodFailed_Error,
                    Reflector <TemplateValidator> .GetMethod(n => n.ValidateCommandSettings(null)).Name);

                throw;
            }
        }
Beispiel #27
0
        public IEnumerable <StageResult> Handle(IReadOnlyDictionary <Guid, List <IAggregatableMessage> > processingResultsMap)
        {
            try
            {
                var commands = processingResultsMap.SelectMany(x => x.Value).Cast <AggregatableMessage <ICommand> >().SelectMany(x => x.Commands).ToList();

                using (Probe.Create("ETL2 Transforming"))
                    using (var transaction = new TransactionScope(TransactionScopeOption.Required, _transactionOptions))
                    {
                        var syncEvents = Handle(commands.OfType <IAggregateCommand>().ToList())
                                         .Select(x => new FlowEvent(AggregatesFlow.Instance, x)).ToList();

                        using (new TransactionScope(TransactionScopeOption.Suppress))
                            _eventLogger.Log <IEvent>(syncEvents);

                        transaction.Complete();
                    }

                var stateEvents = Handle(commands.OfType <IncrementErmStateCommand>().ToList()).Concat(
                    Handle(commands.OfType <IncrementAmsStateCommand>().ToList())).Concat(
                    Handle(commands.OfType <LogDelayCommand>().ToList()))
                                  .Select(x => new FlowEvent(AggregatesFlow.Instance, x)).ToList();
                _eventLogger.Log <IEvent>(stateEvents);

                return(processingResultsMap.Keys.Select(bucketId => MessageProcessingStage.Handling.ResultFor(bucketId).AsSucceeded()));
            }
            catch (Exception ex)
            {
                _tracer.Error(ex, "Error when calculating aggregates");
                return(processingResultsMap.Keys.Select(bucketId => MessageProcessingStage.Handling.ResultFor(bucketId).AsFailed().WithExceptions(ex)));
            }
        }
Beispiel #28
0
        public async Task <IMqttConnectedClient> CreateClientAsync(MqttConfiguration configuration)
        {
            try
            {
                //Adding this to not break backwards compatibility related to the method signature
                //Yielding at this point will cause the method to return immediately after it's called,
                //running the rest of the logic acynchronously
                await Task.Yield();

                var binding             = new PrivateBinding(privateStreamListener, EndpointIdentifier.Client);
                var topicEvaluator      = new MqttTopicEvaluator(configuration);
                var innerChannelFactory = binding.GetChannelFactory(IPAddress.Loopback.ToString(), configuration);
                var channelFactory      = new PacketChannelFactory(innerChannelFactory, topicEvaluator, configuration);
                var packetIdProvider    = new PacketIdProvider();
                var repositoryProvider  = new InMemoryRepositoryProvider();
                var flowProvider        = new ClientProtocolFlowProvider(topicEvaluator, repositoryProvider, configuration);

                return(new MqttConnectedClient(channelFactory, flowProvider, repositoryProvider, packetIdProvider, configuration));
            }
            catch (Exception ex)
            {
                tracer.Error(ex, Properties.Resources.Client_InitializeError);

                throw new MqttClientException(Properties.Resources.Client_InitializeError, ex);
            }
        }
Beispiel #29
0
        /// <summary>
        /// Discards changes since the last <see cref="M:System.ComponentModel.IEditableObject.BeginEdit" /> call.
        /// </summary>
        public virtual void CancelEdit()
        {
            tracer.Verbose("CancelEdit");

            if (this.editing)
            {
                this.editing = false;
                // Restore a clean copy of the object, as if it was brand-new created.
                try
                {
                    var clean = Activator.CreateInstance(this.GetType(), this.manager);
                    foreach (var property in TypeDescriptor.GetProperties(this).Cast <PropertyDescriptor>())
                    {
                        property.SetValue(this, property.GetValue(clean));
                    }

                    this.IsInitialized = false;
                    this.manager.Read(this);
                }
                catch (Exception ex)
                {
                    tracer.Error(ex, Strings.Settings.FailedToRestore);
                    // TODO: failed to restore some properties. Leave current object state as-is?
                }
            }
        }
Beispiel #30
0
        /// <summary>
        /// Creates an MQTT Client
        /// </summary>
        /// <param name="configuration">
        /// The configuration used for creating the Client
        /// See <see cref="MqttConfiguration" /> for more details about the supported values
        /// </param>
        /// <returns>A new MQTT Client</returns>
        /// <exception cref="MqttClientException">MqttClientException</exception>
        public async Task <IMqttClient> CreateClientAsync(MqttConfiguration configuration)
        {
            try
            {
                //Adding this to not break backwards compatibility related to the method signature
                //Yielding at this point will cause the method to return immediately after it's called,
                //running the rest of the logic acynchronously
                await Task.Yield();

                MqttTopicEvaluator         topicEvaluator      = new MqttTopicEvaluator(configuration);
                IMqttChannelFactory        innerChannelFactory = _binding.GetChannelFactory(_hostAddress, configuration);
                PacketChannelFactory       channelFactory      = new PacketChannelFactory(innerChannelFactory, topicEvaluator, configuration);
                PacketIdProvider           packetIdProvider    = new PacketIdProvider();
                InMemoryRepositoryProvider repositoryProvider  = new InMemoryRepositoryProvider();
                ClientProtocolFlowProvider flowProvider        = new ClientProtocolFlowProvider(topicEvaluator, repositoryProvider, configuration);

                return(new MqttClientImpl(channelFactory, flowProvider, repositoryProvider, packetIdProvider, configuration));
            }
            catch (Exception ex)
            {
                _tracer.Error(ex, ClientProperties.Client_InitializeError);

                throw new MqttClientException(ClientProperties.Client_InitializeError, ex);
            }
        }
Beispiel #31
0
        /// <summary>
        /// Synchronizes the targets file on disk with targets file in this version of the toolkit.
        /// </summary>
        internal static void SyncTargets(ITracer tracer, TargetsInfo targetsInfo)
        {
            try
            {
                tracer.Info(Resources.AuthoringPackage_TraceSyncTargetsInitial);

                //Write updated targets file
                WriteUpdatedTargets(tracer, targetsInfo);
            }
            catch (Exception ex)
            {
                tracer.Error(ex, Resources.AuthoringPackage_FailedSyncTargets);
            }
        }
        public static string Evaluate(this IPropertyBindingSettings settings, IBindingFactory bindingFactory, ITracer tracer, Action<IDynamicBindingContext> contextInitializer = null)
        {
            string result;

            if (settings.ValueProvider != null)
            {
                var binding = bindingFactory.CreateBinding<IValueProvider>(settings.ValueProvider);
                // Make the entire set of element interfaces available to VP bindings.
                // We add the owner with its full interfaces. And we add the IProperty as well.
                using (var context = binding.CreateDynamicContext())
                {
                    if (contextInitializer != null)
                        contextInitializer(context);

                    if (binding.Evaluate(context))
                    {
                        result = binding.Value.Evaluate() as string;
                    }
                    else
                    {
                        var failMessage = string.Format(CultureInfo.CurrentCulture,
                            Resources.ValueProviderBinding_FailedToEvaluate,
                            settings.Name,
                            settings.Name,
                            ObjectDumper.ToString(binding.EvaluationResults, 5));

                        tracer.Error(failMessage);

                        throw new InvalidOperationException(failMessage);
                    }
                }
            }
            else
            {
                result = settings.Value;
            }

            return result;
        }