public Task <ExecutionResult> Post( [BindRequired, FromBody] PostBody body, [FromServices] GraphQlEfSampleDbContext dbContext, CancellationToken cancellation) { return(Execute(dbContext, body.Query, body.OperationName, body.Variables, cancellation)); }
public static string Post(string url, PostBody postBody, int timeout = 5000) { try { Logger.Debug($"Post\t{url}"); using (var handler = new HttpClientHandler() { CookieContainer = new CookieContainer() }) using (var client = new HttpClient(handler)) { var content = new FormUrlEncodedContent(postBody.Body); var magicCodeName = string.Empty; if (Config.TryGet("MagicCodeType", out magicCodeName)) { var magicCodeValue = Config.TryGet("MagicCodeValue", ""); var magicCodePath = Config.TryGet("MagicCodePath", "/"); var magicCodeDomain = Config.TryGet("MagicCodeDomain", ".baidu.com"); handler.CookieContainer.Add(new Cookie(magicCodeName, magicCodeValue, magicCodePath, magicCodeDomain)); } var result = client.PostAsync(url, content).Result; result.EnsureSuccessStatusCode(); return result.Content.ReadAsStringAsync().Result; } } catch (Exception e) { Logger.Error(e.ToString()); return e.Message; } }
public async Task PostPhotoAsync(PostBody info, FacebookClient client) { if (!System.IO.File.Exists(info.FilePath)) { throw new FileNotFoundException("Filepath is invalid."); } string extension = Path.GetExtension(info.FilePath).Substring(1); if (!possibleExtensions.Contains($"{extension}")) { throw new FileLoadException("File extension is invalid."); } string attachementPath = info.FilePath; using (var file = new FacebookMediaStream { ContentType = $"image/{extension}", FileName = System.IO.Path.GetFileName(attachementPath) }.SetValue(System.IO.File.OpenRead(attachementPath))) { dynamic result = await client.PostTaskAsync($"{info.PageNameOrId}/photos", new { message = info.DescriptionAndHashtags == null ? "" : info.DescriptionAndHashtags, file }); } }
public static PostView Build(Post i_Post) { PostView postResult = new PostView(i_Post); postResult.Dock = DockStyle.Top; postResult.Padding = new Padding(0, 15, 0, 0); PostDetails details = new PostDetails(); PostBody body = new PostBody(); PostActions actions = new PostActions(); actions.Init(i_Post); body.Init(i_Post); details.Init(i_Post); details.Dock = DockStyle.Top; body.Dock = DockStyle.Top; actions.Dock = DockStyle.Top; postResult.Controls.Add(actions); postResult.Controls.Add(body); postResult.Controls.Add(details); details.UserClicked += postResult.OnUserClicked; return(postResult); }
public Task <ExecutionResult> Post( [BindRequired, FromBody] PostBody body, [FromServices] NorthwindContext dataContext, CancellationToken cancellation) { return(Execute(dataContext, body.Query, body.OperationName, body.Variables, cancellation)); }
public void SendRequest(PostBody message, ITracingService tracingService, ILogger logger) { using (var client = new HttpClient()) { Uri requestUri = new Uri("https://dc.services.visualstudio.com/v2/track"); MemoryStream stream1 = new MemoryStream(); DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(PostBody), new DataContractJsonSerializerSettings() { UseSimpleDictionaryFormat = true }); ser.WriteObject(stream1, message); stream1.Position = 0; StreamReader sr = new StreamReader(stream1); HttpResponseMessage response = client.PostAsync(requestUri, new StringContent(sr.ReadToEnd(), Encoding.UTF8, "application/json")).Result; string result = response.Content.ReadAsStringAsync().Result; logger.LogInformation("Send message to Application Insights", result); if (response.IsSuccessStatusCode) { Console.WriteLine("Request success: "); } else { Console.WriteLine("Request fail, please check the detailed error: "); logger.LogWarning("Send message to Application Insights failed", result); } Console.WriteLine(result); } }
public async Task <IActionResult> PostEndedPage(PostBody data) { var session = await _context.Session.SingleOrDefaultAsync(m => m.Uuid == data.Uuid); if (session == null) { return(NotFound()); } else { Page page = null; page = await _context.Page.SingleOrDefaultAsync(m => m.IdSession == session.IdSession && m.Ended == null); if (page != null) { page.Ended = DateTime.Now; _context.Entry(page).State = EntityState.Modified; await _context.SaveChangesAsync(); return(Ok()); } else { return(NotFound()); } } }
public async Task <string> Post( [BindRequired, FromBody] PostBody body, CancellationToken cancellation) { var result = await Execute(body.Query, body.OperationName, body.Variables, cancellation); return(await writer.WriteToStringAsync(result)); }
public override void PreProcess(SurrogateManager surrogateManager) { Condition.PreProcess(surrogateManager); Body.PreProcess(surrogateManager); if (PostBody != null) { PostBody.PreProcess(surrogateManager); } }
public async Task TestOnlyPictureAsync() { PostBody post = new PostBody() { PageNameOrId = "683744845377993", FilePath = "C:\\Users\\Usevalad_Hardziyenka\\Pictures\\water.png" }; await service.PostPhotoAsync(post, client); }
private static string PrepPost(string json, string name_) { PostBody toReturn = new PostBody { name = name_, config = JObject.Parse(json) }; return(JsonConvert.SerializeObject(toReturn)); }
public async Task TestPngAsync() { PostBody post = new PostBody() { PageNameOrId = "683744845377993", FilePath = "C:\\Users\\Usevalad_Hardziyenka\\Pictures\\water.png", DescriptionAndHashtags = "some text" }; await service.PostPhotoAsync(post, client); }
public async Task TestWrongFileExtensionAsync() { PostBody post = new PostBody() { PageNameOrId = "683744845377993", FilePath = "C:\\Users\\Usevalad_Hardziyenka\\Pictures\\desktop.ini", DescriptionAndHashtags = "some text" }; await Assert.ThrowsAsync <FileLoadException>(() => service.PostPhotoAsync(post, client)); }
public async Task TestWrongPageNameAsync() { PostBody post = new PostBody() { PageNameOrId = "8374487993", FilePath = "C:\\Users\\Usevalad_Hardziyenka\\Pictures\\water.png", DescriptionAndHashtags = "some text" }; await Assert.ThrowsAsync <FacebookApiException>(() => service.PostPhotoAsync(post, client)); }
public async Task TestWrongFilePath() { PostBody post = new PostBody() { PageNameOrId = "683744845377993", FilePath = "wrong file", DescriptionAndHashtags = "some text" }; await Assert.ThrowsAsync <FileNotFoundException>(() => service.PostPhotoAsync(post, client)); }
public async Task CheckAsync(PostBody info) { if (info.PageAccessToken == null) { throw new ArgumentException(nameof(info.PageAccessToken)); } FacebookClient client = new FacebookClient(info.PageAccessToken); await service.PostPhotoAsync(info, client); }
public IActionResult DeleteComic([FromBody] PostBody post) { if (post != null) { var revisedCollection = _collectionManagerService.RemoveComicFromCollection(post.comic, post.userName); return(Ok(revisedCollection)); } else { return(BadRequest()); } }
public SquirrelsResponse Squirrels(PostBody model) { var generator = new JSchemaGenerator(); var schema = generator.Generate(typeof(SquirrelsRequest)); var body = JObject.Parse(model.Body); bool valid = body.IsValid(schema, out IList <string> messages); if (!valid) { //fail, do something } //success }
public ActionResult Post([FromBody] PostBody body) { if (body.Value == "Trajan") { return(BadRequest()); } if (body.Value == "Tosho") { return(NotFound()); } return(Ok(body.Value)); }
private DataTable GetDataTable(PostBody postBody) { DataTable dt = new DataTable(); dt.Columns.Add(postBody.XAxis.Name, GetType(postBody.XAxis.Type)); dt.Columns.Add(postBody.YAxis.Name, GetType(postBody.XAxis.Type)); for (int iter = 0; iter < postBody.XAxis.Values.Length; iter++) { dt.Rows.Add(postBody.XAxis.Values[iter], postBody.YAxis.Values[iter]); } return(dt); }
public void Execute(IServiceProvider serviceProvider) { //https://msdn.microsoft.com/en-us/library/gg509027.aspx //When you use the Update method or UpdateRequest message, do not set the OwnerId attribute on a record unless the owner has actually changed. //When you set this attribute, the changes often cascade to related entities, which increases the time that is required for the update operation. //Extract the tracing service for use in debugging sandboxed plug-ins. ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); tracingService.Trace("Starting SendApplicationInsights at " + DateTime.Now.ToString()); // Obtain the execution context from the service provider. IPluginExecutionContext context = (IPluginExecutionContext) serviceProvider.GetService(typeof(IPluginExecutionContext)); Microsoft.Xrm.Sdk.PluginTelemetry.ILogger logger = (Microsoft.Xrm.Sdk.PluginTelemetry.ILogger) serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.PluginTelemetry.ILogger)); XmlDocument doc = new XmlDocument(); DateTime executionTime = DateTime.Now.ToUniversalTime(); tracingService.Trace("Parse and Search Unsecure Config at " + DateTime.Now.ToString()); doc.LoadXml(_unsecureString); _instrumentationKey = GetValueNode(doc, "instrumentationKey"); PostBody postBody = new PostBody() { iKey = _instrumentationKey }; try { logger.IsEnabled(Microsoft.Xrm.Sdk.PluginTelemetry.LogLevel.Information); logger.LogInformation("test from ILogger"); logger.LogTrace("Log Trace"); logger.LogWarning("Log Trace"); //logger.LogMetric("testMetric", new long()); logger.LogError("Log Trace"); logger.LogCritical("Log Trace"); tracingService.Trace("Create Custom Event Data DTO at " + DateTime.Now.ToString()); postBody.data.baseData = Events.CreateCustomEventData(postBody.data.baseData, context); postBody.data.baseData.properties.Add("ExecutionTime", executionTime.ToString()); tracingService.Trace("Send Custom Event Request at " + DateTime.Now.ToString()); PushMessageToApplicationInsights messenger = new PushMessageToApplicationInsights(); messenger.SendRequest(postBody, tracingService, logger); } catch (InvalidPluginExecutionException ex) { postBody.data.baseData = Exceptions.CreateExceptionEventData(postBody.data.baseData, ex, context); PushMessageToApplicationInsights messenger = new PushMessageToApplicationInsights(); messenger.SendRequest(postBody, tracingService, logger); throw new InvalidPluginExecutionException(ex.Message); } }
public async Task GettingPostBody() { // Arrange using (var server = new HttpServer()) { var poco = new { id = 1, name = "moo" }; var expectedBody = JsonConvert.SerializeObject(poco); string body = null; PostBody bodyObject = null; server.AddJsonDocumentHandler( (processor, stream) => { if (processor.Path != "/post") { return(null); } body = stream.AsString(); bodyObject = stream.As <PostBody>(); return(new { id = 1, body }); }); // Pre-assert // Act var client = new HttpClient(); var message = new HttpRequestMessage( HttpMethod.Post, server.GetFullUrlFor("/post")) { Method = HttpMethod.Post, Content = new ObjectContent <object>( poco, new JsonMediaTypeFormatter()) }; await client.SendAsync(message); // Assert Expect(body).To.Equal(expectedBody); Expect(bodyObject).Not.To.Be.Null(); Expect(bodyObject.Id).To.Equal(poco.id); Expect(bodyObject.Name).To.Equal(poco.name); } }
public void SendRequest(BaseType messageType, IPluginExecutionContext context, ITracingService tracingService) { using (var client = new HttpClient()) { Uri requestUri = new Uri("https://dc.services.visualstudio.com/v2/track"); PostBody postBody = new PostBody(); postBody.iKey = _instrumentationKey; MemoryStream stream1 = new MemoryStream(); DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(PostBody), new DataContractJsonSerializerSettings() { UseSimpleDictionaryFormat = true }); postBody.data.baseType = messageType.ToString(); switch (postBody.data.baseType) { case "EventData": postBody.data.baseData = Events.CreateCustomEventData(postBody.data.baseData, context); break; case "ExceptionData": try { throw new InvalidPluginExecutionException("Test Exception"); } catch (InvalidPluginExecutionException e) { postBody.data.baseData = Exceptions.CreateExceptionEventData(postBody.data.baseData, e, context); } break; case "MetricData": postBody.data.baseData = Metrics.CreateCustomMetricData(postBody.data.baseData, context); break; } ser.WriteObject(stream1, postBody); stream1.Position = 0; StreamReader sr = new StreamReader(stream1); HttpResponseMessage response = client.PostAsync(requestUri, new StringContent(sr.ReadToEnd(), Encoding.UTF8, "application/json")).Result; string result = response.Content.ReadAsStringAsync().Result; if (response.IsSuccessStatusCode) { tracingService.Trace("Request success: "); } else { tracingService.Trace("Request fail, please check the detailed error: "); } tracingService.Trace(result); } }
public async Task <IActionResult> GetSession(PostBody data) { var session = new Session() { Uuid = Guid.NewGuid().ToString(), UrlOrigin = data.Url }; _context.Session.Add(session); await _context.SaveChangesAsync(); return(Ok(new { uuid = session.Uuid })); }
public IActionResult AddComic([FromBody] PostBody post) { if (post != null) { var revisedCollection = _collectionManagerService.AddComicToCollection(post.comic, post.userName); return(CreatedAtAction ( nameof(AddComic), revisedCollection )); } else { return(BadRequest()); } }
public async Task <ActionResult> Post([FromBody] PostBody body) { if (body?.Body == null) { return(BadRequest("No object named 'body' could be found.")); } // TODO: I'm not sure this url is correct. Also, this url should be stored in a settings file so that it can be updated as needed. var url = @"https://urldefense.proofpoint.com/v2/url?u=http-3A__example.com_request&d=DwIGAg&c=iWzD8gpC8N4xSkOHZBDmCw&r=R0U6eziUSfkIiSy6xlVVHEbyT-5CVX85B2177L6G3Po&m=yeOGbdLEit9cyYWgLXxv5PRcMgRiallgPowRbt59hFw&s=lZ8qcf2Nw6VP2qI311Xp3wnZgZDhuaIrUg7krpQgTr4&e= "; var data = new { body = body.Body, callback = "/callback" }; var stringContent = new StringContent(JsonConvert.SerializeObject(data)); stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); string requestId; using (var client = new HttpClient()) { var response = await client.PostAsync(url, stringContent); if (!response.IsSuccessStatusCode) { return(BadRequest("An exception occurred while communicating with the third party service.")); } requestId = await response.Content.ReadAsStringAsync(); } try { await _context.Requests.AddAsync(new Request(requestId)); await _context.SaveChangesAsync(); return(new OkObjectResult(requestId)); } catch (Exception ex) { return(BadRequest(ex.Message)); } }
private void OnPostBody() { RestResponsePanel(); var body = new PostBody("sp958857", "China"); var ob = httpService.PostBody(body, "Unity-Client"); ob.SubscribeOn(Scheduler.ThreadPool) .ObserveOn(Scheduler.MainThread) .Subscribe(data => { Debug.LogFormat("Received on threadId:{0}", Thread.CurrentThread.ManagedThreadId); arg1.ShowArg("json-body", data.data); }, // onSuccess error => { Debug.Log("Retrofit Error:" + error); }); }
public async Task <IActionResult> PostLink(PostBody data) { var session = await _context.Session.SingleOrDefaultAsync(m => m.Uuid == data.Uuid); if (session == null) { return(NotFound()); } else { var link = new Link() { IdSessionNavigation = session, UrlLink = data.Url }; _context.Link.Add(link); await _context.SaveChangesAsync(); return(Ok()); } }
public async Task <IActionResult> PostInitPage(PostBody data) { var session = await _context.Session.SingleOrDefaultAsync(m => m.Uuid == data.Uuid); if (session == null) { return(NotFound()); } else { var page = new Page() { IdSessionNavigation = session, UrlVisit = data.Url }; _context.Page.Add(page); await _context.SaveChangesAsync(); return(Ok()); } }
public void Execute(IServiceProvider serviceProvider) { //https://msdn.microsoft.com/en-us/library/gg509027.aspx //When you use the Update method or UpdateRequest message, do not set the OwnerId attribute on a record unless the owner has actually changed. //When you set this attribute, the changes often cascade to related entities, which increases the time that is required for the update operation. //Extract the tracing service for use in debugging sandboxed plug-ins. ILogger logger = (ILogger)serviceProvider.GetService(typeof(ILogger)); ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); tracingService.Trace("Starting SendApplicationInsights at " + DateTime.Now.ToString()); // Obtain the execution context from the service provider. IPluginExecutionContext context = (IPluginExecutionContext) serviceProvider.GetService(typeof(IPluginExecutionContext)); XmlDocument doc = new XmlDocument(); doc.LoadXml(_unsecureString); tracingService.Trace("Loaded Unsecure Configuration XML " + DateTime.Now.ToString()); _instrumentationKey = GetValueNode(doc, "instrumentationKey"); try { PostBody postBody = new PostBody(); postBody.iKey = _instrumentationKey; tracingService.Trace("Created PostBody with iKey = " + postBody.iKey + " " + DateTime.Now.ToString()); try { throw new InvalidPluginExecutionException("Test Exception"); } catch (InvalidPluginExecutionException e) { postBody.data.baseData = Exceptions.CreateExceptionEventData(postBody.data.baseData, e, context); tracingService.Trace("Set baseData for Exception Request " + DateTime.Now.ToString()); PushMessageToApplicationInsights messenger = new PushMessageToApplicationInsights(); messenger.SendRequest(postBody, tracingService, logger); tracingService.Trace("Sent Request " + DateTime.Now.ToString()); throw e; } } catch (Exception ex) { tracingService.Trace("Caught final exception " + DateTime.Now.ToString()); throw new InvalidPluginExecutionException(ex.Message); } }
public IHttpActionResult Clipboard([FromBody] PostBody body) { if (body == null) { throw new ArgumentNullException(nameof(body)); } if (string.IsNullOrEmpty(body.Data)) { throw new ArgumentNullException(nameof(body.Data)); } //todo improve this, hard coded as dev session id for now if (!CheckHeaderSession()) { //return Unauthorized(); } var time = body.CreatedAt ?? DateTime.Now; var item = new DtoClipboardItem() { Uid = Guid.NewGuid(), CreatedBy = MapToUserId(Request.Headers.GetValues(Constants.HeaderSessionId).First()), CreatedAt = time, Data = body.Data }; string path = GetFullClipboardDataPath(time); AppendNoteToFile(path, item); string indexPath = GetFullClipboardIndexPath(time); AppendObjectToFile(indexPath, DtoLskjsonIndex.From(item)); return(DtoResultV5.Success(Json, $"{body.Data.Length} characters saved to clipboard.")); }
/// <summary> /// This example uses the SocketLabs SDK PostBody object to create a POST /// request for sending one or more SMTP messages through Email-On-Demand. /// The SocketLabs SDK library is required, and for this example we also use /// the RestSharp library to ask as our serializer and client. /// /// The JSON request generated by this sample code looks like this: /// ///{ /// "ServerId": "YOUR SERVER ID HERE", /// "ApiKey": "YOUR API KEY HERE", /// "Messages": [{ /// "MailingId": null, /// "MessageId": null, /// "MergeData": null, /// "Subject": "Email subject line for SDK example.", /// "TextBody": "The text portion of the message.", /// "HtmlBody": "<h1>The HTML portion of the message</h1><br/><p>A paragraph.</p>", /// "CustomHeaders": null, /// "To": [{ /// "EmailAddress": "*****@*****.**", /// "FriendlyName": null /// }], /// "Cc": null, /// "Bcc": null, /// "From": { /// "EmailAddress": "*****@*****.**", /// "FriendlyName": "From Address" /// }, /// "ReplyTo": null, /// "Charset": null, /// "Attachments": null /// }] ///} /// </summary> public static void SimpleInjectionViaSdkObjectAsJson( int serverId, string yourApiKey, string apiUrl) { // The client object processes requests to the SocketLabs Injection API. var client = new RestClient(apiUrl); // Construct the object used to generate JSON for the POST request. var postBody = new PostBody { ServerId = serverId, ApiKey = yourApiKey, Messages = new[] { new EmailMessage { Subject = "Email subject line for SDK example.", To = new[] { new Address { EmailAddress = "*****@*****.**", FriendlyName = null } }, From = new Address { EmailAddress = "*****@*****.**", FriendlyName = "From Address" }, TextBody = "The text portion of the message.", HtmlBody = "<h1>The HTML portion of the message</h1><br/><p>A paragraph.</p>", } } }; try { // Generate a new POST request. var request = new RestRequest(Method.POST) { RequestFormat = DataFormat.Json }; // Store the request data in the request object. request.AddBody(postBody); // Make the POST request. var result = client.ExecuteAsPost<PostResponse>(request, "POST"); // Store the response result in our custom class. using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(result.Content))) { var serializer = new DataContractJsonSerializer(typeof (PostResponse)); var resp = (PostResponse) serializer.ReadObject(stream); // Display the results. if (resp.ErrorCode.Equals("Success")) { Console.WriteLine("Successful injection!"); } else { Console.WriteLine("Failed injection! Returned JSON is: "); Console.WriteLine(result.Content); } } } catch (Exception ex) { Console.WriteLine("Error, something bad happened: " + ex.Message); } }
/// <summary> /// This example uses the SocketLabs SDK PostBody object to create a POST /// request for sending one or more SMTP messages through Email-On-Demand. /// The SocketLabs SDK library is required, and for this example we also use /// the RestSharp library to ask as our serializer and client. /// /// We use as many fields as possible in this example, in order to show usage /// for most of our options in a single example. /// /// The JSON request generated by this sample code looks like this: /// ///{ /// "ServerId": "YOUR SERVER ID HERE", /// "ApiKey": "YOUR API KEY HERE", /// "Messages": [{ /// "MailingId": "Human Resources 017", /// "MessageId": "0000-9999-0000-9999-0000", /// "MergeData": null, /// "Subject": "Welcome to The ABC Company!", /// "TextBody": "Welcome to The ABC Company, new employees! You are all part of our new department.", /// "HtmlBody": "<h1>Welcome to The ABC Company, new employee!</h1><br/><p>You are all part of our new department.</p>", /// "CustomHeaders": [{ /// "Name": "Internal-Email-Type", /// "Value": "HR/New Employee" /// }], /// "To": [{ /// "EmailAddress": "*****@*****.**", /// "FriendlyName": "Robert Smith" /// }, /// { /// "EmailAddress": "*****@*****.**", /// "FriendlyName": "Alice White" /// }, /// { /// "EmailAddress": "*****@*****.**", /// "FriendlyName": "Christine Johnson" /// }], /// "Cc": [{ /// "EmailAddress": "*****@*****.**", /// "FriendlyName": "HR Department" /// }], /// "Bcc": [{ /// "EmailAddress": "*****@*****.**", /// "FriendlyName": "Email Logging Account" /// }], /// "From": { /// "EmailAddress": "*****@*****.**", /// "FriendlyName": "From Address" /// }, /// "ReplyTo": { /// "EmailAddress": "*****@*****.**", /// "FriendlyName": "HR Department" /// }, /// "Charset": "us-ascii", /// "Attachments": [{ /// "Name": "CompanyContacts.txt", /// "ContentType": "text/plain", /// "Content": "VEhJUyBJUyBUSEUgQVRUQUNITUVOVA==", /// "CustomHeaders": null, /// "ContentId": null /// }] /// }, /// { /// "MailingId": "%%MailingId%%", /// "MessageId": "%%CUSTOM-SERIAL-NUMBER-ID%%", /// "MergeData": { /// "PerMessage": [[{ /// "Field": "DeliveryAddress", /// "Value": "*****@*****.**" /// }, /// { /// "Field": "RecipientName", /// "Value": "Robert Smith" /// }, /// { /// "Field": "SeniorEmployeeName", /// "Value": "Elizabeth Johnson" /// }, /// { /// "Field": "CUSTOM-SERIAL-NUMBER-ID", /// "Value": "0000-0000-0000-8888-0001" /// }], /// [{ /// "Field": "DeliveryAddress", /// "Value": "*****@*****.**" /// }, /// { /// "Field": "RecipientName", /// "Value": "Alice White" /// }, /// { /// "Field": "SeniorEmployeeName", /// "Value": "Elizabeth Johnson" /// }, /// { /// "Field": "CUSTOM-SERIAL-NUMBER-ID", /// "Value": "0000-0000-0000-8888-0002" /// }], /// [{ /// "Field": "DeliveryAddress", /// "Value": "*****@*****.**" /// }, /// { /// "Field": "RecipientName", /// "Value": "Christine Johnson" /// }, /// { /// "Field": "SeniorEmployeeName", /// "Value": "Gary Brown" /// }, /// { /// "Field": "CUSTOM-SERIAL-NUMBER-ID", /// "Value": "0000-0000-0000-8888-0003" /// }]], /// "Global": [{ /// "Field": "MailingId", /// "Value": "Human Resources 018" /// }] /// }, /// "Subject": "Employee mentorship program information.", /// "TextBody": "%%RecipientName%%, you have been paired with %%SeniorEmployeeName%% as part of our mentorship program!", /// "HtmlBody": "<h1>%%RecipientName%%, you have been paired with %%SeniorEmployeeName%% as part of our mentorship program!</h1>", /// "CustomHeaders": null, /// "To": [{ /// "EmailAddress": "%%DeliveryAddress%%", /// "FriendlyName": "%%RecipientName%%" /// }], /// "Cc": null, /// "Bcc": null, /// "From": { /// "EmailAddress": "*****@*****.**", /// "FriendlyName": "HR Department" /// }, /// "ReplyTo": null, /// "Charset": null, /// "Attachments": null /// }] ///} /// </summary> public static void CompleteInjectionViaSdkObjectAsJson( int serverId, string yourApiKey, string apiUrl) { // The client object processes requests to the SocketLabs Injection API. var client = new RestClient(apiUrl); // In this example, we will utilize the majority of options available via // the Injection API. More details are noted inline as we use them. // // Construct the object(s) used to generate JSON for the POST request. // // For this example, we will create two messages in a single injection. var postBody = new PostBody { ServerId = serverId, ApiKey = yourApiKey, Messages = new EmailMessage[2] }; // The first of two messages to be injected; this example showcases // most of the options available with the exception of the inline Merge feature. postBody.Messages[0] = new EmailMessage { Subject = "Welcome to The ABC Company!", To = new[] { new Address { EmailAddress = "*****@*****.**", FriendlyName = "Robert Smith" }, new Address { EmailAddress = "*****@*****.**", FriendlyName = "Alice White" }, new Address { EmailAddress = "*****@*****.**", FriendlyName = "Christine Johnson" } }, Cc = new[] { new Address { EmailAddress = "*****@*****.**", FriendlyName = "HR Department" } }, Bcc = new[] { new Address { EmailAddress = "*****@*****.**", FriendlyName = "Email Logging Account" } }, From = new Address { EmailAddress = "*****@*****.**", FriendlyName = "From Address" }, ReplyTo = new Address { EmailAddress = "*****@*****.**", FriendlyName = "HR Department" }, // Please see the API documentation for information on using the MailingId and MessageId // fields for tracking groups of messages. MailingId = "Human Resources 017", MessageId = "0000-9999-0000-9999-0000", Charset = "us-ascii", TextBody = "Welcome to The ABC Company, new employees! You are all part of our new department.", HtmlBody = "<h1>Welcome to The ABC Company, new employee!</h1><br/><p>You are all part of our new department.</p>", // Custom SMTP headers are defined in this way. CustomHeaders = new[] { new CustomHeader { Name = "Internal-Email-Type", Value = "HR/New Employee" } }, // Multiple attachments can be added to a message. Attachments = new[] { new Attachment { Name = "CompanyContacts.txt", ContentType = "text/plain", Content = Convert.ToBase64String(Encoding.ASCII.GetBytes("THIS IS THE ATTACHMENT")), } }, }; // The second of two messages to be injected; this example shows how // to use the inline Merge feature, which customizes a message for its // recipients. postBody.Messages[1] = new EmailMessage { Subject = "Employee mentorship program information.", To = new[] { // DeliveryAddress is required for all inline merges. Additionally, any other addresses // used in the To, Cc, or Bcc fields will be for header display only, and will not receive // the injected email. Only the DeliveryAddress members will receive the injected message. new Address { EmailAddress = "%%DeliveryAddress%%", FriendlyName = "%%RecipientName%%" } }, From = new Address { EmailAddress = "*****@*****.**", FriendlyName = "HR Department" }, MailingId = "%%MailingId%%", // Merge field variables can go anywhere else in the message. A basic use would be to define // a unique MessageId for each outgoing message. MessageId = "%%CUSTOM-SERIAL-NUMBER-ID%%", // We can even reuse the same variable multiple times, such as %%RecipientName%% being used both // to define the name of the recipient in the header, and for addressing the recipient in the // message body. TextBody = "%%RecipientName%%, you have been paired with %%SeniorEmployeeName%% as part of our mentorship program!", HtmlBody = "<h1>%%RecipientName%%, you have been paired with %%SeniorEmployeeName%% as part of our mentorship program!</h1>", }; // Values for each of the merge data fields need to be added. postBody.Messages[1].MergeData = new MergeData(); // Global variables apply to all recipients in the same way. postBody.Messages[1].MergeData.Global = new MergeRow[1]; postBody.Messages[1].MergeData.Global[0] = new MergeRow("MailingId", "Human Resources 018"); // Per-Message variables are unique to each recipient. postBody.Messages[1].MergeData.PerMessage = new MergeRow[3][]; // Recipient 1 of 3 postBody.Messages[1].MergeData.PerMessage[0] = new MergeRow[4]; postBody.Messages[1].MergeData.PerMessage[0][0] = new MergeRow("DeliveryAddress", "*****@*****.**"); postBody.Messages[1].MergeData.PerMessage[0][1] = new MergeRow("RecipientName", "Robert Smith"); postBody.Messages[1].MergeData.PerMessage[0][2] = new MergeRow("SeniorEmployeeName", "Elizabeth Johnson"); postBody.Messages[1].MergeData.PerMessage[0][3] = new MergeRow("CUSTOM-SERIAL-NUMBER-ID", "0000-0000-0000-8888-0001"); // Recipient 2 of 3 postBody.Messages[1].MergeData.PerMessage[1] = new MergeRow[4]; postBody.Messages[1].MergeData.PerMessage[1][0] = new MergeRow("DeliveryAddress", "*****@*****.**"); postBody.Messages[1].MergeData.PerMessage[1][1] = new MergeRow("RecipientName", "Alice White"); postBody.Messages[1].MergeData.PerMessage[1][2] = new MergeRow("SeniorEmployeeName", "Elizabeth Johnson"); postBody.Messages[1].MergeData.PerMessage[1][3] = new MergeRow("CUSTOM-SERIAL-NUMBER-ID", "0000-0000-0000-8888-0002"); // Recipient 3 of 3 postBody.Messages[1].MergeData.PerMessage[2] = new MergeRow[4]; postBody.Messages[1].MergeData.PerMessage[2][0] = new MergeRow("DeliveryAddress", "*****@*****.**"); postBody.Messages[1].MergeData.PerMessage[2][1] = new MergeRow("RecipientName", "Christine Johnson"); postBody.Messages[1].MergeData.PerMessage[2][2] = new MergeRow("SeniorEmployeeName", "Gary Brown"); postBody.Messages[1].MergeData.PerMessage[2][3] = new MergeRow("CUSTOM-SERIAL-NUMBER-ID", "0000-0000-0000-8888-0003"); try { // Generate a new POST request. var request = new RestRequest(Method.POST) { RequestFormat = DataFormat.Json }; // Store the request data in the request object. request.AddBody(postBody); // Make the POST request. var result = client.ExecuteAsPost(request, "POST"); // Store the response result in our custom class. using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(result.Content))) { var serializer = new DataContractJsonSerializer(typeof (PostResponse)); var resp = (PostResponse) serializer.ReadObject(stream); // Display the results. if (resp.ErrorCode.Equals("Success")) { Console.WriteLine("Successful injection!"); } else { Console.WriteLine("Failed injection! Returned JSON is: "); Console.WriteLine(result.Content); } } } catch (Exception ex) { Console.WriteLine("Error, something bad happened: " + ex.Message); } }