Esempio n. 1
0
        private static async Task UpdateConfigFileAsync(ConnectedServiceHandlerContext context, Project project, SalesforceConnectedServiceInstance salesforceInstance)
        {
            await Shell.ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); // The EditableConfigHelper must run on the UI thread.

            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, Resources.LogMessage_UpdatingConfigFile);

            using (EditableXmlConfigHelper configHelper = context.CreateEditableXmlConfigHelper())
            {
                foreach (ConfigSetting configSetting in salesforceInstance.RuntimeAuthentication.GetConfigSettings(salesforceInstance.ConnectedAppName))
                {
                    configHelper.SetAppSetting(
                        ConfigurationKeyNames.GetQualifiedKeyName(configSetting.Key, salesforceInstance.DesignerData.ServiceName),
                        configSetting.Value == null ? string.Empty : configSetting.Value.ToString(),
                        configSetting.Comment);
                }

                if (salesforceInstance.RuntimeAuthentication.AuthStrategy == AuthenticationStrategy.WebServerFlow)
                {
                    string handlerName = Constants.OAuthRedirectHandlerNameFormat.FormatInvariantCulture(salesforceInstance.DesignerData.ServiceName);
                    string qualifiedHandlerTypeName = SalesforceConnectedServiceHandler.GetServiceNamespace(project, salesforceInstance.DesignerData.ServiceName)
                                                      + Type.Delimiter + Constants.OAuthRedirectHandlerTypeName;
                    string redirectUri = ((WebServerFlowInfo)salesforceInstance.RuntimeAuthentication).RedirectUri.ToString();

                    configHelper.RegisterRedirectHandler(handlerName, redirectUri, qualifiedHandlerTypeName);
                }

                configHelper.Save();
            }
        }
Esempio n. 2
0
        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);
        }
Esempio n. 3
0
        public static void RegisterRedirectHandler(this EditableXmlConfigHelper configHelper, string name, string redirectHandlerPath, string fullTypeName)
        {
            // Because the "system.webServer" ConfigurationSection is an IgnoreSection, it must be modified
            // using the raw XML.

            ConfigurationSection webServerSection = configHelper.Configuration.GetSection(ConfigHelperExtensions.WebServerSectionName);

            if (webServerSection == null)
            {
                webServerSection = new IgnoreSection();
                configHelper.Configuration.Sections.Add(ConfigHelperExtensions.WebServerSectionName, webServerSection);
            }

            XElement webServerElement;
            string   webServerSectionRawXml = webServerSection.SectionInformation.GetRawXml();

            if (webServerSectionRawXml == null)
            {
                webServerElement = new XElement(ConfigHelperExtensions.WebServerSectionName);
            }
            else
            {
                webServerElement = XElement.Parse(webServerSectionRawXml);
            }

            XElement handlersElement = webServerElement.Element("handlers");

            if (handlersElement == null)
            {
                handlersElement = new XElement("handlers");
                webServerElement.Add(handlersElement);
            }

            XElement addElement = handlersElement.Elements("add")
                                  .FirstOrDefault(e =>
            {
                XAttribute attr = e.Attribute("type");
                return(attr != null && attr.Value == fullTypeName);
            });

            if (addElement == null)
            {
                addElement = new XElement("add",
                                          new XAttribute("name", name),
                                          new XAttribute("verb", "GET"),
                                          new XAttribute("path", redirectHandlerPath),
                                          new XAttribute("type", fullTypeName));
                handlersElement.Add(addElement);
            }

            webServerSection.SectionInformation.SetRawXml(webServerElement.ToString());
        }
        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);
        }
        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)
        {
            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-beta3a");
            InstallPackage("Microsoft.AspNet.WebHooks.Receivers", "1.2.0-beta3a");

            // 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.NuGetVersionOverride);

                    var classNamePrefix = ((string.IsNullOrEmpty(item.Option.ConfigWireupOverride))
                                    ? item.Option.Name
                                    : item.Option.ConfigWireupOverride);

                    var receiverName = ((string.IsNullOrEmpty(item.Option.ReceiverNameOverride))
                                    ? classNamePrefix
                                    : item.Option.ReceiverNameOverride);

                    var incomingType = ((string.IsNullOrEmpty(item.Option.IncomingTypeOverride))
                                    ? "JObject"
                                    : item.Option.IncomingTypeOverride);

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

                    // remember this provider
                    providers.Add(classNamePrefix);

                    // record the telemetry for the receiver
                    TelemetryWrapper.RecordEvent($"{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);
        }