I tried to write mutation but it gives me error.
as
GraphQL.Client.Http.GraphQLHttpRequestException: 'The HTTP request
failed with status code InternalServerError
The code I wrote is this:
private async Task SendMutationAsync(string endPoint)
{
var options = new GraphQLHttpClientOptions
{
EndPoint = new Uri(endPoint),
MediaType = "application/json",
};
var httpClient = new HttpClient();
var client = new GraphQLHttpClient(options, new NewtonsoftJsonSerializer(), httpClient);
var account = new Account
{
Id = 152,
Name = "a",
Street = "a",
PostalCode = 1,
City = "a",
};
var request = new GraphQLRequest
{
Query = "mutation{createAccount (id: 152, name: \"a\", street: \"a\", postalCode: 1, city: \"a\"){ id,name,street,postalCode,city}}",
OperationName = "createAccount",
Variables = new { id = account.Id, name = account.Name, street = account.Street, postalCode = account.PostalCode, city = account.City }
};
var response = await client.SendQueryAsync<dynamic>(request).ConfigureAwait(false);
}
Related
I'm trying to create a POST call using HttpClient that I have fully working in Postman. Here is the body I'm sending in Postman:
{
"searchType": "games",
"searchTerms": [
"mario"
],
"searchPage": 1,
"size": 20,
"searchOptions": {
"games": {
"userId": 0,
"platform": "",
"sortCategory": "popular",
"rangeCategory": "main",
"rangeTime": {
"min": 0,
"max": 0
},
"gameplay": {
"perspective": "",
"flow": "",
"genre": ""
},
"modifier": ""
},
"users": {
"sortCategory": "postcount"
},
"filter": "",
"sort": 0,
"randomizer": 0
}
}
I have this written as the following in C#:
var client = _httpClientFactory.CreateClient(HttpClients.HowLongToBeat.ToString());
var request = new HowLongToBeatRequest
{
SearchType = "games",
SearchTerms = searchTerm.Trim().Split(" "),
SearchPage = 1,
Size = 20,
SearchOptions = new SearchOptions
{
Games = new SearchOptionsGames
{
UserId = 0,
Platform = "",
SortCategory = "popular",
RangeCategory = "main",
RangeTime = new SearchOptionsGamesRangeTime
{
Min = 0,
Max = 0
},
Gameplay = new SearchOptionsGamesGameplay
{
Perspective = "",
Flow = "",
Genre = ""
},
Modifier = ""
},
Users = new SearchOptionsUsers
{
SortCategory = "postcount"
},
Filter = "",
Sort = 0,
Randomizer = 0
}
};
//var json = JsonSerializer.Serialize(request);
//var content = new StringContent(json, Encoding.UTF8, "application/json");
//var response = await client.PostAsync("api/search", content);
var response = await client.PostAsJsonAsync("api/search", request, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
return new HowLongToBeatResponse();
I have this set up as
The url I'm hitting is: https://www.howlongtobeat.com/api/search and I'm setting it up like so in my Startup.cs
services.AddHttpClient(HttpClients.HowLongToBeat.ToString(), config =>
{
config.BaseAddress = new Uri("https://www.howlongtobeat.com/");
config.DefaultRequestHeaders.Add("Referer", "https://www.howlongtobeat.com/");
});
I am passing this Referer header in my Postman collection as well.
Basically, I can't figure out why this code gets a 403 in C# but the Postman that I think is exactly the same is getting a successful response. Am I missing something?
Let me know if there's any missing info I can provide.
I solved my problem. The issue was that this specific API required a User Agent header specified.
I think the problem is here, The BaseAddress property needs to be suffixed (https://www.howlongtobeat.com/) with a forward slash and here you already set route as well, change it to
services.AddHttpClient(HttpClients.HowLongToBeat.ToString(), config =>
{
config.BaseAddress = new Uri("https://www.howlongtobeat.com/");
config.DefaultRequestHeaders.Add("Referer", "https://www.howlongtobeat.com/api/search");
});
And then
var response = await client.PostAsJsonAsync("api/search", request, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
Updated:
try this, here I have hard-coded the Base URL for testing purposes.
try
{
var data_ = JsonConvert.SerializeObject(root);
var buffer_ = System.Text.Encoding.UTF8.GetBytes(data_);
var byteContent_ = new ByteArrayContent(buffer_);
byteContent_.Headers.ContentType = new MediaTypeHeaderValue("application/json");
string _urls = "https://www.howlongtobeat.com/api/search";
var responses_ = await _httpClient.PostAsJsonAsync(_urls, byteContent_);
if (responses_.StatusCode == HttpStatusCode.OK)
{
Console.WriteLine("[GetPrimeryAccount] Response: Success");
string body = await responses_.Content.ReadAsStringAsync();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); ;
}
I am using the Moq framework for my unit test.
This is my TestMethod:
[TestFixture]
public class UpdateContactTests
{
private static readonly object[] TestValidContact =
{
new object[]
{
"Prueba", "nearlinx#gmail.com", "86456245",
new LookUpItem()
{
LookUpItemId = Guid.NewGuid(), Category = "ContactType", CategoryId = 1, Value = "Bulling Contact"
},
new Company()
{
Id = Guid.NewGuid(), Name = "Company", Email = "company#gmail.com", WebSite = "company.com",
Nda = false, Msa = false, Phone = "84876817"
}
}
};
[TestCaseSource(nameof(TestValidContact))]
[Test]
public void UpdateContact_ValidValues_UpdateContact(string name, string email, string phone, LookUpItem lookUpItem, Company company)
{
//arrange
var id = Guid.NewGuid();
var data =
new[]
{
new Contact { Id = Guid.NewGuid(), Name = "Test1", Email = "nearlinx#gmail.com", Phone = "86456245",
ContactType =
new LookUpItem()
{
LookUpItemId = Guid.NewGuid(), Category = "ContactType", CategoryId = 1, Value = "Bulling Contact"
},
Company =
new Company()
{
Id = Guid.NewGuid(), Name = "Company", Email = "company#gmail.com", WebSite = "company.com",
Nda = false, Msa = false, Phone = "84876817"
}},
new Contact { Id = id, Name = "Test2", Email = "nearlinx#gmail.com", Phone = "86456245",
ContactType =
new LookUpItem()
{
LookUpItemId = Guid.NewGuid(), Category = "ContactType", CategoryId = 1, Value = "Bulling Contact"
},
Company =
new Company()
{
Id = Guid.NewGuid(), Name = "Company", Email = "company#gmail.com", WebSite = "company.com",
Nda = false, Msa = false, Phone = "84876817"
}},
};
var contact = new Contact()
{
Id = id,
Name = name,
Email = email,
Phone = phone,
ContactType = lookUpItem,
Company = company
};
var _unitOfWork = new Mock<IUnitOfWork>();
_unitOfWork.Setup(mock => mock.Contact.Get(null, null, null)).Returns(data);
_unitOfWork.Setup(mock => mock.Company.Get(null, null, null)).Returns(new List<Company>());
_unitOfWork.Setup(mock => mock.LookUpItem.Get(null, null, null)).Returns(new List<LookUpItem>());
var contactService = new ContactService(_unitOfWork.Object);
//act
contactService.UpdateContact(contact);
//assert
Assert.That(data.First(m => m.Id == id).Name, Is.EqualTo(contact.Name));
_unitOfWork.Verify(mock => mock.Contact.Update(It.IsAny<Contact>()), Times.Once);
}
}
My problem is that when I run the test a NullReferenceException is thrown, I suppose it is because the list that has the object that I want to modify is not being assigned
I've never really used Moq and I don't know much about unit tests either, so what am I really doing wrong
Edit:
i change one of the setup because the one called when the update is done was another
instead of
_unitOfWork.Setup(mock => mock.Contact.Get(null, null, null)).Returns(data);
is
_unitOfWork.Setup(mock => mock.Contact.Where(c => c.Id == contact.Id,null,null).FirstOrDefault()).Returns(() => data.Where(c => c.Id == contact.Id));
Without seeing the rest
_unitOfWork.Setup(mock => mock.Contact.Get(null, null, null))
the mock.Contact returns null
best thing is to debug the test, breakpoint the first line and step through to find exactly where it is throwing the null exception
I found the solution
I was doing the set like this
_unitOfWork.Setup(mock => mock.Contact.Where(c => c.Id == contact.Id,null,null).FirstOrDefault()).Returns(() => data.Where(c => c.Id == contact.Id));
while in the update method the condition was this
_unitOfWork.Setup(mock => mock.Contact.Where(c => c.Id == contact.Id).FirstOrDefault()).Returns(() => data.Where(c => c.Id == contact.Id));
changing the condition in the method fixed the problem
Trying to post array of products using c# httpClinet to shopify.But getting 400 bad request. Also tried to post array of product = new object like items, but also getting 400 code.
var arrayOfProducts = new
{
products = new[]
{
new
{
title = "qqwqw",
description = "test",
product_type = "Game",
vendor = "test"
},
new
{
title = "1233eewq",
description = "test",
product_type = "Game",
vendor = "test"
}
}
};
var resp = await http.PostAsync($"{_shopify.Path}/products.json", new StringContent(
JsonSerializer.Serialize(arrayOfProducts)
, Encoding.UTF8, "application/json"), stoppingToken);
I am currently performing a SuiteTalk search via C# that joins multiple tables, one of which is for Sales Orders. When performing a typical GET on a SalesOrder record, the property customFieldList gets populated with an array of transaction custom fields/etc. I am curious how to get the same when doing a search like:
SearchResult searchResult = Client.Service.search(new TransactionSearchAdvanced()
{
criteria = new TransactionSearch()
{
basic = new TransactionSearchBasic()
{
type = new SearchEnumMultiSelectField()
{
#operator = SearchEnumMultiSelectFieldOperator.anyOf,
operatorSpecified = true,
searchValue = new String[] { "_salesOrder" },
},
lastModifiedDate = new SearchDateField()
{
#operator = SearchDateFieldOperator.after,
operatorSpecified = true,
searchValue = fromLastModifiedDateTime.ToUniversalTime(),
searchValueSpecified = true
}
},
},
columns = new TransactionSearchRow()
{
basic = new TransactionSearchRowBasic()
{
internalId = new SearchColumnSelectField[] { new SearchColumnSelectField() },
tranId = new SearchColumnStringField[] { new SearchColumnStringField() },
tranDate = new SearchColumnDateField[] { new SearchColumnDateField() },
dateCreated = new SearchColumnDateField[] { new SearchColumnDateField() },
item = new SearchColumnSelectField[] { new SearchColumnSelectField() },
quantity = new SearchColumnDoubleField[] { new SearchColumnDoubleField() },
lastModifiedDate = new SearchColumnDateField[] { new SearchColumnDateField() },
email = new SearchColumnStringField[] { new SearchColumnStringField() },
//customFieldList = new SearchColumnCustomField[] { },
},
itemJoin = new ItemSearchRowBasic()
{
itemId = new SearchColumnStringField[] { new SearchColumnStringField() },
type = new SearchColumnEnumSelectField[] { new SearchColumnEnumSelectField() },
},
customerJoin = new CustomerSearchRowBasic()
{
internalId = new SearchColumnSelectField[] { new SearchColumnSelectField() },
billAddress = new SearchColumnStringField[] { new SearchColumnStringField() },
companyName = new SearchColumnStringField[] { new SearchColumnStringField() },
phone = new SearchColumnStringField[] { new SearchColumnStringField() },
email = new SearchColumnStringField[] { new SearchColumnStringField() },
},
customSearchJoin = new CustomSearchRowBasic[]
{
},
}
});
The property I want populated is commented out within the TransactionSearchRowBasic object:
//customFieldList = new SearchColumnCustomField[] { },
Any ideas? Thank you in advance!
The search operation doesn't return as much information as a GET operation does on the SuiteTalk Web Services.
For each record that is returned in your SearchResult, use the internalId or document number to GET that record. This should then include your custom fields.
NetSuiteService _service = new NetSuiteService();
ReadResponse res = _service.get(new RecordRef { internalId = internalID, type = RecordType.salesOrder, typeSpecified = true });
We require two signers and one carbon copy recipient which receives a carbon copy for every status change of the signing process.
Using DocuSign.eSign Nuget package 2.1.4, I tried:
adding the carbon copy recipient (RecipientId=1)
adding the first signer (RecipientId=2)
adding the same carbon copy recipient as in step 1 (RecipientId=1)
adding the second signer (RecipientId=3)
adding the same carbon copy recipient as in step 1 (RecipientId=1)
I'm increasing RoutingOrder along the way (from 1 to 5)
A recipient simply contains values for: Email, Name, RecipientId and RoutingOrder, nothing more.
This, however causes the API to return
ENVELOPE_HAS_DUPLICATE_RECIPIENTS.
I tried to find a solution for this in the documentation, but can't seem to find the correct paragraph.
If you are using the DocuSign c# SDK, then the following code should accomplish what you are trying. See full example here.
The envelope has the recipients in the following order
CC Recipient (janecc#acme.com)
Signer (janedoe#acme.com)
CC Recipient (janecc#acme.com)
Signer (bobbydoe#acme.com)
CC Recipient (janecc#acme.com)
public void CreateEnvelopeDuplicateRecipients()
{
string accountID = "";//Initialization code here.
byte[] fileBytes = System.IO.File.ReadAllBytes(#"C:\temp\test.pdf");
var envDef = new EnvelopeDefinition()
{
EmailSubject = "Envelope with CC & Signers",
Status = "Sent",
Documents = new List<Document>()
{
new Document()
{
DocumentBase64 = System.Convert.ToBase64String(fileBytes),
Name = "Dummy",
DocumentId = "1"
}
},
Recipients = new Recipients()
{
CarbonCopies = new List<CarbonCopy>()
{
new CarbonCopy()
{
Email = "janecc#acme.com",
Name = "jane cc",
RecipientId = "1",
RoutingOrder = "1"
},
new CarbonCopy()
{
Email = "janecc#acme.com",
Name = "jane cc",
RecipientId = "3",
RoutingOrder = "3"
},
new CarbonCopy()
{
Email = "janecc#acme.com",
Name = "jane cc",
RecipientId = "5",
RoutingOrder = "5"
}
},
Signers = new List<Signer>()
{
new Signer()
{
Email = "janedoe#acme.com",
Name = "jane doe",
RecipientId = "2",
RoutingOrder = "2",
Tabs = new Tabs()
{
SignHereTabs = new List<SignHere>()
{
new SignHere()
{
DocumentId = "1", XPosition = "100", YPosition = "200", PageNumber = "1",
}
}
}
},
new Signer()
{
Email = "bobbydoe#acme.com",
Name = "bobbydoe Demo",
RecipientId = "4",
RoutingOrder = "4",
Tabs = new Tabs()
{
SignHereTabs = new List<SignHere>()
{
new SignHere()
{
DocumentId = "1", XPosition = "100", YPosition = "300", PageNumber = "1",
}
}
}
}
}
}
};
var envelopesApi = new EnvelopesApi();
EnvelopeSummary envelopeSummary = envelopesApi.CreateEnvelope(accountID, envDef);
Console.WriteLine(envelopeSummary);
}