MongoDb as a Datasource for C# .net - c#

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;
}
}
}

Related

Requests POST with Bearer token in ASP.NET

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

Displaying progress of file download in a ProgressBar with SSH.NET

I want to show the progress of a downloading process on my ProgressBar. I tried to do somethings like this code for upload, but I failed. Here is an example of my failed attempts
private void button5_Click(object sender, EventArgs e)
{
Task.Run(() => Download());
}
private void Download()
{
try
{
int Port = (int)numericUpDown1.Value;
string Host = comboBox1.Text;
string Username = textBox3.Text;
string Password = textBox4.Text;
string SourcePath = textBox5.Text;
string RemotePath = textBox6.Text;
string FileName = textBox7.Text;
using (var file = File.OpenWrite(SourcePath + FileName))
using (var Stream = new FileStream(SourcePath + FileName, FileMode.Open))
using (var Client = new SftpClient(Host, Port, Username, Password))
{
Client.Connect();
progressBar1.Invoke((MethodInvoker)
delegate
{
progressBar1.Maximum = (int)Stream.Length;
});
Client.DownloadFile(RemotePath + FileName, /*file*/ Stream, DownloadProgresBar);
Client.Disconnect();
}
}
catch (Exception Ex)
{
System.Windows.Forms.MessageBox.Show(Ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void DownloadProgresBar(ulong Downloaded)
{
progressBar1.Invoke((MethodInvoker)
delegate
{
progressBar1.Value = (int)Downloaded;
});
}
Thank you in advance
As you correctly did, similarly to the code for displaying progress of file upload, you have to provide a callback to the downloadCallback argument of SftpClient.DownloadFile.
public void DownloadFile(
string path, Stream output, Action<ulong> downloadCallback = null)
Also you correctly download on a background thread. Alternatively, you could use an asynchronous upload (SftpClient.BeginDownloadFile).
What is wrong and needs change:
You have to open/create the local file for writing (FileMode.Create).
You have to retrieve a size of the remote file, not the local one (not existing yet). Use SftpClient.GetAttributes.
Example using a background thread (task):
private void button1_Click(object sender, EventArgs e)
{
// Run Download on background thread
Task.Run(() => Download());
}
private void Download()
{
try
{
int Port = 22;
string Host = "example.com";
string Username = "username";
string Password = "password";
string RemotePath = "/remote/path/";
string SourcePath = #"C:\local\path\";
string FileName = "download.txt";
string SourceFilePath = SourcePath + FileName;
using (var stream = new FileStream(SourceFilePath, FileMode.Create))
using (var client = new SftpClient(Host, Port, Username, Password))
{
client.Connect();
string RemoteFilePath = RemotePath + FileName;
SftpFileAttributes attrs = client.GetAttributes(RemoteFilePath);
// Set progress bar maximum on foreground thread
int max = (int)attrs.Size;
progressBar1.Invoke(
(MethodInvoker)delegate { progressBar1.Maximum = max; });
// Download with progress callback
client.DownloadFile(RemoteFilePath, stream, DownloadProgresBar);
MessageBox.Show("Download complete");
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
private void DownloadProgresBar(ulong uploaded)
{
// Update progress bar on foreground thread
progressBar1.Invoke(
(MethodInvoker)delegate { progressBar1.Value = (int)uploaded; });
}
For upload see:
Displaying progress of file upload in a ProgressBar with SSH.NET

Windows Phone 8 FtpClient won't upload stream data previously used for issue with BitmapImage

I will try my best to explain the issue clearly. I'm using the code from
http://msdn.microsoft.com/en-us/magazine/dn385710.aspx
to create a photo sharing app. I am able to FTP images to my server fine. The issue I'm facing is when I tried to create the app to preview the picture and then FTP it. The FTP will still transfer the file, but the file size is always 0 size. I'm not sure if this is a bug or possibly me not disposing a certain object before FTP. Below are my codes:
Page 1
BitmapImage bitmapImage;
public PhotoPreview()
{
InitializeComponent();
btnYes.Tap += btnYes_Tap;
imgPreview.Width = G.getScreenWidth();
imgPreview.Height = G.getScreenHeight() - 250;
//windows phone 8 bug. When bitmap image is set...it blocks the FTP process thread. Will perform FTP on seperate page
previewPhoto();
}
void previewPhoto()
{
bitmapImage = new BitmapImage();
bitmapImage.SetSource(G.myStream);
imgPreview.Source = bitmapImage;
}
private void btnYes_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
disposeImage(bitmapImage);
NavigationService.Navigate(new Uri("/PhotoFTP.xaml", UriKind.Relative));
}
private void disposeImage(BitmapImage img)
{
if (img != null)
{
try
{
using (var ms = new MemoryStream(new byte[] { 0x0 }))
{
img = new BitmapImage();
img.SetSource(ms);
}
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("ImageDispose FAILED " + e.Message);
}
}
}
Page 2
const string
IP_ADDRESS = "888.88.888",
FTP_USERNAME = "test",
FTP_PASSWORD = "test123"
;
string filename;
FtpClient ftpClient = null;
TestLogger logger = null;
public PhotoFTP()
{
InitializeComponent();
DateTime thisDay = DateTime.Today;
string timestamp = thisDay.Hour.ToString() + "_" + thisDay.Minute.ToString() + "_" + thisDay.Second.ToString();
filename = timestamp + ".jpg";
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Test_connect();
}
private async void Test_connect()
{
logger = TestLogger.GetDefault(this.Dispatcher);
lstLogs.ItemsSource = logger.Logs;
ftpClient = new FtpClient(IP_ADDRESS, this.Dispatcher);
ftpClient.FtpConnected += ftpClient_FtpConnected;
ftpClient.FtpFileUploadSucceeded += ftpClient_FtpFileUploadSucceeded;
ftpClient.FtpFileUploadFailed += ftpClient_FtpFileUploadFailed;
ftpClient.FtpAuthenticationSucceeded += ftpClient_FtpAuthenticationSucceeded;
ftpClient.FtpAuthenticationFailed += ftpClient_FtpAuthenticationFailed;
logger = TestLogger.GetDefault(this.Dispatcher);
await ftpClient.ConnectAsync();
logger.AddLog("Connecting...");
}
async void ftpClient_FtpConnected(object sender, EventArgs e)
{
logger.AddLog("Preparing...");
await (sender as FtpClient).AuthenticateAsync(FTP_USERNAME, FTP_PASSWORD);
}
private async void Test_upload()
{
logger.AddLog("Uploading photo...");
await ftpClient.UploadFileAsync(G.myStream, "username_timestamp.jpg");
}
void ftpClient_FtpAuthenticationFailed(object sender, EventArgs e)
{
logger.AddLog("Connection error.");
}
void ftpClient_FtpAuthenticationSucceeded(object sender, EventArgs e)
{
logger.AddLog("Connection established.");
Test_upload();
}
void ftpClient_FtpFileUploadFailed(object sender, FtpFileTransferFailedEventArgs e)
{
logger.AddLog("Failed.");
}
Boolean firstTime = true;
void ftpClient_FtpFileUploadSucceeded(object sender, FtpFileTransferEventArgs e)
{
logger.AddLog("Completed.");
}
If I comment out the line previewPhoto(); in page 1, it will FTP the file to my server fine. I believe the issue is the
bitmapImage.SetSource(G.myStream);
I've also tried to create two separate stream. One to preview the photo and the other to FTP. The result still resulted in 0 size file when FTP to the my server.
It's because the BitmapImage reads to the end of the stream, so the FtpClient has no data to read/upload.
Use Stream.Seek to reset the stream pointer back to the beginning.
G.myStream.Seek(0, SeekOrigin.Begin);

I want to upload files with a C# windows forms project to a webserver

I want to create a C# application using windows forms that let me upload files to a webserver, i have seen a lot of tutorial and everyone of them prove to be useless to solve my problem.
and with my project i have the next code in the button for upload
WebClient client = new WebClient();
client.UploadFile("http://localhost:8080/", location);
from here i had have several errors, an try multiple ideas, some of my more common errors are 404 not found or innaccessible path, also sometimes it doenst display me an error and works but the file doesn't save in the indicated path.
some of the links i use to solve the problem are the next ones:
http://www.c-sharpcorner.com/UploadFile/scottlysle/UploadwithCSharpWS05032007121259PM/UploadwithCSharpWS.aspx
http://www.c-sharpcorner.com/Blogs/8180/
How to upload a file in window forms?
upload a file to FTP server using C# from our local hard disk.
private void UploadFileToFTP()
{
FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create("ftp://www.server.com/sample.txt");
ftpReq.UseBinary = true;
ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
ftpReq.Credentials = new NetworkCredential("user", "pass");
byte[] b = File.ReadAllBytes(#"E:\sample.txt");
ftpReq.ContentLength = b.Length;
using (Stream s = ftpReq.GetRequestStream())
{
s.Write(b, 0, b.Length);
}
FtpWebResponse ftpResp = (FtpWebResponse)ftpReq.GetResponse();
if (ftpResp != null)
{
if(ftpResp.StatusDescription.StartsWith("226"))
{
Console.WriteLine("File Uploaded.");
}
}
}
In windows:
private void uploadButton_Click(object sender, EventArgs e)
{
var openFileDialog = new OpenFileDialog();
var dialogResult = openFileDialog.ShowDialog();
if (dialogResult != DialogResult.OK) return;
Upload(openFileDialog.FileName);
}
private void Upload(string fileName)
{
var client = new WebClient();
var uri = new Uri("http://www.yoursite.com/UploadMethod/");
try
{
client.Headers.Add("fileName", System.IO.Path.GetFileName(fileName));
var data = System.IO.File.ReadAllBytes(fileName);
client.UploadDataAsync(uri, data);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
In server:
[HttpPost]
public async Task<object> UploadMethod()
{
var file = await Request.Content.ReadAsByteArrayAsync();
var fileName = Request.Headers.GetValues("fileName").FirstOrDefault();
var filePath = "/upload/files/";
try
{
File.WriteAllBytes(HttpContext.Current.Server.MapPath(filePath) + fileName, file);
}
catch (Exception ex)
{
// ignored
}
return null;
}
winform
string fullUploadFilePath = #"C:\Users\cc\Desktop\files\test.txt";
string uploadWebUrl = "http://localhost:8080/upload.aspx";
client.UploadFile(uploadWebUrl , fullUploadFilePath );
asp.net create upload.aspx as below
<%# Import Namespace="System"%>
<%# Import Namespace="System.IO"%>
<%# Import Namespace="System.Net"%>
<%# Import NameSpace="System.Web"%>
<Script language="C#" runat=server>
void Page_Load(object sender, EventArgs e) {
foreach(string f in Request.Files.AllKeys) {
HttpPostedFile file = Request.Files[f];
file.SaveAs(Server.MapPath("~/Uploads/" + file.FileName));
}
}
</Script>
<html>
<body>
<p> Upload complete. </p>
</body>
</html>
you should set in win app
WebClient myWebClient = new WebClient();
string fileName = "File Address";
Console.WriteLine("Uploading {0} to {1} ...",fileName,uriString);
// Upload the file to the URI.
// The 'UploadFile(uriString,fileName)' method implicitly uses HTTP POST method.
byte[] responseArray = myWebClient.UploadFile(uriString,fileName);
then set read and write permission for SubDir
create a simple API Controller file in the Controllers folder and name it UploadController.
Let’s modify that file by adding a new action that will be responsible for the upload logic:
[HttpPost, DisableRequestSizeLimit]
public IActionResult UploadFile()
{
try
{
var file = Request.Form.Files[0];
string folderName = "Upload";
string webRootPath = _host.WebRootPath;
string newPath = Path.Combine(webRootPath, folderName);
string ext = Path.GetExtension(file.FileName);
if (!Directory.Exists(newPath))
{
Directory.CreateDirectory(newPath);
}
if (file.Length > 0)
{
string fileName = "";
string name = Path.GetFileNameWithoutExtension(file.FileName);
string fullPath = Path.Combine(newPath, name + ext);
int counter = 2;
while (System.IO.File.Exists(fullPath))
{
fileName = name + "(" + counter + ")" + ext;
fullPath = Path.Combine(newPath, fileName);
counter++;
}
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
}
return Ok();
}
return Ok();
}
catch (System.Exception ex)
{
return BadRequest();
}
}
We are using a POST action for the upload-related logic and disabling the request size limit as well.
and use code below in Winform
private void Upload(string fileName)
{
var client = new WebClient();
var uri = new Uri("https://localhost/api/upload");
try
{
client.Headers.Add("fileName", System.IO.Path.GetFileName(fileName));
client.UploadFileAsync(uri, directoryfile);
client.UploadFileCompleted += Client_UploadFileCompleted;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Client_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
{
MessageBox.Show("done");
}
Goodluck

uploadfile windows form C# web service

i'm new here,
help me out here please,
i am working with web service and doing upload file.
here's my code for uploading file
private void Button_Click(object sender, RoutedEventArgs e)
{
testServiceClient = new TestServiceClient();
var uploadFile = "C:\\Computer1\\Sample.csv";
try
{
var dir = #"\\Computer2\UploadedFile\";
string myUploadPath = dir;
var myFileName = Path.GetFileName(uploadFile);
var client = new WebClient { Credentials = CredentialCache.DefaultNetworkCredentials };
client.UploadFile(myUploadPath + myFileName, "PUT", uploadFile);
client.Dispose();
MessageBox.Show("ok");
testServiceClient.Close();
}
catch (Exception ex)
{
ex.ToString();
}
}
i can upload file in the same network, but my question is this,
how can i upload file when the two computer is not in the same network?
i've tried changing the
var dir = #"\\Computer2\UploadedFile\";
to
var dir = #"https://Computer2/UploadedFile/";
but i'm getting an error 'unable to connect to remote server'
help me out here pls.
In windows:
private void uploadButton_Click(object sender, EventArgs e)
{
var openFileDialog = new OpenFileDialog();
var dialogResult = openFileDialog.ShowDialog();
if (dialogResult != DialogResult.OK) return;
Upload(openFileDialog.FileName);
}
private void Upload(string fileName)
{
var client = new WebClient();
var uri = new Uri("https://Computer2/UploadedFile/");
try
{
client.Headers.Add("fileName", System.IO.Path.GetFileName(fileName));
var data = System.IO.File.ReadAllBytes(fileName);
client.UploadDataAsync(uri, data);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
In server:
[HttpPost]
public async Task<object> UploadedFile()
{
var file = await Request.Content.ReadAsByteArrayAsync();
var fileName = Request.Headers.GetValues("fileName").FirstOrDefault();
var filePath = "/upload/files/";
try
{
File.WriteAllBytes(HttpContext.Current.Server.MapPath(filePath) + fileName, file);
}
catch (Exception ex)
{
// ignored
}
return null;
}
I think the problem is that you are not actually sending the file with your UploadFile() method, you are just sending the file path. you should be sending the file bytes.
This link is quite usefull: http://www.codeproject.com/Articles/22985/Upload-Any-File-Type-through-a-Web-Service

Categories

Resources