Esempio n. 1
0
        protected override void Execute(CodeActivityContext context)
        {
            #region Workflow Arguments

            var switchInvokePowerShell = SwitchInvokePowerShell.Get(context);
            var powerShellScriptPath   = PowerShellScriptPath.Get(context);
            var nuGetExeFilePath       = NuGetExeFilePath.Get(context);
            var nuSpecFilePath         = NuSpecFilePath.Get(context);
            var basePath          = BasePath.Get(context);
            var outputDirectory   = OutputDirectory.Get(context);
            var version           = Version.Get(context);
            var switchInvokePush  = SwitchInvokePush.Get(context);
            var apiKey            = ApiKey.Get(context);
            var pushDestination   = PushDestination.Get(context);
            var additionalOptions = AdditionalOptions.Get(context);

            #endregion

            var resultMessages = SummarizePropertyValues(switchInvokePowerShell, powerShellScriptPath, nuGetExeFilePath,
                                                         nuSpecFilePath, basePath, outputDirectory, version, switchInvokePush, apiKey,
                                                         pushDestination, additionalOptions);

            for (var i = 0; i < resultMessages.Length - 1; i++)
            {
                // Write to the log
                context.WriteBuildMessage(resultMessages[i], BuildMessageImportance.High);
            }
        }
        protected override IOcrClient GetOcrClient(AsyncCodeActivityContext context)
        {
            var apiKey    = ApiKey.Get(context);
            var secretKey = SecretKey.Get(context);

            return(new BaiduOcrClient(apiKey, secretKey));
        }
Esempio n. 3
0
        protected override void Execute(CodeActivityContext context)
        {
            #region Extract Workflow Argument Values

            // The file path of the nuget.exe - if null or empty then
            //  assume nuget is "installed" on the build server and in the path
            var nuGetExeFilePath = NuGetExeFilePath.Get(context);

            // The path of the nuspec file
            var packageLocation = PackageLocation.Get(context);

            // The API Key for pushing
            var apiKey = ApiKey.Get(context);

            // The destination location if deployment is to be done
            var pushDestination = PushDestination.Get(context);

            #endregion

            // Don't assume that DI will have happened.  If the value is null then create the default object.)
            if (NuGetProcess == null)
            {
                NuGetProcess = new NuGetProcess();
            }

            // Call the method that will do the work
            var results = NuGetPublishing(nuGetExeFilePath, packageLocation, pushDestination, apiKey, context);

            // Send the result back to the workflow
            NuGetPushResult.Set(context, results);
        }
Esempio n. 4
0
        protected override void Execute(CodeActivityContext context)
        {
            // Get the various inputs
            var    text     = Text.Get(context);
            var    apiKey   = ApiKey.Get(context);
            var    bundleId = BundleId.Get(context);
            string tags     = JsonConvert.SerializeObject(Tags.Get(context));

            // Build the item json
            var jsonValues = new Dictionary <string, dynamic>()
            {
                { "text", text },
                { "bundle_id", bundleId }
            };

            // If there are tags to be assigned, add this key/value to the json
            if (tags.Length > 0)
            {
                jsonValues["tags"] = tags;
            }
            ;

            // Serialize the json
            string json = JsonConvert.SerializeObject(jsonValues);

            // Build URL content (e.g. api_key etc.) and encode it correctly
            // classify = true requires Ingenia to return the classification results in real time.
            var urlContent = new Dictionary <string, string>
            {
                { "api_key", apiKey },
                { "classify", "true" },
                { "json", json }
            };
            var content = new FormUrlEncodedContent(urlContent);

            // Post to Ingenia Items URL to do item#create
            try
            {
                using (var client = new HttpClient())
                {
                    var response = client.PostAsync("https://ingeniapi.com/v2/items", content).Result;

                    if (response.IsSuccessStatusCode)
                    {
                        var responseContent = response.Content;

                        string responseString = responseContent.ReadAsStringAsync().Result;

                        //
                        // This output currently assigns OutArgument IngeniaResponse.
                        //
                        IngeniaResponse.Set(context, responseString);
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        /// <summary>
        /// Main activity method
        /// </summary>
        /// <param name="context"></param>
        protected override void Execute(CodeActivityContext context)
        {
            var textToTranslate    = Text.Get(context);
            var targetLanguageCode = TargetLanguageCode.Get(context);
            var apiKey             = ApiKey.Get(context);

            if (apiKey != null)
            {
                // Sets to the user's apiKey, if supplied; if not, defaults to a free key
                MicrosoftTranslationClient.ApiKey = apiKey;
            }

            try
            {
                var translatedText         = MicrosoftTranslationClient.TranslateText(textToTranslate, targetLanguageCode);
                var detectedSourceLanguage = MicrosoftTranslationClient.Detect(textToTranslate);

                TranslatedText.Set(context, translatedText);
                DetectedSourceLanguage.Set(context, detectedSourceLanguage);
            }
            catch (System.Exception ex)
            {
                throw new System.Exception($"Actual Error: {ex.Message}\n{MicrosoftTranslationClient.InvalidApiKeyResolution}");
            }
        }
        /// <summary>
        /// Main activity method
        /// </summary>
        /// <param name="context"></param>
        protected override void Execute(CodeActivityContext context)
        {
            var inputFileSelection = Document.Get(context);

            string[]      files = inputFileSelection.Split("|".ToCharArray());
            List <string> filesForTranslation = new List <string>();
            List <string> translatedFiles     = new List <string>();

            if (files.Length == 1)
            {
                if (!File.Exists(files[0]))
                {
                    // Check if only one file is selected and if it exists
                    throw new System.IO.FileNotFoundException("The document specified is not found. Make sure the file exists or full path is typed correctly.");
                }
                else
                {
                    filesForTranslation.Add(files[0]);
                }
            }
            else
            {
                foreach (var selectedFile in files)
                {
                    if (File.Exists(selectedFile))
                    {
                        filesForTranslation.Add(selectedFile);
                    }
                }

                if (filesForTranslation.Count == 0)
                {
                    // All files specified are not found.
                    throw new System.IO.FileNotFoundException("All files specified are not found. Make sure the file exists or full path is typed correctly.");
                }
            }

            var targetLanguageCode = TargetLanguageCode.Get(context);
            var apiKey             = ApiKey.Get(context);

            if (apiKey != null && apiKey != "")
            {
                // Sets to the user's apiKey, if supplied; if not, defaults to a free key
                MicrosoftTranslationClient.ApiKey = apiKey;
            }
            try
            {
                translatedFiles = DocumentTranslationClient.TranslateDocument(String.Join(",", filesForTranslation), targetLanguageCode);
                TranslatedDoc.Set(context, translatedFiles);
            }
            catch (System.UnauthorizedAccessException uex)
            {
                throw new System.UnauthorizedAccessException($"FULL OUTPUT: {uex.Message}\n{MicrosoftTranslationClient.InvalidApiKeyResolution}");
            }
            catch (System.Exception ex)
            {
                throw new System.Exception(ex.Message);
            }
        }
Esempio n. 7
0
        protected override void Execute(NativeActivityContext context)
        {
            var apiKey      = ApiKey.Get(context);
            var apiUrl      = ApiURL.Get(context);
            var application = new Application(apiKey, apiUrl);

            if (Body != null)
            {
                context.ScheduleAction <Application>(Body, application, OnCompleted, OnFaulted);
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Execution Logic
        /// </summary>
        protected override void Execute(CodeActivityContext context)
        {
            try
            {
                MembersCount.Set(context, 0);
                MembersNames.Set(context, new Collection <string>()
                {
                });

                string host     = "https://api.meetup.com/2/rsvps?event_id={0}&sign=true&key={1}";
                string url      = string.Format(host, EventID.Get(context), ApiKey.Get(context));
                string response = string.Empty;

                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

                if (null == request)
                {
                    throw new ApplicationException("HttpWebRequest failed");
                }
                using (StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream()))
                {
                    response = sr.ReadToEnd();
                }

                RawResponse.Set(context, response);

                Collection <string> names = new Collection <string>()
                {
                };

                JObject o = JObject.Parse(response);
                JArray  a = (JArray)o["results"];

                foreach (JToken item in a)
                {
                    names.Add(item["member"]["name"].ToString());
                }

                MembersCount.Set(context, a.Count);
                MembersNames.Set(context, names);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 9
0
        protected override async Task <Action <NativeActivityContext> > ExecuteAsync(NativeActivityContext context, CancellationToken cancellationToken)
        {
            // Initialize Application
            var apiKey    = ApiKey.Get(context);
            var secretKey = SecretKey.Get(context);

            App = new  Application(apiKey, secretKey);

            // Schedule the child activities in the scope's body to run and make the client available to them
            if (Body != null)
            {
                context.ScheduleAction <Application>(Body, App, OnCompleted, OnFaulted);
            }

            // Any actions to perform after the child activities are scheduled go here
            return(_ => { });
        }
Esempio n. 10
0
        /// <summary>
        /// Main activity method
        /// </summary>
        /// <param name="context"></param>
        protected override void Execute(CodeActivityContext context)
        {
            var textInput = Text.Get(context);

            textInput = textInput.Replace(System.Environment.NewLine, " ");
            var apiKey = ApiKey.Get(context);

            if (apiKey != null)
            {
                // Sets to the user's apiKey, if supplied; if not, defaults to a free key
                ContentModeratorHelper.ApiKey = apiKey;
            }

            try
            {
                // Screen the input text: check for profanity, classify the text into three categories
                // do autocorrect text, and check for personally identifying
                // information (PII)
                _contentModeratorOutput = ContentModeratorHelper.GetTextEvaluationOutput(textInput);
                if (_contentModeratorOutput == null)
                {
                    throw new System.Exception("Null Output");
                }
                else
                {
                    FriendlyOutput.Set(context, _contentModeratorOutput.FriendlyOutput);
                    JsonOutput.Set(context, _contentModeratorOutput.JsonOutput);
                    AutoCorrectedText.Set(context, _contentModeratorOutput.AutoCorrectedText);
                    NormalizedText.Set(context, _contentModeratorOutput.NormalizedText);
                    ProfanityCategory1Score.Set(context, _contentModeratorOutput.ProfanityCategory1Score);
                    ProfanityCategory2Score.Set(context, _contentModeratorOutput.ProfanityCategory2Score);
                    ProfanityCategory3Score.Set(context, _contentModeratorOutput.ProfanityCategory3Score);
                    ReviewRecommended.Set(context, _contentModeratorOutput.ReviewRecommended);
                }
            }
            catch (System.Exception ex)
            {
                throw new System.Exception($"Actual Exception Message: {ex.Message}\n{GeneralException}");
            }
        }
        /// <summary>
        /// Execution Logic
        /// </summary>
        /// <param name="context"></param>
        protected override void Execute(CodeActivityContext context)
        {
            MembersCount.Set(context, 0);
            MembersNames.Set(context, new Collection <String>()
            {
            });

            string host     = "https://api.meetup.com/2/members?order=name&sign=true&group_urlname={0}&key={1}";
            string url      = String.Format(host, GroupUrlName.Get(context), ApiKey.Get(context));
            string response = String.Empty;

            HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;

            if (null == request)
            {
                throw new ApplicationException("HttpWebRequest failed");
            }
            using (StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream()))
            {
                response = sr.ReadToEnd();
            }

            RawResponse.Set(context, response);

            var names = new Collection <String>()
            {
            };

            JObject o = JObject.Parse(response);
            JArray  a = (JArray)o["results"];

            foreach (var item in a)
            {
                names.Add(item["name"].ToString());
            }

            MembersCount.Set(context, a.Count);
            MembersNames.Set(context, names);
        }
Esempio n. 12
0
        protected override void Execute(NativeActivityContext context)
        {
            string spreadsheetId = SpreadsheetId.Get(context);
            GoogleSheetProperty googleSheetProperty;

            switch (AuthenticationType)
            {
            case GoogleAuthenticationType.ApiKey:
                string apiKey = ApiKey.Get(context);
                googleSheetProperty = GoogleSheetProperty.Create(apiKey, spreadsheetId);
                break;

            case GoogleAuthenticationType.OAuth2User:
                string credentialID     = CredentialID.Get(context);
                string credentialSecret = CredentialSecret.Get(context);
                googleSheetProperty = Task.Run(async() =>
                {
                    return(await GoogleSheetProperty.Create(credentialID, credentialSecret, spreadsheetId));
                }).Result;
                break;

            case GoogleAuthenticationType.OAuth2ServiceAccount:
                string serviceAccountEmail = ServiceAccountEmail.Get(context);
                string keyPath             = KeyPath.Get(context);
                string password            = Password.Get(context);
                googleSheetProperty = GoogleSheetProperty.Create(keyPath, password, serviceAccountEmail, spreadsheetId);
                break;

            default:
                googleSheetProperty = GoogleSheetProperty.Create("wrongkey", spreadsheetId);
                break;
            }

            if (Body != null)
            {
                context.ScheduleAction <GoogleSheetProperty>(Body, googleSheetProperty, OnCompleted, OnFaulted);
            }
        }
        protected override void Execute(CodeActivityContext context)
        {
            var serviceUrl  = ServiceUrl.Get(context);
            var apiKey      = ApiKey.Get(context);
            var versionDate = VersionDate.Get(context);

            var authenticator = new IamAuthenticator(apikey: apiKey);
            var service       = new AssistantService(versionDate, authenticator);

            service.SetServiceUrl(serviceUrl);

            var assistantId = AssistantId.Get(context);
            var text        = Text.Get(context);

            // SuggestedIntentの取得
            var suggestedIntent = FetchSuggestedIntent(assistantId, text, service);

            SuggestedIntent.Set(context, suggestedIntent);

            // Confidenciesの取得
            var confidencies = FetchIntentConfidencies(assistantId, text, service);

            Confidencies.Set(context, confidencies);
        }
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            if (!Request.Headers.TryGetValue(ApiKeyHeaderName, out var apiKeyHeaderValues))
            {
                return(AuthenticateResult.NoResult());
            }

            var providedApiKey = apiKeyHeaderValues.FirstOrDefault();

            if (apiKeyHeaderValues.Count == 0 || string.IsNullOrWhiteSpace(providedApiKey))
            {
                return(AuthenticateResult.NoResult());
            }

            var existingApiKey = await ApiKey.Get(_db, providedApiKey);

            if (existingApiKey != null)
            {
                var claims = new List <Claim> {
                    new Claim(ClaimTypes.Name, existingApiKey.Owner)
                };

                claims.AddRange(existingApiKey.Roles.Select(role => new Claim(ClaimTypes.Role, role)));

                var identity   = new ClaimsIdentity(claims, Options.AuthenticationType);
                var identities = new List <ClaimsIdentity> {
                    identity
                };
                var principal = new ClaimsPrincipal(identities);
                var ticket    = new AuthenticationTicket(principal, Options.Scheme);

                return(AuthenticateResult.Success(ticket));
            }

            return(AuthenticateResult.Fail("Invalid API Key provided."));
        }
Esempio n. 15
0
        protected override void Execute(CodeActivityContext context)
        {
            // Instatiate HttpClient
            HttpClient client = new HttpClient();
            string     url    = URL.Get(context);

            // Get Base64 Encoded Key from Username and API Key
            string username = Username.Get(context);
            string apikey   = ApiKey.Get(context);
            string authKey;

            // Convert username:apikey to Base64
            try
            {
                string base64Decoded = username + ":" + apikey;
                authKey = System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(base64Decoded));
            }
            catch (Exception e)
            {
                throw new Exception("AuthKey generation failed. Check Username/ApiKey fields. " + e.Message);
            }

            // Authenticate with AuthKey
            try
            {
                client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authKey);
            }
            catch (Exception e)
            {
                throw new Exception("Authorization failed. Check Username/ApiKey. " + e.Message);
            }

            // Get variables from context
            string attachmentPath = AttachmentPath.Get(context);
            string issueid        = IssueKey.Get(context);

            // Get Mime Type of attachment
            string mimeType;

            string[] uriSegments;
            try
            {
                uriSegments = attachmentPath.Split('\\'); // now it works for relative paths
                mimeType    = uriSegments[uriSegments.Length - 1].Split('.')[1];
            }
            catch (Exception e)
            {
                throw new Exception("Could not get MIME type. Attachment Path incorrect. " + e.Message);
            }


            // Add token header
            client.DefaultRequestHeaders.Add("X-Atlassian-Token", "nocheck");

            // Prepare payload
            MultipartFormDataContent payload = new MultipartFormDataContent();

            try
            {
                HttpContent content = new ByteArrayContent(File.ReadAllBytes(attachmentPath));
                content.Headers.ContentType = MediaTypeHeaderValue.Parse("image/" + mimeType);
                payload.Add(content, "file", uriSegments[uriSegments.Length - 1]);
            }
            catch (Exception e)
            {
                throw new Exception("File could not be read in. Please check the AttachmentPath parameter. " + e.Message);
            }

            // API Call begins here
            try
            {
                Console.WriteLine("API Call here");
                // Make POST call with issueid and content
                HttpResponseMessage postResponse = client.PostAsync(url + "/rest/api/2/issue/" + issueid + "/attachments", payload).Result;
                // Throw error if status code is negative
                if (!postResponse.IsSuccessStatusCode)
                {
                    throw new Exception("Response status code: " + ((int)postResponse.StatusCode).ToString() + " " + postResponse.StatusCode);
                }
                Console.WriteLine(postResponse.Content.ReadAsStringAsync().Result);
                Console.WriteLine("-- Done --");
            }
            catch (HttpRequestException e)
            {
                throw new Exception("Error sending request. " + e.Message);
            }
            catch (Exception e)
            {
                throw new Exception("API call failed. " + e.Message);
            }
        }
Esempio n. 16
0
        protected override void Execute(CodeActivityContext context)
        {
            // Instatiate HttpClient
            HttpClient client = new HttpClient();
            string     url    = URL.Get(context);

            // Get Base64 Encoded Key from Username and API Key
            string username = Username.Get(context);
            string apikey   = ApiKey.Get(context);
            string authKey;

            // Convert username:apikey to Base64
            try
            {
                string base64Decoded = username + ":" + apikey;
                authKey = System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(base64Decoded));
            }
            catch (Exception e)
            {
                throw new Exception("AuthKey generation failed. Check Username/ApiKey fields. " + e.Message);
            }

            // Authenticate with AuthKey
            try
            {
                client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authKey);
            }
            catch (Exception e)
            {
                throw new Exception("Authorization failed. Check Username/ApiKey. " + e.Message);
            }

            // Get variables from context
            string body    = Body.Get(context);
            string issueid = IssueKey.Get(context);

            // Convert body message into JSON format
            JObject       payloadJSON;
            StringContent payload;

            try
            {
                payloadJSON = new JObject(new JProperty("body", body));
                payload     = new StringContent(JsonConvert.SerializeObject(payloadJSON), Encoding.UTF8, "application/json");
            }
            catch (Exception e)
            {
                throw new Exception("Unable to convert comment into JSON format. Please check the body parameter. " + e.Message);
            }

            // API Call begins here
            try
            {
                // Make POST call with issueid and content
                HttpResponseMessage postResponse = client.PostAsync(url + "/rest/api/2/issue/" + issueid + "/comment", payload).Result;
                // Throw error if status code is negative
                if (!postResponse.IsSuccessStatusCode)
                {
                    throw new Exception("Response status code: " + ((int)postResponse.StatusCode).ToString() + " " + postResponse.StatusCode);
                }
                Console.WriteLine(postResponse.Content.ReadAsStringAsync().Result);
                Console.WriteLine("-- Done --");
            }
            catch (HttpRequestException e)
            {
                throw new Exception("Error sending request. " + e.Message);
            }
            catch (Exception e)
            {
                throw new Exception("API call failed. " + e.Message);
            }
        }
        /// <summary>
        /// Executes the workflow activity.
        /// </summary>
        /// <param name="executionContext">The execution context.</param>
        protected override void Execute(CodeActivityContext executionContext)
        {
            // Create the tracing service
            ITracingService tracingService = executionContext.GetExtension <ITracingService>();

            if (tracingService == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve tracing service.");
            }

            tracingService.Trace("Entered " + _activityName + ".Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}",
                                 executionContext.ActivityInstanceId,
                                 executionContext.WorkflowInstanceId);

            // Create the context
            IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>();

            if (context == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve workflow context.");
            }

            tracingService.Trace(_activityName + ".Execute(), Correlation Id: {0}, Initiating User: {1}",
                                 context.CorrelationId,
                                 context.InitiatingUserId);

            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                string inputText = TextInput.Get(executionContext);
                if (inputText != string.Empty)
                {
                    //strip any html characters from the text to analyze
                    inputText = HtmlTools.StripHTML(inputText);
                    tracingService.Trace(string.Format("stripped text: {0}", inputText));

                    //escape any double quote characters (") so they don't cause problems when posting the json later
                    string escapedText = inputText.Replace("\"", "\\\"");
                    tracingService.Trace(string.Format("escaped text: {0}", escapedText));

                    //create the webrequest object
                    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(_webAddress);

                    //set request content type so it is treated as a regular form post
                    req.ContentType = "application/x-www-form-urlencoded";

                    //set method to post
                    req.Method = "POST";

                    //buld the request
                    StringBuilder postData = new StringBuilder();

                    //note the Id value set to 1 - we can hardcode this because we're only sending a batch of one
                    postData.Append("{\"Inputs\":[{\"Id\":\"1\",\"Text\":\"" + escapedText + "\"}]}");

                    //set the authentication using the azure service access key
                    string authInfo = "AccountKey:" + ApiKey.Get(executionContext);
                    authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
                    req.Headers["Authorization"] = "Basic " + authInfo;

                    //create a stream
                    byte[] bytes = System.Text.Encoding.ASCII.GetBytes(postData.ToString());
                    req.ContentLength = bytes.Length;
                    System.IO.Stream os = req.GetRequestStream();
                    os.Write(bytes, 0, bytes.Length);
                    os.Close();

                    //post the request and get the response
                    System.Net.WebResponse resp = req.GetResponse();

                    //deserialize the response to a SentimentBatchResult object
                    SentimentBatchResult sentimentResult = new SentimentBatchResult();
                    System.Runtime.Serialization.Json.DataContractJsonSerializer deserializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(sentimentResult.GetType());
                    sentimentResult = deserializer.ReadObject(resp.GetResponseStream()) as SentimentBatchResult;

                    //if no errors, return the sentiment
                    if (sentimentResult.Errors.Count == 0)
                    {
                        //set output values from the fields of the deserialzed myjsonresponse object
                        Score.Set(executionContext, sentimentResult.SentimentBatch[0].Score);
                    }
                    else
                    {
                        //otherwise raise an exception with the returned error message
                        throw new InvalidPluginExecutionException(String.Format("Sentiment analyis error: {0)", sentimentResult.Errors[0].Message));
                    }
                }
            }

            catch (WebException exception)
            {
                string str = string.Empty;
                if (exception.Response != null)
                {
                    using (StreamReader reader =
                               new StreamReader(exception.Response.GetResponseStream()))
                    {
                        str = reader.ReadToEnd();
                    }
                    exception.Response.Close();
                }
                if (exception.Status == WebExceptionStatus.Timeout)
                {
                    throw new InvalidPluginExecutionException(
                              "The timeout elapsed while attempting to issue the request.", exception);
                }
                throw new InvalidPluginExecutionException(String.Format(CultureInfo.InvariantCulture,
                                                                        "A Web exception ocurred while attempting to issue the request. {0}: {1}",
                                                                        exception.Message, str), exception);
            }
            catch (FaultException <OrganizationServiceFault> e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());

                // Handle the exception.
                throw;
            }
            catch (Exception e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());
                throw;
            }

            tracingService.Trace("Exiting " + _activityName + ".Execute(), Correlation Id: {0}", context.CorrelationId);
        }
Esempio n. 18
0
        /// <summary>
        /// Executes the workflow activity.
        /// </summary>
        /// <param name="executionContext">The execution context.</param>
        protected override void Execute(CodeActivityContext executionContext)
        {
            // Create the tracing service
            ITracingService tracingService = executionContext.GetExtension <ITracingService>();

            if (tracingService == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve tracing service.");
            }

            tracingService.Trace("Entered " + _activityName + ".Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}",
                                 executionContext.ActivityInstanceId,
                                 executionContext.WorkflowInstanceId);

            // Create the context
            IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>();

            if (context == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve workflow context.");
            }

            tracingService.Trace(_activityName + ".Execute(), Correlation Id: {0}, Initiating User: {1}",
                                 context.CorrelationId,
                                 context.InitiatingUserId);

            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                //create a new myjsonrequest object from which data will be serialized
                JsonRequest myRequest = new JsonRequest();
                myRequest.InputObj = new CrmAzureMlDemo.Input1();
                Input input = new Input();

                string[] columns = { "address1_stateorprovince", "annualincome",            "lpa_age",
                                     "numberofchildren",         "educationcodename",       "familystatuscodename",
                                     "gendercodename",           "lpa_commutedistancename", "lpa_homeownername",
                                     "lpa_occupationname",       "lpa_numberofcarsowned",   "lpa_numberofchildrenathome" };

                object[] values = { StateOrProvince.Get(executionContext), AnnualIncome.Get(executionContext),    Age.Get(executionContext),
                                    NumChildren.Get(executionContext),     Education.Get(executionContext),       MaritalStatus.Get(executionContext),
                                    Gender.Get(executionContext),          CommuteDistance.Get(executionContext), Homeowner.Get(executionContext),
                                    Occupation.Get(executionContext),      NumCars.Get(executionContext),         NumChildrenAtHome.Get(executionContext) };

                input.Columns = columns;
                input.Values  = new object[][] { values };

                myRequest.InputObj.Inputs = new Input();
                myRequest.InputObj.Inputs = input;

                //serialize the myjsonrequest to json
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(myRequest.GetType());
                MemoryStream ms = new MemoryStream();
                serializer.WriteObject(ms, myRequest);
                string jsonMsg = Encoding.Default.GetString(ms.ToArray());

                //create the webrequest object and execute it (and post jsonmsg to it)
                System.Net.WebRequest req = System.Net.WebRequest.Create(Endpoint.Get(executionContext));

                //must set the content type for json
                req.ContentType = "application/json";

                //must set method to post
                req.Method = "POST";

                //add authorization header
                req.Headers.Add(string.Format("Authorization:Bearer {0}", ApiKey.Get(executionContext)));

                tracingService.Trace("json request: {0}", jsonMsg);

                //create a stream
                byte[] bytes = System.Text.Encoding.ASCII.GetBytes(jsonMsg.ToString());
                req.ContentLength = bytes.Length;
                System.IO.Stream os = req.GetRequestStream();
                os.Write(bytes, 0, bytes.Length);
                os.Close();

                //get the response
                System.Net.WebResponse resp = req.GetResponse();

                Stream responseStream = CopyAndClose(resp.GetResponseStream());
                // Do something with the stream
                StreamReader reader         = new StreamReader(responseStream, Encoding.UTF8);
                String       responseString = reader.ReadToEnd();
                tracingService.Trace("json response: {0}", responseString);

                responseStream.Position = 0;
                //deserialize the response to a myjsonresponse object
                JsonResponse myResponse = new JsonResponse();
                System.Runtime.Serialization.Json.DataContractJsonSerializer deserializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(myResponse.GetType());
                myResponse = deserializer.ReadObject(responseStream) as JsonResponse;

                //set output values from the fields of the deserialzed myjsonresponse object
                BikeBuyer.Set(executionContext, myResponse.Results.Output1.Value.Values[0][0]);
            }

            catch (WebException exception)
            {
                string str = string.Empty;
                if (exception.Response != null)
                {
                    using (StreamReader reader =
                               new StreamReader(exception.Response.GetResponseStream()))
                    {
                        str = reader.ReadToEnd();
                    }
                    exception.Response.Close();
                }
                if (exception.Status == WebExceptionStatus.Timeout)
                {
                    throw new InvalidPluginExecutionException(
                              "The timeout elapsed while attempting to issue the request.", exception);
                }
                throw new InvalidPluginExecutionException(String.Format(CultureInfo.InvariantCulture,
                                                                        "A Web exception ocurred while attempting to issue the request. {0}: {1}",
                                                                        exception.Message, str), exception);
            }
            catch (FaultException <OrganizationServiceFault> e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());

                // Handle the exception.
                throw;
            }
            catch (Exception e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());
                throw;
            }

            tracingService.Trace("Exiting " + _activityName + ".Execute(), Correlation Id: {0}", context.CorrelationId);
        }
Esempio n. 19
0
        protected override void Execute(CodeActivityContext context)
        {
            // Instatiate HttpClient
            HttpClient client = new HttpClient();
            string     url    = URL.Get(context);

            // Get Base64 Encoded Key from Username and API Key
            string username = Username.Get(context);
            string apikey   = ApiKey.Get(context);
            string authKey;

            // Convert username:apikey to Base64
            try
            {
                string base64Decoded = username + ":" + apikey;
                authKey = System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(base64Decoded));
            }
            catch (Exception e)
            {
                throw new Exception("AuthKey generation failed. Check Username/ApiKey fields. " + e.Message);
            }

            // Authenticate with AuthKey
            try
            {
                client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authKey);
            }
            catch (Exception e)
            {
                throw new Exception("Authorization failed. Check Username/ApiKey. " + e.Message);
            }

            // Get variables from context
            string jsonfilepath = JsonFilePath.Get(context);
            string issueid      = IssueKey.Get(context);

            // Read in JSON file
            string content;

            try
            {
                content = File.ReadAllText(jsonfilepath);
            }
            catch (Exception e)
            {
                throw new Exception("Could not read file. Check JsonFilePath parameter. " + e.Message);
            }
            var payload = new StringContent(content, Encoding.UTF8, "application/json");


            // API Call begins here
            try
            {
                // Make PUT call with issueid and content
                HttpResponseMessage putResponse = client.PutAsync(url + "/rest/api/2/issue/" + issueid, payload).Result;
                // Throw error if status code is negative
                if (!putResponse.IsSuccessStatusCode)
                {
                    throw new Exception("Response status code: " + ((int)putResponse.StatusCode).ToString() + " " + putResponse.StatusCode);
                }
                Console.WriteLine(putResponse.Content.ReadAsStringAsync().Result);
                Console.WriteLine("-- Done --");
            }
            catch (HttpRequestException e)
            {
                throw new Exception("Error sending request. " + e.Message);
            }
            catch (Exception e)
            {
                throw new Exception("API call failed. " + e.Message);
            }
        }