Reports anonymous usage through ApplicationInsights
Example #1
11
        public async Task<bool> TelemetryIngest(Telemetry telemetry)
        {

            string serviceBusNamespace = "iotmc-ns";
            string serviceBusUri = string.Format("{0}.servicebus.windows.net", serviceBusNamespace);
            string eventHubName = "IoTMC";
            string eventHubSASKeyName = "Device01";
            string eventHubSASKey = "<< Your SAS Key here >>";

            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri(String.Format("https://{0}", serviceBusUri));
                httpClient.DefaultRequestHeaders.Accept.Clear();

                string sBToken = CreateServiceBusSASToken(eventHubSASKeyName, eventHubSASKey, serviceBusUri);
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("SharedAccessSignature", sBToken);
                HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(telemetry), Encoding.UTF8);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
              
                string ingestPath = String.Format("/{0}/publishers/device01/messages", eventHubName);
                var response = await httpClient.PostAsync(ingestPath, httpContent);
                if (response.IsSuccessStatusCode)
                {
                    return true;
                }

                return false;
            }
        }
Example #2
0
 public Car(Telemetry telemetry, int carIdx)
 {
     this.telemetry = telemetry;
     this.carIdx = carIdx;
     this.driver = telemetry.SessionData.DriverInfo.CompetingDrivers[carIdx];
     this.Details = new CarDetails(telemetry, carIdx);
 }
Example #3
0
        public bool TelemetryIngest(Telemetry telemetry)
        {
            string serviceBusNamespace = "iotmc-ns";
            string serviceBusUri = string.Format("{0}.servicebus.windows.net", serviceBusNamespace);
            string eventHubName = "IoTMC";
            string eventHubSASKeyName = "Device01";
            string eventHubSASKey = "t0JK19v94H3R8yAZ1uVkGcIUFi8zmGmBts4N09aNI0s=";

            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri(String.Format("https://{0}", serviceBusUri));
                httpClient.DefaultRequestHeaders.Accept.Clear();

                string sBToken = CreateServiceBusSASToken(eventHubSASKeyName, eventHubSASKey, serviceBusUri);
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("SharedAccessSignature", sBToken);
                HttpContent httpContent = new StringContent(telemetry.asJson(), Encoding.UTF8);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                string ingestPath = String.Format("/{0}/publishers/device01/messages", eventHubName);
                Task<HttpResponseMessage> response = httpClient.PostAsync(ingestPath, httpContent);
                response.Wait();
                if (response.Result.IsSuccessStatusCode)
                {
                    return true;
                }
                return false;
            }
        }
        public void setup()
        {
            telemetry = new Telemetry();

            driver = new SessionData._DriverInfo._Drivers { CarNumberRaw = 1 };

            telemetry.SessionData = new SessionData
            {
                DriverInfo = new SessionData._DriverInfo
                {
                    Drivers = new SessionData._DriverInfo._Drivers[] 
                    {
                        driver
                    }
                }
            };
        }
        public async Task<IEnumerable<Telemetry>> GetLatestTelemetry(string deviceId)
        {
            var storageConnectionString = _settings.StorageConnectionString;
            var table = await AzureTableStorageHelper.GetTableAsync(storageConnectionString, _settings.TelemetryTableName);
            var startTime = DateTimeOffset.Now.AddSeconds(-TimeOffsetInSeconds).DateTime;

            var deviceFilter = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, deviceId);
            var timestampFilter = TableQuery.GenerateFilterConditionForDate("Timestamp", QueryComparisons.GreaterThanOrEqual, startTime);
            var filter = TableQuery.CombineFilters(deviceFilter, TableOperators.And, timestampFilter);

            TableQuery<TelemetryEntity> query = new TableQuery<TelemetryEntity>()
                .Where(filter)
                .Take(MaxRecordsToReceive)
                .Select(new[] { "sensor11", "sensor14", "sensor15", "sensor9" });

            var result = new Collection<Telemetry>();
            var entities = table.ExecuteQuery(query)
                .OrderByDescending(x => x.Timestamp)
                .Take(MaxRecordsToSend);

            foreach (var entity in entities)
            {
                var telemetry = new Telemetry
                {
                    DeviceId = entity.PartitionKey,
                    RecordId = entity.RowKey,
                    Timestamp = entity.Timestamp.DateTime,
                    Sensor1 = Math.Round(double.Parse(entity.sensor11)),
                    Sensor2 = Math.Round(double.Parse(entity.sensor14)),
                    Sensor3 = Math.Round(double.Parse(entity.sensor15)),
                    Sensor4 = Math.Round(double.Parse(entity.sensor9))
                };
                result.Add(telemetry);
            }

            return result.OrderBy(x => x.Timestamp);
        }
Example #6
0
 private void OnTelemetryUpdated(Telemetry.TelemetryEventArgs args)
 {
     if (TelemetryUpdated != null)
         TelemetryUpdated(this, args);
 }
        private async void VoiceController_CommandReceived(object sender, VoiceCommandControllerEventArgs e)
        {
            string response = "Sorry, I didn't get that.";

            try
            {
                var voiceCommand = (VoiceCommand)e.Data;

                switch (voiceCommand.CommandType)
                {
                case VoiceCommandType.Navigate:
                    int dest = (int)voiceCommand.Data;
                    if (controller.Navigation.DoesRoomExist(dest))
                    {
                        Telemetry.SendReport(Telemetry.MessageType.VoiceCommand, "Successful Command.");

                        response = "Navigating to " + dest + "...";
                        Speak(response);
                        WriteToCommandTextBlock(response, "👌", 1);
                        await controller.NavigateToDestination(dest);
                    }
                    else
                    {
                        response = "Sorry, I don't know where " + dest + " is.";
                        Speak(response);
                        WriteToCommandTextBlock(response, "🤷‍♂️");
                    }

                    break;

                case VoiceCommandType.Move:

                    response = "Moving...";
                    Speak(response);
                    WriteToCommandTextBlock(response, "🏃‍♂️", 1);

                    cts = new CancellationTokenSource();
                    await ThreadPool.RunAsync(async (s) =>
                    {
                        await controller.ContinuousMove(100, 700, cts.Token);
                        EnableButton(moveButton, true);
                    });

                    break;

                case VoiceCommandType.Stop:
                    response = "Stopping...";
                    Speak(response);
                    WriteToCommandTextBlock(response, "🛑", 1);

                    cts?.Cancel();
                    WriteToOutputTextBlock("Stopping...");
                    controller.Roomba.Halt(StopReason.Cancellation);
                    break;

                default:
                    response = "Sorry, I didn't get that." + Environment.NewLine + "Try \"Go to room 2011\"";
                    Speak(response);
                    WriteToCommandTextBlock(response, "🤷‍♂️");
                    break;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
        }
Example #8
0
        private void Browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            try
            {
                object obj = null;

                _eventsEnabled = false;

                long sofar = _sw.ElapsedMilliseconds;
                Telemetry.Write(module, "Timing", $"ChemDoodle Web loaded in {sofar.ToString("#,##0", CultureInfo.InvariantCulture)}ms");

                this.Text = ms_AppTitle + ExecuteJavaScript("GetVersion");

                // Send JSON to ChemDoodle
                ExecuteJavaScript("SetJSON", _tempJson, AverageBondLength);

                if (AverageBondLength < Constants.MinimumBondLength - Constants.BondLengthTolerance ||
                    AverageBondLength > Constants.MaximumBondLength + Constants.BondLengthTolerance)
                {
                    nudBondLength.Value = (decimal)Constants.StandardBondLength;
                }
                else
                {
                    AverageBondLength   = Math.Round(AverageBondLength / 5.0) * 5;
                    nudBondLength.Value = (int)AverageBondLength;
                }
                ExecuteJavaScript("ReScale", nudBondLength.Value);

                if (UserOptions.ShowHydrogens)
                {
                    ExecuteJavaScript("ShowHydrogens", true);
                    chkToggleShowHydrogens.Checked = true;
                }
                else
                {
                    ExecuteJavaScript("ShowHydrogens", false);
                    chkToggleShowHydrogens.Checked = false;
                }

                if (UserOptions.ColouredAtoms)
                {
                    ExecuteJavaScript("AtomsInColour", true);
                    chkColouredAtoms.Checked = true;
                }
                else
                {
                    ExecuteJavaScript("AtomsInColour", false);
                    chkColouredAtoms.Checked = false;
                }

                if (UserOptions.ShowCarbons)
                {
                    ExecuteJavaScript("ShowCarbons", true);
                    chkToggleShowCarbons.Checked = true;
                }
                else
                {
                    ExecuteJavaScript("ShowCarbons", false);
                    chkToggleShowCarbons.Checked = false;
                }

                obj = ExecuteJavaScript("GetFormula");
                if (obj != null)
                {
                    Before_Formula = obj.ToString();
                }

                long sofar2 = _sw.ElapsedMilliseconds;
                Telemetry.Write(module, "Timing", $"ChemDoodle Web ready in {sofar2.ToString("#,##0", CultureInfo.InvariantCulture)}ms");

                _eventsEnabled = true;
                _sw.Reset();
                Cursor.Current = Cursors.Default;
            }
            catch (Exception ex)
            {
                new ReportError(Telemetry, TopLeft, module, ex).ShowDialog();
            }
        }
Example #9
0
        public async System.Threading.Tasks.Task GenerateAsync(string outputPath, Project project, GenerationType generationType)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            try
            {
                if (string.IsNullOrEmpty(outputPath))
                {
                    throw new ArgumentException(outputPath, nameof(outputPath));
                }

                if (project.Properties.Item("TargetFrameworkMoniker") == null)
                {
                    EnvDteHelper.ShowError("The selected project type has no TargetFrameworkMoniker");
                    return;
                }

                if (!project.IsNetCore30OrHigher())
                {
                    EnvDteHelper.ShowError("Only .NET Core 3.0+ projects are supported - TargetFrameworkMoniker: " + project.Properties.Item("TargetFrameworkMoniker").Value);
                    return;
                }

                var result = await project.ContainsEfCoreDesignReferenceAsync();

                if (string.IsNullOrEmpty(result.Item2))
                {
                    EnvDteHelper.ShowError("EF Core 3.1 or later not found in project");
                    return;
                }

                if (!result.Item1)
                {
                    if (!Version.TryParse(result.Item2, out Version version))
                    {
                        EnvDteHelper.ShowError($"Cannot support version {result.Item2}, notice that previews have limited supported. You can try to manually install Microsoft.EntityFrameworkCore.Design preview.");
                        return;
                    }
                    var nugetHelper = new NuGetHelper();
                    nugetHelper.InstallPackage("Microsoft.EntityFrameworkCore.Design", project, version);
                    EnvDteHelper.ShowError($"Installing EFCore.Design version {version}, please retry the command");
                    return;
                }

                var processLauncher = new ProcessLauncher(project);

                var processResult = await processLauncher.GetOutputAsync(outputPath, generationType, null);

                if (string.IsNullOrEmpty(processResult))
                {
                    throw new ArgumentException("Unable to collect model information", nameof(processResult));
                }

                if (processResult.StartsWith("Error:"))
                {
                    throw new ArgumentException(processResult, nameof(processResult));
                }

                var modelResult = processLauncher.BuildModelResult(processResult);

                switch (generationType)
                {
                case GenerationType.Dgml:
                    GenerateDgml(modelResult, project);
                    Telemetry.TrackEvent("PowerTools.GenerateModelDgml");
                    break;

                case GenerationType.Ddl:
                    var files = project.GenerateFiles(modelResult, ".sql");
                    foreach (var file in files)
                    {
                        _package.Dte2.ItemOperations.OpenFile(file);
                    }
                    Telemetry.TrackEvent("PowerTools.GenerateSqlCreate");
                    break;

                case GenerationType.DebugView:
                    var views = project.GenerateFiles(modelResult, ".txt");
                    foreach (var file in views)
                    {
                        _package.Dte2.ItemOperations.OpenFile(file);
                    }
                    Telemetry.TrackEvent("PowerTools.GenerateDebugView");
                    break;

                default:
                    break;
                }
            }
            catch (Exception exception)
            {
                _package.LogError(new List <string>(), exception);
            }
        }
Example #10
0
        private async Task UpdateHud(CancellationToken cancellationToken)
        {
            try
            {
                while (true)
                {
                    var text = "";
                    var obj  = await Telemetry.GetFlightData();

                    int delay = 1000;

                    if (obj != null && obj["type"] != "dummy_plane")
                    {
                        if (!prevDataValid)
                        {
                            currentCraftName = obj["type"];

                            prevDataValid                 = true;
                            CurrentCraftNameLbl.Text      = currentCraftName;
                            CurrentCraftNameLbl.ForeColor = System.Drawing.Color.DarkGreen;
                            ReloadBtn.Enabled             = true;
                            LoadBtn.Enabled               = true;

                            LogEntriesLbl.Text  = "0";
                            LogFileSizeLbl.Text = "0 kb";

                            await ReloadParams();

                            LoadSavedConfig();

                            if (LoggingEnableChkBox.Checked)
                            {
                                StartLogging();
                            }
                            else
                            {
                                LogFileNameLbl.Text = "Logging not active";
                            }
                        }

                        if (LoggingEnableChkBox.Checked)
                        {
                            var loggingDict = new Dictionary <byte, float>();

                            byte id = 0;
                            foreach (var item in paramIdToName)
                            {
                                if ((activeParamsBs.Contains(new ParamDescription(item)) && LogShownRB.Checked) || LogAllRB.Checked)
                                {
                                    if (float.TryParse(obj[item], NumberStyles.Any, CultureInfo.InvariantCulture, out float value))
                                    {
                                        loggingDict.Add(id, value);
                                    }
                                }
                                id++;
                            }

                            LogWriter.AddRecord(ref loggingDict);

                            LogEntriesLbl.Text  = LogWriter.NumEntries.ToString();
                            LogFileSizeLbl.Text = $"{LogWriter.FileSize / 1024} kb";
                        }

                        foreach (ParamDescription item in activeParamsBs)
                        {
                            if (!obj.ContainsKey(item.Name))
                            {
                                continue;
                            }

                            try
                            {
                                var formatString = $"{{0,{item.Format}}}";

                                var temp = $"{item.Description,-6}";
                                temp += String.Format(CultureInfo.InvariantCulture, formatString, double.Parse(obj[item.Name], CultureInfo.InvariantCulture));
                                temp += " " + item.Unit + "\n";

                                text += temp;
                            }
                            catch (FormatException)
                            {
                                text += $"{item.Description,-6} Bad format string\n";
                            }
                        }

                        delay = Properties.Settings.Default.RefreshRate;
                    }
                    else
                    {
                        if (prevDataValid)
                        {
                            LogShownRB.Enabled = true;
                            LogAllRB.Enabled   = true;

                            prevDataValid                 = false;
                            ReloadBtn.Enabled             = false;
                            LoadBtn.Enabled               = false;
                            CurrentCraftNameLbl.ForeColor = System.Drawing.Color.DarkRed;

                            LogWriter.FinalizeLog();
                        }
                    }

                    hudForm.HUDLabel.Text = text;

                    Task waitTask = Task.Delay(delay, cancellationToken);
                    try
                    {
                        await waitTask;
                    }
                    catch (TaskCanceledException)
                    {
                        return;
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Hud update task exited!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void OnFileSaved(object sender, TextDocumentFileActionEventArgs e)
        {
            if (LibraryCommandService.IsOperationInProgress)
            {
                Logger.LogEvent(Resources.Text.OperationInProgress, LogLevel.Operation);
            }

            var textDocument = sender as ITextDocument;

            if (e.FileActionType == FileActionTypes.ContentSavedToDisk && textDocument != null)
            {
                _ = Task.Run(async() =>
                {
                    try
                    {
                        IDependencies dependencies = DependenciesFactory.FromConfigFile(textDocument.FilePath);
                        var newManifest            = Manifest.FromJson(textDocument.TextBuffer.CurrentSnapshot.GetText(), dependencies);
                        IEnumerable <ILibraryOperationResult> results = await LibrariesValidator.GetManifestErrorsAsync(newManifest, dependencies, CancellationToken.None).ConfigureAwait(false);

                        if (!results.All(r => r.Success))
                        {
                            AddErrorsToList(results);
                            Logger.LogErrorsSummary(results, OperationType.Restore);
                            Telemetry.LogErrors("Fail-ManifestFileSaveWithErrors", results);
                        }
                        else
                        {
                            if (_manifest == null || await _manifest.RemoveUnwantedFilesAsync(newManifest, CancellationToken.None).ConfigureAwait(false))
                            {
                                _manifest = newManifest;

                                await LibraryCommandService.RestoreAsync(textDocument.FilePath, _manifest, CancellationToken.None).ConfigureAwait(false);
                                Telemetry.TrackUserTask("Invoke-RestoreOnSave");
                            }
                            else
                            {
                                string textMessage = string.Concat(Environment.NewLine, LibraryManager.Resources.Text.Restore_OperationHasErrors, Environment.NewLine);
                                Logger.LogErrorsSummary(new[] { textMessage }, OperationType.Restore);
                                Telemetry.TrackUserTask("Fail-RemovedUnwantedFiles", TelemetryResult.Failure);
                            }
                        }
                    }
                    catch (OperationCanceledException ex)
                    {
                        string textMessage = string.Concat(Environment.NewLine, LibraryManager.Resources.Text.Restore_OperationCancelled, Environment.NewLine);

                        Logger.LogEvent(textMessage, LogLevel.Task);
                        Logger.LogEvent(ex.ToString(), LogLevel.Error);

                        Telemetry.TrackException("RestoreOnSaveCancelled", ex);
                    }
                    catch (Exception ex)
                    {
                        // TO DO: Restore to previous state
                        // and add a warning to the Error List

                        string textMessage = string.Concat(Environment.NewLine, LibraryManager.Resources.Text.Restore_OperationHasErrors, Environment.NewLine);

                        Logger.LogEvent(textMessage, LogLevel.Task);
                        Logger.LogEvent(ex.ToString(), LogLevel.Error);
                        Telemetry.TrackException("RestoreOnSaveFailed", ex);
                    }
                });
            }
        }
Example #12
0
 private static void LogInfo(string key, IDictionary <string, string> properties = null)
 => Telemetry.TrackEvent(key, properties);
Example #13
0
 public SetAggregator(MetricAggregatorParameters parameters, Telemetry optionalTelemetry)
 {
     _aggregator        = new AggregatorFlusher <StatsMetricSet>(parameters, MetricType.Set);
     _pool              = new Pool <StatsMetricSet>(pool => new StatsMetricSet(pool), 2 * parameters.MaxUniqueStatsBeforeFlush);
     _optionalTelemetry = optionalTelemetry;
 }
Example #14
0
 public override void LogTelemetry(string eventName, IDictionary <string, string> properties) => Telemetry.Add(new Tuple <string, IDictionary <string, string> >(eventName, properties));
Example #15
0
 protected override void OnStop()
 {
     Telemetry.TrackEvent("Inside ONStop of Service");
     // EventLog.WriteEntry("Inside ONStop");
 }
Example #16
0
        private static async void SendDeviceToCloudMessagesAsync()
        {
            Console.WriteLine("=== Serializing the Sensor Data to JSON format ===========");

            // Connect to the IoT hub using the MQTT protocol
            s_deviceClient = DeviceClient.CreateFromConnectionString(s_connectionString, TransportType.Mqtt);

            // Initial telemetry values
            double currentTemperature = 0;

            using (var settings = RTIMUSettings.CreateDefault())
                using (var imu = settings.CreateIMU())
                    using (var pressure = settings.CreatePressure())
                        using (var humidity = settings.CreateHumidity())

                            while (true)
                            {
                                var imuData            = imu.GetData();
                                var humidityReadResult = humidity.Read();
                                var pressureReadResult = pressure.Read();

                                // Display RAW sensor data
                                Console.WriteLine();
                                Console.WriteLine($"Timestamp: {imuData.Timestamp:O}");
                                Console.WriteLine($"FusionPose: {imuData.FusionPose}");
                                Console.WriteLine($"FusionQPose: {imuData.FusionQPose}");
                                Console.WriteLine($"Gyro: {imuData.Gyro}");
                                Console.WriteLine($"Accel: {imuData.Accel}");
                                Console.WriteLine($"Compass: {imuData.Compass}");
                                Console.WriteLine();
                                Console.WriteLine($"Pressure: {pressureReadResult.Pressure}");
                                Console.WriteLine($"Humidity: {humidityReadResult.Humidity}");
                                Console.WriteLine($"Temperature C: {humidityReadResult.Temperatur}");

                                // Convert Celsius to Fahrenheit
                                currentTemperature = humidityReadResult.Temperatur * 1.8 + 32;

                                // Convert with Offset. (Board reads to high)
                                currentTemperature = currentTemperature - 8;

                                Console.WriteLine($"Temperature F: {currentTemperature}");

                                // Send Temperature to the SenseHAT matrix lights
                                TestLedMessage("Temp = " + Math.Round(currentTemperature, 2).ToString() + "   ");

                                // Create JSON message
                                Telemetry telemetryRow = new Telemetry();
                                telemetryRow.DeviceId    = "<Your Raspberry Pi Device Name>"; // i.e. raspberrypi-det-01
                                telemetryRow.MessageId   = 314;
                                telemetryRow.CreatedDate = DateTime.UtcNow;
                                telemetryRow.Temperature = Math.Round(Convert.ToDecimal(currentTemperature), 2);
                                telemetryRow.Humidity    = Math.Round(Convert.ToDecimal(humidityReadResult.Humidity), 2);
                                telemetryRow.Pressure    = Math.Round(Convert.ToDecimal(pressureReadResult.Pressure), 2);

                                // Serialize sensor data to JSON format
                                string messageString = JsonConvert.SerializeObject(telemetryRow);

                                // Encode the characters into a sequence of bytes.
                                var message = new Message(Encoding.ASCII.GetBytes(messageString));

                                Console.WriteLine();
                                Console.WriteLine("=== Sending data to IoT Hub ==============================");

                                // Send the telemetry message
                                await s_deviceClient.SendEventAsync(message).ConfigureAwait(false);

                                Console.WriteLine($"=== {DateTime.Now}, {messageString}");
                                Console.WriteLine();

                                // Wait 5 secs
                                await Task.Delay(5000).ConfigureAwait(false);
                            }
        }
Example #17
0
 public AboutDialog()
 {
     InitializeComponent();
     Telemetry.TrackPageView(nameof(AboutDialog));
 }
Example #18
0
 public DataContextDialog()
 {
     Telemetry.TrackPageView(nameof(DataContextDialog));
     InitializeComponent();
     this.Background = Helpers.VsThemes.GetWindowBackground();
 }
 void ITelemetryService.LogEncDebugSession(Telemetry.EncDebuggingSessionInfo session)
 {
 }
Example #20
0
        private void SearchButton_Click(object sender, EventArgs e)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            if (!string.IsNullOrEmpty(SearchFor.Text))
            {
                Telemetry.Write(module, "Information", $"User searched for '{SearchFor.Text}'");
                Cursor = Cursors.WaitCursor;

                var securityProtocol = ServicePointManager.SecurityProtocol;
                ServicePointManager.SecurityProtocol = securityProtocol | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

                UriBuilder     builder = new UriBuilder(UserOptions.OpsinWebServiceUri + SearchFor.Text);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(builder.Uri);
                request.Timeout   = 30000;
                request.Accept    = "chemical/x-cml";
                request.UserAgent = "Chem4Word";

                HttpWebResponse response;
                try
                {
                    response = (HttpWebResponse)request.GetResponse();
                    if (response.StatusCode.Equals(HttpStatusCode.OK))
                    {
                        ProcessResponse(response);
                    }
                    else
                    {
                        Telemetry.Write(module, "Warning", $"Status code {response.StatusCode} was returned by the server");
                        ShowFailureMessage($"An unexpected status code {response.StatusCode} was returned by the server");
                    }
                }
                catch (WebException ex)
                {
                    HttpWebResponse webResponse = (HttpWebResponse)ex.Response;
                    switch (webResponse.StatusCode)
                    {
                    case HttpStatusCode.NotFound:
                        ShowFailureMessage($"No valid representation of the name '{SearchFor.Text}' has been found");
                        break;

                    case HttpStatusCode.RequestTimeout:
                        ShowFailureMessage("Please try again later - the service has timed out");
                        break;

                    default:
                        Telemetry.Write(module, "Warning", $"Status code: {webResponse.StatusCode}  was returned by the server");
                        break;
                    }
                }
                catch (Exception ex)
                {
                    Telemetry.Write(module, "Exception", ex.Message);
                    Telemetry.Write(module, "Exception", ex.StackTrace);
                    ShowFailureMessage($"An unexpected error has occurred: {ex.Message}");
                }
                finally
                {
                    ServicePointManager.SecurityProtocol = securityProtocol;
                    Cursor = Cursors.Default;
                }
            }
        }
Example #21
0
 private static ExplainedInteractionHappinessGrade ValidatePingPong(Telemetry telemetry)
 {
     return ExplainedInteractionHappinessGrade.Perfect();
 }
Example #22
0
 private static void LogError(Exception ex)
 => Telemetry.TrackException(ex);
Example #23
0
        private async System.Threading.Tasks.Task GenerateFilesAsync(Project project, ReverseEngineerOptions options, Tuple <bool, string> containsEfCoreReference)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            var startTime = DateTime.Now;

            if (options.UseHandleBars)
            {
                DropTemplates(options.OptionsPath, options.CodeGenerationMode);
            }

            options.UseNullableReferences = !await project.IsLegacyAsync() && options.UseNullableReferences;

            await VS.StatusBar.ShowProgressAsync(ReverseEngineerLocale.GeneratingCode, 1, 3);

            var revEngResult = await EfRevEngLauncher.LaunchExternalRunnerAsync(options, options.CodeGenerationMode, project);

            await VS.StatusBar.ShowProgressAsync(ReverseEngineerLocale.GeneratingCode, 2, 3);

            var tfm = await project.GetAttributeAsync("TargetFrameworkMoniker");

            bool isNetStandard = tfm?.Contains(".NETStandard,Version=v2.") ?? false;

            if ((options.SelectedToBeGenerated == 0 || options.SelectedToBeGenerated == 2) &&
                !await project.IsNetCore31OrHigherAsync() && !isNetStandard)
            {
                foreach (var filePath in revEngResult.EntityTypeFilePaths)
                {
                    await project.AddExistingFilesAsync(new List <string> {
                        filePath
                    }.ToArray());
                }
            }

            if (options.SelectedToBeGenerated == 0 || options.SelectedToBeGenerated == 1)
            {
                if (!await project.IsNetCore31OrHigherAsync() && !isNetStandard)
                {
                    foreach (var filePath in revEngResult.ContextConfigurationFilePaths)
                    {
                        await project.AddExistingFilesAsync(new List <string> {
                            filePath
                        }.ToArray());
                    }

                    await project.AddExistingFilesAsync(new List <string> {
                        revEngResult.ContextFilePath
                    }.ToArray());
                }

                if (AdvancedOptions.Instance.OpenGeneratedDbContext)
                {
                    var readmeName = "PowerToolsReadMe.txt";
                    var finalText  = reverseEngineerHelper.GetReadMeText(options, File.ReadAllText(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), readmeName), Encoding.UTF8));
                    var readmePath = Path.Combine(Path.GetTempPath(), readmeName);

                    File.WriteAllText(readmePath, finalText, Encoding.UTF8);

                    await VS.Documents.OpenAsync(readmePath);

                    await VS.Documents.OpenAsync(revEngResult.ContextFilePath);
                }
            }

            await VS.StatusBar.ShowProgressAsync(ReverseEngineerLocale.GeneratingCode, 3, 3);

            var duration = DateTime.Now - startTime;

            var missingProviderPackage = containsEfCoreReference.Item1 ? null : containsEfCoreReference.Item2;

            if (options.InstallNuGetPackage || options.SelectedToBeGenerated == 2)
            {
                missingProviderPackage = null;
            }

            var errors = reverseEngineerHelper.ReportRevEngErrors(revEngResult, missingProviderPackage);

            await VS.StatusBar.ShowMessageAsync(string.Format(ReverseEngineerLocale.ReverseEngineerCompleted, duration.ToString("h\\:mm\\:ss")));

            if (errors != ReverseEngineerLocale.ModelGeneratedSuccesfully + Environment.NewLine)
            {
                VSHelper.ShowMessage(errors);
            }

            if (revEngResult.EntityErrors.Count > 0)
            {
                package.LogError(revEngResult.EntityErrors, null);
            }

            if (revEngResult.EntityWarnings.Count > 0)
            {
                package.LogError(revEngResult.EntityWarnings, null);
            }

            Telemetry.TrackFrameworkUse(nameof(ReverseEngineerHandler), options.CodeGenerationMode);
        }
        public async void ReverseEngineerCodeFirst(Project project)
        {
            try
            {
                var    dteH         = new EnvDteHelper();
                string dacpacSchema = null;

                if (_package.Dte2.Mode == vsIDEMode.vsIDEModeDebug)
                {
                    EnvDteHelper.ShowError("Cannot generate code while debugging");
                    return;
                }

                var startTime    = DateTime.Now;
                var projectPath  = project.Properties.Item("FullPath").Value.ToString();
                var optionsPath  = Path.Combine(projectPath, "efpt.config.json");
                var renamingPath = Path.Combine(projectPath, "efpt.renaming.json");

                var databaseList = EnvDteHelper.GetDataConnections(_package);
                var dacpacList   = _package.Dte2.DTE.GetDacpacFilesInActiveSolution(EnvDteHelper.GetProjectFilesInSolution(_package));

                var psd = _package.GetView <IPickServerDatabaseDialog>();

                if (databaseList != null && databaseList.Any())
                {
                    psd.PublishConnections(databaseList.Select(m => new DatabaseConnectionModel
                    {
                        ConnectionName   = m.Value.Caption,
                        ConnectionString = m.Value.ConnectionString,
                        DatabaseType     = m.Value.DatabaseType
                    }));
                }

                if (dacpacList != null && dacpacList.Any())
                {
                    psd.PublishDefinitions(dacpacList.Select(m => new DatabaseDefinitionModel
                    {
                        FilePath = m
                    }));
                }

                var pickDataSourceResult = psd.ShowAndAwaitUserResponse(true);
                if (!pickDataSourceResult.ClosedByOK)
                {
                    return;
                }

                var useEFCore5 = pickDataSourceResult.Payload.IncludeViews;

                _package.Dte2.StatusBar.Text = "Loading schema information...";

                // Reload the database list, in case the user has added a new database in the dialog
                databaseList = EnvDteHelper.GetDataConnections(_package);

                DatabaseInfo dbInfo = null;
                if (pickDataSourceResult.Payload.Connection != null)
                {
                    dbInfo = databaseList.Single(m => m.Value.ConnectionString == pickDataSourceResult.Payload.Connection?.ConnectionString).Value;
                }
                var dacpacPath = pickDataSourceResult.Payload.Definition?.FilePath;

                if (dbInfo == null)
                {
                    dbInfo = new DatabaseInfo();
                }

                if (!string.IsNullOrEmpty(dacpacPath))
                {
                    dbInfo.DatabaseType     = DatabaseType.SQLServer;
                    dbInfo.ConnectionString = "Data Source=.;Initial Catalog=" + Path.GetFileNameWithoutExtension(dacpacPath);
                    dacpacPath = _package.Dte2.DTE.BuildSqlProj(dacpacPath);
                    if (string.IsNullOrEmpty(dacpacPath))
                    {
                        EnvDteHelper.ShowMessage("Unable to build selected Database Project");
                        return;
                    }
                }

                if (dbInfo.DatabaseType == DatabaseType.SQLCE35)
                {
                    EnvDteHelper.ShowError($"Unsupported provider: {dbInfo.ServerVersion}");
                    return;
                }

                if (dbInfo.DatabaseType == DatabaseType.SQLCE40)
                {
                    EnvDteHelper.ShowError($"Unsupported provider with EF Core 3.0: {dbInfo.DatabaseType}");
                    return;
                }

                var options = ReverseEngineerOptionsExtensions.TryRead(optionsPath);

                List <TableInformationModel> predefinedTables = !string.IsNullOrEmpty(dacpacPath)
                                           ? GetDacpacTables(dacpacPath, useEFCore5)
                                           : GetTables(dbInfo.ConnectionString, dbInfo.DatabaseType, useEFCore5);

                var preselectedTables = new List <TableInformationModel>();
                if (options != null)
                {
                    dacpacSchema = options.DefaultDacpacSchema;
                    if (options.Tables.Count > 0)
                    {
                        var normalizedTables = reverseEngineerHelper.NormalizeTables(options.Tables, dbInfo.DatabaseType == DatabaseType.SQLServer);
                        preselectedTables.AddRange(normalizedTables);
                    }
                }

                var ptd = _package.GetView <IPickTablesDialog>()
                          .AddTables(predefinedTables)
                          .PreselectTables(preselectedTables);

                var customNameOptions = CustomNameOptionsExtensions.TryRead(renamingPath);

                var pickTablesResult = ptd.ShowAndAwaitUserResponse(true);
                if (!pickTablesResult.ClosedByOK)
                {
                    return;
                }

                var classBasis    = EnvDteHelper.GetDatabaseName(dbInfo.ConnectionString, dbInfo.DatabaseType);
                var model         = reverseEngineerHelper.GenerateClassName(classBasis) + "Context";
                var packageResult = project.ContainsEfCoreReference(dbInfo.DatabaseType);

                var presets = new ModelingOptionsModel
                {
                    InstallNuGetPackage = !packageResult.Item1,
                    ModelName           = options != null ? options.ContextClassName : model,
                    ProjectName         = project.Name,
                    Namespace           = options != null ? options.ProjectRootNamespace : project.Properties.Item("DefaultNamespace").Value.ToString(),
                    DacpacPath          = dacpacPath,
                };
                if (options != null)
                {
                    presets.UseDataAnnotations         = !options.UseFluentApiOnly;
                    presets.UseDatabaseNames           = options.UseDatabaseNames;
                    presets.UsePluralizer              = options.UseInflector;
                    presets.UseDbContextSplitting      = options.UseDbContextSplitting;
                    presets.UseHandelbars              = options.UseHandleBars;
                    presets.SelectedHandlebarsLanguage = options.SelectedHandlebarsLanguage;
                    presets.ReplaceId               = options.IdReplace;
                    presets.DoNotCombineNamespace   = options.DoNotCombineNamespace;
                    presets.IncludeConnectionString = options.IncludeConnectionString;
                    presets.ModelName               = options.ContextClassName;
                    presets.Namespace               = options.ProjectRootNamespace;
                    presets.OutputPath              = options.OutputPath;
                    presets.OutputContextPath       = options.OutputContextPath;
                    presets.ModelNamespace          = options.ModelNamespace;
                    presets.ContextNamespace        = options.ContextNamespace;
                    presets.SelectedToBeGenerated   = options.SelectedToBeGenerated;
                    presets.DacpacPath              = options.Dacpac;
                }

                var modelDialog = _package.GetView <IModelingOptionsDialog>()
                                  .ApplyPresets(presets);

                _package.Dte2.StatusBar.Text = "Getting options...";

                var modelingOptionsResult = modelDialog.ShowAndAwaitUserResponse(true);
                if (!modelingOptionsResult.ClosedByOK)
                {
                    return;
                }

                options = new ReverseEngineerOptions
                {
                    UseFluentApiOnly           = !modelingOptionsResult.Payload.UseDataAnnotations,
                    ConnectionString           = dbInfo.ConnectionString,
                    ContextClassName           = modelingOptionsResult.Payload.ModelName,
                    DatabaseType               = (ReverseEngineer20.DatabaseType)dbInfo.DatabaseType,
                    ProjectPath                = projectPath,
                    OutputPath                 = modelingOptionsResult.Payload.OutputPath,
                    OutputContextPath          = modelingOptionsResult.Payload.OutputContextPath,
                    ContextNamespace           = modelingOptionsResult.Payload.ContextNamespace,
                    ModelNamespace             = modelingOptionsResult.Payload.ModelNamespace,
                    ProjectRootNamespace       = modelingOptionsResult.Payload.Namespace,
                    UseDatabaseNames           = modelingOptionsResult.Payload.UseDatabaseNames,
                    UseInflector               = modelingOptionsResult.Payload.UsePluralizer,
                    UseLegacyPluralizer        = options?.UseLegacyPluralizer ?? false,
                    UseSpatial                 = options?.UseSpatial ?? false,
                    UseNodaTime                = options?.UseNodaTime ?? false,
                    UseDbContextSplitting      = modelingOptionsResult.Payload.UseDbContextSplitting,
                    IdReplace                  = modelingOptionsResult.Payload.ReplaceId,
                    DoNotCombineNamespace      = modelingOptionsResult.Payload.DoNotCombineNamespace,
                    UseHandleBars              = modelingOptionsResult.Payload.UseHandelbars,
                    SelectedHandlebarsLanguage = modelingOptionsResult.Payload.SelectedHandlebarsLanguage,
                    IncludeConnectionString    = modelingOptionsResult.Payload.IncludeConnectionString,
                    SelectedToBeGenerated      = modelingOptionsResult.Payload.SelectedToBeGenerated,
                    Dacpac = dacpacPath,
                    DefaultDacpacSchema = dacpacSchema,
                    Tables          = pickTablesResult.Payload.ToList(),
                    CustomReplacers = customNameOptions
                };

                _package.Dte2.StatusBar.Text = "Generating code...";

                var  tfm           = project.Properties.Item("TargetFrameworkMoniker").Value.ToString();
                bool isNetStandard = tfm.Contains(".NETStandard,Version=v2.");

                if (modelingOptionsResult.Payload.UseHandelbars)
                {
                    var dropped = (DropTemplates(projectPath));
                    if (dropped && !project.IsNetCore() && !isNetStandard)
                    {
                        project.ProjectItems.AddFromDirectory(Path.Combine(projectPath, "CodeTemplates"));
                    }
                }

                var revEngResult = LaunchExternalRunner(options, useEFCore5);

                if (modelingOptionsResult.Payload.SelectedToBeGenerated == 0 || modelingOptionsResult.Payload.SelectedToBeGenerated == 2)
                {
                    foreach (var filePath in revEngResult.EntityTypeFilePaths)
                    {
                        if (!project.IsNetCore() && !isNetStandard)
                        {
                            project.ProjectItems.AddFromFile(filePath);
                        }
                    }
                    if (modelingOptionsResult.Payload.SelectedToBeGenerated == 2)
                    {
                        if (File.Exists(revEngResult.ContextFilePath))
                        {
                            File.Delete(revEngResult.ContextFilePath);
                        }
                    }
                }
                if (modelingOptionsResult.Payload.SelectedToBeGenerated == 0 || modelingOptionsResult.Payload.SelectedToBeGenerated == 1)
                {
                    if (!project.IsNetCore() && !isNetStandard)
                    {
                        project.ProjectItems.AddFromFile(revEngResult.ContextFilePath);
                        _package.Dte2.ItemOperations.OpenFile(revEngResult.ContextFilePath);
                    }
                    if (modelingOptionsResult.Payload.SelectedToBeGenerated == 1)
                    {
                        foreach (var filePath in revEngResult.EntityTypeFilePaths)
                        {
                            if (File.Exists(filePath))
                            {
                                File.Delete(filePath);
                            }
                        }
                    }
                }

                var missingProviderPackage = packageResult.Item1 ? null : packageResult.Item2;
                if (modelingOptionsResult.Payload.InstallNuGetPackage || modelingOptionsResult.Payload.SelectedToBeGenerated == 2)
                {
                    missingProviderPackage = null;
                }

                _package.Dte2.StatusBar.Text = "Reporting result...";
                var errors = reverseEngineerHelper.ReportRevEngErrors(revEngResult, missingProviderPackage);

                SaveOptions(project, optionsPath, options);

                if (modelingOptionsResult.Payload.InstallNuGetPackage)
                {
                    _package.Dte2.StatusBar.Text = "Installing EF Core provider package";
                    var nuGetHelper = new NuGetHelper();
                    await nuGetHelper.InstallPackageAsync(packageResult.Item2, project);
                }
                var duration = DateTime.Now - startTime;
                _package.Dte2.StatusBar.Text = $"Reverse engineer completed in {duration:h\\:mm\\:ss}";

                EnvDteHelper.ShowMessage(errors);

                if (revEngResult.EntityErrors.Count > 0)
                {
                    _package.LogError(revEngResult.EntityErrors, null);
                }
                if (revEngResult.EntityWarnings.Count > 0)
                {
                    _package.LogError(revEngResult.EntityWarnings, null);
                }
                Telemetry.TrackEvent("PowerTools.ReverseEngineer");
            }
            catch (AggregateException ae)
            {
                foreach (var innerException in ae.Flatten().InnerExceptions)
                {
                    _package.LogError(new List <string>(), innerException);
                }
            }
            catch (Exception exception)
            {
                _package.LogError(new List <string>(), exception);
            }
        }
Example #25
0
        public async System.Threading.Tasks.Task ReverseEngineerCodeFirstAsync(Project project, string optionsPath, bool onlyGenerate)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            try
            {
                if (await VSHelper.IsDebugModeAsync())
                {
                    VSHelper.ShowError(ReverseEngineerLocale.CannotGenerateCodeWhileDebugging);
                    return;
                }

                var renamingPath         = project.GetRenamingPath(optionsPath);
                var namingOptionsAndPath = CustomNameOptionsExtensions.TryRead(renamingPath, optionsPath);

                Tuple <bool, string> containsEfCoreReference = null;

                var options = ReverseEngineerOptionsExtensions.TryRead(optionsPath, Path.GetDirectoryName(project.FullPath));

                if (options == null)
                {
                    options = new ReverseEngineerOptions
                    {
                        ProjectRootNamespace = await project.GetAttributeAsync("RootNamespace"),
                    };
                }

                legacyDiscoveryObjects = options.Tables?.Where(t => t.UseLegacyResultSetDiscovery).Select(t => t.Name).ToList() ?? new List <string>();
                mappedTypes            = options.Tables?
                                         .Where(t => !string.IsNullOrEmpty(t.MappedType) && t.ObjectType == ObjectType.Procedure)
                                         .Select(m => new { m.Name, m.MappedType }).ToDictionary(m => m.Name, m => m.MappedType) ?? new Dictionary <string, string>();

                options.ProjectPath = Path.GetDirectoryName(project.FullPath);
                options.OptionsPath = Path.GetDirectoryName(optionsPath);

                bool forceEdit = false;

                if (onlyGenerate)
                {
                    forceEdit = !await ChooseDataBaseConnectionByUiHintAsync(options);

                    if (forceEdit)
                    {
                        await VS.StatusBar.ShowMessageAsync(ReverseEngineerLocale.DatabaseConnectionNotFoundCannotRefresh);
                    }
                    else
                    {
                        var dbInfo = await GetDatabaseInfoAsync(options);

                        if (dbInfo == null)
                        {
                            return;
                        }

                        containsEfCoreReference     = new Tuple <bool, string>(true, null);
                        options.CustomReplacers     = namingOptionsAndPath.Item1;
                        options.InstallNuGetPackage = false;
                    }
                }

                if (!onlyGenerate || forceEdit)
                {
                    if (!await ChooseDataBaseConnectionAsync(options))
                    {
                        return;
                    }

                    await VS.StatusBar.ShowMessageAsync(ReverseEngineerLocale.GettingReadyToConnect);

                    var dbInfo = await GetDatabaseInfoAsync(options);

                    if (dbInfo == null)
                    {
                        return;
                    }

                    VerifySQLServerRightsAndVersion(options);

                    await VS.StatusBar.ShowMessageAsync(ReverseEngineerLocale.LoadingDatabaseObjects);

                    if (!await LoadDataBaseObjectsAsync(options, dbInfo, namingOptionsAndPath))
                    {
                        return;
                    }

                    await VS.StatusBar.ShowMessageAsync(ReverseEngineerLocale.LoadingOptions);

                    containsEfCoreReference = await project.ContainsEfCoreReferenceAsync(options.DatabaseType);

                    options.InstallNuGetPackage = !containsEfCoreReference.Item1;

                    if (!await GetModelOptionsAsync(options, project.Name))
                    {
                        return;
                    }

                    await SaveOptionsAsync(project, optionsPath, options, new Tuple <List <Schema>, string>(options.CustomReplacers, namingOptionsAndPath.Item2));
                }

                await GenerateFilesAsync(project, options, containsEfCoreReference);

                await InstallNuGetPackagesAsync(project, onlyGenerate, containsEfCoreReference, options, forceEdit);

                var postRunFile = Path.Combine(Path.GetDirectoryName(optionsPath), "efpt.postrun.cmd");
                if (File.Exists(postRunFile))
                {
                    Process.Start($"\"{postRunFile}\"");
                }

                Telemetry.TrackEvent("PowerTools.ReverseEngineer");
            }
            catch (AggregateException ae)
            {
                foreach (var innerException in ae.Flatten().InnerExceptions)
                {
                    package.LogError(new List <string>(), innerException);
                }
            }
            catch (Exception exception)
            {
                package.LogError(new List <string>(), exception);
            }
        }
Example #26
0
 public SQLiteConnectionDialog()
 {
     Telemetry.TrackPageView(nameof(SQLiteConnectionDialog));
     InitializeComponent();
 }
Example #27
0
        public ActionResult ChangeTelemetryState(bool DisableTelemetry)
        {
            Telemetry.SetOptOut(DisableTelemetry);

            return(Json(true));
        }
Example #28
0
        private void FormChemDoodleEditor_Load(object sender, EventArgs e)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            try
            {
                Cursor.Current = Cursors.WaitCursor;
                _sw.Start();

                _eventsEnabled = false;

                if (TopLeft.X != 0 && TopLeft.Y != 0)
                {
                    Left = (int)TopLeft.X;
                    Top  = (int)TopLeft.Y;
                }

                this.Show();
                Application.DoEvents();

                Stopwatch sw = new Stopwatch();
                sw.Start();

                string otherVersion = Path.Combine(ProductAppDataPath, "ChemDoodle-Web-800.txt");
                if (File.Exists(otherVersion))
                {
                    Telemetry.Write(module, "Information", "Deleting CDW 800 resources from disk");
                    File.Delete(otherVersion);
                    DelTree(Path.Combine(ProductAppDataPath, "ChemDoodleWeb"));
                }

                string markerFile = Path.Combine(ProductAppDataPath, "ChemDoodle-Web-702.txt");
                if (!File.Exists(markerFile))
                {
                    Telemetry.Write(module, "Information", "Writing resources to disk");
                    File.WriteAllText(markerFile, "Delete this file to refresh ChemDoodle Web");

                    Stream stream = ResourceHelper.GetBinaryResource(Assembly.GetExecutingAssembly(), "ChemDoodleWeb.ChemDoodleWeb_702.zip");

                    // NB: Top level of zip file must be the folder ChemDoodleWeb
                    using (ZipFile zip = ZipFile.Read(stream))
                    {
                        zip.ExtractAll(ProductAppDataPath, ExtractExistingFileAction.OverwriteSilently);
                    }

                    string cssfile = ResourceHelper.GetStringResource(Assembly.GetExecutingAssembly(), "ChemDoodleWeb.Chem4Word.css");
                    File.WriteAllText(Path.Combine(ProductAppDataPath, "Chem4Word.css"), cssfile);

                    string jsfile = ResourceHelper.GetStringResource(Assembly.GetExecutingAssembly(), "ChemDoodleWeb.Chem4Word.js");
                    File.WriteAllText(Path.Combine(ProductAppDataPath, "Chem4Word.js"), jsfile);
                }

                Telemetry.Write(module, "Information", "Writing html to disk");
                string htmlfile = "";
                if (IsSingleMolecule)
                {
                    htmlfile = ResourceHelper.GetStringResource(Assembly.GetExecutingAssembly(), "ChemDoodleWeb.Single.html");
                    chkSingleOrMany.Checked    = false;
                    chkSingleOrMany.ImageIndex = 0;
                    toolTip1.SetToolTip(chkSingleOrMany, "Change to Multiple molecules mode");
                }
                else
                {
                    htmlfile = ResourceHelper.GetStringResource(Assembly.GetExecutingAssembly(), "ChemDoodleWeb.Multi.html");
                    chkSingleOrMany.Checked    = true;
                    chkSingleOrMany.ImageIndex = 1;
                    toolTip1.SetToolTip(chkSingleOrMany, "Change to Single molecule mode");
                }
                File.WriteAllText(Path.Combine(ProductAppDataPath, "Editor.html"), htmlfile);

                long sofar = sw.ElapsedMilliseconds;

                Telemetry.Write(module, "Timing", $"Writing resources to disk took {sofar.ToString("#,##0", CultureInfo.InvariantCulture)}ms");

                _tempJson = Before_JSON;

                _eventsEnabled = true;

                Telemetry.Write(module, "Information", $"Starting browser");
                browser.Navigate(Path.Combine(ProductAppDataPath, "Editor.html"));
            }
            catch (Exception ex)
            {
                new ReportError(Telemetry, TopLeft, module, ex).ShowDialog();
            }
        }
Example #29
0
 public PickTablesDialog()
 {
     Telemetry.TrackPageView(nameof(PickTablesDialog));
     InitializeComponent();
     this.Background = Helpers.VsThemes.GetWindowBackground();
 }
Example #30
0
 protected void SendTelemetry(Telemetry telemetry)
 {
     TelemetryReceived?.Invoke(this, telemetry);
 }
 void ITelemetryService.LogLightBulbSession(Telemetry.LightBulbSessionInfo lightBulbSession)
 {
 }
Example #32
0
 public void AddEvent(Telemetry.Event evt, params Telemetry.Pair[] infoPair)
 {
     if (Mod.DEBUG_LOG_ON) { Helper.dbgLog("AddEvent Event!"); }
     this.AddEvent(evt.Name<Telemetry.Event>(), infoPair);
 }
Example #33
0
        private void EnableCompileOnBuild(object sender, EventArgs e)
        {
            if (_project == null)
            {
                return;
            }

            var componentModel = (IComponentModel)Package.GetGlobalService(typeof(SComponentModel));

            if (!_isInstalled)
            {
                var question = MessageBox.Show("A NuGet package will be installed to augment the MSBuild process, but no files will be added to the project.\rThis may require an internet connection.\r\rDo you want to continue?", Constants.VSIX_NAME, MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (question == DialogResult.No)
                {
                    return;
                }

                Telemetry.TrackEvent("VS add compile on build");
                Version version = new Version(WebCompilerPackage.Version);

#if DEBUG
                version = (Version)null;
#endif
                System.Threading.ThreadPool.QueueUserWorkItem((o) =>
                {
                    try
                    {
                        WebCompilerPackage._dte.StatusBar.Text = $"Installing {Constants.NUGET_ID} v{WebCompilerPackage.Version} NuGet package, this may take a minute...";
                        WebCompilerPackage._dte.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationSync);

                        var installer = componentModel.GetService <IVsPackageInstaller>();
                        installer.InstallPackage(null, _project, Constants.NUGET_ID, version, false);

                        WebCompilerPackage._dte.StatusBar.Text = $"Finished installing the {Constants.NUGET_ID} v{WebCompilerPackage.Version} NuGet package";
                    }
                    catch (Exception ex)
                    {
                        Logger.Log(ex);
                        WebCompilerPackage._dte.StatusBar.Text = $"Unable to install the {Constants.NUGET_ID} v{WebCompilerPackage.Version} NuGet package";
                    }
                    finally
                    {
                        WebCompilerPackage._dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationSync);
                    }
                });
            }
            else
            {
                Telemetry.TrackEvent("VS remove compile on build");

                System.Threading.ThreadPool.QueueUserWorkItem((o) =>
                {
                    try
                    {
                        WebCompilerPackage._dte.StatusBar.Text = $"Uninstalling {Constants.NUGET_ID} NuGet package, this may take a minute...";
                        WebCompilerPackage._dte.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationSync);
                        var uninstaller = componentModel.GetService <IVsPackageUninstaller>();
                        uninstaller.UninstallPackage(_project, Constants.NUGET_ID, false);

                        WebCompilerPackage._dte.StatusBar.Text = $"Finished uninstalling the {Constants.NUGET_ID} NuGet package";
                    }
                    catch (Exception ex)
                    {
                        Logger.Log(ex);
                        WebCompilerPackage._dte.StatusBar.Text = $"Unable to ininstall the {Constants.NUGET_ID} NuGet package";
                    }
                    finally
                    {
                        WebCompilerPackage._dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationSync);
                    }
                });
            }
        }
Example #34
0
        //For Kalista

        private static void Start()
        {
            RandGen.Start();
            bool generic = false;

            switch (ObjectManager.Player.Hero)
            {
            case Champion.Ashe:
                myChamp = new Ashe();
                break;

            case Champion.Caitlyn:
                myChamp = new Caitlyn();
                break;

            case Champion.Ezreal:
                myChamp = new Ezreal();
                break;

            case Champion.Cassiopeia:
                myChamp = new Cassiopeia();
                break;

            case Champion.Ryze:
                myChamp = new Ryze();
                break;

            case Champion.Soraka:
                myChamp = new Soraka();
                break;

            case Champion.Kayle:
                myChamp = new Kayle();
                break;

            case Champion.Tristana:
                myChamp = new Tristana();
                break;

            case Champion.Sivir:
                myChamp = new Sivir();
                break;

            case Champion.Ahri:
                myChamp = new Ahri();
                break;

            case Champion.Anivia:
                myChamp = new Anivia();
                break;

            case Champion.Annie:
                myChamp = new Annie();
                break;

            case Champion.Corki:
                myChamp = new Corki();
                break;

            case Champion.Brand:
                myChamp = new Brand();
                break;

            case Champion.Azir:
                myChamp = new Azir();
                break;

            case Champion.Xerath:
                myChamp = new Xerath();
                break;

            case Champion.Morgana:
                myChamp = new Morgana();
                break;

            case Champion.Draven:
                myChamp = new Draven();
                break;

            case Champion.Twitch:
                myChamp = new Twitch();
                break;

            case Champion.Kalista:
                myChamp = new Kalista();
                break;

            case Champion.Velkoz:
                myChamp = new Velkoz();
                break;

            case Champion.Leblanc:
                myChamp = new Leblanc();
                break;

            case Champion.Jinx:
                myChamp = new Jinx();
                break;

            case Champion.Katarina:
                myChamp = new Katarina();
                break;

            case Champion.Nidalee:
                myChamp = new Nidalee();
                break;

            default:
                generic = true;
                myChamp = new Generic();
                break;
            }

            CustomLvlSeq cl = new CustomLvlSeq(menu, AutoWalker.p, Path.Combine(SandboxConfig.DataDirectory
                                                                                , "AutoBuddy\\Skills"));

            if (!generic)
            {
                AutoShop bc = new AutoShop(menu, myChamp.ShopSequence);
            }
            else if (MainMenu.GetMenu("AB_" + ObjectManager.Player.ChampionName) != null &&
                     MainMenu.GetMenu("AB_" + ObjectManager.Player.ChampionName).Get <Label>("shopSequence") != null)
            {
                Chat.Print("Autobuddy: Loaded shop plugin for " + ObjectManager.Player.ChampionName);
                AutoShop bc = new AutoShop(menu, MainMenu.GetMenu("AB_" + ObjectManager.Player.ChampionName)
                                           .Get <Label>("shopSequence")
                                           .DisplayName);
            }
            else
            {
                AutoShop bc = new AutoShop(menu, myChamp.ShopSequence);
            }

            Logic = new LogicSelector(myChamp, menu);
            new Disrespekt();
            Telemetry.SendEvent("GameStart", new Dictionary <string, string>()
            {
                { "GameChamp", AutoWalker.p.ChampionName },
                { "GameType", BrutalExtensions.GetGameType() },
                { "GameRegion", Game.Region },
                { "GameID", "" + AutoWalker.GameID },
            });
        }
Example #35
0
 private void end(object o, EventArgs e)
 {
     Telemetry.SendEvent("gameEnd", "K=" + localAwareness.me.kills2 + "|D=" + localAwareness.me.deaths + "|A=" + localAwareness.me.assists + "|F=" + localAwareness.me.farm);
 }
 void ITelemetryService.LogRenameSession(Telemetry.RenameSessionInfo renameSession)
 {
 }
Example #37
0
        private void ExecuteSearch()
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            ErrorsAndWarnings.Text = "";
            using (new WaitCursor())
            {
                display1.Chemistry = null;
                if (!string.IsNullOrEmpty(SearchFor.Text))
                {
                    ChebiWebServiceService ws = new ChebiWebServiceService();
                    getLiteEntityResponse  results;

                    var securityProtocol = ServicePointManager.SecurityProtocol;
                    ServicePointManager.SecurityProtocol = securityProtocol | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

                    ws.Url       = UserOptions.ChEBIWebServiceUri;
                    ws.UserAgent = "Chem4Word";

                    results = ws.getLiteEntity(new getLiteEntity
                    {
                        search         = SearchFor.Text,
                        maximumResults = UserOptions.MaximumResults,
                        searchCategory = SearchCategory.ALL,
                        stars          = StarsCategory.ALL
                    });

                    try
                    {
                        var allResults = results.@return;
                        ResultsListView.Items.Clear();
                        ResultsListView.Enabled = true;
                        if (allResults.Length > 0)
                        {
                            foreach (LiteEntity res in allResults)
                            {
                                var li = new ListViewItem();
                                li.Text = res.chebiId;
                                li.Tag  = res;
                                ListViewItem.ListViewSubItem name = new ListViewItem.ListViewSubItem(li, res.chebiAsciiName);
                                li.SubItems.Add(name);

                                ListViewItem.ListViewSubItem score = new ListViewItem.ListViewSubItem(li, res.searchScore.ToString());
                                li.SubItems.Add(score);
                                ResultsListView.Items.Add(li);
                            }

                            ResultsListView.Columns[0].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
                        }
                        else
                        {
                            ErrorsAndWarnings.Text = "Sorry: No results found.";
                        }
                    }
                    catch (Exception ex)
                    {
                        if (ex.Message.Equals("The operation has timed out"))
                        {
                            ErrorsAndWarnings.Text = "Please try again later - the service has timed out";
                        }
                        else
                        {
                            ErrorsAndWarnings.Text = ex.Message;
                            Telemetry.Write(module, "Exception", ex.Message);
                            Telemetry.Write(module, "Exception", ex.StackTrace);
                        }
                    }
                    finally
                    {
                        ServicePointManager.SecurityProtocol = securityProtocol;
                    }
                }
            }
            EnableImport();
        }
Example #38
0
        public async void ReverseEngineerCodeFirst(Project project)
        {
            try
            {
                var    dteH         = new EnvDteHelper();
                var    revEng       = new EfCoreReverseEngineer();
                string dacpacSchema = null;

                if (_package.Dte2.Mode == vsIDEMode.vsIDEModeDebug)
                {
                    EnvDteHelper.ShowError("Cannot generate code while debugging");
                    return;
                }

                var startTime    = DateTime.Now;
                var projectPath  = project.Properties.Item("FullPath").Value.ToString();
                var optionsPath  = Path.Combine(projectPath, "efpt.config.json");
                var renamingPath = Path.Combine(projectPath, "efpt.renaming.json");

                var databaseList = EnvDteHelper.GetDataConnections(_package);
                var dacpacList   = _package.Dte2.DTE.GetDacpacFilesInActiveSolution();

                var psd = new PickServerDatabaseDialog(databaseList, _package, dacpacList);
                if (psd.ShowModal() != true)
                {
                    return;
                }

                _package.Dte2.StatusBar.Text = "Loading schema information...";

                var dbInfo     = psd.SelectedDatabase.Value;
                var dacpacPath = psd.DacpacPath;

                if (dbInfo == null)
                {
                    dbInfo = new DatabaseInfo();
                }

                if (!string.IsNullOrEmpty(dacpacPath))
                {
                    dbInfo.DatabaseType     = DatabaseType.SQLServer;
                    dbInfo.ConnectionString = "Data Source=.;Initial Catalog=" + Path.GetFileNameWithoutExtension(dacpacPath);
                    dacpacPath = _package.Dte2.DTE.BuildSqlProj(dacpacPath);
                    if (string.IsNullOrEmpty(dacpacPath))
                    {
                        EnvDteHelper.ShowMessage("Unable to build selected Database Project");
                        return;
                    }
                }

                if (dbInfo.DatabaseType == DatabaseType.SQLCE35)
                {
                    EnvDteHelper.ShowError($"Unsupported provider: {dbInfo.ServerVersion}");
                    return;
                }

                var ptd = new PickTablesDialog {
                    IncludeTables = true
                };
                if (!string.IsNullOrEmpty(dacpacPath))
                {
                    ptd.Tables = revEng.GetDacpacTables(dacpacPath);
                }
                else
                {
                    ptd.Tables = GetTablesFromRepository(dbInfo);
                }
                var options = ReverseEngineerOptionsExtensions.TryRead(optionsPath);
                if (options != null)
                {
                    dacpacSchema = options.DefaultDacpacSchema;
                    if (options.Tables.Count > 0)
                    {
                        ptd.SelectedTables = options.Tables;
                    }
                }

                var customNameOptions = CustomNameOptionsExtensions.TryRead(renamingPath);


                if (ptd.ShowModal() != true)
                {
                    return;
                }

                var classBasis = string.Empty;
                if (dbInfo.DatabaseType == DatabaseType.Npgsql)
                {
                    classBasis = EnvDteHelper.GetNpgsqlDatabaseName(dbInfo.ConnectionString);
                }
                else
                {
                    classBasis = RepositoryHelper.GetClassBasis(dbInfo.ConnectionString, dbInfo.DatabaseType);
                }
                var model         = revEng.GenerateClassName(classBasis) + "Context";
                var packageResult = project.ContainsEfCoreReference(dbInfo.DatabaseType);

                var modelDialog = new EfCoreModelDialog(options)
                {
                    InstallNuGetPackage = !packageResult.Item1,
                    ModelName           = options != null ? options.ContextClassName : model,
                    ProjectName         = project.Name,
                    NameSpace           = options != null ? options.ProjectRootNamespace : project.Properties.Item("DefaultNamespace").Value.ToString(),
                    DacpacPath          = dacpacPath
                };

                _package.Dte2.StatusBar.Text = "Getting options...";
                if (modelDialog.ShowModal() != true)
                {
                    return;
                }

                options = new ReverseEngineerOptions
                {
                    UseFluentApiOnly        = !modelDialog.UseDataAnnotations,
                    ConnectionString        = dbInfo.ConnectionString,
                    ContextClassName        = modelDialog.ModelName,
                    DatabaseType            = (ReverseEngineer20.DatabaseType)dbInfo.DatabaseType,
                    ProjectPath             = projectPath,
                    OutputPath              = modelDialog.OutputPath,
                    ProjectRootNamespace    = modelDialog.NameSpace,
                    UseDatabaseNames        = modelDialog.UseDatabaseNames,
                    UseInflector            = modelDialog.UsePluralizer,
                    IdReplace               = modelDialog.ReplaceId,
                    UseHandleBars           = modelDialog.UseHandelbars,
                    IncludeConnectionString = modelDialog.IncludeConnectionString,
                    SelectedToBeGenerated   = modelDialog.SelectedTobeGenerated,
                    Dacpac = dacpacPath,
                    DefaultDacpacSchema = dacpacSchema,
                    Tables          = ptd.Tables,
                    CustomReplacers = customNameOptions
                };

                _package.Dte2.StatusBar.Text = "Generating code...";

                var  tfm           = project.Properties.Item("TargetFrameworkMoniker").Value.ToString();
                bool isNetStandard = tfm.Contains(".NETStandard,Version=v2.0");

                if (modelDialog.UseHandelbars)
                {
                    var dropped = (DropTemplates(projectPath));
                    if (dropped && !project.IsNetCore() && !isNetStandard)
                    {
                        project.ProjectItems.AddFromDirectory(Path.Combine(projectPath, "CodeTemplates"));
                    }
                }

                var revEngResult = revEng.GenerateFiles(options);

                if (modelDialog.SelectedTobeGenerated == 0 || modelDialog.SelectedTobeGenerated == 2)
                {
                    foreach (var filePath in revEngResult.EntityTypeFilePaths)
                    {
                        project.ProjectItems.AddFromFile(filePath);
                    }
                    if (modelDialog.SelectedTobeGenerated == 2)
                    {
                        if (File.Exists(revEngResult.ContextFilePath))
                        {
                            File.Delete(revEngResult.ContextFilePath);
                        }
                    }
                }
                if (modelDialog.SelectedTobeGenerated == 0 || modelDialog.SelectedTobeGenerated == 1)
                {
                    project.ProjectItems.AddFromFile(revEngResult.ContextFilePath);
                    if (!project.IsNetCore() && !isNetStandard)
                    {
                        _package.Dte2.ItemOperations.OpenFile(revEngResult.ContextFilePath);
                    }
                    if (modelDialog.SelectedTobeGenerated == 1)
                    {
                        foreach (var filePath in revEngResult.EntityTypeFilePaths)
                        {
                            if (File.Exists(filePath))
                            {
                                File.Delete(filePath);
                            }
                        }
                    }
                }

                var missingProviderPackage = packageResult.Item1 ? null : packageResult.Item2;
                if (modelDialog.InstallNuGetPackage || modelDialog.SelectedTobeGenerated == 2)
                {
                    missingProviderPackage = null;
                }

                _package.Dte2.StatusBar.Text = "Reporting result...";
                var errors = ReportRevEngErrors(revEngResult, missingProviderPackage);

                SaveOptions(project, optionsPath, options);

                if (modelDialog.InstallNuGetPackage)
                {
                    _package.Dte2.StatusBar.Text = "Installing EF Core provider package";
                    var nuGetHelper = new NuGetHelper();
                    await nuGetHelper.InstallPackageAsync(packageResult.Item2, project);
                }
                var duration = DateTime.Now - startTime;
                _package.Dte2.StatusBar.Text = $"Reverse engineer completed in {duration:h\\:mm\\:ss}";

                EnvDteHelper.ShowMessage(errors);

                if (revEngResult.EntityErrors.Count > 0)
                {
                    _package.LogError(revEngResult.EntityErrors, null);
                }
                if (revEngResult.EntityWarnings.Count > 0)
                {
                    _package.LogError(revEngResult.EntityWarnings, null);
                }
                Telemetry.TrackEvent("PowerTools.ReverseEngineer");
            }
            catch (AggregateException ae)
            {
                foreach (var innerException in ae.Flatten().InnerExceptions)
                {
                    _package.LogError(new List <string>(), innerException);
                }
            }
            catch (Exception exception)
            {
                _package.LogError(new List <string>(), exception);
            }
        }
 public static string GetString(Telemetry telemetry) => Serialize(telemetry);
Example #40
0
        internal static int ProcessArgs(string[] args, ITelemetry telemetryClient = null)
        {
            // CommandLineApplication is a bit restrictive, so we parse things ourselves here. Individual apps should use CLA.

            bool? verbose = null;
            var success = true;
            var command = string.Empty;
            var lastArg = 0;
            using (INuGetCacheSentinel nugetCacheSentinel = new NuGetCacheSentinel())
            {
                for (; lastArg < args.Length; lastArg++)
                {
                    if (IsArg(args[lastArg], "v", "verbose"))
                    {
                        verbose = true;
                    }
                    else if (IsArg(args[lastArg], "version"))
                    {
                        PrintVersion();
                        return 0;
                    }
                    else if (IsArg(args[lastArg], "info"))
                    {
                        PrintInfo();
                        return 0;
                    }
                    else if (IsArg(args[lastArg], "h", "help"))
                    {
                        HelpCommand.PrintHelp();
                        return 0;
                    }
                    else if (args[lastArg].StartsWith("-"))
                    {
                        Reporter.Error.WriteLine($"Unknown option: {args[lastArg]}");
                        success = false;
                    }
                    else
                    {
                        ConfigureDotNetForFirstTimeUse(nugetCacheSentinel);

                        // It's the command, and we're done!
                        command = args[lastArg];
                        break;
                    }
                }
                if (!success)
                {
                    HelpCommand.PrintHelp();
                    return 1;
                }

                if (telemetryClient == null)
                {
                    telemetryClient = new Telemetry(nugetCacheSentinel);
                }
            }

            var appArgs = (lastArg + 1) >= args.Length ? Enumerable.Empty<string>() : args.Skip(lastArg + 1).ToArray();

            if (verbose.HasValue)
            {
                Environment.SetEnvironmentVariable(CommandContext.Variables.Verbose, verbose.ToString());
                Console.WriteLine($"Telemetry is: {(telemetryClient.Enabled ? "Enabled" : "Disabled")}");
            }

            if (string.IsNullOrEmpty(command))
            {
                command = "help";
            }

            telemetryClient.TrackEvent(command, null, null);

            int exitCode;
            Func<string[], int> builtIn;
            if (s_builtIns.TryGetValue(command, out builtIn))
            {
                exitCode = builtIn(appArgs.ToArray());
            }
            else
            {
                CommandResult result = Command.Create("dotnet-" + command, appArgs, FrameworkConstants.CommonFrameworks.NetStandardApp15)
                    .Execute();
                exitCode = result.ExitCode;
            }

            return exitCode;

        }
Example #41
0
 // Update is called once per frame
 void Update()
 {
     Telemetry.info("hello telemetry!");
 }