protected override AddServiceInstanceResult CreateAddServiceInstanceResult(ConnectedServiceHandlerContext context)
 {
     return new AddServiceInstanceResult(
         context.ServiceInstance.Name,
         new Uri("http://aka.ms/azure-iot-hub-vs-cs-cs")
         );
 }
Exemplo n.º 2
0
 public V4CodeGenDescriptor(string metadataUri, ConnectedServiceHandlerContext context, Project project)
     : base(metadataUri, context, project)
 {
     this.ClientNuGetPackageName = Common.Constants.V4ClientNuGetPackage;
     this.ClientDocUri = Common.Constants.V4DocUri;
     this.ServiceConfiguration = base.ServiceConfiguration as ServiceConfigurationV4;
 }
        public override async Task<AddServiceInstanceResult> AddServiceInstanceAsync(ConnectedServiceHandlerContext context, CancellationToken ct)
        {
            SalesforceConnectedServiceInstance salesforceInstance = (SalesforceConnectedServiceInstance)context.ServiceInstance;

            try
            {
                Project project = ProjectHelper.GetProjectFromHierarchy(context.ProjectHierarchy);
                string generatedArtifactSuffix = SalesforceConnectedServiceHandler.GetGeneratedArtifactSuffix(
                    context, project, salesforceInstance.RuntimeAuthentication.AuthStrategy);
                salesforceInstance.DesignerData.ServiceName = SalesforceConnectedServiceHandler.GetServiceInstanceName(generatedArtifactSuffix);

                await TaskScheduler.Default; // Switch to a worker thread to avoid blocking the UI thread (e.g. the progress dialog).

                await SalesforceConnectedServiceHandler.CreateConnectedAppAsync(context, project, salesforceInstance);
                await SalesforceConnectedServiceHandler.UpdateConfigFileAsync(context, project, salesforceInstance);
                await this.AddNuGetPackagesAsync(context, project);
                await SalesforceConnectedServiceHandler.AddAssemblyReferencesAsync(context, salesforceInstance);
                await SalesforceConnectedServiceHandler.AddGeneratedCodeAsync(context, project, salesforceInstance);

                salesforceInstance.DesignerData.StoreExtendedDesignerData(context);

                salesforceInstance.TelemetryHelper.TrackAddServiceSucceededEvent(salesforceInstance);

                return new AddServiceInstanceResult(
                    salesforceInstance.DesignerData.ServiceName,
                    new Uri(Constants.NextStepsUrl));
            }
            catch (Exception e)
            {
                salesforceInstance.TelemetryHelper.TrackAddServiceFailedEvent(salesforceInstance, e);
                throw;
            }
        }
 protected override AddServiceInstanceResult CreateAddServiceInstanceResult(ConnectedServiceHandlerContext context)
 {
     return new AddServiceInstanceResult(
         "",
         null
         );
 }
        private async Task AddNuGetPackagesAsync(ConnectedServiceHandlerContext context, Project currentProject, Version version)
        {
            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Adding Nuget Packages");
            Version packageVersion = null;
            if (version.Major.Equals(3))
            {
                var wcfDSInstallLocation = CodeGeneratorUtils.GetWCFDSInstallLocation();

                var packageSource = Path.Combine(wcfDSInstallLocation, @"bin\NuGet");
                if (Directory.Exists(packageSource))
                {
                    var files = Directory.EnumerateFiles(packageSource, "*.nupkg").ToList();
                    foreach (var nugetPackage in Constant.V3NuGetPackages)
                    {
                        if (!files.Any(f => Regex.IsMatch(f, nugetPackage + @"(.\d){2,4}.nupkg")))
                        {
                            packageSource = Constant.NuGetOnlineRepository;
                        }
                    }
                }
                else
                {
                    packageSource = Constant.NuGetOnlineRepository;
                }

                if (!PackageInstallerServices.IsPackageInstalled(currentProject, Constant.V3ClientNuGetPackage))
                {
                    PackageInstaller.InstallPackage(packageSource, currentProject, Constant.V3ClientNuGetPackage, packageVersion, false);
                }
            }
        }
Exemplo n.º 6
0
 private async Task AddAssemblyReferences(ConnectedServiceHandlerContext context)
 {
     await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Adding References");
     //Need to add this reference for reading values from the .config file
     context.HandlerHelper.AddAssemblyReference("System.Configuration");
     context.HandlerHelper.AddAssemblyReference("System.ComponentModel.DataAnnotations");
 }
        public override async Task<AddServiceInstanceResult> AddServiceInstanceAsync(ConnectedServiceHandlerContext context, CancellationToken ct)
        {
            // See Handler Samples for how to work with the project system 
            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Handler Invoked");

            return new AddServiceInstanceResult("SampleServiceSinglePageUITemplate", null);
        }
 /// <summary>
 /// Called to update an existing Connected Service to the project.
 /// </summary>
 public override async Task<UpdateServiceInstanceResult> UpdateServiceInstanceAsync(ConnectedServiceHandlerContext context, CancellationToken ct)
 {
     // See Handler samples for examples of how to work with the project system 
     await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Handler Invoked to Update Project Artifacts");
     UpdateServiceInstanceResult updateResult = new UpdateServiceInstanceResult();
     updateResult.GettingStartedDocument = new GettingStartedDocument(new Uri(Handler.GettingStartedUrl));
     return updateResult;
 }
Exemplo n.º 9
0
        public override async Task<UpdateServiceInstanceResult> UpdateServiceInstanceAsync(ConnectedServiceHandlerContext context, CancellationToken ct)
        {
            Project project = ProjectHelper.GetProjectFromHierarchy(context.ProjectHierarchy);
            ODataConnectedServiceInstance codeGenInstance = (ODataConnectedServiceInstance)context.ServiceInstance;

            var codeGenDescriptor = await GenerateCode(codeGenInstance.ServiceConfig.Endpoint, codeGenInstance.ServiceConfig.EdmxVersion, context, project);
            context.SetExtendedDesignerData<ServiceConfiguration>(codeGenInstance.ServiceConfig);
            return new UpdateServiceInstanceResult();
        }
Exemplo n.º 10
0
        public BaseCodeGenDescriptor(string metadataUri, ConnectedServiceHandlerContext Context, Project project)
        {
            this.Init();

            this.MetadataUri = metadataUri;
            this.Context = Context;
            this.Project = project;
            this.ServiceConfiguration = ((ODataConnectedServiceInstance)this.Context.ServiceInstance).ServiceConfig;
        }
        public async override Task<AddServiceInstanceResult> AddServiceInstanceAsync(ConnectedServiceHandlerContext context, CancellationToken ct)
        {
            string token = (string)context.Args[Constants.CONNECTED_SERVICE_METADATA_KEY_FOR_ADAL_TOKEN];
            string subscriptionId = (string)context.Args[Constants.CONNECTED_SERVICE_METADATA_KEY_FOR_SUB_ID];
            string swaggerJson = (string)context.Args[Constants.CONNECTED_SERVICE_METADATA_KEY_FOR_SWAGGER];
            IEnumerable<ApiManagementProduct> products = (IEnumerable<ApiManagementProduct>)context.Args[Constants.CONNECTED_SERVICE_METADATA_KEY_FOR_PRODUCTS];
            ApiManagementInstance apimInstance = (ApiManagementInstance)context.Args[Constants.CONNECTED_SERVICE_METADATA_KEY_FOR_APIM_INSTANCE];
            ApiAppResource apiApp = (ApiAppResource)context.Args[Constants.CONNECTED_SERVICE_METADATA_KEY_FOR_API_APP];

            using (var apiManagementClient = new ApiManagementClient(
                new TokenCloudCredentials(subscriptionId, token)
                ))
            {
                await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information,
                    Resources.ProgressMessageImportingSwaggerTemplate,
                    apiApp.Name,
                    apimInstance.Name);

                // import the api
                using (MemoryStream stream = new MemoryStream())
                {
                    var writer = new StreamWriter(stream);
                    writer.Write(swaggerJson);
                    writer.Flush();
                    stream.Position = 0;

                    apiManagementClient.Apis.Import(
                        ResourceUtilities.GetResourceGroupFromResourceId(apimInstance.ResourceId),
                        apimInstance.Name,
                        apiApp.Name,
                        Constants.SWAGGER_CONTENT_TYPE,
                        stream,
                        apiApp.Name);
                }

                // add the api to products
                foreach (var product in products)
                {
                    await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information,
                        Resources.ProgressMessageAddingApiToProductTemplate,
                        apiApp.Name,
                        product.Name);

                    apiManagementClient.ProductApis.Add(
                        ResourceUtilities.GetResourceGroupFromResourceId(apimInstance.ResourceId),
                        apimInstance.Name,
                        product.Id,
                        apiApp.Name);
                }
            }

            AddServiceInstanceResult result = new AddServiceInstanceResult(
               "AzureApiManagement",
               null);

            return result;
        }
        /// <summary>
        /// Called to add a new Connected Service to the project.
        /// </summary>
        public override async Task<AddServiceInstanceResult> AddServiceInstanceAsync(ConnectedServiceHandlerContext context, CancellationToken ct)
        {
            // See Handler samples for examples of how to work with the project system 
            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Handler Invoked to Add Project Artifacts");

            // Adds the 'ConnectedService.json' and 'Getting Started' artifacts to the project in the "SampleSinglePage" directory and opens the page
            // This would be your guidance on how a developer would complete development for the service
            // What Happened, and required Next Steps, and Sample code
            return new AddServiceInstanceResult(context.ServiceInstance.Name + " UpdateSupport", new Uri(Handler.GettingStartedUrl));
        }
 private void InstallNuGetPackages(ConnectedServiceHandlerContext context, Project project)
 {
     string feed = NuGetConstants.DefaultFeedUrl;
     
     NuGetInstaller.InstallPackage(
         feed,
         project,
         "simple.odata.client",
         "4.10.0",
         false
         );
 }
Exemplo n.º 14
0
        public override async Task<AddServiceInstanceResult> AddServiceInstanceAsync(ConnectedServiceHandlerContext context, CancellationToken ct)
        {
            Project project = ProjectHelper.GetProjectFromHierarchy(context.ProjectHierarchy);

            await this.AddAssemblyReferences(context);
            await this.AddNuGetPackagesAsync(context, project);
            await this.UpdateConfigAsync(context);
            await this.GenerateScaffolding(context);

            return new AddServiceInstanceResult(context.ServiceInstance.Name, 
                new Uri(Properties.Resources.GettingStartedURL));
        }
        public static async Task AddGeneratedCodeAsync(
            ConnectedServiceHandlerContext context,
            Project project,
            string templateFileName,
            string outputDirectory,
            Func<ITextTemplatingSessionHost, IEnumerable<ITextTemplatingSession>> getSessions,
            Func<IPreprocessedT4Template> getPreprocessedT4Template,
            Func<ITextTemplatingSession, string> getArtifactName)
        {
            string templatePath = Path.Combine(
                    RegistryHelper.GetCurrentUsersVisualStudioLocation(),
                    "Templates\\ConnectedServiceTemplates\\Visual C#\\Salesforce",
                    templateFileName + ".tt");
            bool useCustomTemplate = File.Exists(templatePath);

            SalesforceConnectedServiceInstance salesforceInstance = (SalesforceConnectedServiceInstance)context.ServiceInstance;
            salesforceInstance.TelemetryHelper.TrackCodeGeneratedEvent(salesforceInstance, templateFileName, useCustomTemplate);

            ITextTemplating textTemplating = GeneratedCodeHelper.TextTemplating;
            ITextTemplatingSessionHost sessionHost = (ITextTemplatingSessionHost)textTemplating;
            Func<ITextTemplatingSession, string> generateText;

            if (useCustomTemplate)
            {
                // The current user has a customized template, process and use it.
                string customTemplate = File.ReadAllText(templatePath);
                generateText = (session) =>
                {
                    sessionHost.Session = session;
                    return textTemplating.ProcessTemplate(templatePath, customTemplate);
                };
            }
            else
            {
                // No customized template exists for the current user, use the preprocessed one for increased performance.
                generateText = (session) =>
                {
                    IPreprocessedT4Template t4Template = getPreprocessedT4Template();
                    t4Template.Session = session;
                    t4Template.Initialize();
                    return t4Template.TransformText();
                };
            }

            foreach (ITextTemplatingSession session in getSessions(sessionHost))
            {
                string generatedText = generateText(session);
                string tempFileName = GeneratedCodeHelper.CreateTempFile(generatedText);
                string targetPath = Path.Combine(outputDirectory, getArtifactName(session) + ".cs");
                await context.HandlerHelper.AddFileAsync(tempFileName, targetPath);
            }
        }
        public override async Task<AddServiceInstanceResult> AddServiceInstanceAsync(ConnectedServiceHandlerContext context, CancellationToken ct)
        {
            // See Handler samples for examples of how to work with the project system 
            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Handler Invoked");

            Instance instance = (Instance)context.ServiceInstance;
            foreach (ObjectPickerObject obj in instance.SelectedObjects)
            {
                await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Handler doing something with the selected '{0}' object.", obj.Name);
            }

            return new AddServiceInstanceResult("SampleServiceObjectPicker", null);
        }
 /// <summary>
 /// Returns a suffix for the generated artifacts which guarantees that they don't conflict with any
 /// existing artifacts in the project.
 /// </summary>
 private static string GetGeneratedArtifactSuffix(ConnectedServiceHandlerContext context, Project project, AuthenticationStrategy authStrategy)
 {
     using (XmlConfigHelper configHelper = context.CreateReadOnlyXmlConfigHelper())
     {
         return(GeneralUtilities.GetUniqueSuffix(suffix =>
         {
             string serviceName = SalesforceConnectedServiceHandler.GetServiceInstanceName(suffix);
             return configHelper.IsPrefixUsedInAppSettings(serviceName) ||
             (authStrategy == AuthenticationStrategy.WebServerFlow &&
              configHelper.IsHandlerNameUsed(Constants.OAuthRedirectHandlerNameFormat.FormatInvariantCulture(serviceName))) ||
             SalesforceConnectedServiceHandler.IsSuffixUsedInGeneratedFilesDirectories(context, serviceName, project);
         }));
     }
 }
Exemplo n.º 18
0
        private async Task <Device> CreateNewDevice(ConnectedServiceHandlerContext context, RegistryManager registryManager, string deviceId)
        {
            try
            {
                var device = await registryManager.AddDeviceAsync(new Device(deviceId));

                return(device);
            }
            catch (Exception ex)
            {
                await context.Logger.WriteMessageAsync(LoggerMessageCategory.Warning, Resource.DeviceCreationFailure, deviceId);
            }
            return(null);
        }
Exemplo n.º 19
0
        internal async Task <string> ReGenerateCSharpFileAsync(ConnectedServiceHandlerContext context, Instance instance)
        {
            var serviceFolder = instance.Name;
            var rootFolder    = context.HandlerHelper.GetServiceArtifactsRootFolder();
            var folderPath    = context.ProjectHierarchy.GetProject().GetServiceFolderPath(rootFolder, serviceFolder);

            var nswagFilePath = Path.Combine(folderPath, $"{serviceFolder}.nswag");
            var document      = await NSwagDocument.LoadWithTransformationsAsync(nswagFilePath, instance.ServiceConfig.Variables);

            document.Runtime = instance.ServiceConfig.Runtime;
            await document.ExecuteAsync();

            return(document.SelectedSwaggerGenerator.OutputFilePath);
        }
 public BaseCodeGenDescriptor Create(Version edmxVersion, string metadataUri, ConnectedServiceHandlerContext context, Project project)
 {
     if (edmxVersion == Common.Constants.EdmxVersion1 ||
         edmxVersion == Common.Constants.EdmxVersion2 ||
         edmxVersion == Common.Constants.EdmxVersion3)
     {
         return(CreateV3CodeGenDescriptor(metadataUri, context, project));
     }
     else if (edmxVersion == Common.Constants.EdmxVersion4)
     {
         return(CreateV4CodeGenDescriptor(metadataUri, context, project));
     }
     throw new Exception(string.Format(CultureInfo.InvariantCulture, "Not supported Edmx Version {0}", edmxVersion.ToString()));
 }
Exemplo n.º 21
0
 private async Task AddNuGetPackagesAsync(ConnectedServiceHandlerContext context, Project project)
 {
     await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Adding Nuget Packages");
     if (!PackageInstallerServices.IsPackageInstalled(project, "Newtonsoft.Json"))
     {
         PackageInstaller.InstallPackagesFromVSExtensionRepository(
             "VSOnlineConnectedService.e30335d6-f9c7-4d08-b422-f011f3f18477",
             false,
             false,
             project,
             new Dictionary<string, string> {
             { "Newtonsoft.Json", "6.0.8" }
         });
     }
 }
        private async Task <BaseCodeGenDescriptor> SaveServiceInstanceAsync(ConnectedServiceHandlerContext context)
        {
            Project project         = ProjectHelper.GetProjectFromHierarchy(context.ProjectHierarchy);
            var     serviceInstance = (ODataConnectedServiceInstance)context.ServiceInstance;

            var codeGenDescriptor = await GenerateCodeAsync(serviceInstance.ServiceConfig.Endpoint, serviceInstance.ServiceConfig.EdmxVersion, context, project);

            // We don't save headers and proxy details to designer data
            serviceInstance.ServiceConfig.CustomHttpHeaders = null;
            serviceInstance.ServiceConfig.WebProxyNetworkCredentialsUsername = null;
            serviceInstance.ServiceConfig.WebProxyNetworkCredentialsPassword = null;

            context.SetExtendedDesignerData(serviceInstance.ServiceConfig);
            return(codeGenDescriptor);
        }
Exemplo n.º 23
0
        public override async Task<AddServiceInstanceResult> AddServiceInstanceAsync(ConnectedServiceHandlerContext context, CancellationToken ct)
        {
            Project project = ProjectHelper.GetProjectFromHierarchy(context.ProjectHierarchy);
            ODataConnectedServiceInstance codeGenInstance = (ODataConnectedServiceInstance)context.ServiceInstance;

            var codeGenDescriptor = await GenerateCode(codeGenInstance.MetadataTempFilePath, codeGenInstance.ServiceConfig.EdmxVersion, context, project);

            context.SetExtendedDesignerData<ServiceConfiguration>(codeGenInstance.ServiceConfig);

            var result = new AddServiceInstanceResult(
                context.ServiceInstance.Name,
                new Uri(codeGenDescriptor.ClientDocUri));

            return result;
        }
        public static async System.Threading.Tasks.Task GenerateCodeFromTemplateAndAddToProject(
            ConnectedServiceHandlerContext context,
            string templateFileName,
            string targetPath,
            IDictionary<string, object> parameters)
        {
            ITextTemplating t4 = TextTemplating;
            ITextTemplatingSessionHost sessionHost = (ITextTemplatingSessionHost)t4;
            sessionHost.Session = sessionHost.CreateSession();

            if (parameters != null)
                foreach (string key in parameters.Keys)
                    sessionHost.Session[key] = parameters[key];

            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information,
                "Opening the template '{0}'",
                templateFileName);

            //Stream templateStream = File.OpenRead(
            //    string.Format(@"Content\{0}.tt", templateFileName)
            //    );

            Stream templateStream = Assembly.GetAssembly(typeof(GeneratedCodeHelper))
                .GetManifestResourceStream(
                    string.Format("AspNet.WebHooks.ConnectedService.Content.{0}.tt", templateFileName)
                );

            if (templateStream == null)
            {
                throw new Exception("Could not find code generation template");
            }

            string templateContent = new StreamReader(templateStream).ReadToEnd();

            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information,
                "Generating code from template '{0}'",
                templateFileName);

            string generatedCode = t4.ProcessTemplate("", templateContent, new T4Callback(context));
            string tempFile = CreateTempFile(generatedCode);

            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information,
                "Adding code generated from template '{0}' as new file {1}",
                templateFileName,
                targetPath);

            await context.HandlerHelper.AddFileAsync(tempFile, targetPath);
        }
Exemplo n.º 25
0
        private async Task GenerateScaffolding(ConnectedServiceHandlerContext context)
        {
            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Scaffolding Code");

            Instance tfsContext = (Instance)context.ServiceInstance;

            string templateResourceUri = null;

            switch (tfsContext.RuntimeAuthOption)
            {
            case RuntimeAuthOptions.IntegratedAuth:
                templateResourceUri = "pack://application:,,/" + this.GetType().Assembly.ToString() + ";component/Templates/IntegratedAuthTemplate.cs";
                break;

            case RuntimeAuthOptions.BasicAuth:
                templateResourceUri = "pack://application:,,/" + this.GetType().Assembly.ToString() + ";component/Templates/BasicAuthTemplate.cs";
                break;

            case RuntimeAuthOptions.UsernamePasswordServiceAuth:
                templateResourceUri = "pack://application:,,/" + this.GetType().Assembly.ToString() + ";component/Templates/ServiceAuthTemplate.cs";
                context.HandlerHelper.TokenReplacementValues.Add("Instance:Username", tfsContext.Name + CONFIGKEY_USERNAME);
                context.HandlerHelper.TokenReplacementValues.Add("Instance:Password", tfsContext.Name + CONFIGKEY_PASSWORD);
                break;

            default:
                throw new InvalidOperationException("Unsupported runtime authentication option:" + tfsContext.RuntimeAuthOption);
            }

            // Generate a code file into the user's project from a template.
            // The tokens in the template will be replaced by the HandlerHelper.
            // Place service specific scaffolded code under the service folder
            context.HandlerHelper.TokenReplacementValues.Add("Instance:Endpoint", tfsContext.Name + CONFIGKEY_TFSURI);
            context.HandlerHelper.TokenReplacementValues.Add("Instance:TeamProjectName", tfsContext.Name + CONFIGKEY_TEAMPROJECTNAME);
            context.HandlerHelper.TokenReplacementValues.Add("Instance:TeamProjectCollectionName", tfsContext.Name + CONFIGKEY_TEAMPROJECTCOLLECTIONNAME);

            string serviceFolder = string.Format("Service References\\{0}\\", tfsContext.Name);

            await context.HandlerHelper.AddFileAsync(templateResourceUri,
                                                     Path.Combine(context.HandlerHelper.GetServiceArtifactsRootFolder(),
                                                                  context.ServiceInstance.Name,
                                                                  "VSOnlineService.cs"));

            templateResourceUri = "pack://application:,,/" + this.GetType().Assembly.ToString() + ";component/Templates/WorkItem.cs";
            await context.HandlerHelper.AddFileAsync(templateResourceUri,
                                                     Path.Combine("Models",
                                                                  context.ServiceInstance.Name,
                                                                  "WorkItem.cs"));
        }
Exemplo n.º 26
0
        private async Task AddNuGetPackagesAsync(ConnectedServiceHandlerContext context, Project project)
        {
            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Adding Nuget Packages");

            if (!PackageInstallerServices.IsPackageInstalled(project, "Newtonsoft.Json"))
            {
                PackageInstaller.InstallPackagesFromVSExtensionRepository(
                    "VSOnlineConnectedService.e30335d6-f9c7-4d08-b422-f011f3f18477",
                    false,
                    false,
                    project,
                    new Dictionary <string, string> {
                    { "Newtonsoft.Json", "6.0.8" }
                });
            }
        }
Exemplo n.º 27
0
        private async Task <string> GenerateCSharpFileAsync(ConnectedServiceHandlerContext context, Instance instance)
        {
            var serviceFolder = instance.Name;
            var rootFolder    = context.HandlerHelper.GetServiceArtifactsRootFolder();
            var folderPath    = context.ProjectHierarchy.GetProject().GetServiceFolderPath(rootFolder, serviceFolder);

            var nswagFilePath = Path.Combine(folderPath, $"{serviceFolder}.nswag");
            var document      = await NSwagDocument.LoadAsync(nswagFilePath);

            await document.ExecuteAsync();

            var generatedFilePath = document.CodeGenerators.SwaggerToCSharpClientCommand.OutputFilePath;
            var generatedFullPath = Path.Combine(folderPath, generatedFilePath);
            await context.HandlerHelper.AddFileAsync(generatedFullPath, generatedFilePath);

            return(generatedFilePath);
        }
Exemplo n.º 28
0
        private async Task GenerateClientCodeWithoutDataSvcUtil(ConnectedServiceHandlerContext context, Project project)
        {
            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Generating Client Proxy ...");

            ODataConnectedServiceInstance codeGenInstance = (ODataConnectedServiceInstance)context.ServiceInstance;
            var address = codeGenInstance.Endpoint;

            if (address.StartsWith("https:") || address.StartsWith("http"))
            {
                if (!address.EndsWith("$metadata"))
                {
                    address = address.TrimEnd('/') + "/$metadata";
                }
            }

            EntityClassGenerator generator = new EntityClassGenerator(LanguageOption.GenerateCSharpCode);

            generator.UseDataServiceCollection = codeGenInstance.UseDataServiceCollection;
            generator.Version = DataServiceCodeVersion.V3;

            var referenceFolderPath = await CheckAndAddReferenceFolder(context, project);

            string outputFile = Path.Combine(referenceFolderPath, "Reference.cs");

            XmlReaderSettings settings = new XmlReaderSettings();

            if (!String.IsNullOrEmpty(address))
            {
                XmlResolver resolver = new XmlUrlResolver();
                {
                    resolver.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
                }

                settings.XmlResolver = resolver;
            }

            using (XmlReader reader = XmlReader.Create(address, settings))
            {
                using (StreamWriter writer = File.CreateText(outputFile))
                {
                    var error = generator.GenerateCode(reader, writer, codeGenInstance.NamespacePrefix);
                }
            }
            await context.HandlerHelper.AddFileAsync(outputFile, outputFile);
        }
        public override async Task<UpdateServiceInstanceResult> UpdateServiceInstanceAsync(ConnectedServiceHandlerContext context, CancellationToken ct)
        {
            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, Resources.LogMessage_UpdatingConnectedService);

            SalesforceConnectedServiceInstance salesforceInstance = (SalesforceConnectedServiceInstance)context.ServiceInstance;

            try
            {
                Project project = ProjectHelper.GetProjectFromHierarchy(context.ProjectHierarchy);

                await TaskScheduler.Default; // Switch to a worker thread to avoid blocking the UI thread (e.g. the progress dialog).

                // Update currently only supports adding additional scaffolded objects.  Before they are added, ensure the correct NuGets are
                // installed.  Additionally, ensure the required assemblies exist as not all are added initially if no objects are scaffolded.
                await this.AddNuGetPackagesAsync(context, project);
                await SalesforceConnectedServiceHandler.AddAssemblyReferencesAsync(context, salesforceInstance);

                try
                {
                    await SalesforceConnectedServiceHandler.AddGeneratedCodeAsync(context, project, salesforceInstance);
                }
                catch (COMException comException)
                {
                    if (comException.HResult == -2147467259)
                    {
                        // Provide a better exception message for when an invalid path ModelsHintPath was specified.
                        throw new InvalidOperationException(
                            Resources.LogMessage_InvalidModelsHintPath.FormatCurrentCulture(salesforceInstance.DesignerData.ModelsHintPath),
                            comException);
                    }
                }

                salesforceInstance.DesignerData.StoreExtendedDesignerData(context);

                salesforceInstance.TelemetryHelper.TrackUpdateServiceSucceededEvent(salesforceInstance);
                await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, Resources.LogMessage_UpdatedConnectedService);

                return new UpdateServiceInstanceResult();
            }
            catch (Exception e)
            {
                salesforceInstance.TelemetryHelper.TrackUpdateServiceFailedEvent(salesforceInstance, e);
                throw;
            }
        }
        public override async Task<UpdateServiceInstanceResult> UpdateServiceInstanceAsync(ConnectedServiceHandlerContext context, CancellationToken ct)
        {
            Project project = ProjectHelper.GetProjectFromHierarchy(context.ProjectHierarchy);
            ODataConnectedServiceInstance codeGenInstance = (ODataConnectedServiceInstance)context.ServiceInstance;

            if (codeGenInstance.GenByDataSvcUtil)
            {
                await this.AddNuGetPackagesAsync(context, project, new Version(3, 0));
                await this.GenerateClientCode(context, project);
            }
            else
            {
                await this.AddNuGetPackagesAsync(context, project, new Version(3, 0));
                await this.GenerateClientCodeWithoutDataSvcUtil(context, project);
            }

            UpdateServiceInstanceResult result = new UpdateServiceInstanceResult();
            return result;
        }
Exemplo n.º 31
0
        internal async Task <bool> GenerateCodeAsync(ConnectedServiceHandlerContext context, Instance instance)
        {
            var result             = false;
            var serviceFolder      = instance.Name;
            var clientTempFileName = Path.GetTempFileName();

            try
            {
                var rootFolder     = context.HandlerHelper.GetServiceArtifactsRootFolder();
                var folderPath     = context.ProjectHierarchy.GetProject().GetServiceFolderPath(rootFolder, serviceFolder);
                var generationUtil = new CrmSvcUtil(this);
                result = await generationUtil.StartGenerationAsync(GetArguments(instance.ServiceConfig, clientTempFileName));

                if (!result)
                {
                    await this.Context.Logger.WriteMessageAsync(LoggerMessageCategory.Error, $"Internal error occured. See upper.");
                }
                else
                {
                    await this.Context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, $"Copying generated file to project...");

                    await context.HandlerHelper.AddFileAsync(clientTempFileName,
                                                             Path.Combine(folderPath,
                                                                          $"{instance.ServiceConfig.GeneratedFileNamePrefix}Generated.{instance.ServiceConfig.LanguageOption.ToLower()}"),
                                                             new AddFileOptions { OpenOnComplete = instance.ServiceConfig.OpenGeneratedFilesOnComplete });

                    await this.Context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, $"Generated file was copied.");
                }
            }
            catch (Exception ex)
            {
                await this.Context.Logger.WriteMessageAsync(LoggerMessageCategory.Warning, $"Error: {ex.Message}.");
            }
            finally
            {
                if (File.Exists(clientTempFileName))
                {
                    File.Delete(clientTempFileName);
                }
            }
            return(result);
        }
        private async Task <string> GenerateCSharpFileAsync(ConnectedServiceHandlerContext context, Instance instance)
        {
            var    serviceFolder = instance.Name;
            string jsonPath      = instance.JSONPath;

            var rootFolder = context.HandlerHelper.GetServiceArtifactsRootFolder();
            var folderPath = context.ProjectHierarchy.GetProject().GetServiceFolderPath(rootFolder);

            var text      = File.ReadAllText(jsonPath);
            var schema    = NJsonSchema.JsonSchema.FromSampleJson(text);
            var generator = new CSharpGenerator(schema);
            var result    = await System.Threading.Tasks.Task.FromResult(generator.GenerateFile());

            var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(jsonPath);
            var fileName          = $"{fileNameWithoutExtension}.cs";
            var generatedFullPath = Path.Combine(folderPath, fileName);
            await context.HandlerHelper.AddFileAsync(generatedFullPath, fileName);

            return(generatedFullPath);
        }
        private async Task AddNuGetPackagesAsync(ConnectedServiceHandlerContext context, Project project)
        {
            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, Resources.LogMessage_AddingNuGetPackages);

            // DeveloperForce.Force is the only NuGet package the experience has a direct dependency on, the rest are dependencies of it.
            // If the DeveloperForce.Force version is changed, the versions of its dependencies must also be updated as appropriate.
            this.PackageInstaller.InstallPackagesFromVSExtensionRepository(
                "Salesforce.VisualStudio.Services.55451A07-E6E0-47CC-855D-8A25B0B59409",
                false,
                false,
                project,
                new Dictionary <string, string> {
                { "DeveloperForce.Force", "1.0.0" },
                { "Microsoft.Bcl", "1.1.10" },
                { "Microsoft.Bcl.Async", "1.0.168" },
                { "Microsoft.Bcl.Build", "1.0.21" },
                { "Microsoft.Net.Http", "2.2.29" },
                { "Newtonsoft.Json", "6.0.5" },
            });
        }
Exemplo n.º 34
0
        private async Task <BaseCodeGenDescriptor> SaveServiceInstanceAsync(ConnectedServiceHandlerContext context)
        {
            Project project         = ProjectHelper.GetProjectFromHierarchy(context.ProjectHierarchy);
            var     serviceInstance = (ODataConnectedServiceInstance)context.ServiceInstance;

            var codeGenDescriptor = await GenerateCodeAsync(serviceInstance.ServiceConfig.Endpoint, serviceInstance.ServiceConfig.EdmxVersion, context, project).ConfigureAwait(false);

            if (!serviceInstance.ServiceConfig.StoreCustomHttpHeaders)
            {
                serviceInstance.ServiceConfig.CustomHttpHeaders = null;
            }
            if (!serviceInstance.ServiceConfig.StoreWebProxyNetworkCredentials)
            {
                serviceInstance.ServiceConfig.WebProxyNetworkCredentialsUsername = null;
                serviceInstance.ServiceConfig.WebProxyNetworkCredentialsPassword = null;
                serviceInstance.ServiceConfig.WebProxyNetworkCredentialsDomain   = null;
            }

            context.SetExtendedDesignerData(serviceInstance.ServiceConfig);
            return(codeGenDescriptor);
        }
Exemplo n.º 35
0
        private static async Task UpdateConfigFileAsync(ConnectedServiceHandlerContext context)
        {
            // Push an update to the progress notifications
            // Introduce Resources as the means to manage strings shown to users, which may get localized
            // Or, at least verified by someone that should be viewing strings, not buried in the code
            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Adding settings to the project's config file.");

            // Now that we're passing more elaborate values between the provider and the handler
            // We'll start using a specific Instance so we can get stronger type verification
            Instance instance = (Instance)context.ServiceInstance;

            // Launch the EditableConfigHelper to write several entries to the Config file
            using (EditableXmlConfigHelper configHelper = context.CreateEditableXmlConfigHelper())
            {
                // We ahve the option to write name/value pairs
                configHelper.SetAppSetting("ConsumerKey",
                                           instance.ConfigOptions.ConsumerKey,
                                           "Heading on the first entry to identify the block of settings");
                configHelper.SetAppSetting("ConsumerSecret",
                                           instance.ConfigOptions.ConsumerSecret,
                                           "Second Comment");
                configHelper.SetAppSetting("RedirectUrl",
                                           instance.ConfigOptions.RedirectUrl);
                // no comment on the third

                // Write the values to disk
                configHelper.Save();
            }

            // Some updates to the progress dialog
            Thread.Sleep(1000);
            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Doing Something Else");

            Thread.Sleep(1000);
            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Another Entry to show progress");

            Thread.Sleep(1000);
        }
Exemplo n.º 36
0
        private async Task GenerateClientCode(ConnectedServiceHandlerContext context, Project project)
        {
            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Generating Client Proxy ...");

            ODataConnectedServiceInstance codeGenInstance = (ODataConnectedServiceInstance)context.ServiceInstance;

            string command = Path.Combine(CodeGeneratorUtils.GetWCFDSInstallLocation(), @"bin\tools\DataSvcUtil.exe");

            string referenceFolderPath = GetReferenceFolderName(context, project);
            string outputFile          = Path.Combine(referenceFolderPath, "Reference.cs");

            StringBuilder arguments = new StringBuilder(string.Format("/c \"\"{0}\" /version:3.0 /language:{1} /out:\"{2}\" /uri:{3}", command, "CSharp", outputFile, codeGenInstance.Endpoint));

            if (codeGenInstance.UseDataServiceCollection)
            {
                arguments.Append("/dataServiceCollection");
            }

            arguments.Append("\"");

            ProcessHelper.ExecuteCommand(command, arguments.ToString());
            await context.HandlerHelper.AddFileAsync(outputFile, outputFile);
        }
Exemplo n.º 37
0
        private async Task<BaseCodeGenDescriptor> GenerateCode(string metadataUri, Version edmxVersion, ConnectedServiceHandlerContext context, Project project)
        {
            BaseCodeGenDescriptor codeGenDescriptor;

            if (edmxVersion == Common.Constants.EdmxVersion1
                || edmxVersion == Common.Constants.EdmxVersion2
                || edmxVersion == Common.Constants.EdmxVersion3)
            {
                codeGenDescriptor = new V3CodeGenDescriptor(metadataUri, context, project);
            }
            else if (edmxVersion == Common.Constants.EdmxVersion4)
            {
                codeGenDescriptor = new V4CodeGenDescriptor(metadataUri, context, project);
            }
            else
            {
                throw new Exception(string.Format("Not supported Edmx Version {0}", edmxVersion.ToString()));
            }

            await codeGenDescriptor.AddNugetPackages();
            await codeGenDescriptor.AddGeneratedClientCode();
            return codeGenDescriptor;
        }
Exemplo n.º 38
0
        private async Task UpdateConfigAsync(ConnectedServiceHandlerContext context)
        {
            
            await Shell.ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); // The EditableConfigHelper must run on the UI thread.
            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Adding Config values");
            Instance instance = (Instance)context.ServiceInstance;

            using (EditableXmlConfigHelper configHelper = context.CreateEditableXmlConfigHelper())
            {
                configHelper.SetAppSetting(instance.Name + CONFIGKEY_TFSURI, instance.VSOnlineUri, comment:"VSOnline");
                configHelper.SetAppSetting(instance.Name + CONFIGKEY_TEAMPROJECTNAME, instance.TeamProjectName);
                configHelper.SetAppSetting(instance.Name + CONFIGKEY_TEAMPROJECTCOLLECTIONNAME, instance.TeamProjectCollectionName);
                if (instance.RuntimeAuthOption == RuntimeAuthOptions.UsernamePasswordServiceAuth)
                {
                    if (!configHelper.IsPrefixUsedInAppSettings(instance.Name + CONFIGKEY_USERNAME))
                    {
                        configHelper.SetAppSetting(instance.Name + CONFIGKEY_USERNAME, "RequiredValue");
                        configHelper.SetAppSetting(instance.Name + CONFIGKEY_PASSWORD, "RequiredValue");
                    }
                }
                configHelper.Save();
            }
        }
Exemplo n.º 39
0
        private async Task UpdateConfigAsync(ConnectedServiceHandlerContext context)
        {
            await Shell.ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); // The EditableConfigHelper must run on the UI thread.

            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Adding Config values");

            Instance instance = (Instance)context.ServiceInstance;

            using (EditableXmlConfigHelper configHelper = context.CreateEditableXmlConfigHelper())
            {
                configHelper.SetAppSetting(instance.Name + CONFIGKEY_TFSURI, instance.VSOnlineUri, comment: "VSOnline");
                configHelper.SetAppSetting(instance.Name + CONFIGKEY_TEAMPROJECTNAME, instance.TeamProjectName);
                configHelper.SetAppSetting(instance.Name + CONFIGKEY_TEAMPROJECTCOLLECTIONNAME, instance.TeamProjectCollectionName);
                if (instance.RuntimeAuthOption == RuntimeAuthOptions.UsernamePasswordServiceAuth)
                {
                    if (!configHelper.IsPrefixUsedInAppSettings(instance.Name + CONFIGKEY_USERNAME))
                    {
                        configHelper.SetAppSetting(instance.Name + CONFIGKEY_USERNAME, "RequiredValue");
                        configHelper.SetAppSetting(instance.Name + CONFIGKEY_PASSWORD, "RequiredValue");
                    }
                }
                configHelper.Save();
            }
        }
        public async override Task<AddServiceInstanceResult> AddServiceInstanceAsync(ConnectedServiceHandlerContext context, CancellationToken ct)
        {
            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Updating Config");
            using (EditableXmlConfigHelper configHelper = context.CreateEditableXmlConfigHelper())
            {
                configHelper.SetAppSetting(
                    string.Format("{0}:ConnectionString", context.ServiceInstance.Name),
                    "SomeServiceConnectionString",
                    context.ServiceInstance.Name
                    );
                configHelper.Save();
            }
            Thread.Sleep(1000);
            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Adding NuGets");
            Thread.Sleep(1000);
            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Adding References");
            Thread.Sleep(1000);

            AddServiceInstanceResult result = new AddServiceInstanceResult(
                    context.ServiceInstance.Name,
                    new Uri("https://github.com/Microsoft/ConnectedServices-ProviderAuthorSamples"));

            return result;
        }
        public override async Task <UpdateServiceInstanceResult> UpdateServiceInstanceAsync(ConnectedServiceHandlerContext context, CancellationToken ct)
        {
            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Updating service instance...");

            var codeGenInstance = (Instance)context.ServiceInstance;

            var codeGenDescriptor = await GenerateCodeAsync(codeGenInstance.ServiceConfig.EdmxVersion, context);

            codeGenInstance.ServiceConfig.FunctionImports  = null;
            codeGenInstance.ServiceConfig.OperationImports = null;

            context.SetExtendedDesignerData(codeGenInstance.ServiceConfig);

            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Updating service instance complete.");

            return(new UpdateServiceInstanceResult {
                GettingStartedDocument = new GettingStartedDocument(new Uri(codeGenDescriptor.ClientDocUri))
            });
        }
Exemplo n.º 42
0
 protected virtual BaseCodeGenDescriptor CreateV4CodeGenDescriptor(string metadataUri, ConnectedServiceHandlerContext context, Project project)
 {
     return(new V4CodeGenDescriptor(metadataUri, context, project, new ODataT4CodeGeneratorFactory()));
 }
 protected override ConnectedServiceHandlerHelper GetConnectedServiceHandlerHelper(ConnectedServiceHandlerContext context)
 {
     return new AzureIoTHubConnectedServiceHandlerHelper(context);
 }
Exemplo n.º 44
0
        public override async Task <AddServiceInstanceResult> AddServiceInstanceAsync(ConnectedServiceHandlerContext context, CancellationToken ct)
        {
            // See Handler Samples for how to work with the project system
            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Handler Invoked");

            await UpdateConfigFileAsync(context);

            return(new AddServiceInstanceResult("SampleServiceXmlConfigManagement", null));
        }
        public override async Task <UpdateServiceInstanceResult> UpdateServiceInstanceAsync(ConnectedServiceHandlerContext context, CancellationToken ct)
        {
            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Updating service instance...");

            var project         = ProjectHelper.GetProjectFromHierarchy(context.ProjectHierarchy);
            var codeGenInstance = (Instance)context.ServiceInstance;

            var codeGenDescriptor = await GenerateCode(codeGenInstance.ServiceConfig.Endpoint, codeGenInstance.ServiceConfig.EdmxVersion, context);

            context.SetExtendedDesignerData <ServiceConfiguration>(codeGenInstance.ServiceConfig);

            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Updating service instance complete.");

            return(new UpdateServiceInstanceResult {
                GettingStartedDocument = new GettingStartedDocument(new Uri(codeGenDescriptor.ClientDocUri))
            });
        }
Exemplo n.º 46
0
 public TestV3CodeGenDescriptor(string metadataUri, ConnectedServiceHandlerContext context, Project project) : base(metadataUri, context, project)
 {
 }
 protected override ConnectedServiceHandlerHelper GetConnectedServiceHandlerHelper(ConnectedServiceHandlerContext context)
 {
     return context.HandlerHelper;
 }
Exemplo n.º 48
0
        public override async Task <AddServiceInstanceResult> AddServiceInstanceAsync(ConnectedServiceHandlerContext context, CancellationToken ct)
        {
            SalesforceConnectedServiceInstance salesforceInstance = (SalesforceConnectedServiceInstance)context.ServiceInstance;

            try
            {
                Project project = ProjectHelper.GetProjectFromHierarchy(context.ProjectHierarchy);
                string  generatedArtifactSuffix = SalesforceConnectedServiceHandler.GetGeneratedArtifactSuffix(
                    context, project, salesforceInstance.RuntimeAuthentication.AuthStrategy);
                salesforceInstance.DesignerData.ServiceName = SalesforceConnectedServiceHandler.GetServiceInstanceName(generatedArtifactSuffix);

                await TaskScheduler.Default; // Switch to a worker thread to avoid blocking the UI thread (e.g. the progress dialog).

                await SalesforceConnectedServiceHandler.CreateConnectedAppAsync(context, project, salesforceInstance);

                await SalesforceConnectedServiceHandler.UpdateConfigFileAsync(context, project, salesforceInstance);

                await this.AddNuGetPackagesAsync(context, project);

                await SalesforceConnectedServiceHandler.AddAssemblyReferencesAsync(context, salesforceInstance);

                await SalesforceConnectedServiceHandler.AddGeneratedCodeAsync(context, project, salesforceInstance);

                salesforceInstance.DesignerData.StoreExtendedDesignerData(context);

                salesforceInstance.TelemetryHelper.TrackAddServiceSucceededEvent(salesforceInstance);

                return(new AddServiceInstanceResult(
                           salesforceInstance.DesignerData.ServiceName,
                           new Uri(Constants.NextStepsUrl)));
            }
            catch (Exception e)
            {
                salesforceInstance.TelemetryHelper.TrackAddServiceFailedEvent(salesforceInstance, e);
                throw;
            }
        }
        private Task<string> CheckAndAddReferenceFolder(ConnectedServiceHandlerContext context, Project project)
        {
            ODataConnectedServiceInstance codeGenInstance = (ODataConnectedServiceInstance)context.ServiceInstance;
            var serviceReferenceFolderName = context.HandlerHelper.GetServiceArtifactsRootFolder();

            ProjectItem serviceReferenceFolder;
            ProjectItem namespaceFolder;
            project.ProjectItems.TryGetFolder(serviceReferenceFolderName, out serviceReferenceFolder);

            if (codeGenInstance.NamespacePrefix != null)
            {
                if (!serviceReferenceFolder.ProjectItems.TryGetFolder(codeGenInstance.NamespacePrefix, out namespaceFolder))
                {
                    serviceReferenceFolder.ProjectItems.AddFolder(codeGenInstance.NamespacePrefix);
                }
            }

            var referenceFolderPath = Path.Combine(
                ProjectHelper.GetProjectFullPath(project),
                serviceReferenceFolderName,
                codeGenInstance.NamespacePrefix ?? "");

            return Task.FromResult<string>(referenceFolderPath);
        }
Exemplo n.º 50
0
 internal static IEdmModel GetODataEdmModel(this ServiceConfigurationV4 serviceConfiguration, ConnectedServiceHandlerContext context = null)
 {
     using (var reader = serviceConfiguration.GetXmlReaderForEndpoint())
     {
         var edmxReaderSettings = new CsdlReaderSettings
         {
             IgnoreUnexpectedAttributesAndElements = serviceConfiguration.IgnoreUnexpectedElementsAndAttributes
         };
         if (!CsdlReader.TryParse(reader, Enumerable.Empty <IEdmModel>(), edmxReaderSettings, out var model, out var parseErrors))
         {
             if (context != null)
             {
                 foreach (var error in parseErrors)
                 {
                     var task = context.Logger.WriteMessageAsync(LoggerMessageCategory.Warning,
                                                                 error.ErrorMessage);
                     task.RunSynchronously();
                 }
             }
         }
Exemplo n.º 51
0
        public override async Task <UpdateServiceInstanceResult> UpdateServiceInstanceAsync(ConnectedServiceHandlerContext context, CancellationToken ct)
        {
            SalesforceConnectedServiceInstance salesforceInstance = (SalesforceConnectedServiceInstance)context.ServiceInstance;

            try
            {
                Project project = ProjectHelper.GetProjectFromHierarchy(context.ProjectHierarchy);

                await TaskScheduler.Default; // Switch to a worker thread to avoid blocking the UI thread (e.g. the progress dialog).

                // Update currently only supports adding additional scaffolded objects.  Before they are added, ensure the correct NuGets are
                // installed.  Additionally, ensure the required assemblies exist as not all are added initially if no objects are scaffolded.
                await this.AddNuGetPackagesAsync(context, project);

                await SalesforceConnectedServiceHandler.AddAssemblyReferencesAsync(context, salesforceInstance);

                try
                {
                    await SalesforceConnectedServiceHandler.AddGeneratedCodeAsync(context, project, salesforceInstance);
                }
                catch (COMException comException)
                {
                    if (comException.HResult == -2147467259)
                    {
                        // Provide a better exception message for when an invalid path ModelsHintPath was specified.
                        throw new InvalidOperationException(
                                  Resources.LogMessage_InvalidModelsHintPath.FormatCurrentCulture(salesforceInstance.DesignerData.ModelsHintPath),
                                  comException);
                    }
                }

                salesforceInstance.DesignerData.StoreExtendedDesignerData(context);

                salesforceInstance.TelemetryHelper.TrackUpdateServiceSucceededEvent(salesforceInstance);

                return(new UpdateServiceInstanceResult());
            }
            catch (Exception e)
            {
                salesforceInstance.TelemetryHelper.TrackUpdateServiceFailedEvent(salesforceInstance, e);
                throw;
            }
        }
Exemplo n.º 52
0
 public V3CodeGenDescriptor(string metadataUri, ConnectedServiceHandlerContext context, Project project)
     : base(metadataUri, context, project)
 {
     this.ClientNuGetPackageName = Common.Constants.V3ClientNuGetPackage;
     this.ClientDocUri           = Common.Constants.V3DocUri;
 }
Exemplo n.º 53
0
 public TestV4CodeGenDescriptor(string metadataUri, ConnectedServiceHandlerContext context, Project project, IODataT4CodeGeneratorFactory codeGenFactory)
     : base(metadataUri, context, project, codeGenFactory)
 {
 }
 /// <summary>
 /// Called to add a new Connected Service to the project.
 /// </summary>
 public override Task<AddServiceInstanceResult> AddServiceInstanceAsync(ConnectedServiceHandlerContext context, CancellationToken ct)
 {
     return Task.FromResult(new AddServiceInstanceResult(context.ServiceInstance.Name, new Uri(Handler.GettingStartedUrl)));
 }
        public override async Task <AddServiceInstanceResult> AddServiceInstanceAsync(ConnectedServiceHandlerContext context, CancellationToken ct)
        {
            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Adding service instance...");

            var project         = ProjectHelper.GetProjectFromHierarchy(context.ProjectHierarchy);
            var codeGenInstance = (Instance)context.ServiceInstance;

            var codeGenDescriptor = await GenerateCode(codeGenInstance.MetadataTempFilePath, codeGenInstance.ServiceConfig.EdmxVersion, context);

            context.SetExtendedDesignerData <ServiceConfiguration>(codeGenInstance.ServiceConfig);

            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Adding service instance complete!");

            return(new AddServiceInstanceResult(context.ServiceInstance.Name, new Uri(codeGenDescriptor.ClientDocUri)));
        }
 public T4Callback(ConnectedServiceHandlerContext context)
 {
     _context = context;
 }
        private static async Task <BaseCodeGenDescriptor> GenerateCode(string metadataUri, Version edmxVersion, ConnectedServiceHandlerContext context)
        {
            var instance = (Instance)context.ServiceInstance;
            BaseCodeGenDescriptor codeGenDescriptor;

            if (edmxVersion == Common.Constants.EdmxVersion1 ||
                edmxVersion == Common.Constants.EdmxVersion2 ||
                edmxVersion == Common.Constants.EdmxVersion3)
            {
                codeGenDescriptor = new V3CodeGenDescriptor(context, instance);
            }
            else if (edmxVersion == Common.Constants.EdmxVersion4)
            {
                codeGenDescriptor = new V4CodeGenDescriptor(context, instance);
            }
            else
            {
                throw new Exception(string.Format(CultureInfo.InvariantCulture, "Not supported Edmx Version{0}", (edmxVersion != null ? $" {edmxVersion}." : ". Try with Endpoint ends \"/$metadata\".")));
            }

            var codeGenInstance = (Instance)context.ServiceInstance;

            codeGenDescriptor.UseNetworkCredentials      = codeGenInstance.ServiceConfig.UseNetworkCredentials;
            codeGenDescriptor.NetworkCredentialsUserName = codeGenInstance.ServiceConfig.NetworkCredentialsUserName;
            codeGenDescriptor.NetworkCredentialsPassword = codeGenInstance.ServiceConfig.NetworkCredentialsPassword;
            codeGenDescriptor.NetworkCredentialsDomain   = codeGenInstance.ServiceConfig.NetworkCredentialsDomain;

            codeGenDescriptor.UseWebProxy                        = codeGenInstance.ServiceConfig.UseWebProxy;
            codeGenDescriptor.UseWebProxyCredentials             = codeGenInstance.ServiceConfig.UseWebProxyCredentials;
            codeGenDescriptor.WebProxyNetworkCredentialsUserName = codeGenInstance.ServiceConfig.WebProxyNetworkCredentialsUserName;
            codeGenDescriptor.WebProxyNetworkCredentialsPassword = codeGenInstance.ServiceConfig.WebProxyNetworkCredentialsPassword;
            codeGenDescriptor.WebProxyNetworkCredentialsDomain   = codeGenInstance.ServiceConfig.WebProxyNetworkCredentialsDomain;
            codeGenDescriptor.WebProxyUri                        = codeGenInstance.ServiceConfig.WebProxyUri;

            await codeGenDescriptor.AddNugetPackages();

            await codeGenDescriptor.AddGeneratedClientCode();

            return(codeGenDescriptor);
        }
Exemplo n.º 58
0
 protected virtual BaseCodeGenDescriptor CreateV3CodeGenDescriptor(string metadataUri, ConnectedServiceHandlerContext context, Project project)
 {
     return(new V3CodeGenDescriptor(metadataUri, context, project));
 }
Exemplo n.º 59
0
 private static string GetServiceDirectoryName(ConnectedServiceHandlerContext context, string serviceName)
 {
     return(Path.Combine(
                context.HandlerHelper.GetServiceArtifactsRootFolder(),
                serviceName));
 }
        public async override Task<AddServiceInstanceResult> AddServiceInstanceAsync(ConnectedServiceHandlerContext context,
            CancellationToken ct)
        {
            AddServiceInstanceResult result = new AddServiceInstanceResult(
                Resources.ConnectedServiceProjectFolderName,
                new Uri(Resources.MoreInfoUrl));

            Project = ProjectHelper.GetProjectFromHierarchy(context.ProjectHierarchy);
            string projectNamespace = Project.Properties.Item("DefaultNamespace").Value.ToString();

            // get the collection of keys to be added
            var receiverSecrets = context.ServiceInstance.Metadata[Constants.MetadataKeyForStoringReceiverSecrets]
                as IEnumerable<WebHookReceiverSecret>;

            // install all of the base WebHook NuGets
            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information,
                Resources.LogMessageGettingCoreNuGets);

            InstallPackage("Microsoft.AspNet.WebApi.WebHost", "5.2.3");
            InstallPackage("Microsoft.AspNet.WebHooks.Common", "1.2.0-beta3");
            InstallPackage("Microsoft.AspNet.WebHooks.Receivers", "1.2.0-beta3");

            // remember the list of providers selected
            List<string> providers = new List<string>();

            using (EditableXmlConfigHelper configHelper = context.CreateEditableXmlConfigHelper())
            {
                // iterate over the selected hook receivers
                foreach (var item in receiverSecrets)
                {
                    // add the keys in the web.config for each provider
                    configHelper.SetAppSetting(item.ReceiverSecretConfigSettingName, item.Secret);

                    // pull in the NuGet for the receiver
                    await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information,
                        string.Format(Resources.LogMessageGettingReceiver, item.Option.Name));

                    InstallPackage(item.Option.NuGetPackage, item.Option.NuGetVersion);

                    // add the handler code to the project
                    await GeneratedCodeHelper
                        .GenerateCodeFromTemplateAndAddToProject(
                            context,
                            "WebHookHandler",
                            string.Format($@"WebHookHandlers\{item.Option.Name}WebHookHandler.cs"),
                            new Dictionary<string, object>
                            {
                                {"ns", projectNamespace},
                                {"receiverName", item.Option.Name}
                            });

                    // remember this provider
                    providers.Add(item.Option.Name);

                    // record the telemetry for the receiver
                    TelemetryWrapper.RecordEvent("Receiver Selected",
                        properties: new Dictionary<string, string>()
                        {
                            {"Name", item.Option.Name}
                        });
                }

                // add the code to the project to configure all of the providers
                await GeneratedCodeHelper
                    .GenerateCodeFromTemplateAndAddToProject(
                        context,
                        "WebHookConfig",
                        string.Format($@"App_Start\WebHookConfig.cs"),
                        new Dictionary<string, object>
                        {
                            {"ns", projectNamespace},
                            {"providers", providers.ToArray() }
                        });

                // persist the configuration changes
                configHelper.Save();
            }

            // record that we finished
            TelemetryWrapper.RecordEvent("WebHook Experience Completed");

            // return
            return result;
        }