How to consume DELETE request from windows client application - c#

In my web API delete request, which containing multiple parameters.I need to consume this DELETE request using C# windows form application and my code as bellow.
private void btnDelete_Click(object sender, EventArgs e)
{
using (var client = new HttpClient())
{
person p = new person { ID = 1, SID = 5, Name = "paul"};
client.BaseAddress = new Uri("http://localhost:2733/");
var response = client.DeleteAsync("api/person/").Result;
if (response.IsSuccessStatusCode)
{
Console.Write("Success");
}
else
Console.Write("Error");
}
}
This is how I consume this using Postman, and its works finehttp://localhost:2733/api/person/1/5/"paul" How to consume this using my windows client. I try these two way,
var response = client.DeleteAsync("api/person/",p).Result;
and
var response = client.DeleteAsync("api/person/"+1+5+"paul").Result;
But those are not working. How can I pass parameters to DELETE request.
Updated:
This is my controller class,
[Route("api/person/{id:int}/{pid:int}/{pname}")]
[HttpDelete]
public void Delete(int id, int pid, string pname)
{
var pModel = new PModel
{
ID = id,
SID = pid,
Name= pname
};
Person p = new Person();
p.deletePerson(pModel);
}
This is Person class
public void deletePerson(PModel p)
{
try
{
string sql = $"DELETE from person WHERE ID = {p.ID} AND SID = {p.SID} AND Name= {p.Name}"; ;
MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(sqlString, conn);
cmd.ExecuteNonQuery();
long x = cmd.LastInsertedId;
}
catch (MySqlException x)
{
int errr = x.Number;
Console.WriteLine(errr);
}
}

Try the below. It should replicate the way you have tried consuming your API through PostMan.
var response = client.DeleteAsync($"api/person/{p.ID}/{p.SID}/\"{p.Name}\"").Result;

Related

POST Data To ASP.NET API With Xamarin

I am using C# asp.net and attempting to create my first Xamarin app. I have altered my asp.net API to hold the below syntax
private SqlConnection con;
private SqlCommand com;
private void connection()
{
string constr = ConfigurationManager.ConnectionStrings["getconn"].ToString();
con = new SqlConnection(constr);
}
[HttpPost]
public string AddUser(User user)
{
connection();
com = new SqlCommand("InsertData", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#FName", user.FName);
com.Parameters.AddWithValue("#Lname", user.LName);
com.Parameters.AddWithValue("#Phone", user.Phone);
com.Parameters.AddWithValue("#Compnay", user.Company);
com.Parameters.AddWithValue("#Email", user.Email);
com.Parameters.AddWithValue("#Pass", user.Pass);
com.Parameters.AddWithValue("#Registrationdate", user.Registrationdate);
con.Open();
int i = com.ExecuteNonQuery();
con.Close();
if (i >= 1)
{
return "New User Added Successfully";
}
else
{
return "Failed to Add User";
}
}
[HttpGet]
public string Get()
{
return "";
}
And I Have in my Xamarin syntax the below
void OnRegisterTap(object sender, EventArgs e)
{
InsertUser().ConfigureAwait(true);
}
private async Task InsertUser()
{
try
{
var httpClient = new HttpClient();
var url = "http://XXX.XXX.X.XXX:8888/api/user/adduser";
var data = new
{
FName = fname.Text,
LName = lname.Text,
Company = company.Text,
Email = Email.Text,
Pass = Password.Text,
Registrationdate = DateTime.UtcNow.ToString()
};
var jsonData = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
var result = await httpClient.PostAsync(url, jsonData);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
Now there is no error thrown when I press the button from my Xamarin app, I have verified that all the variables holds the appropriate values, however my issue is that no data is actually input into the database.
What step did I miss or did I improperly code that is keeping the data from being inserted?
Try changing
var result = await client.PostAsync(url, jsonData);
To
var response = await client.PostAsync(url, jsonData);
var result = await response.Content.ReadAsStringAsync();
Add FromBody to your controller (assuming User class is correct)
[HttpPost]
public string AddUser([FromBody] User user)
Use fiddler to Watch your request & response also your controller should return a proper HTTP response.

Nethereum C# automated ether transfer

I wish to automate the transfer of ether to a list of people.
Assume the list is in a csv.
I wrote some code to automate the process.
class Program
{
int nonce = 0;
static void Main(string[] args)
{
var account = SetupAccount();
var recipients = ReadCsv();
var web3Init = GetConnection();
nonce = web3.Eth.Transactions.GetTransactionCount.SendRequestAsync(account.Address).Result;
//var recipients = new List<Records>() { new Records() { Value = 10000000000000000, Address = "0x5CC494843e3f4AC175A5e730c300b011FAbF2cEa" } };
foreach (var recipient in recipients)
{
try
{
var web3 = GetConnection();
var receipt = SendEther(account, recipient, web3).Result;
}
catch (System.Exception)
{
MessageBox.Show("Failed");
}
Thread.Sleep(30000);
}
}
private static async Task<TransactionReceipt> SendEther(Account account, Records recipient, Web3 web3)
{
var transactionPolling = web3.TransactionManager.TransactionReceiptService;
//var currentBalance = await web3.Eth.GetBalance.SendRequestAsync(account.Address);
//assumed client is mining already
//when sending a transaction using an Account, a raw transaction is signed and send using the private key
return await transactionPolling.SendRequestAndWaitForReceiptAsync(() =>
{
var transactionInput = new TransactionInput
{
From = account.Address,
//Gas = new HexBigInteger(25000),
GasPrice = new HexBigInteger(10 ^ 10),
To = recipient.Address,
Value = new HexBigInteger(new BigInteger(recipient.Value)),
Nonce = nonce
};
var txSigned = new Nethereum.Signer.TransactionSigner();
var signedTx = txSigned.SignTransaction(account.PrivateKey, transactionInput.To, transactionInput.Value, transactionInput.Nonce);
var transaction = new Nethereum.RPC.Eth.Transactions.EthSendRawTransaction(web3.Client);
nonce++;
return transaction.SendRequestAsync(signedTx);
});
}
private static Web3 GetConnection()
{
return new Web3("https://mainnet.infura.io");
}
private static Account SetupAccount()
{
var password = "#Password";
var accountFilePath = #"filePath";
return Account.LoadFromKeyStoreFile(accountFilePath, password);
}
private static List<Records> ReadCsv()
{
string filePath = #"C:\Users\Potti\source\repos\ConversionFiles\XrcfRecipients.csv";
if (File.Exists(filePath))
{
using (StreamReader stream = new StreamReader(filePath))
{
CsvReader reader = new CsvReader(stream, new Configuration
{
TrimOptions = TrimOptions.Trim,
HasHeaderRecord = true,
HeaderValidated = null
});
reader.Configuration.RegisterClassMap<RecordMapper>();
return reader.GetRecords<Records>().ToList();
}
}
else
{
return null;
}
}
}
class Records
{
public string Address { get; set; }
public decimal Value { get; set; }
}
sealed class RecordMapper : ClassMap<Records>
{
public RecordMapper()
{
Map(x => x.Address).Name("Address");
Map(x => x.Value).Name("Value");
}
}
How do i modify the process to execute all the transactions at once instead of waiting for each to complete? (Fire and forget)
Also, are there any security considerations of doing this?
What you are currently doing is waiting for each transaction to be mined. What you can do is the following:
var account = new Account("privateKey"); // or load it from your keystore file as you are doing.
var web3 = new Web3(account, "https://mainnet.infura.io");
First create a web3 instance using the same Account object, because we are using an account with a private key, Nethereum will sign your transactions offline before sending them.
Now using the TransactionManager, you can then send a transaction per each recepient
var transactionHashes = new List<string>();
foreach(var recepient in recepients){
var transactionInput = new TransactionInput
{
From = account.Address,
GasPrice = Web3.Convert.ToWei(1.5, UnitConversion.EthUnit.Gwei);,
To = recipient.Address,
Value = new HexBigInteger(new BigInteger(recipient.Value)),
};
var transactionHash = web3.Eth.TransactionManager.SendTransactionAsync(transactionInput);
transanctionHashes.Add(transactionHash);
}
Note that when Nethereum uses the same instance of an Account and TransactionManager (or Web3 in this scenario) it creates a default NonceMemoryService, so you don't need to keep track of your nonces (Transaction number), to sign the transaction.
Also I have done a conversion for the GasPrice from Gwei to Wei, as an example of Unit conversions, I assume that you already have converted to Wei the Ether amounts you are going to send.
Finally, another note, to further simplify this, there is an upcoming EtherTransferService which allows you to input Ether amounts and Gwei price amounts to avoid doing conversions. Also the gas price will be calculated for you, if not passed any parameter.
web3.Eth.GetEtherTransferService().TransferEtherAsync("toAddress", EtherAmount);

Web service call takes too long

I created a client Webservice with C# to be able to retrieve informations about a book that i get from a server.
When i make the call to get books informations from bookIds that i pass in paremeters, sometimes the call is fast, sometimes it takes 1 min and sometimes it takes forever. I only store the bookIds in my dataBase, so when i need more informations about the books (title, dateOfPublication, etc) i contact the webService to get them. I'm using the chrome debugger and under the Network tab and i only have "CAUTION ; request is not finished yet"...and no other informations that can help me to see what happens exactly! –
The function i call is getBooksByAuthor(authorId) and i should only have 8 results related to the authorId, so it should not take that long ! Here's all my code:
public async Task<T> GetObject<T>(string uriActionString)
{
T wsObject =
default(T);
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(#"https://books.server.net");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// connect to the server
var byteArray = Encoding.ASCII.GetBytes("NXXXXX:Passxxxx");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
HttpResponseMessage response = await client.GetAsync(uriActionString);
response.EnsureSuccessStatusCode();
wsObject = JsonConvert.DeserializeObject<T>(await((HttpResponseMessage)response).Content.ReadAsStringAsync());
}
return wsObject;
}
catch (Exception e)
{
throw (e);
}
}
public async Task<Book> viewBook(int id)
{
Book book = new Book();
string urlAction = String.Format("api/book/{0}", id);
book = await GetWSObject<Book>(urlAction);
return book;
}
public string getBooksByAuthor (int authorId) {
string result = "";
var books = from a in db.Authors
where a.id == authorId
select new
{
id = a.id
};
foreach (var book in books.ToList())
{
var bookdata = await ws.viewBook(book .id);
result += this.getBookObject(book.id).name + ", ";
}
return result;
}
/* How to return a string from a task ? */
foreach (var author in listOfAuthors)
{
booksFromAuthors.Add(new { id = author.id, book = getBooksByAuthor(author.id) // ? how convert it to a string ? });
}
Lose the getBookObject function, you're just complicating things by starting a new Task there.
You can simply await the result from getBooksByAuthor if you make that function async.
public async Task<Book> getBook(int id)
{
string urlAction = String.Format("api/book/{0}", id);
return await GetWSObject<Book>(urlAction);
}
public async Task<string> getBooksByAuthor (int authorId)
{
string result = "";
var books = from a in db.Authors
where a.id == authorId
select new
{
id = a.id
};
foreach (var book in books.ToList())
{
var bookdata = await this.getBook(book.id);
result += bookdata.name + ", ";
}
return result;
}
If you want to to make concurrent http requests, you can create a number of Tasks and use Task.WhenAll, e.g.
https://stackoverflow.com/a/30668277/1538039

To know reason of not added record in NetSuite

Trying to add new customer to NetSuite like it described in sample in manual.
private static void Main(string[] args)
{
ApplicationInfo _appInfo;
var service = new NetSuiteService();
service.CookieContainer = new CookieContainer();
_appInfo = new ApplicationInfo();
_appInfo.applicationId = "FB31C4F2-CA6C-4E5F-6B43-57632594F96";
service.applicationInfo = _appInfo;
var passport = new Passport();
passport.account = "5920356_SB9";
passport.email = "a#a.com";
var role = new RecordRef();
role.internalId = "3";
passport.role = role;
passport.password = "#sdkkr_5543";
try
{
var status = service.login(passport).status;
}
catch (Exception e)
{
Console.Out.WriteLine(e.Message);
throw;
}
var cust = new Customer();
cust.entityId = "XYZ Inc";
cust.altEmail = "aaa#aaa.aaa";
var response = service.add(cust);
Console.Out.WriteLine("response.status.isSuccess " + response.status.isSuccess) ;
Console.Out.WriteLine("response.status.isSuccessSpecified " + response.status.isSuccessSpecified);
service.logout();
}
As result I got:
response.status.isSuccess False
response.status.isSuccessSpecified True
I suppose customer was not inserted. What is wrong and how to know that?
When you call add() on the service, the response contains a status property which contains a statusDetail property. statusDetail is an array of the messages (warnings and errors) that resulted from your add(). You can loop through these to find out why saving your customer record was unsuccessful:
var response = service.add(cust);
if (!response.status.isSuccess)
{
foreach (var error in response.status.statusDetail)
{
Console.WriteLine($"Error creating customer: {error.type} {error.message}");
}
}

MailChimp Integaration with MVC 5

I am working on an MVC5 project, the client is interested in using MailChimp for sending emails. I have explored the MailChimp and wrappers ( MailChimp.NET ) and tried in my project as well. I tested the REST API as well and it seems to work , for example; I was able to grab lists and templates using REST API. But, still I am having issues with sending email through MailChimp.
So far, I have tried the following code and its working. Now I want to send an email to a newly registered user. Kindly give me detailed code example that How can I achieve this, because I am totally struck here..
var apiKey = "myapikey-us11";
var listId = "mylistid";
var subscribeRequest = new
{
apikey = apiKey,
id = listId,
email = new
{
email = "muhammad.waqas#seventechnology.co.uk"
},
double_optin = true,
};
var requestJson = JsonConvert.SerializeObject(subscribeRequest);
var reqresult = CallMailChimpApi("lists/", requestJson);
CallMailChimApi
private static string CallMailChimpApi(string method, string requestJson)
{
var endpoint = String.Format("https://{0}.api.mailchimp.com/3.0/{1}", "us11", method);
var wc = new WebClient();
try
{
return wc.UploadString(endpoint, requestJson);
}
catch (WebException we)
{
using (var sr = new StreamReader(we.Response.GetResponseStream()))
{
return sr.ReadToEnd();
}
}
}
I Use this function and it work successfully
public void SendEmailByApiMailChimp ()
{
try
{
string UserEmail = " Exemple#gmail.com ";
MailChimpManager mc = new MailChimpManager("16d***********-us14");
EmailParameter email = new EmailParameter()
{
Email = UserEmail
};
EmailParameter resulte = mc.Subscribe("yourlistnumber", email);
var test = resulte;
}
catch (Exception ex)
{
var ters = ex;
}
}

Categories

Resources