Exemplo n.º 1
0
        private string CreateUrl(string url)
        {
            string serverUrl = url.WithTrailingSlash();

            //Ensure http/https present
            serverUrl =
                (serverUrl.ToLower().StartsWith("http://") || serverUrl.ToLower().StartsWith("https://"))
                    ? serverUrl
                    : "http://" + serverUrl;
            var    uri  = new Uri(serverUrl);
            string path = uri.PathAndQuery.Contains("?") ? uri.PathAndQuery.SplitOnFirst("?")[0] : uri.PathAndQuery;

            if (!path.EndsWith(typesHandler.RelativeTypesUrl + "/"))
            {
                serverUrl += typesHandler.RelativeTypesUrl + "/";
            }

            string result = serverUrl.ToParentPath();

            if (!IsTypedScriptReference)
            {
                return(result);
            }


            result = result.AddQueryParam("ExportAsTypes", TypeScriptOnlyDefinitions ? "False" : "True");
            // Update native types handler to handle different file names.
            typesHandler = TypeScriptOnlyDefinitions
                ? new TypeScriptNativeTypesHandler()
                : new TypeScriptConcreteNativeTypesHandler() as INativeTypesHandler;
            return(result);
        }
        public static List <string> ValidVsProjectTypeGuids(this INativeTypesHandler handler)
        {
            if (handler.TypesLanguage == NativeTypesLanguage.CSharp)
            {
                return(new List <string> {
                    VsHelperGuids.CSharpProjectKind
                });
            }

            if (handler.TypesLanguage == NativeTypesLanguage.FSharp)
            {
                return(new List <string> {
                    VsHelperGuids.FSharpProjectKind
                });
            }

            if (handler.TypesLanguage == NativeTypesLanguage.VbNet)
            {
                return(new List <string> {
                    VsHelperGuids.VbNetProjectKind
                });
            }

            if (handler.TypesLanguage == NativeTypesLanguage.TypeScript)
            {
                return(new List <string>
                {
                    VsHelperGuids.CSharpProjectKind,
                    VsHelperGuids.FSharpProjectKind,
                    VsHelperGuids.VbNetProjectKind
                });
            }
            return(new List <string>());
        }
Exemplo n.º 3
0
        private static INativeTypesHandler GetNativeTypeHandler(string lang = null)
        {
            INativeTypesHandler result = null;

            if (lang == null)
            {
                foreach (var nativeTypesHandlerPair in All)
                {
                    if (AppDomain.CurrentDomain.FriendlyName.Contains(nativeTypesHandlerPair.Key))
                    {
                        result = nativeTypesHandlerPair.Value;
                        break;
                    }
                }
                if (result == null)
                {
                    Console.WriteLine("WARN: Invalid language '" + lang + "'. Defaulting to CSharp.");
                    result = CSharpNativeTypesHandler;
                }
            }
            else if (All.ContainsKey(lang.ToLowerInvariant()))
            {
                result = All[lang.ToLowerInvariant()];
            }

            if (result == null)
            {
                Console.WriteLine("WARN: Invalid language '" + lang + "'. Defaulting to CSharp.");
            }

            return(result ?? CSharpNativeTypesHandler);
        }
Exemplo n.º 4
0
        private static void ProcessAdd(string url, string path = null, string language = null)
        {
            INativeTypesHandler nativeTypesHandler = GetNativeTypeHandler(language);

            path = path ?? "ServiceStackReference" + nativeTypesHandler.CodeFileExtension;
            bool fileNameContainsExtension =
                path.LastIndexOf(".", StringComparison.Ordinal) > path.LastIndexOf(Path.DirectorySeparatorChar) &&
                (path.LastIndexOf(".", StringComparison.Ordinal) != path.LastIndexOf(Path.DirectorySeparatorChar));

            path = fileNameContainsExtension ? path : path + nativeTypesHandler.CodeFileExtension;

            string code;

            try
            {
                code = nativeTypesHandler.GetUpdatedCode(url, null);
            }
            catch (Exception)
            {
                Console.WriteLine("Failed to get ServiceStack reference from '" + url + "'.");
                throw;
            }
            try
            {
                File.WriteAllText(path, code);
            }
            catch (Exception)
            {
                Console.WriteLine("Failed to write ServiceStack reference to '" + path + "'.");
                throw;
            }
        }
 public AddServiceStackReference(string fileName, INativeTypesHandler nativeTypesHandler)
 {
     suggestedFileName = fileName;
     InitializeComponent();
     FileNameTextBox.Text = suggestedFileName;
     this.KeyDown        += ListenForShortcutKeys;
     typesHandler         = nativeTypesHandler;
 }
 public AddServiceStackReference(string fileName, INativeTypesHandler nativeTypesHandler)
 {
     suggestedFileName = fileName;
     InitializeComponent();
     FileNameTextBox.Text = suggestedFileName;
     this.KeyDown += ListenForShortcutKeys;
     typesHandler = nativeTypesHandler;
 }
Exemplo n.º 7
0
        private static void HandleDtoUpdate(Document document, INativeTypesHandler typesHandler,
                                            OutputWindowWriter outputWindowWriter)
        {
            string fullPath = document.ProjectItem.GetFullPath();

            outputWindowWriter.ShowOutputPane(document.DTE);
            outputWindowWriter.Show();
            outputWindowWriter.WriteLine(
                "--- Updating ServiceStack Reference '" +
                fullPath.Substring(fullPath.LastIndexOf("\\", StringComparison.Ordinal) + 1) +
                "' ---");
            var    existingGeneratedCode = File.ReadAllLines(fullPath).Join(Environment.NewLine);
            string baseUrl;

            if (!typesHandler.TryExtractBaseUrl(existingGeneratedCode, out baseUrl))
            {
                outputWindowWriter.WriteLine("Failed to update ServiceStack Reference: Unabled to find BaseUrl");
                return;
            }
            try
            {
                var    options     = typesHandler.ParseComments(existingGeneratedCode);
                string updatedCode = typesHandler.GetUpdatedCode(baseUrl, options);

                //Can't work out another way that ensures UI is updated.
                //Overwriting the file inconsistently prompts the user that file has changed.
                //Sometimes old code persists even though file has changed.
                document.Close();
                using (var streamWriter = File.CreateText(fullPath))
                {
                    streamWriter.Write(updatedCode);
                    streamWriter.Flush();
                }
                try
                {
                    bool optOutOfStats = Dte.GetOptOutStatsSetting();
                    if (!optOutOfStats)
                    {
                        var langName = typesHandler.RelativeTypesUrl.Substring(6);
                        Analytics.SubmitAnonymousUpdateReferenceUsage(langName);
                    }
                }
                catch (Exception)
                {
                    // Ignore errors
                }
                //HACK to ensure new file is loaded
                Task.Run(() => { document.DTE.ItemOperations.OpenFile(fullPath); });
            }
            catch (Exception e)
            {
                outputWindowWriter.WriteLine("Failed to update ServiceStack Reference: Unhandled error - " + e.Message);
            }

            outputWindowWriter.WriteLine("--- Update ServiceStack Reference Complete ---");
        }
Exemplo n.º 8
0
        public AddServiceStackReference(string fileName, INativeTypesHandler nativeTypesHandler)
        {
            InitializeComponent();
            FileNameTextBox.Text = fileName;
            KeyDown               += ListenForShortcutKeys;
            typesHandler           = nativeTypesHandler;
            IsTypedScriptReference = nativeTypesHandler is TypeScriptConcreteNativeTypesHandler ||
                                     nativeTypesHandler is TypeScriptNativeTypesHandler;

            TypeScriptCheckbox.Visibility = IsTypedScriptReference ? Visibility.Visible : Visibility.Hidden;
        }
Exemplo n.º 9
0
 public AddReferenceDialog(string fileName, INativeTypesHandler nativeTypesHandler)
 {
     this.Build ();
     typesHandler = nativeTypesHandler;
     nameEntry.Text = fileName;
     this.KeyReleaseEvent += (o, keyEventArgs) => {
         if (keyEventArgs.Event.Key == Gdk.Key.Return) {
             CreateServiceReference();
         }
         if (keyEventArgs.Event.Key == Gdk.Key.Escape) {
             this.OnClose ();
         }
     };
 }
Exemplo n.º 10
0
        public static bool TryExtractBaseUrl(this INativeTypesHandler typesHandler, string codeFromFile, out string baseUrl)
        {
            baseUrl = "";
            var options = typesHandler.ParseComments(codeFromFile);

            if (options.ContainsKey("BaseUrl"))
            {
                baseUrl = options["BaseUrl"];
                if (!string.IsNullOrEmpty(baseUrl))
                {
                    return(true);
                }
            }
            return(false);
        }
Exemplo n.º 11
0
 public static bool IsValidResponse(this INativeTypesHandler typesHandler, string code)
 {
     if (typesHandler is VbNetNativeTypesHandler)
     {
         return(code.StartsWith("' Options:"));
     }
     if (typesHandler is FSharpNativeTypesHandler)
     {
         return(code.StartsWith("(* Options:"));
     }
     else
     {
         return(code.StartsWith("/* Options:"));
     }
 }
Exemplo n.º 12
0
 public AddReferenceDialog(string fileName, INativeTypesHandler nativeTypesHandler)
 {
     this.Build();
     typesHandler          = nativeTypesHandler;
     nameEntry.Text        = fileName;
     this.KeyReleaseEvent += (o, keyEventArgs) => {
         if (keyEventArgs.Event.Key == Gdk.Key.Return)
         {
             CreateServiceReference();
         }
         if (keyEventArgs.Event.Key == Gdk.Key.Escape)
         {
             this.OnClose();
         }
     };
 }
        private void UpdateGeneratedDtos(ProjectItem projectItem, INativeTypesHandler typesHandler)
        {
            OutputWindowWriter.Show();
            OutputWindowWriter.ShowOutputPane(dte);
            OutputWindowWriter.WriteLine("--- Updating ServiceStack Reference '" + projectItem.Name + "' ---");
            string projectItemPath = projectItem.GetFullPath();
            var    selectedFiles   = projectItem.DTE.SelectedItems.Cast <SelectedItem>().ToList();
            bool   isDtoSelected   = selectedFiles.Any(item => item.Name.ToLowerInvariant().EndsWith(typesHandler.CodeFileExtension));

            if (isDtoSelected)
            {
                string filePath = projectItemPath;
                var    existingGeneratedCode = File.ReadAllLines(filePath).Join(Environment.NewLine);

                string baseUrl;
                if (!typesHandler.TryExtractBaseUrl(existingGeneratedCode, out baseUrl))
                {
                    OutputWindowWriter.WriteLine("Unable to read URL from DTO file. Please ensure the file was generated correctly from a ServiceStack server.");
                    return;
                }
                try
                {
                    var    options     = typesHandler.ParseComments(existingGeneratedCode);
                    string updatedCode = typesHandler.GetUpdatedCode(baseUrl, options);
                    using (var streamWriter = File.CreateText(filePath))
                    {
                        streamWriter.Write(updatedCode);
                        streamWriter.Flush();
                    }
                }
                catch (Exception e)
                {
                    OutputWindowWriter.WriteLine("Failed to update ServiceStack Reference: Unhandled error - " + e.Message);
                }

                OutputWindowWriter.WriteLine("--- Update ServiceStack Reference Complete ---");
            }
            else
            {
                OutputWindowWriter.WriteLine("--- Valid file not found ServiceStack Reference '" + projectItem.Name + "' ---");
            }
        }
        private void AddServiceStackReference(string folderPath, INativeTypesHandler typesHandler)
        {
            int fileNameNumber = 1;

            //Find a version of the default name that doesn't already exist,
            //mimicing VS default file name behaviour.
            while (File.Exists(Path.Combine(folderPath, "ServiceReference" + fileNameNumber + typesHandler.CodeFileExtension)))
            {
                fileNameNumber++;
            }
            var dialog = new AddServiceStackReference("ServiceReference" + fileNameNumber, typesHandler);

            dialog.ShowDialog();
            if (!dialog.AddReferenceSucceeded)
            {
                return;
            }
            string templateCode = dialog.CodeTemplate;

            AddNewDtoFileToProject(dialog.FileNameTextBox.Text + typesHandler.CodeFileExtension, templateCode, typesHandler.RequiredNuGetPackages);
        }
Exemplo n.º 15
0
        public void RunStarted(object automationObject, Dictionary <string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
        {
            userProviderItemName = replacementsDictionary["$safeitemname$"];
            if (runKind == WizardRunKind.AsNewItem)
            {
                string   wizardData        = replacementsDictionary["$wizarddata$"];
                XElement element           = XElement.Parse("<WizardData>" + wizardData + "</WizardData>");
                var      nativeTypeElement = element
                                             .Descendants().FirstOrDefault(x => x.Name.LocalName.EqualsIgnoreCase("NativeType"));
                if (nativeTypeElement == null)
                {
                    return;
                }

                var nativeTypeName = nativeTypeElement.Value;
                var typesHandler   = NativeTypesHandlers.Where(x => x.Key.EqualsIgnoreCase(nativeTypeName)).Select(x => x.Value).FirstOrDefault();
                if (typesHandler == null)
                {
                    throw new WizardBackoutException("Unable to find associated INativeTypesHandler from '" + nativeTypeName + "'");
                }
                currentNativeTypesHandle = typesHandler;

                var dialog = new AddServiceStackReference(userProviderItemName, currentNativeTypesHandle);
                dialog.ShowDialog();
                if (!dialog.AddReferenceSucceeded)
                {
                    throw new WizardBackoutException("Cancelled");
                }
                finalUserProvidedName = dialog.FileNameTextBox.Text;
                replacementsDictionary.Add("$basereferenceurl$", dialog.ServerUrl.Replace(typesHandler.RelativeTypesUrl, string.Empty));
            }
            else
            {
                throw new WizardBackoutException("Invalid template runkind. Expecting 'WizardRunKind.AsNewItem'");
            }
        }
Exemplo n.º 16
0
        public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
        {
            userProviderItemName = replacementsDictionary["$safeitemname$"];
            if (runKind == WizardRunKind.AsNewItem)
            {
                string wizardData = replacementsDictionary["$wizarddata$"];
                XElement element = XElement.Parse("<WizardData>" + wizardData + "</WizardData>");
                var nativeTypeElement = element
                    .Descendants().FirstOrDefault(x => x.Name.LocalName.EqualsIgnoreCase("NativeType"));
                if (nativeTypeElement == null) return;

                var nativeTypeName = nativeTypeElement.Value;
                var typesHandler = NativeTypesHandlers.Where(x => x.Key.EqualsIgnoreCase(nativeTypeName)).Select(x => x.Value).FirstOrDefault();
                if (typesHandler == null)
                {
                    throw new WizardBackoutException("Unable to find associated INativeTypesHandler from '" + nativeTypeName + "'");
                }
                currentNativeTypesHandle = typesHandler;

                var dialog = new AddServiceStackReference(userProviderItemName, currentNativeTypesHandle);
                dialog.ShowDialog();
                if (!dialog.AddReferenceSucceeded)
                {
                    throw new WizardBackoutException("Cancelled");
                }
                finalUserProvidedName = dialog.FileNameTextBox.Text;
                replacementsDictionary.Add("$basereferenceurl$", dialog.ServerUrl.Replace(typesHandler.RelativeTypesUrl,string.Empty));
            }
            else
            {
                throw new WizardBackoutException("Invalid template runkind. Expecting 'WizardRunKind.AsNewItem'");
            }
        }
Exemplo n.º 17
0
        protected override void Run()
        {
            DotNetProject project            = IdeApp.ProjectOperations.CurrentSelectedProject as DotNetProject;
            var           dotNetProjectProxy = new DotNetProjectProxy(project);

            if (project == null)
            {
                return;
            }
            INativeTypesHandler nativeTypesHandler = null;

            //SupportedLanguage names currently returns an empty item and the 'languageName' the DotNetProject
            //is initialized with. This might be an array to enable extension for other projects? DotNetProject
            //only returns an empty and languageName. See source link.
            // https://github.com/mono/monodevelop/blob/dcafac668cbe8f63b4e42ea7f8f032f13aba8221/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/DotNetProject.cs#L198
            if (project.SupportedLanguages.Contains("C#"))
            {
                nativeTypesHandler = NativeTypeHandlers.CSharpNativeTypesHandler;
            }

            if (project.SupportedLanguages.Contains("F#"))
            {
                nativeTypesHandler = NativeTypeHandlers.FSharpNativeTypesHandler;
            }

            if (project.SupportedLanguages.Contains("VBNet"))
            {
                nativeTypesHandler = NativeTypeHandlers.VbNetNativeTypesHandler;
            }

            if (nativeTypesHandler == null)
            {
                throw new ArgumentNullException("No supported languages found");
            }

            string fileName = "ServiceReference";

            int  count  = 0;
            bool exists = true;

            while (exists)
            {
                count++;
                var existingFile = project.Files.FirstOrDefault(x => x.FilePath.FileName == fileName + count.ToString() + nativeTypesHandler.CodeFileExtension);
                exists = existingFile != null;
            }

            var dialog = new AddReferenceDialog(fileName + count.ToString(), nativeTypesHandler);

            dialog.Run();
            string finalFileName = dialog.ReferenceName + nativeTypesHandler.CodeFileExtension;
            string code          = dialog.CodeTemplate;

            dialog.Destroy();
            if (!dialog.AddReferenceSucceeded)
            {
                return;
            }
            IdeApp.Workbench.StatusBar.ShowReady();
            IdeApp.Workbench.StatusBar.ShowMessage("Adding ServiceStack Reference...");
            IdeApp.Workbench.StatusBar.Pulse();
            string fullPath = Path.Combine(project.BaseDirectory.FullPath.ToString(), finalFileName);

            using (var streamWriter = File.CreateText(fullPath)) {
                streamWriter.Write(code);
                streamWriter.Flush();
            }

            project.AddFile(fullPath, BuildAction.Compile);

            try {
                Task.Run(() => {
                    AddNuGetPackageReference(dotNetProjectProxy, "ServiceStack.Client");
                    AddNuGetPackageReference(dotNetProjectProxy, "ServiceStack.Interfaces");
                    AddNuGetPackageReference(dotNetProjectProxy, "ServiceStack.Text");
                }).ContinueWith(task => {
                    IdeApp.Workbench.StatusBar.ShowReady();
                    IdeApp.Workbench.StatusBar.Pulse();
                }, TaskScheduler.FromCurrentSynchronizationContext());
            } catch (Exception ex) {
                //TODO Error message for user
                var messageDialog = new MessageDialog(
                    (Gtk.Window)IdeApp.Workbench.RootWindow.Toplevel,
                    DialogFlags.Modal,
                    MessageType.Warning,
                    ButtonsType.Close,
                    "An error occurred trying to add required NuGet packages. Error : " + ex.Message +
                    "\r\n\r\nGenerated service reference will require ServiceStack.Interfaces as a minimum.");
                messageDialog.Run();
                messageDialog.Destroy();
                IdeApp.Workbench.StatusBar.ShowReady();
                IdeApp.Workbench.StatusBar.Pulse();
            }
        }
Exemplo n.º 18
0
        private void UpdateGeneratedDtos(ProjectItem projectItem, INativeTypesHandler typesHandler)
        {
            OutputWindowWriter.WriterWindow.Show();
            OutputWindowWriter.WriterWindow.ShowOutputPane(dte);
            OutputWindowWriter.WriterWindow.WriteLine("--- Updating ServiceStack Reference '" + projectItem.Name + "' ---");
            string projectItemPath = projectItem.GetFullPath();
            var    selectedFiles   = projectItem.DTE.SelectedItems.Cast <SelectedItem>().ToList();
            bool   isDtoSelected   = false;

            isDtoSelected = selectedFiles
                            .Any(item => typesHandler.IsHandledFileType(item.Name));

            //Handle FSharp file extension name change for DTO files, eg .dto.fs to .dtos.fs
            if (!isDtoSelected && typesHandler is FSharpNativeTypesHandler)
            {
                isDtoSelected = selectedFiles
                                .Any(item => item.Name.ToLowerInvariant()
                                     .EndsWith(".dto.fs"));
            }

            if (isDtoSelected)
            {
                string filePath = projectItemPath;
                var    existingGeneratedCode = File.ReadAllLines(filePath).Join(Environment.NewLine);

                string baseUrl;
                if (!typesHandler.TryExtractBaseUrl(existingGeneratedCode, out baseUrl))
                {
                    OutputWindowWriter.WriterWindow.WriteLine("Unable to read URL from DTO file. Please ensure the file was generated correctly from a ServiceStack server.");
                    return;
                }
                try
                {
                    var  options = typesHandler.ParseComments(existingGeneratedCode);
                    bool setSslValidationCallback = false;
                    //Don't set validation callback if one has already been set for VS.
                    if (ServicePointManager.ServerCertificateValidationCallback == null)
                    {
                        //Temp set validation callback to return true to avoid common dev server ssl certificate validation issues.
                        setSslValidationCallback = true;
                        ServicePointManager.ServerCertificateValidationCallback =
                            (sender, certificate, chain, errors) => true;
                    }
                    string updatedCode = typesHandler.GetUpdatedCode(baseUrl, options);
                    if (setSslValidationCallback)
                    {
                        //If callback was set to return true, reset back to null.
                        ServicePointManager.ServerCertificateValidationCallback = null;
                    }
                    using (var streamWriter = File.CreateText(filePath))
                    {
                        streamWriter.Write(updatedCode);
                        streamWriter.Flush();
                    }
                    try
                    {
                        bool optOutOfStats = dte.GetOptOutStatsSetting();
                        if (!optOutOfStats)
                        {
                            var langName = typesHandler.RelativeTypesUrl.Substring(6);
                            Analytics.SubmitAnonymousUpdateReferenceUsage(langName);
                        }
                    }
                    catch (Exception)
                    {
                        // Ignore errors
                    }
                }
                catch (Exception e)
                {
                    OutputWindowWriter.WriterWindow.WriteLine("Failed to update ServiceStack Reference: Unhandled error - " + e.Message);
                }

                OutputWindowWriter.WriterWindow.WriteLine("--- Update ServiceStack Reference Complete ---");
            }
            else
            {
                OutputWindowWriter.WriterWindow.WriteLine("--- Valid file not found ServiceStack Reference '" + projectItem.Name + "' ---");
            }
        }
Exemplo n.º 19
0
        private static void HandleDtoUpdate(Document document, INativeTypesHandler typesHandler,
            OutputWindowWriter outputWindowWriter)
        {
            string fullPath = document.ProjectItem.GetFullPath();
            outputWindowWriter.ShowOutputPane(document.DTE);
            outputWindowWriter.Show();
            outputWindowWriter.WriteLine(
                "--- Updating ServiceStack Reference '" +
                fullPath.Substring(fullPath.LastIndexOf("\\", StringComparison.Ordinal) + 1) +
                "' ---");
            var existingGeneratedCode = File.ReadAllLines(fullPath).Join(Environment.NewLine);
            string baseUrl;
            if (!typesHandler.TryExtractBaseUrl(existingGeneratedCode, out baseUrl))
            {
                outputWindowWriter.WriteLine("Failed to update ServiceStack Reference: Unabled to find BaseUrl");
                return;
            }
            try
            {
                var options = typesHandler.ParseComments(existingGeneratedCode);
                string updatedCode = typesHandler.GetUpdatedCode(baseUrl, options);

                //Can't work out another way that ensures UI is updated.
                //Overwriting the file inconsistently prompts the user that file has changed.
                //Sometimes old code persists even though file has changed.
                document.Close();
                using (var streamWriter = File.CreateText(fullPath))
                {
                    streamWriter.Write(updatedCode);
                    streamWriter.Flush();
                }
                //HACK to ensure new file is loaded
                Task.Run(() => { document.DTE.ItemOperations.OpenFile(fullPath); });
            }
            catch (Exception e)
            {
                outputWindowWriter.WriteLine("Failed to update ServiceStack Reference: Unhandled error - " + e.Message);
            }

            outputWindowWriter.WriteLine("--- Update ServiceStack Reference Complete ---");
        }
Exemplo n.º 20
0
        private void UpdateGeneratedDtos(ProjectItem projectItem, INativeTypesHandler typesHandler)
        {
            OutputWindowWriter.Show();
            OutputWindowWriter.ShowOutputPane(dte);
            OutputWindowWriter.WriteLine("--- Updating ServiceStack Reference '" + projectItem.Name + "' ---");
            string projectItemPath = projectItem.GetFullPath();
            var selectedFiles = projectItem.DTE.SelectedItems.Cast<SelectedItem>().ToList();
            bool isDtoSelected = false;
            isDtoSelected = selectedFiles
                .Any(item => item.Name.ToLowerInvariant()
                    .EndsWith(typesHandler.CodeFileExtension));

            //Handle FSharp file extension name change for DTO files, eg .dto.fs to .dtos.fs
            if (!isDtoSelected && typesHandler is FSharpNativeTypesHandler)
            {
                isDtoSelected = selectedFiles
                .Any(item => item.Name.ToLowerInvariant()
                    .EndsWith(".dto.fs"));
            }

            if (isDtoSelected)
            {
                string filePath = projectItemPath;
                var existingGeneratedCode = File.ReadAllLines(filePath).Join(Environment.NewLine);

                string baseUrl;
                if (!typesHandler.TryExtractBaseUrl(existingGeneratedCode, out baseUrl))
                {
                    OutputWindowWriter.WriteLine("Unable to read URL from DTO file. Please ensure the file was generated correctly from a ServiceStack server.");
                    return;
                }
                try
                {
                    var options = typesHandler.ParseComments(existingGeneratedCode);
                    bool setSslValidationCallback = false;
                    //Don't set validation callback if one has already been set for VS.
                    if (ServicePointManager.ServerCertificateValidationCallback == null)
                    {
                        //Temp set validation callback to return true to avoid common dev server ssl certificate validation issues.
                        setSslValidationCallback = true;
                        ServicePointManager.ServerCertificateValidationCallback =
                            (sender, certificate, chain, errors) => true;
                    }
                    string updatedCode = typesHandler.GetUpdatedCode(baseUrl, options);
                    if (setSslValidationCallback)
                    {
                        //If callback was set to return true, reset back to null.
                        ServicePointManager.ServerCertificateValidationCallback = null;
                    }
                    using (var streamWriter = File.CreateText(filePath))
                    {
                        streamWriter.Write(updatedCode);
                        streamWriter.Flush();
                    }
                }
                catch (Exception e)
                {
                    OutputWindowWriter.WriteLine("Failed to update ServiceStack Reference: Unhandled error - " + e.Message);
                }

                OutputWindowWriter.WriteLine("--- Update ServiceStack Reference Complete ---");
            }
            else
            {
                OutputWindowWriter.WriteLine("--- Valid file not found ServiceStack Reference '" + projectItem.Name + "' ---");
            }
        }
Exemplo n.º 21
0
 private void AddServiceStackReference(string folderPath, INativeTypesHandler typesHandler)
 {
     int fileNameNumber = 1;
     //Find a version of the default name that doesn't already exist,
     //mimicing VS default file name behaviour.
     while (File.Exists(Path.Combine(folderPath, "ServiceReference" + fileNameNumber + typesHandler.CodeFileExtension)))
     {
         fileNameNumber++;
     }
     var dialog = new AddServiceStackReference("ServiceReference" + fileNameNumber, typesHandler);
     dialog.ShowDialog();
     if (!dialog.AddReferenceSucceeded)
     {
         return;
     }
     string templateCode = dialog.CodeTemplate;
     AddNewDtoFileToProject(dialog.FileNameTextBox.Text + typesHandler.CodeFileExtension, templateCode, typesHandler.RequiredNuGetPackages);
 }