public static void Run(ILogger logger) { OnlineClient client = Bootstrap.Client(logger); logger.LogInformation("Executing create test object function to API"); TestObjectCreate create = new TestObjectCreate() { Name = "hello world", }; Task <OnlineResponse> createTask = client.Execute(create); createTask.Wait(); OnlineResponse createResponse = createTask.Result; Result createResult = createResponse.Results[0]; try { int recordNo = int.Parse(createResult.Data[0].Element("id").Value); Console.WriteLine("Created record ID " + recordNo.ToString()); } catch (NullReferenceException e) { logger.LogDebug("No response in Data. {0}", e); } finally { LogManager.Flush(); } }
/// <summary> /// Create a new session-based ClientConfig, based on a different ClientConfig /// </summary> /// <param name="config"></param> /// <returns></returns> /// <exception cref="IntacctException"></exception> public static async Task <ClientConfig> Factory(ClientConfig config = null) { if (config == null) { config = new ClientConfig(); } RequestConfig requestConfig = new RequestConfig() { ControlId = "sessionProvider", NoRetryServerErrorCodes = new int[] { }, // Retry all 500 level errors }; OnlineClient client = new OnlineClient(config); OnlineResponse response = await client.Execute(new ApiSessionCreate(), requestConfig); Authentication authentication = response.Authentication; Result result = response.Results[0]; result.EnsureStatusSuccess(); // Throw any result errors List <XElement> data = result.Data; XElement api = data[0]; config.SessionId = api.Element("sessionid").Value; config.EndpointUrl = api.Element("endpoint").Value; config.CompanyId = authentication.CompanyId; config.UserId = authentication.UserId; config.Credentials = new SessionCredentials(config, new SenderCredentials(config)); return(config); }
public async Task ExecuteTest() { string xml = @"<?xml version=""1.0"" encoding=""utf-8""?> <response> <control> <status>success</status> <senderid>testsenderid</senderid> <controlid>requestUnitTest</controlid> <uniqueid>false</uniqueid> <dtdversion>3.0</dtdversion> </control> <operation> <authentication> <status>success</status> <userid>testuser</userid> <companyid>testcompany</companyid> <sessiontimestamp>2015-12-06T15:57:08-08:00</sessiontimestamp> </authentication> <result> <status>success</status> <function>getAPISession</function> <controlid>func1UnitTest</controlid> <data> <api> <sessionid>unittest..</sessionid> <endpoint>https://unittest.intacct.com/ia/xml/xmlgw.phtml</endpoint> </api> </data> </result> </operation> </response>"; HttpResponseMessage mockResponse1 = new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK, Content = new StringContent(xml) }; List <HttpResponseMessage> mockResponses = new List <HttpResponseMessage> { mockResponse1, }; MockHandler mockHandler = new MockHandler(mockResponses); ClientConfig clientConfig = new ClientConfig { SenderId = "testsender", SenderPassword = "******", SessionId = "testsession..", MockHandler = mockHandler, }; OnlineClient client = new OnlineClient(clientConfig); OnlineResponse response = await client.Execute(new ApiSessionCreate("func1UnitTest")); Assert.Equal("requestUnitTest", response.Control.ControlId); }
public void StatusAbortedTest() { string xml = @"<?xml version=""1.0"" encoding=""utf-8""?> <response> <control> <status>success</status> <senderid>testsenderid</senderid> <controlid>ControlIdHere</controlid> <uniqueid>false</uniqueid> <dtdversion>3.0</dtdversion> </control> <operation> <authentication> <status>success</status> <userid>fakeuser</userid> <companyid>fakecompany</companyid> <locationid></locationid> <sessiontimestamp>2015-10-25T10:08:34-07:00</sessiontimestamp> </authentication> <result> <status>aborted</status> <function>readByQuery</function> <controlid>testFunctionId</controlid> <errormessage> <error> <errorno>Query Failed</errorno> <description></description> <description2>Object definition VENDOR9 not found</description2> <correction></correction> </error> <error> <errorno>XL03000009</errorno> <description></description> <description2>The entire transaction in this operation has been rolled back due to an error.</description2> <correction></correction> </error> </errormessage> </result> </operation> </response>"; Stream stream = new MemoryStream(); StreamWriter streamWriter = new StreamWriter(stream); streamWriter.Write(xml); streamWriter.Flush(); stream.Position = 0; OnlineResponse response = new OnlineResponse(stream); Result result = response.Results[0]; var ex = Record.Exception(() => result.EnsureStatusSuccess()); Assert.IsType <ResultException>(ex); Assert.Equal("Result status: aborted for Control ID: testFunctionId - Query Failed Object definition VENDOR9 not found - XL03000009 The entire transaction in this operation has been rolled back due to an error.", ex.Message); }
protected async Task <OnlineResponse> ExecuteOnlineRequest(List <IFunction> functions, RequestConfig requestConfig = null) { if (requestConfig == null) { requestConfig = new RequestConfig(); } RequestHandler requestHandler = new RequestHandler(this.Config, requestConfig); OnlineResponse response = await requestHandler.ExecuteOnline(functions).ConfigureAwait(false); return(response); }
public void StatusFailureTest() { string xml = @"<?xml version=""1.0"" encoding=""utf-8""?> <response> <control> <status>success</status> <senderid>testsenderid</senderid> <controlid>ControlIdHere</controlid> <uniqueid>false</uniqueid> <dtdversion>3.0</dtdversion> </control> <operation> <authentication> <status>success</status> <userid>fakeuser</userid> <companyid>fakecompany</companyid> <locationid></locationid> <sessiontimestamp>2015-10-25T10:08:34-07:00</sessiontimestamp> </authentication> <result> <status>failure</status> <function>read</function> <controlid>testFunctionId</controlid> <errormessage> <error> <errorno>XXX</errorno> <description></description> <description2>Object definition VENDOR2 not found</description2> <correction></correction> </error> </errormessage> </result> </operation> </response>"; Stream stream = new MemoryStream(); StreamWriter streamWriter = new StreamWriter(stream); streamWriter.Write(xml); streamWriter.Flush(); stream.Position = 0; OnlineResponse response = new OnlineResponse(stream); Result result = response.Results[0]; var ex = Record.Exception(() => result.EnsureStatusNotFailure()); Assert.IsType <ResultException>(ex); Assert.Equal("Result status: failure for Control ID: testFunctionId - XXX Object definition VENDOR2 not found", ex.Message); }
public static void Run(ILogger logger) { OnlineClient client = Bootstrap.Client(logger); Read read = new Read() { ObjectName = "CUSTOMER", Fields = { "RECORDNO", "CUSTOMERID", "NAME", }, Keys = { 33 // Replace with the record number of a customer in your company } }; Task <OnlineResponse> task = client.Execute(read); task.Wait(); OnlineResponse response = task.Result; Result result = response.Results[0]; dynamic json = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(result.Data)); try { string jsonString = json.ToString(); logger.LogDebug( "Read successful [ Company ID={0}, User ID={1}, Request control ID={2}, Function control ID={3}, Total count={4}, Data={5}]", response.Authentication.CompanyId, response.Authentication.UserId, response.Control.ControlId, result.ControlId, result.TotalCount, jsonString ); Console.WriteLine("Success! Found these customers: " + json); } catch (NullReferenceException e) { logger.LogDebug("No response in Data. {0}", e); } finally { LogManager.Flush(); } }
public void SuccessTest() { string xml = @"<?xml version=""1.0"" encoding=""utf-8""?> <response> <control> <status>success</status> <senderid>testsenderid</senderid> <controlid>ControlIdHere</controlid> <uniqueid>false</uniqueid> <dtdversion>3.0</dtdversion> </control> <operation> <authentication> <status>success</status> <userid>fakeuser</userid> <companyid>fakecompany</companyid> <locationid></locationid> <sessiontimestamp>2015-10-24T18:56:52-07:00</sessiontimestamp> </authentication> <result> <status>success</status> <function>getAPISession</function> <controlid>testControlId</controlid> <data> <api> <sessionid>faKEsesSiOnId..</sessionid> <endpoint>https://api.intacct.com/ia/xml/xmlgw.phtml</endpoint> <locationid></locationid> </api> </data> </result> </operation> </response>"; Stream stream = new MemoryStream(); StreamWriter streamWriter = new StreamWriter(stream); streamWriter.Write(xml); streamWriter.Flush(); stream.Position = 0; OnlineResponse response = new OnlineResponse(stream); Authentication auth = response.Authentication; Assert.Equal("success", auth.Status); Assert.Equal("fakeuser", auth.UserId); Assert.Equal("fakecompany", auth.CompanyId); Assert.Equal("", auth.EntityId); }
/// <summary> /// Sends a Hours Journal to the Intacct STATISTIC System /// </summary> /// <param name="client"></param> /// <param name="Org"></param> /// <param name="lines"></param> /// <param name="PostingDate"></param> /// <param name="ReferenceNumber"></param> /// <param name="JournalSymbol"></param> /// <param name="Description"></param> /// <param name="HistoryComment"></param> /// <param name="AsDraft"></param> /// <returns></returns> private async Task SendStatHoursJournalCmd(OnlineClient client, int Org, IEnumerable <IntacctStatHours> lines, DateTime PostingDate, string ReferenceNumber, string JournalSymbol, string Description, string HistoryComment, bool AsDraft) { StatisticalJournalEntryCreate create = new StatisticalJournalEntryCreate(); create.JournalSymbol = JournalSymbol; create.ReferenceNumber = ReferenceNumber; create.PostingDate = PostingDate; create.Description = Description; create.HistoryComment = HistoryComment; if (AsDraft) { create.CustomFields.Add("STATE", "Draft"); } foreach (var item in lines) { StatisticalJournalEntryLineCreate line = new StatisticalJournalEntryLineCreate { StatAccountNumber = item.Account, Amount = decimal.Parse(item.Hours.ToString("F2")), Memo = $"Part of Practice Engine Batch #{item.BatchID}" }; if (!String.IsNullOrWhiteSpace(item.EmployeeID)) { line.EmployeeId = item.EmployeeID; } if (!String.IsNullOrWhiteSpace(item.ProjectID)) { line.ProjectId = item.ProjectID; } if (!String.IsNullOrWhiteSpace(item.IntacctCustomerID)) { line.CustomerId = item.IntacctCustomerID; } if (!String.IsNullOrWhiteSpace(item.IntacctDepartment)) { line.DepartmentId = item.IntacctDepartment; } if (!String.IsNullOrWhiteSpace(item.IntacctLocation)) { line.LocationId = item.IntacctLocation; } create.Lines.Add(line); } OnlineResponse onlineResponse = await client.Execute(create); foreach (var result in onlineResponse.Results) { result.EnsureStatusSuccess(); } }
/// <summary> /// Sends a Journal to the Intacct GL System /// </summary> /// <param name="client"></param> /// <param name="Org"></param> /// <param name="lines"></param> /// <param name="PostingDate"></param> /// <param name="ReferenceNumber"></param> /// <param name="JournalSymbol"></param> /// <param name="Description"></param> /// <param name="HistoryComment"></param> /// <param name="AsDraft"></param> /// <returns></returns> private async Task SendJournalCmd(OnlineClient client, int Org, IEnumerable <JournalExtract> lines, DateTime PostingDate, string ReferenceNumber, string JournalSymbol, string Description, string HistoryComment, bool AsDraft) { JournalEntryCreate create = new JournalEntryCreate(); create.JournalSymbol = JournalSymbol; create.ReferenceNumber = ReferenceNumber; create.PostingDate = PostingDate; create.Description = Description; create.HistoryComment = HistoryComment; if (AsDraft) { create.CustomFields.Add("STATE", "Draft"); } foreach (var item in lines) { JournalEntryLineCreate line = new JournalEntryLineCreate { GlAccountNumber = item.AccountCode, TransactionAmount = decimal.Parse(item.NomAmount.ToString("F2")), Memo = String.IsNullOrWhiteSpace(item.NomTransRef) ? item.NomNarrative : item.NomNarrative + " (" + item.NomTransRef + ")" }; if (!String.IsNullOrWhiteSpace(item.IntacctCustomerID)) { line.CustomerId = item.IntacctCustomerID; } if (!String.IsNullOrWhiteSpace(item.IntacctEmployeeID)) { line.EmployeeId = item.IntacctEmployeeID; } if (!String.IsNullOrWhiteSpace(item.IntacctProjectID)) { line.ProjectId = item.IntacctProjectID; } if (!String.IsNullOrWhiteSpace(item.IntacctDepartment)) { line.DepartmentId = item.IntacctDepartment; } if (!String.IsNullOrWhiteSpace(item.IntacctLocation)) { line.LocationId = item.IntacctLocation; } create.Lines.Add(line); } OnlineResponse onlineResponse = await client.Execute(create); foreach (var result in onlineResponse.Results) { result.EnsureStatusSuccess(); } }
public void GetErrorsTest() { string xml = @"<?xml version=""1.0"" encoding=""utf-8""?> <response> <control> <status>success</status> <senderid>testsenderid</senderid> <controlid>ControlIdHere</controlid> <uniqueid>false</uniqueid> <dtdversion>3.0</dtdversion> </control> <operation> <authentication> <status>success</status> <userid>fakeuser</userid> <companyid>fakecompany</companyid> <locationid></locationid> <sessiontimestamp>2015-10-25T11:07:22-07:00</sessiontimestamp> </authentication> <result> <status>failure</status> <function>readByQuery</function> <controlid>testControlId</controlid> <errormessage> <error> <errorno>Query Failed</errorno> <description></description> <description2>Object definition BADOBJECT not found</description2> <correction></correction> </error> </errormessage> </result> </operation> </response>"; Stream stream = new MemoryStream(); StreamWriter streamWriter = new StreamWriter(stream); streamWriter.Write(xml); streamWriter.Flush(); stream.Position = 0; OnlineResponse response = new OnlineResponse(stream); var result = response.Results[0]; Assert.Equal("failure", result.Status); Assert.IsType <List <string> >(result.Errors); }
public void GetOperationTest() { string xml = @"<?xml version=""1.0"" encoding=""utf-8""?> <response> <control> <status>success</status> <senderid>testsenderid</senderid> <controlid>ControlIdHere</controlid> <uniqueid>false</uniqueid> <dtdversion>3.0</dtdversion> </control> <operation> <authentication> <status>success</status> <userid>fakeuser</userid> <companyid>fakecompany</companyid> <locationid></locationid> <sessiontimestamp>2015-10-22T20:58:27-07:00</sessiontimestamp> </authentication> <result> <status>success</status> <function>getAPISession</function> <controlid>testControlId</controlid> <data> <api> <sessionid>fAkESesSiOnId..</sessionid> <endpoint>https://api.intacct.com/ia/xml/xmlgw.phtml</endpoint> <locationid></locationid> </api> </data> </result> </operation> </response>"; Stream stream = new MemoryStream(); StreamWriter streamWriter = new StreamWriter(stream); streamWriter.Write(xml); streamWriter.Flush(); stream.Position = 0; OnlineResponse response = new OnlineResponse(stream); Assert.IsType <List <Result> >(response.Results); }
public void SuccessTest() { string xml = @"<?xml version=""1.0"" encoding=""utf-8""?> <response> <control> <status>success</status> <senderid>testsenderid</senderid> <controlid>ControlIdHere</controlid> <uniqueid>false</uniqueid> <dtdversion>3.0</dtdversion> </control> <operation> <authentication> <status>success</status> <userid>fakeuser</userid> <companyid>fakecompany</companyid> <locationid></locationid> <sessiontimestamp>2015-10-25T10:08:34-07:00</sessiontimestamp> </authentication> <result> <status>success</status> <function>readByQuery</function> <controlid>testControlId</controlid> <data listtype=""department"" count=""0"" totalcount=""0"" numremaining=""0"" resultId=""""/> </result> </operation> </response>"; Stream stream = new MemoryStream(); StreamWriter streamWriter = new StreamWriter(stream); streamWriter.Write(xml); streamWriter.Flush(); stream.Position = 0; OnlineResponse response = new OnlineResponse(stream); var result = response.Results[0]; Assert.IsType <Result>(result); Assert.Equal("success", result.Status); Assert.Equal("readByQuery", result.Function); Assert.Equal("testControlId", result.ControlId); Assert.IsType <List <XElement> >(result.Data); result.EnsureStatusSuccess(); }
/// <summary> /// Execute one Intacct API function /// </summary> /// <param name="apiFunction"></param> /// <param name="requestConfig"></param> /// <returns></returns> public async Task <OnlineResponse> Execute(IFunction apiFunction, RequestConfig requestConfig = null) { if (requestConfig == null) { requestConfig = new RequestConfig(); } List <IFunction> apiFunctions = new List <IFunction> { apiFunction }; OnlineResponse response = await this.ExecuteOnlineRequest(apiFunctions, requestConfig).ConfigureAwait(false); response.Results[0].EnsureStatusSuccess(); return(response); }
/// <summary> /// Execute multiple Intacct API functions /// </summary> /// <param name="apiFunctions"></param> /// <param name="requestConfig"></param> /// <returns></returns> public async Task <OnlineResponse> ExecuteBatch(List <IFunction> apiFunctions, RequestConfig requestConfig = null) { if (requestConfig == null) { requestConfig = new RequestConfig(); } OnlineResponse response = await this.ExecuteOnlineRequest(apiFunctions, requestConfig).ConfigureAwait(false); if (requestConfig.Transaction == true) { foreach (Result result in response.Results) { result.EnsureStatusNotFailure(); } } return(response); }
public void LegacyCreateClassKeyTest() { string xml = @"<?xml version=""1.0"" encoding=""utf-8""?> <response> <control> <status>success</status> <senderid>testsenderid</senderid> <controlid>ControlIdHere</controlid> <uniqueid>false</uniqueid> <dtdversion>3.0</dtdversion> </control> <operation> <authentication> <status>success</status> <userid>fakeuser</userid> <companyid>fakecompany</companyid> <locationid></locationid> <sessiontimestamp>2015-10-25T10:08:34-07:00</sessiontimestamp> </authentication> <result> <status>success</status> <function>create_class</function> <controlid>d4814563-1e97-4708-b9c5-9a49569d2a0d</controlid> <key>C1234</key> </result> </operation> </response>"; Stream stream = new MemoryStream(); StreamWriter streamWriter = new StreamWriter(stream); streamWriter.Write(xml); streamWriter.Flush(); stream.Position = 0; OnlineResponse response = new OnlineResponse(stream); Result result = response.Results[0]; Assert.Equal("C1234", result.Key); }
public IActionResult Online([FromQuery] Request <OnlineRequest> request) { var shapshots = new List <OnlineResponse.OnlineSnapshot>(); var response = new OnlineResponse { Snapshots = shapshots }; var personIds = request.Data.PersonIds.IsNullOrEmpty() ? null : request.Data.PersonIds; var validPersonIds = _personRepository.Select(p => personIds == null || personIds.Contains(p.Id), p => p.Id).ToArray(); if (validPersonIds.IsEmpty()) { return(this.ApiResult(request, response)); } foreach (var watch in _watches) { var webResourceId = watch.WebResourceId; var onlineTimelines = watch.GetOnlineTimelines(request.Data.Begin, request.Data.End, validPersonIds); shapshots.AddRange(onlineTimelines.Select(onlineTimeline => new OnlineResponse.OnlineSnapshot { From = onlineTimeline.From, PersonId = onlineTimeline.PersonId, WebResourceId = webResourceId, AccountId = onlineTimeline.AccountId, Chunks = onlineTimeline.Chunks.Select(c => new OnlineResponse.TimelineChunk { OnlineType = c.OnlineType, OnlineMeta = c.OnlineMeta, Length = c.Length }) })); } return(this.ApiResult(request, response)); }
public SensiConnection() { Trace.WriteLine("SensiConnection ctor"); this._cookieJar = new CookieContainer(); this._hubConnection = new HubConnection(_urlBase + "realtime", false); this._hubConnection.CookieContainer = this._cookieJar; this._hubProxy = this._hubConnection.CreateHubProxy("thermostat-v1"); this._subscriptions = new List <string>(); this._hubConnection.StateChanged += (state) => { Debug.WriteLine($"State Changed from {state.OldState} to {state.NewState}"); }; this._hubConnection.ConnectionSlow += () => { Debug.WriteLine("Connection Slow"); }; this._hubConnection.Reconnected += () => { Debug.WriteLine("Reconnected"); }; this._hubConnection.Reconnecting += () => { Debug.WriteLine("Reconnecting"); }; this._hubConnection.Error += async(ex) => { Trace.WriteLine(ex, "HubConnection Error"); if (ex is System.Net.WebException) { if (((System.Net.WebException)ex).Status == WebExceptionStatus.ProtocolError) { var response = ((System.Net.WebException)ex).Response as HttpWebResponse; if (response != null && ( response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.InternalServerError) ) { Trace.WriteLine("Restarting Realtime due to WebExpection"); while (await this.BeginRealtime() == false) { Trace.WriteLine("Not Connected, Delaying..."); this.StopRealtime(); await Task.Delay(5000); } foreach (var sub in _subscriptions) { Trace.WriteLine("Attempt Re-Subscription for " + sub); this.Subscribe(sub).Wait(); } return; } } } else if (ex is System.Net.Sockets.SocketException) { Trace.WriteLine("Restarting Realtime due to SocketException"); while (await this.BeginRealtime() == false) { Trace.WriteLine("Not Connected, Delaying..."); this.StopRealtime(); await Task.Delay(5000); } foreach (var sub in _subscriptions) { Trace.WriteLine("Attempt Re-Subscription for " + sub); this.Subscribe(sub).Wait(); } return; } }; this._hubConnection.Received += (data) => { Debug.WriteLine("Data Received"); }; this._hubProxy.On <object>("initalized", (data) => { Trace.WriteLine(data, "Initalized"); }); this._hubProxy.On <object, object>("online", (icd, data) => { //Trace.WriteLine(Environment.NewLine + data, $"Received Online Message for ICD [{icd}]"); Trace.WriteLine($"Received Online Message for ICD [{icd}]"); this.LastUpdateReceived = DateTime.Now; try { var msg = JsonConvert.DeserializeObject <OnlineResponse>(data.ToString()); var args = (ThermostatOnlineEventArgs)msg; args.Icd = icd.ToString(); ThermostatOnline?.Invoke(this, args); } catch (Exception ex) { Trace.WriteLine(ex); } }); this._hubProxy.On <object, object>("update", (icd, data) => { //Trace.WriteLine(Environment.NewLine + data, $"Received Update Message for ICD [{icd}]"); Trace.WriteLine($"Received Update Message for ICD [{icd}]"); this.LastUpdateReceived = DateTime.Now; OnlineResponse msg = null; try { msg = JsonConvert.DeserializeObject <OnlineResponse>(data.ToString()); } catch (Exception ex) { Trace.WriteLine(ex); } if (msg != null) { if (msg != null && msg.OperationalStatus != null) { OperationalStatusUpdated?.Invoke(this, new OperationalStatusUpdatedEventArgs { Icd = icd.ToString(), OperationalStatus = msg.OperationalStatus }); } if (msg != null && msg.EnvironmentControls != null) { EnvironmentalControlsUpdated?.Invoke(this, new EnvironmentalControlsUpdatedEventArgs { Icd = icd.ToString(), EnvironmentControls = msg.EnvironmentControls }); } if (msg != null && msg.Capabilities != null) { CapabilitiesUpdated?.Invoke(this, new CapabilitiesUpdatedEventArgs { Icd = icd.ToString(), Capabilities = msg.Capabilities }); } if (msg != null && msg.Settings != null) { SettingsUpdated?.Invoke(this, new SettingsUpdatedEventArgs { Icd = icd.ToString(), Settings = msg.Settings }); } if (msg != null && msg.Product != null) { ProductUpdated?.Invoke(this, new ProductUpdatedEventArgs { Icd = icd.ToString(), Product = msg.Product }); } } }); this._hubProxy.On <object, object>("offline", (icd, data) => { //Trace.WriteLine(Environment.NewLine + data, $"Received Offline Message for ICD [{icd}]"); Trace.WriteLine($"Received Offline Message for ICD [{icd}]"); this.LastUpdateReceived = DateTime.Now; }); }
public static void Run(ILogger logger) { OnlineClient client = Bootstrap.Client(logger); logger.LogInformation("Executing CRUD customer functions to API"); CustomerCreate create = new CustomerCreate() { CustomerName = "Joshua Granley", Active = false, }; Task <OnlineResponse> createTask = client.Execute(create); createTask.Wait(); OnlineResponse createResponse = createTask.Result; Result createResult = createResponse.Results[0]; string customerId = createResult.Data[0].Element("CUSTOMERID").Value; int recordNo = int.Parse(createResult.Data[0].Element("RECORDNO").Value); Console.WriteLine("Created inactive customer ID " + customerId); CustomerUpdate update = new CustomerUpdate() { CustomerId = customerId, Active = true, }; Task <OnlineResponse> updateTask = client.Execute(update); updateTask.Wait(); Console.WriteLine("Updated customer ID " + customerId + " to active"); Read read = new Read() { ObjectName = "CUSTOMER", Fields = { "RECORDNO", "CUSTOMERID", "STATUS", }, Keys = { recordNo, } }; Task <OnlineResponse> readTask = client.Execute(read); readTask.Wait(); Console.WriteLine("Read customer ID " + customerId); CustomerDelete delete = new CustomerDelete() { CustomerId = customerId, }; Task <OnlineResponse> deleteTask = client.Execute(delete); deleteTask.Wait(); Console.WriteLine("Deleted customer ID " + customerId); LogManager.Flush(); }
public async Task LoggerTest() { string xml = @"<?xml version=""1.0"" encoding=""utf-8""?> <response> <control> <status>success</status> <senderid>testsenderid</senderid> <controlid>requestUnitTest</controlid> <uniqueid>false</uniqueid> <dtdversion>3.0</dtdversion> </control> <operation> <authentication> <status>success</status> <userid>testuser</userid> <companyid>testcompany</companyid> <locationid></locationid> <sessiontimestamp>2015-12-06T15:57:08-08:00</sessiontimestamp> </authentication> <result> <status>success</status> <function>readByQuery</function> <controlid>func1UnitTest</controlid> <data listtype=""customer"" count=""1"" totalcount=""1"" numremaining=""0"" resultId=""""> <customer> <CUSTOMERID>C0001</CUSTOMERID> <NAME>Intacct Corporation</NAME> </customer> </data> </result> </operation> </response>"; HttpResponseMessage mockResponse1 = new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK, Content = new StringContent(xml) }; List <HttpResponseMessage> mockResponses = new List <HttpResponseMessage> { mockResponse1, }; MockHandler mockHandler = new MockHandler(mockResponses); var guid = Guid.NewGuid().ToString(); MemoryTarget target = new MemoryTarget { Name = guid, Layout = "${message}" }; SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); ClientConfig config = new ClientConfig { SenderId = "testsender", SenderPassword = "******", SessionId = "testsession..", MockHandler = mockHandler, Logger = LogManager.GetLogger(guid), }; OnlineClient client = new OnlineClient(config); OnlineResponse response = await client.Execute(new ReadByQuery("func1UnitTest")); Assert.True(true); // TODO fix this test from randomly failing //Assert.Contains("<password>REDACTED</password>", target.Logs[0]); }
public static void Run(ILogger logger) { OnlineClient client = Bootstrap.Client(logger); ReadByQuery query = new ReadByQuery() { ObjectName = "VENDOR", PageSize = 2, // Keep the count to just 2 for the example Fields = { "RECORDNO", "VENDORID", } }; logger.LogInformation("Executing query to Intacct API"); Task <OnlineResponse> task = client.Execute(query); task.Wait(); OnlineResponse response = task.Result; Result result = response.Results[0]; try { dynamic json = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(result.Data)); string jsonString = json.ToString(); logger.LogDebug( "Query successful - page 1 [ Total count={0}, Data={1} ]", result.TotalCount, jsonString ); Console.WriteLine("Page 1 success! Number of vendor objects found: " + result.TotalCount + ". Number remaining: " + result.NumRemaining); } catch (NullReferenceException e) { logger.LogDebug("No response in Data. {0}", e); } LogManager.Flush(); int i = 1; while (result.NumRemaining > 0 && i <= 3 && !string.IsNullOrEmpty(result.ResultId)) { i++; ReadMore more = new ReadMore() { ResultId = result.ResultId }; Task <OnlineResponse> taskMore = client.Execute(more); taskMore.Wait(); OnlineResponse responseMore = taskMore.Result; Result resultMore = responseMore.Results[0]; try { dynamic resultMoreJson = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(resultMore.Data)); string resultMoreJsonString = resultMoreJson.ToString(); logger.LogDebug( "Read More successful - page " + i + " [ Total remaining={0}, Data={1} ]", resultMore.NumRemaining, resultMoreJsonString ); Console.WriteLine("Page " + i + " success! Records remaining: " + resultMore.NumRemaining); } catch (NullReferenceException e) { logger.LogDebug("No response in Data. {0}", e); } finally { LogManager.Flush(); } } Console.WriteLine("Successfully read " + i + " pages"); }
public async Task MockExecuteSynchronousTest() { string xml = @"<?xml version=""1.0"" encoding=""UTF-8""?> <response> <control> <status>success</status> <senderid>testsenderid</senderid> <controlid>sessionProvider</controlid> <uniqueid>false</uniqueid> <dtdversion>3.0</dtdversion> </control> <operation> <authentication> <status>success</status> <userid>testuser</userid> <companyid>testcompany</companyid> <sessiontimestamp>2015-12-06T15:57:08-08:00</sessiontimestamp> </authentication> <result> <status>success</status> <function>getAPISession</function> <controlid>func1UnitTest</controlid> <data> <api> <sessionid>unittest..</sessionid> <endpoint>https://unittest.intacct.com/ia/xml/xmlgw.phtml</endpoint> </api> </data> </result> </operation> </response>"; HttpResponseMessage mockResponse = new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK, Content = new StringContent(xml) }; List <HttpResponseMessage> mockResponses = new List <HttpResponseMessage> { mockResponse, }; MockHandler mockHandler = new MockHandler(mockResponses); ClientConfig clientConfig = new ClientConfig() { SenderId = "testsenderid", SenderPassword = "******", SessionId = "testsession..", MockHandler = mockHandler, }; RequestConfig requestConfig = new RequestConfig() { ControlId = "unittest", }; List <IFunction> contentBlock = new List <IFunction> { new ApiSessionCreate() }; RequestHandler requestHandler = new RequestHandler(clientConfig, requestConfig); OnlineResponse response = await requestHandler.ExecuteOnline(contentBlock); Assert.IsType <OnlineResponse>(response); }
public void ReadByQueryClassTest() { string xml = @"<?xml version=""1.0"" encoding=""utf-8""?> <response> <control> <status>success</status> <senderid>testsenderid</senderid> <controlid>ControlIdHere</controlid> <uniqueid>false</uniqueid> <dtdversion>3.0</dtdversion> </control> <operation> <authentication> <status>success</status> <userid>fakeuser</userid> <companyid>fakecompany</companyid> <locationid></locationid> <sessiontimestamp>2015-10-25T10:08:34-07:00</sessiontimestamp> </authentication> <result> <status>success</status> <function>readByQuery</function> <controlid>818b0a96-3faf-4931-97e6-1cf05818ea44</controlid> <data listtype=""class"" count=""1"" totalcount=""2"" numremaining=""1"" resultId=""myResultId""> <class> <RECORDNO>8</RECORDNO> <CLASSID>C1234</CLASSID> <NAME>hello world</NAME> <DESCRIPTION></DESCRIPTION> <STATUS>active</STATUS> <PARENTKEY></PARENTKEY> <PARENTID></PARENTID> <PARENTNAME></PARENTNAME> <WHENCREATED>07/24/2017 15:19:46</WHENCREATED> <WHENMODIFIED>07/24/2017 15:19:46</WHENMODIFIED> <CREATEDBY>9</CREATEDBY> <MODIFIEDBY>9</MODIFIEDBY> <MEGAENTITYKEY></MEGAENTITYKEY> <MEGAENTITYID></MEGAENTITYID> <MEGAENTITYNAME></MEGAENTITYNAME> </class> </data> </result> </operation> </response>"; Stream stream = new MemoryStream(); StreamWriter streamWriter = new StreamWriter(stream); streamWriter.Write(xml); streamWriter.Flush(); stream.Position = 0; OnlineResponse response = new OnlineResponse(stream); Result result = response.Results[0]; Assert.Equal(1, result.Count); Assert.Equal(2, result.TotalCount); Assert.Equal(1, result.NumRemaining); Assert.Equal("myResultId", result.ResultId); Assert.Single(result.Data); }
public void LegacyGetListClassTest() { string xml = @"<?xml version=""1.0"" encoding=""utf-8""?> <response> <control> <status>success</status> <senderid>testsenderid</senderid> <controlid>ControlIdHere</controlid> <uniqueid>false</uniqueid> <dtdversion>3.0</dtdversion> </control> <operation> <authentication> <status>success</status> <userid>fakeuser</userid> <companyid>fakecompany</companyid> <locationid></locationid> <sessiontimestamp>2015-10-25T10:08:34-07:00</sessiontimestamp> </authentication> <result> <status>success</status> <function>get_list</function> <controlid>ccdeafa7-4f22-49ae-b6ae-b5e1a39423e7</controlid> <listtype start=""0"" end=""1"" total=""2"">class</listtype> <data> <class> <key>C1234</key> <name>hello world</name> <description/> <parentid/> <whenmodified>07/24/2017 15:19:46</whenmodified> <status>active</status> </class> <class> <key>C1235</key> <name>hello world</name> <description/> <parentid/> <whenmodified>07/24/2017 15:20:27</whenmodified> <status>active</status> </class> </data> </result> </operation> </response>"; Stream stream = new MemoryStream(); StreamWriter streamWriter = new StreamWriter(stream); streamWriter.Write(xml); streamWriter.Flush(); stream.Position = 0; OnlineResponse response = new OnlineResponse(stream); Result result = response.Results[0]; Assert.Equal(0, result.Start); Assert.Equal(1, result.End); Assert.Equal(2, result.TotalCount); Assert.Equal(2, result.Data.Count); }
public async Task MockExecuteWithDebugLoggerTest() { string xml = @"<?xml version=""1.0"" encoding=""UTF-8""?> <response> <control> <status>success</status> <senderid>testsenderid</senderid> <controlid>sessionProvider</controlid> <uniqueid>false</uniqueid> <dtdversion>3.0</dtdversion> </control> <operation> <authentication> <status>success</status> <userid>testuser</userid> <companyid>testcompany</companyid> <sessiontimestamp>2015-12-06T15:57:08-08:00</sessiontimestamp> </authentication> <result> <status>success</status> <function>getAPISession</function> <controlid>func1UnitTest</controlid> <data> <api> <sessionid>unittest..</sessionid> <endpoint>https://unittest.intacct.com/ia/xml/xmlgw.phtml</endpoint> </api> </data> </result> </operation> </response>"; HttpResponseMessage mockResponse = new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK, Content = new StringContent(xml) }; List <HttpResponseMessage> mockResponses = new List <HttpResponseMessage> { mockResponse, }; MockHandler mockHandler = new MockHandler(mockResponses); var guid = Guid.NewGuid().ToString(); MemoryTarget target = new MemoryTarget { Name = guid, Layout = "${message}" }; SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); ClientConfig clientConfig = new ClientConfig() { SenderId = "testsenderid", SenderPassword = "******", SessionId = "testsession..", MockHandler = mockHandler, Logger = LogManager.GetLogger(guid), }; RequestConfig requestConfig = new RequestConfig(); List <IFunction> contentBlock = new List <IFunction> { new ApiSessionCreate() }; RequestHandler requestHandler = new RequestHandler(clientConfig, requestConfig); OnlineResponse response = await requestHandler.ExecuteOnline(contentBlock); // Check for the user agent Assert.True(true); // TODO fix this test from randomly failing //Assert.Contains("intacct-api-net-client/", target.Logs[0]); }
public static void Run(ILogger logger) { OnlineClient client = Bootstrap.Client(logger); List <IFilter> filterList = new List <IFilter>(); filterList.Add((new Filter("CUSTOMERID")).SetLike("c%")); filterList.Add((new Filter("CUSTOMERID")).SetLike("1%")); OrOperator filter = new OrOperator(filterList); OrderBuilder orderBuilder = new OrderBuilder(); IOrder[] orders = orderBuilder.Descending("CUSTOMERID").GetOrders(); SelectBuilder selectBuilder = new SelectBuilder(); ISelect[] fields = selectBuilder. Fields(new[] { "CUSTOMERID", "CUSTOMERNAME" }). Sum("TOTALDUE"). GetFields(); QueryFunction query = new QueryFunction() { SelectFields = fields, FromObject = "ARINVOICE", Filter = filter, CaseInsensitive = true, PageSize = 100, OrderBy = orders }; logger.LogInformation("Executing query to Intacct API"); Task <OnlineResponse> task = client.Execute(query); task.Wait(); OnlineResponse response = task.Result; Result result = response.Results[0]; dynamic json = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(result.Data)); if (json != null && json.First != null) { Console.WriteLine("Success! Number of ARINVOICE objects found: " + result.TotalCount); Console.WriteLine("First ARINVOICE result found"); Console.WriteLine("CUSTOMERID: " + json.First["ARINVOICE"]["CUSTOMERID"].Value); Console.WriteLine("CUSTOMERNAME: " + json.First["ARINVOICE"]["CUSTOMERNAME"].Value); Console.WriteLine("SUM.TOTALDUE: " + json.First["ARINVOICE"]["SUM.TOTALDUE"].Value); Console.WriteLine("See the log file (logs/intacct.log) for the complete list of results."); } else { Console.WriteLine("The query executed, but no ARINVOICE objects met the query criteria."); Console.WriteLine("Either modify the filter or comment it out from the query."); Console.WriteLine("See the log file (logs/intacct.log) for the XML request."); } try { string jsonString = json.ToString(); logger.LogDebug( "Query successful [ Company ID={0}, User ID={1}, Request control ID={2}, Function control ID={3}, Total count={4}, Data={5} ]", response.Authentication.CompanyId, response.Authentication.UserId, response.Control.ControlId, result.ControlId, result.TotalCount, jsonString ); } catch (NullReferenceException e) { logger.LogDebug("No response in Data. {0}", e); } finally { LogManager.Flush(); } }