Requests POST with Bearer token in ASP.NET - c#

I've an API secured by Bearer token to be consumed in a MVC project. I want to take the values to send from a text file every time a text file is created in a Windows folder, I used fileSystemWatcher to monitor the folder and I use a routine to read the lines from the new text file. I'm stuck creating a new record in a Business Central customer table.
namespace MonitorChanges
{
public partial class Form1 : Form
{
string Path = #"D:\...", Ruta;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
fileSystemWatcher1.Path = Path;
GetFiles();
}
public void GetFiles()
{
string[] lst = Directory.GetFiles(Path);
textBox1.Text = "";
foreach(var sFile in lst)
{
textBox1.Text += sFile + Environment.NewLine;
Ruta = sFile;
}
}
private void fileSystemWatcher1_Changed(object sender, FileSystemEventArgs e)
{
}
private async void fileSystemWatcher1_Created(object sender, FileSystemEventArgs e)
{
GetFiles();
await GetToken(GetRuta());
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private string GetRuta()
{
return Ruta;
}
static async Task GetToken(string ruta)
{
string ClientId = "2825017b...";
string ClientSecret = "cGO8Q~...";
string TenantId = "36393c6b...";
string URL = "https://login.microsoftonline.com/" + TenantId + "/oauth2/v2.0/token";
HttpClient client = new HttpClient();
var content = new StringContent("grant_type = client_credentials" +
"&scope=https://api.businesscentral.dynamics.com/.default" +
"&client_id=" + HttpUtility.UrlEncode(ClientId) +
"&client_secret=" + HttpUtility.UrlEncode(ClientSecret));
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
var response = await client.PostAsync(URL, content);
if (response.IsSuccessStatusCode)
{
JObject Result = JObject.Parse(await response.Content.ReadAsStringAsync());
string BearerToken = Result["access_token"].ToString();
string URL2 = "https://api.businesscentral.dynamics.com/v2.0/36393c6b.../Production/ODataV4/Company('CRONUS%20MX')/VistaClientes";
HttpClient testclient = new HttpClient();
testclient.DefaultRequestHeaders.Add("Authorization", "Bearer " + BearerToken);
var result = await testclient.GetAsync(URL2);
if (result.IsSuccessStatusCode)
{
MessageBox.Show(await result.Content.ReadAsStringAsync());
List<Record> records = new List<Record>();
List<string> rows = File.ReadAllLines(ruta).ToList();
foreach (var row in rows)
{
string[] entries = row.Split(',');
//I consider entering the code here to send the values to the exposed page of Business Central
}
}
else
{
MessageBox.Show(result.StatusCode.ToString());
}
}
else
{
MessageBox.Show(response.StatusCode.ToString());
}
}
}
}
I've tried this
var newClient = "{\"Name\": " + entries[0] + ",\"Name_2\": " + entries[1] + ",\"Location_Code\": " + entries[2] + ",\"Post_Code\": " + entries[3] + ",\"Country_Region_Code\": " + entries[4] + ",\"Phone_Code\": " + entries[5] + "}";
HttpContent dataHttpContent = new StringContent(newClient, Encoding.UTF8, "application/json");
var dataResponse = await testclient.PostAsync(URL2, dataHttpContent);
MessageBox.Show(await dataResponse.Content.ReadAsStringAsync());
I get this error
Post request error

Related

Quickly iterate over the list and wait for a response

I have a large database with a list of site URLs that need to be processed. Faced the problem that it takes a very long time.
I haven't written anything in C # for a long time, I've forgotten it.
Tell me, is it really possible to make my while quickly go through the file, collect and send each line for processing.
I will explain. File - 5m links. Run while - he quickly read all lines and asynchronously made 5m httpwebrequest requests. You just have to wait.
If not, how can this be accelerated?
Start function: startSearch();
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace URLParser
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
label5.AutoSize = false;
label5.Height = 2;
label5.BorderStyle = BorderStyle.Fixed3D;
label5.Width = ClientRectangle.Width;
textBox2.Text = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
textBox3.Text = "FilenameExample";
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Text file";
ofd.Filter = "URL list (*.txt)|*.txt";
if (ofd.ShowDialog() == DialogResult.OK)
{
textBox1.Text = ofd.FileName;
}
}
private async void button3_Click(object sender, EventArgs e)
{
await startSearch();
}
private void button2_Click(object sender, EventArgs e)
{
using (FolderBrowserDialog dialog = new FolderBrowserDialog())
{
if (dialog.ShowDialog() == DialogResult.OK)
{
textBox2.Text = dialog.SelectedPath;
}
}
}
public int count;
public async Task startSearch()
{
var csv = new StringBuilder();
string outPath = textBox2.Text;
string outName = textBox3.Text;
count = 0;
string fileName = textBox1.Text;
if (File.Exists(fileName))
{
const Int32 BufferSize = 128;
using (var fileStream = File.OpenRead(fileName))
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8, true, BufferSize))
{
String line;
while ((line = streamReader.ReadLine()) != null)
{
var r = await cURL(line.Trim());
if(r != null)
{
using (var tw = new StreamWriter(outPath + "\\" + outName + ".csv", true))
{
tw.WriteLine(String.Join(", ", r));
}
}
textBox4.Text = count.ToString();
count++;
//break;
}
}
} else
{
MessageBox.Show("File not exist", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public async Task<string[]> cURL(string url)
{
String[] responseText = await Task.Run(() =>
{
string startURL = "", statusGet = "", respURL = "", getCMS = "", emailList = "";
if (!url.Contains("http"))
{
url = "http://" + url;
}
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.KeepAlive = true;
httpWebRequest.Date = DateTime.Now.Date;
httpWebRequest.Timeout = 4000;
httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36";
string requestResult = null;
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
int status = (int)httpResponse.StatusCode;
if (status == 200)
{
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
requestResult = streamReader.ReadToEnd();
string respUrl = httpResponse.ResponseUri.ToString();
HashSet<string> emails = new HashSet<string>();
Regex ItemRegex = new Regex(#"[a-z0-9_\-\+]+#[a-z0-9\-]+\.((?!.*png|.*jpg)[a-z]{2,10})(?:\.[a-z]{2})?", RegexOptions.Compiled);
foreach (Match ItemMatch in ItemRegex.Matches(requestResult))
{
emails.Add(ItemMatch.ToString());
}
startURL = url;
statusGet = status.ToString();
respURL = respUrl;
getCMS = GetCMS(requestResult);
emailList = String.Join(";", emails);
}
}
}
catch { }
if (!string.IsNullOrEmpty(statusGet) && !string.IsNullOrEmpty(respURL))
{
return new[] { startURL, statusGet, respURL, getCMS, emailList };
}
else
{
return null;
}
});
return responseText;
}
public string GetCMS(string html)
{
if(html.Contains(#"src=""/bitrix/") && html.Contains(#"<link href=""/bitrix")) {
return "Bitrix";
} else if(html.Contains(#"<meta name=""modxru""")) {
return "Modx";
} else if(html.Contains(#"idontknowhowtofindthiscms:D")) {
//return "October-CMS";
} else if(html.Contains(#"/netcat_files/") && html.Contains(#"<script type=""text/javascript"" src=""/netcat")) {
return "Netcat";
} else if(html.Contains(#"<img src=""/phpshop") && html.Contains(#"<script src=""/phpshop")) {
return "PhpShop";
} else if(html.Contains(#"<script type=""text/x-magento-init") && html.Contains(#"Magento_Ui/")) {
return "Magento";
} else if(html.Contains(#"/wa-data/public")) {
return "Shop-Script";
} else if(html.Contains(#"catalog/view/theme")) {
return "OpenCart";
} else if(html.Contains(#"data-drupal-")) {
return "Drupal";
} else if(html.Contains(#"/wp-content/")) {
return "Wordpress";
} else if(html.Contains(#"<meta name=""generator"" content=""Joomla")) {
return "Joomla";
} else if(html.Contains(#"var dle_admin")) {
return "DataLife Engine";
}
return String.Empty;
}
}
}
As per HttpWebRequest documentation:
We don't recommend that you use HttpWebRequest for new development. Instead, use the System.Net.Http.HttpClient class.
Also HttpClient fluently and by default reusing the connections and has async API out-of-the-box.
Here's an example with HttpClient and some additional tweaks. Only changed methods:
// HttpClient is intended to be instantiated once per application, rather than per-use.
private static readonly HttpClient httpClient = new HttpClient();
private void Form1_Load(object sender, EventArgs e)
{
// ...existing code...
ServicePointManager.DefaultConnectionLimit = 10; // this line is not needed in .NET Core
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36");
httpClient.DefaultRequestHeaders.Connection.ParseAdd("keep-alive");
httpClient.Timeout = TimeSpan.FromSeconds(4);
}
// rewritten method
public async Task<string[]> cURL(string url, SemaphoreSlim semaphore)
{
try
{
if (!url.StartsWith("http")) url = "http://" + url;
using (HttpResponseMessage response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false))
{
if (response.IsSuccessStatusCode)
{
string statusGet = ((int)response.StatusCode).ToString();
string respURL = response.RequestMessage.RequestUri.ToString();
string requestResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
HashSet<string> emails = new HashSet<string>();
Regex ItemRegex = new Regex(#"[a-z0-9_\-\+]+#[a-z0-9\-]+\.((?!.*png|.*jpg)[a-z]{2,10})(?:\.[a-z]{2})?", RegexOptions.Compiled);
foreach (Match ItemMatch in ItemRegex.Matches(requestResult))
{
emails.Add(ItemMatch.ToString());
}
string getCMS = GetCMS(requestResult);
string emailList = string.Join(";", emails);
return new[] { url, statusGet, respURL, getCMS, emailList };
}
}
return null;
}
catch
{
return null;
}
finally
{
semaphore.Release();
}
}
This code must be faster than existing one.
For more performance boost need adding some concurrency for startSearch():
using (StreamReader sr = new StreamReader(fileStream, Encoding.UTF8, true, BufferSize))
using (SemaphoreSlim semaphore = new SemaphoreSlim(Environment.ProcessorCount * 2))
{
List<Task<string[]>> tasks = new List<Task<string[]>>();
while (!sr.EndOfStream)
{
await semaphore.WaitAsync();
tasks.Add(cURL(sr.ReadLine().Trim(), semaphore));
if (tasks.Count == 1000 || sr.EndOfStream) // flush results
{
string[][] results = await Task.WhenAll(tasks);
using (StreamWriter sw = new StreamWriter(outPath + "\\" + outName + ".csv", true))
{
foreach (string[] r in results)
{
if (r != null) sw.WriteLine(string.Join(", ", r));
}
}
tasks.Clear();
}
textBox4.Text = count.ToString();
count++;
}
}

Pass parameters to WebClient.DownloadFileCompleted event

I am using the WebClient.DownloadFileAsync() method, and wanted to know how can i pass a parameter to the WebClient.DownloadFileCompleted event (or any other event for that matter), and use it in the invoked method.
My code:
public class MyClass
{
string downloadPath = "some_path";
void DownloadFile()
{
int fileNameID = 10;
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += DoSomethingOnFinish;
Uri uri = new Uri(downloadPath + "\" + fileNameID );
webClient.DownloadFileAsync(uri,ApplicationSettings.GetBaseFilesPath +"\" + fileNameID);
}
void DoSomethingOnFinish(object sender, AsyncCompletedEventArgs e)
{
//How can i use fileNameID's value here?
}
}
How can I pass a parameter to DoSomethingOnFinish()?
You can use webClient.QueryString.Add("FileName", YourFileNameID); to add extra information.
Then to access it in your DoSomethingOnFinish function,
use string myFileNameID = ((System.Net.WebClient)(sender)).QueryString["FileName"]; to receive the file name.
This is what the code should look like:
string downloadPath = "some_path";
void DownloadFile()
{
int fileNameID = 10;
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(DoSomethingOnFinish);
webClient.QueryString.Add("fileName", fileNameID.ToString());
Uri uri = new Uri(downloadPath + "\\" + fileNameID);
webClient.DownloadFileAsync(uri,ApplicationSettings.GetBaseFilesPath +"\\" + fileNameID);
}
void DoSomethingOnFinish(object sender, AsyncCompletedEventArgs e)
{
//How can i use fileNameID's value here?
string myFileNameID = ((System.Net.WebClient)(sender)).QueryString["fileName"];
}
Even if this should work, you should be using Unity's UnityWebRequest class. You probably haven't heard about it but this is what it should look like:
void DownloadFile(string url)
{
StartCoroutine(downloadFileCOR(url));
}
IEnumerator downloadFileCOR(string url)
{
UnityWebRequest www = UnityWebRequest.Get(url);
yield return www.Send();
if (www.isError)
{
Debug.Log(www.error);
}
else
{
Debug.Log("File Downloaded: " + www.downloadHandler.text);
// Or retrieve results as binary data
byte[] results = www.downloadHandler.data;
}
}

How to connect/pair devices correctly on wifi direct?

It is my first program on wifi direct so I made a simple program that just discover all nearby devices and then try to connect to one of them the discovery works fine and gets all the devices the problem is in the connection that always fails after using this function WiFiDirectDevice.FromIdAsync() it keeps paring for too long and then it fails always.
I was following the code on this microsoft tutorial: https://channel9.msdn.com/Events/Build/2015/3-98
Here is my code:
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace App7
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
DeviceInformationCollection DevicesFound;
WiFiDirectAdvertisementPublisher pub;
WiFiDirectConnectionListener listener;
CancellationTokenSource m_CancellationTokenSource;
private async void button_Click(object sender, RoutedEventArgs e)
{
String DeviceSelector = WiFiDirectDevice.GetDeviceSelector(WiFiDirectDeviceSelectorType.AssociationEndpoint);
DevicesFound = await DeviceInformation.FindAllAsync(DeviceSelector);
if(DevicesFound.Count>0)
{
connectedDeviceslist.ItemsSource = DevicesFound;
var dialog = new MessageDialog(DevicesFound[0].Name);
await dialog.ShowAsync();
}
}
private async void button1_Click(object sender, RoutedEventArgs e)
{
int selectedIndex = connectedDeviceslist.SelectedIndex;
String deviceID = DevicesFound[selectedIndex].Id;
var selecetedDevice = DevicesFound[selectedIndex];
try
{
WiFiDirectConnectionParameters connectionParams = new WiFiDirectConnectionParameters();
connectionParams.GroupOwnerIntent = Convert.ToInt16("1");
connectionParams.PreferredPairingProcedure = WiFiDirectPairingProcedure.GroupOwnerNegotiation;
m_CancellationTokenSource = new CancellationTokenSource();
var wfdDevice = await WiFiDirectDevice.FromIdAsync(selecetedDevice.Id, connectionParams).AsTask(m_CancellationTokenSource.Token);
var EndpointPairs = wfdDevice.GetConnectionEndpointPairs();
}
catch(Exception ex)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.High, async() =>
{
var dialog = new MessageDialog(ex.Message);
await dialog.ShowAsync();
});
}
}
private void button2_Click(object sender, RoutedEventArgs e)
{
pub = new WiFiDirectAdvertisementPublisher();
pub.Advertisement.ListenStateDiscoverability = WiFiDirectAdvertisementListenStateDiscoverability.Normal;
listener = new WiFiDirectConnectionListener();
listener.ConnectionRequested += OnConnectionRequested;
pub.Start();
}
private async void OnConnectionRequested(WiFiDirectConnectionListener sender, WiFiDirectConnectionRequestedEventArgs args)
{
try
{
var ConnectionRequest = args.GetConnectionRequest();
var tcs = new TaskCompletionSource<bool>();
var dialogTask = tcs.Task;
var messageDialog = new MessageDialog("Connection request received from " + ConnectionRequest.DeviceInformation.Name, "Connection Request");
// Add commands and set their callbacks; both buttons use the same callback function instead of inline event handlers
messageDialog.Commands.Add(new UICommand("Accept", null, 0));
messageDialog.Commands.Add(new UICommand("Decline", null, 1));
// Set the command that will be invoked by default
messageDialog.DefaultCommandIndex = 1;
// Set the command to be invoked when escape is pressed
messageDialog.CancelCommandIndex = 1;
await Dispatcher.RunAsync(CoreDispatcherPriority.High, async () =>
{
// Show the message dialog
var commandChosen = await messageDialog.ShowAsync();
tcs.SetResult((commandChosen.Label == "Accept") ? true : false);
});
var fProceed = await dialogTask;
if (fProceed == true)
{
var tcsWiFiDirectDevice = new TaskCompletionSource<WiFiDirectDevice>();
var wfdDeviceTask = tcsWiFiDirectDevice.Task;
// WriteToOutput("Connecting to " + ConnectionRequest.DeviceInformation.Name + "...");
WiFiDirectConnectionParameters ConnectionParams = new WiFiDirectConnectionParameters();
await Dispatcher.RunAsync(CoreDispatcherPriority.High, async () =>
{
try
{
ConnectionParams.GroupOwnerIntent = 14;
tcsWiFiDirectDevice.SetResult(await WiFiDirectDevice.FromIdAsync(ConnectionRequest.DeviceInformation.Id, ConnectionParams));
}
catch (Exception ex)
{
// WriteToOutput("FromIdAsync task threw an exception: " + ex.ToString());
}
});
WiFiDirectDevice wfdDevice = await wfdDeviceTask;
var EndpointPairs = wfdDevice.GetConnectionEndpointPairs();
/* m_ConnectedDevices.Add("dummy", wfdDevice);
WriteToOutput("Devices connected on L2, listening on IP Address: " + EndpointPairs[0].LocalHostName.ToString() + " Port: " + Globals.strServerPort);
StreamSocketListener listenerSocket = new StreamSocketListener();
listenerSocket.ConnectionReceived += OnSocketConnectionReceived;
await listenerSocket.BindEndpointAsync(EndpointPairs[0].LocalHostName, Globals.strServerPort);*/
}
else
{
/* // Decline the connection request
WriteToOutput("Connection request from " + ConnectionRequest.DeviceInformation.Name + " was declined");
ConnectionRequest.Dispose();*/
}
}
catch (Exception ex)
{
//WriteToOutput("FromIdAsync threw an exception: " + ex.ToString());
}
}
}
}

MongoDb as a Datasource for C# .net

Hi Im trying to display the Items I saved in a gridfs in a datagrid view and retrieve them by clicking it, but So far Im having trouble just querying mongo. Im not sure what the nominal Document type it requires
var cursor = collection.FindAs()
most other examples use collection.Find(). But I didnt tie Mongo to a class.
heres my code , can you help me get it to work.
public partial class WebForm1 : System.Web.UI.Page
{
MongoClient client;
MongoServer server;
MongoDatabase database;
MongoGridFs gridFs;
MongoCollection gridCol;
protected void Page_Load(object sender, EventArgs e)
{
client = new MongoClient();
server = client.GetServer();
database = server.GetDatabase("mydb");
gridCol = database.GetCollection("fs");
}
protected void Button1_Click1(object sender, EventArgs e)
{
//gridCol.FindAllAs<CFilez>
MongoCollection collection = database.GetCollection("fs");
var searchQuery = Query.EQ("gefunden", "one");
var cursor = collection.FindAs(
MongoCursor<CFilez> cursor = collection.FindAllAs<CFilez>();
cursor.SetLimit(5);
var list = cursor.ToList();
GridView1.DataSource = list;
GridView1.DataBind();
StatusLabel.Text = "Jive";
}
protected void Button2_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
client = new MongoClient();
server = client.GetServer();
database = server.GetDatabase("mydb");
string filename = FileUpload1.FileName;
////File file = File.OpenRead(filename);
FileUpload1.SaveAs(Server.MapPath("~/Data/") + filename);
String Fpath = Server.MapPath("~/Data/") + filename;
////FileUpload1.SaveAs(Server.MapPath("~/Data/") + filename);
////var id = ObjectId.Empty;
//Stream file = File.OpenRead(Fpath);
////gridFs.AddFile(file, filename);
//gridFs.AddFile(filename);
using (var fs = new FileStream(Fpath, FileMode.Open))
{
var gridFsInfo = database.GridFS.Upload(fs, filename);
var fileId = gridFsInfo.Id;
}
StatusLabel.Text = "Upload status: File uploaded!";
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}

how to get log file for multiple users in c#

public partial class Loginform : Form
{
public Loginform()
{
InitializeComponent();
}
private void btnlogin_Click(object sender, EventArgs e)
{
string dir = "D://Login.hhh";
if (!File.Exists(dir))
{
File.Create(dir);
}
string filePath = dir;
string s = System.Environment.GetEnvironmentVariable("COMPUTERNAME");
string s1 = getIP();
using (StreamWriter swrObj = new StreamWriter(filePath, true))
{
swrObj.Write(s1 + "|" + s + "|" + Txtusername.Text + "|" + "user logged in on :|" + DateTime.Now.ToShortDateString() + " at " + DateTime.Now.ToShortTimeString());
swrObj.Write("\t\t");
swrObj.Write("\t\t");
swrObj.WriteLine();
MessageBox.Show("Login success");
}
}
private void Loginform_Load(object sender, EventArgs e)
{
}
private string getIP()
{
IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily.ToString() == "InterNetwork")
{
localIP = ip.ToString();
}
}
return localIP;
}
}
I want to apply log file for project in C#, I am using above method to to create log file for getting system name, IP address and user login, but it is applicable in single user environment, if apply this in multi-user environment, How to get all users log info? please any one help me?
i assume that you want to create Log file for each user , then you can just do it like this:-
private void btnlogin_Click(object sender, EventArgs e)
{
string s1 = getIP();
string dir = "D://"+s1+"-"+DateTime.Now+"Login.hhh";
if (!File.Exists(dir))
{
File.Create(dir);
}
string filePath = dir;
string s = System.Environment.GetEnvironmentVariable("COMPUTERNAME");
using (StreamWriter swrObj = new StreamWriter(filePath, true))
{
swrObj.Write(s1 + "|" + s + "|" + Txtusername.Text + "|" + "user logged in on :|" + DateTime.Now.ToShortDateString() + " at " + DateTime.Now.ToShortTimeString());
swrObj.Write("\t\t");
swrObj.Write("\t\t");
swrObj.WriteLine();
MessageBox.Show("Login success");
}
}

Categories

Resources