Adding record to Zoho creator - c#

Hi I am using following code to add a record to Zoho Creator form using asp.net c#.
However I receive in respose "The form has been removed from publish."
I have checked form at Zoho creator its working fine & has been published.
Please help me figure out the problem.
public partial class WebForm1 : System.Web.UI.Page
{
protected void btnSubmit_OnClick(object sender, EventArgs e)
{
var response = Http.Post("https://creator.zoho.com/saadelboury1/myfirstApp/form-perma/NEWDISTRIBUTOR/record/add/", new NameValueCollection() {
{ "authtoken", "<KEY>" },
{ "scope", "creatorapi" },
{ "First_Name", "John" },
{ "Last_Name", "Doe" },
{ "Email", "someone22#gmail.com" },
});
string result = System.Text.Encoding.UTF8.GetString(response);
Response.Write(result);
}
}
}
public static class Http
{
public static byte[] Post(string uri, NameValueCollection pairs)
{
byte[] response = null;
using (WebClient client = new WebClient())
{
response = client.UploadValues(uri, pairs);
}
return response;
}

Turned out, the url I was calling was wrong.
The correct url format is:
https://creator.zoho.com/api/[username]/xml/[application_name]/form/[form_name]/record/add/

Here I push the records from the school form to the student form with the help of add record task.
var = Insert into Student
[
Name = input.Name
Email = input.Email
Phone = input.Phone
Address = input. Address
];
Variable holding the ID of the new record.
<<form_link_name> Link name of the field for which the value is specified.
Value to be assigned to the field. You can directly specify a value, or you can specify an expression.

Related

C# Update Azure Cosmos Db json item with Upsert

I'm (new to CosmosDb) and trying to update an item in an Azure Cosmos db, but it's inserting instead.
The object sent is
public class Bank
{
public string id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}
I tried passing only the Code and the Name values back (i.e. I did not include the id in the object, which causes an insert (I wanted an update).
I am now including the id which results in an error.
Error returned is:
ResourceType Document is unexpected.
ActivityId: a0d50426-c556-4b17-9646-93052699026e, Windows/10.0.19044 documentdb-netcore-sdk/2.16.2
So, it's values after a front end update (only changing the Name value) are:
Code: "FNB"
Name: "aa First Update Test"
id: "d76ade3d-7d02-46e5-a458-e9f0781bf044"
The DAL code:
var documentUri = UriFactory.CreateDocumentUri(DBName, "Banks", bank.Code);
try
{
Document doc = await client.UpsertDocumentAsync(documentUri, bank);
}
How do I get it to update?
TIA
Your Code is not clear and dont have enough information.try these functions.
protected DataContext(string endpointUrl, string databaseId,
string masterKey)
{
_databaseId = databaseId;
_masterKey = masterKey;
_databaseUri = UriFactory.CreateDatabaseUri(_databaseId);
this._client = new DocumentClient(new Uri(endpointUrl), _masterKey);
this._client.CreateDatabaseIfNotExistsAsync(new Database
{ Id = _databaseId });
this._client.CreateDocumentCollectionIfNotExistsAsync(
UriFactory.CreateDatabaseUri(_databaseId),
new DocumentCollection { Id = CollectionId });
_databaseCollectionUri = UriFactory.CreateDocumentCollectionUri(
_databaseId, CollectionId);
}
insert and update using
public async Task<Document> UpsertDocumentAsync(T entity)
{
var result = await this._client.UpsertDocumentAsync(
_databaseCollectionUri, entity);
return result;
}
Or Try please using the nuget Microsoft.Azure.Cosmos;
string cosmosDbConnectionString = CosmosDbConnectionKey;
CosmosClient cosmosClient = new CosmosClient(cosmosDbConnectionString);
var db = CosmosDbNameKey;
var container = ContainerKey;
await container.UpsertItemAsync(Model, new PartitionKey(Model.PK));
What I needed was the DocumentCollection (DocumentCollection Link) in the Upsert, but I had the Document Link (documentUri)
So,
public async Task<ExBool> UpdateAsyncPOCO(Bank bank)
{
// NB: UpsertDocumentAsync should take the DocumentCollection link, instead of Document link.
// This is a DocumentLink
var documentUri = UriFactory.CreateDocumentUri(DBName, "Banks", bank.Code);
// This is a DocumentCollection
var CollectionUri = UriFactory.CreateDocumentCollectionUri("demo", "Banks");
try
{
Document doc = await client.UpsertDocumentAsync(CollectionUri, bank);
}
catch (Exception ex)
{
HandleException(ex);
}
return result;
}
Insert and update work perfectly now.
The model and values for the update:
Code: "updated FNB 2"
Name: "updated First National Bank 22"
id: "d76ade3d-7d02-46e5-a458-e9f0781bf044"
Similarly, the Insert
Code: "qwerty"
Name: "qwertyuiop"
id: ""

HTTP client method null exception

I have an API project and I need to develop a web project using the API I wrote some code but not able to find the exception and problem and not getting data from the link.
Here is my Service Code:
public async Task<IEnumerable<AgentReadDto>> GetAgent()
{
IEnumerable<AgentReadDto> agents = new List<AgentReadDto>();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://localhost:44331/api/");
var response = client.GetAsync("Agent/GetAllAgent");
response.Wait();
var result = response.Result;
if (result.IsSuccessStatusCode)
{
var readTask =JsonConvert.DeserializeObject<IList<AgentReadDto>>(await result.Content.ReadAsStringAsync());
agents = readTask;
}
}
return agents;
}
And my controller code is look like this:
public IActionResult AgentLists()
{
var agentsList = _agentRespositoryWeb.GetAgent();
if (agentsList != null )
{
ViewBag.Message = "There was a problem retrieving agent from the database or no agents exists";
}
ViewBag.SuccessMessage = TempData["SuccessMessage"];
return View(agentsList);
}
My api return the value following:
{
"agentDetail": [
{
"usersId": 85,
"firstName": "Amit",
"lastName": "One",
"gender": "Male",
"informationTips": [
{
"video": "https://www.w3schools.com/html/movie.mp4"
},
{
"video": "https://www.w3schools.com/html/movie.mp4"
},
]
},
{
"usersId": 86,
"firstName": "Amit",
"lastName": "Two",
"gender": "Male",
"informationTips": [
{
"video": "https://www.w3schools.com/html/movie.mp4"
}
]
}
]
}
For exception I added image there is three image that take screen on the different steps:
Your model is set to IEnumerable<AgentReadDto>, but you've forgotten to await the call to GetAgent inside of the AgentLists action. This means there's a mismatch between what the view expects (IEnumerable<AgentReadDto>) and what it receives (Task<IEnumerable<AgentReadDto>>).
To fix this, convert AgentLists to an async method and then await the call to GetAgent. Here's a fixed version of the AgentLists action:
public async Task<IActionResult> AgentLists()
{
var agentsList = await _agentRespositoryWeb.GetAgent();
if (agentsList != null)
{
ViewBag.Message =
"There was a problem retrieving agent from the database or no agents exists";
}
ViewBag.SuccessMessage = TempData["SuccessMessage"];
return View(agentsList);
}
It looks like you also have a mismatch between the type you expect to be returned and the JSON actually being returned. The JSON represents an object with a list inside of it, but you're attempting to parse it as a simple list. To fix that, create a wrapper class that matches the structure of the response. For example, create the following class:
public class ApiResponse
{
public IEnumerable<AgentReadDto> AgentDetail { get; set; }
}
Update the deserialization logic to use this new type:
var apiResponse = JsonConvert.DeserializeObject<ApiResponse>(...);
var agentsLit = apiResponse.AgentDetail;

Swift 4 Alamofire upload file with parameters to ASP.NET MVC Controller

I have an ASP.NET MVC Controller defined like so:
[HttpPost]
public string uploadQAImage(FileUploadClass fileUploadClass, HttpPostedFile image)
{
}
And this what the class FileUploadClass looks like.
public class FileUploadClass
{
public string job { get; set; }
public string createdBy { get; set; }
public string itemId { get; set; }
}
What I am trying to do with Alamofire in iOS is call this Controller, I have tried using parameters:
func saveQAPhotos(_ cellHolder: PhotoClass, completion: #escaping (_ result: Dictionary<String, Any>) -> Void)
{
let parameters: Parameters = [
"job" : cellHolder.job!,
"itemId" : cellHolder.itemId!,
"createdBy" : appDelegate.username!
]
let urlComponents = NSURLComponents(string: webservice + "uploadQAImage");
urlComponents?.user = appDelegate.username;
urlComponents?.password = appDelegate.password;
let url = urlComponents?.url;
Alamofire.upload(multipartFormData: { (multipartFormData) in
for (key, value) in parameters {
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
}
if let data = cellHolder.photo {
multipartFormData.append(data, withName: "image", fileName: "image.png", mimeType: "image/png")
}
}, usingThreshold: UInt64.init(), to: url!, method: .post, headers: nil) { (result) in
switch result{
case .success(let upload, _, _):
upload.responseJSON { response in
if let result = response.result.value {
let jsonData = result as! Dictionary<String, Any>
completion(jsonData)
}
}
case .failure(_):
print("error")
}
}
}
But that didn't work on the ASP.NET side I get this error:
can't bind multiple parameters to the request's content
I have also tried sending the data as [AnyHashable: Any] like so:
func saveQAPhotos(_ cellHolder: PhotoClass, completion: #escaping (_ result: Dictionary<String, Any>) -> Void)
{
var jsonDict = [AnyHashable: Any]()
jsonDict["job"] = cellHolder.job
jsonDict["itemId"] = cellHolder.itemId
jsonDict["createdBy"] = appDelegate.username
let jsonData: Data? = try? JSONSerialization.data(withJSONObject: jsonDict, options: .prettyPrinted)
let urlComponents = NSURLComponents(string: webservice + "uploadQAImage");
urlComponents?.user = appDelegate.username;
urlComponents?.password = appDelegate.password;
let url = urlComponents?.url;
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(jsonData!, withName: "fileUploadClass", mimeType: "application/json")
if let data = cellHolder.photo {
multipartFormData.append(data, withName: "image", fileName: "image.png", mimeType: "image/png")
}
}, usingThreshold: UInt64.init(), to: url!, method: .post, headers: nil) { (result) in
switch result{
case .success(let upload, _, _):
upload.responseJSON { response in
if let result = response.result.value {
let jsonData = result as! Dictionary<String, Any>
completion(jsonData)
}
}
case .failure(_):
print("error")
}
}
}
Same error as before
can't bind multiple parameters to the request's content
Now when I change the ASP.NET Controller to only get FileUploadClass like so:
[HttpPost]
public string uploadQAImage(FileUploadClass fileUploadClass)
{
}
I get this error:
Object reference not set to an instance of an object.
I can only assume if I do fix the can't bind multiple parameters to the request's content error I will get this error next.
I am pretty sure I am sending the data incorrectly, so I guess my question is how do I send data from Alamofire upload method to an ASP.NET MVC method?

ASP.NET C# WebSocket

I have created an ASP.NET C# project which consists of a web form and a WebSocket handler. I would like to send 2 data (name & price data) from the web form in JSON string format to the WebSocket handler. Here is the code snippet in the web form:
ws.onopen = function()
{
var name = "Client Product";
var price = 10.8;
ws.send(JSON.stringify(name));
ws.send(JSON.stringify(price));
alert("Message is sent...");
};
In the WebSocket handler's OnMessage(string) method, I would like to retrieve the 2 data sent by the web form and deserialize the 2 data to c# format. Here is the code snippet in the WebSocket handler:
public override void OnMessage(string message)
{
string serverName="";
string serverPrice = "";
serverName = JsonConvert.DeserializeObject<string>(message);
serverPrice = JsonConvert.DeserializeObject<string>(message);
}
However, under the WebSocket handler's onMessage(string) method, both the variable serverName and serverPrice would be assigned as "Client Product". I want the variable serverPrice to be assigned as "10.8", instead of "Client Product".
Can somebody please tell me how I could achieve that? WILL really appreciate if you could help me :) Thank You :)
If you want to send multiple pieces of data in a single JSON message, you'll need to combine them into an object. Try it like this:
On the client:
ws.onopen = function()
{
var obj = {
name: "Client Product",
price: "10.8"
};
ws.send(JSON.stringify(obj));
alert("Message is sent...");
};
On the server:
public override void OnMessage(string message)
{
MyData obj = JsonConvert.DeserializeObject<MyData>(message);
string serverName = obj.Name;
string serverPrice = obj.Price;
...
}
public class MyData
{
// Important: these JsonProperty attributes MUST match
// the names of the properties in the client object
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("price")]
public string Price { get; set; }
}

c# dictionary as a value of a hashtable

I have to code a little C# Console application (but my knowledge on .NET is almost NULL) to make a POST request to a PHP API, for which I'm using an HttpClient instance. The API accepts a JSON like this
{
"User": {
"email": "email#host.com",
"password": "something"
},
"Establishment": {
"id": 147
}
}
After doing some research on how to do this what I've done so far is this:
static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://italdelo.web.development.co/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
// HTTP POST
Dictionary<string, string> user = new Dictionary<string, string>();
Dictionary<string, int> establishment = new Dictionary<string, int>();
HashTable postdata = new HashTable();
user.Add("email","email#host.com");
user.Add("password","something");
establishment.Add("id",147);
postdata.Add("User",user);
postdata.Add("Establishment",establishment);
HttpResponseMessage response = await client.PostAsJsonAsync("apiname/service", postdata);
response.EnsureSuccessStatusCode(); // Throw if not a success code.
}
catch (HttpRequestException e)
{
Console.WriteLine("Exception details: " + e.ToString());
}
}
}
Running this code I got this error message:
Severity Code Description Project File Line Suppression State Error CS0246 The type or namespace name 'HashTable' could not be found (are you missing a using directive or an assembly reference?) ProjectName C:\Users\...\Program.cs 47 Active
I know the error is the way I'm trying to setup the JSON to send to the API, which is a hashtable containing values (hashtable's key-value notation) as dictionaries. I'm pretty sure this is dumb but I don't really know how to setup this JSON for the API, I have no choice, I need to use C#. Can you help me please giving me some advice on how to fix this or get this done in another way? Thanks in advance.
you can create a class that will serve as parameter for consuming API.
//you classes
public class Parameter
{
public User user { get; set;}
public Establishment {get; set;}
}
public class User
{
public string email {get; set;}
public string password {get; set}
}
public class Establishment
{
public int id {get;set;}
}
//in your api calling method:
`var p = new Parameter
{
Establishment = new Establishment
{
id = 123
},
User = new User
{
email = "email",
password = "password"
}
};
HttpResponseMessage response = await client.PostAsJsonAsync("apiname/service", p);
Use c# anonymous classes
var payload = new{
User=new {
email= "email#host.com",
password= "something"
},
Establishment=new {
id= 147
}
}
then use newtonsoft json.net
var json = JsonConvert.SerializeObject(payload);
Looks like a typo, C# Hashtable does not capitalize the middle T:
https://msdn.microsoft.com/en-us/library/system.collections.hashtable(v=vs.110).aspx

Categories