Abcpdf HttpContent.Create FileNotFoundException in ASP.net mvc context but file exist - c#

I use Abcpdf,
Sometimes I get in production FileNotFoundException after creation of HttpMultipartMimeForm with path use by the HttpContent.Create( methode
The major part of time this code works well
The PDF is creat in context where
ASP.NET website A is called
A call website B to generate the PDF
Website B call url on B for HTML to PDF abcpdf method.
After previous request to B is finish, website A send file to server C via HttpClient HttpMultipartMimeForm and Exception is throw sometimes, but when I look on the server the file exist
A and B is on the same machine and sharing the same directories.
I supposed that the file is not finish to write on disk when I try to acces on it. But how to resolved this ?
Thanks.
1. Server A
using (HttpClient pdfClient = new HttpClient("http://" + ConfigurationManager.AppSettings["xxx"]))
{
using (HttpResponseMessage message = pdfClient.Get(UrlDictionary.callxxx(xxxID, xxxID)))
{
message.EnsureStatusIsSuccessful();
message.Content.ReadAsStream();
}
}
2. Server B
theDoc.Save(HostingEnvironment.ApplicationPhysicalPath + "/xxx/" + ".pdf");
theDoc.Clear();
3. Server A
HttpMultipartMimeForm request = new HttpMultipartMimeForm();
FileInfo info = new FileInfo(pathFile);
HttpFormFile file = new HttpFormFile();
file.Content = **HttpContent.Create(info, "multipart/form-data")**; (Exception FileNotFoundException)
file.FileName = info.Name;
file.Name = "file";
request.Files.Add(file);
request.Add("id", id);
using (HttpResponseMessage response = client.Post(
string.Format("/xxx/{0}", id),
request.CreateHttpContent()))
{
ExceptionIfBadRequest(response);
Contrat contrat = (Contrat)FromXml(response.Content.ReadAsString(), typeof(Contrat));
return contrat;
}

Check the permissions on the PDF file and the directory, check the file doesn't have some 'zone' information attached to it.

Related

file saved path on Azure

I'm new to .NET Core and Azure I have created an API with SQL-Server and I used Dapper for saving the path to the database for POST form-data with an image, like this:
private async Task<string> WriteFile(Image image)
{
String fileName;
IFormFile file = image.image;
long Id = image.ShopId;
try
{
var extension = "." + file.FileName.Split('.')[file.FileName.Split('.').Length - 1];
fileName = Guid.NewGuid().ToString() + extension;
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\cccc", fileName);
using (var bits = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(bits);
}
Image imageupload = new Image(path,Id);
toDb(imageupload);
}
catch (Exception e)
{
return e.Message;
}
return fileName;
}
public void toDb(Image imageUpload)
{
string path = imageUpload.path;
long ShopId = unchecked((int)imageUpload.ShopId);
using (IDbConnection dbConnection = Connection)
{
string sQuery = "UPDATE shop SET path = #path WHERE ShopId = #ShopId ;";
dbConnection.Open();
dbConnection.Execute(sQuery, new {path = path,ShopId = ShopId});
}
}
Before I deployed to Azure it returned image path "F:\\xxxx\\yyyyy\\zzzzzz\\aaaaaa\\wwwroot\\bbbbbb\\5d665cbc-679d-4926-862b-4e10f9358e8a.png"
After i deployed it return my image path
D:\\home\\site\\wwwroot\\wwwroot\\Shops\\a81c757e-df7e-4cf6-b778-20fc5fcf922d.png
can i view image by using this path if it possible how it view;
If the error is my path that file tried to save to how can I fix it? If I changed saved path to wwwroot\\bbbbbb\\5d665cbc-679d-4926-862b-4e10f9358e8a.png can I viewed file it from client app if its also not possible. How can i fixed this?
can i view image by using this path if it possible how it view.
Yes, in the Azure WebApp D:\home is shared for us. We could get more information about Azure WebApp Sandbox from this tutorial.
We could use the Kudu(To access your KUDU console, using your DEPLOYMENT credentials, navigate to https://*****.scm.azurewebsites.net where ***** is the name of your Web App.) to view, upload or download the files.
We also could use the FTP tool to download or upload the files to Azure WebApp site.
can I viewed file it from client app if its also not possible. How can i fixed this?
I recommand that you could store the image information to Azure storge. It is easy for us to access from client side. For more information about how to use Azure Storage, please refer to this document.

Add downloaded images to resource folder

I have downloaded an image with the following code:
bool pageExists = false;
// Check if webpage exists
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://image.tmdb.org/t/p/w780" + imagePath);
request.Method = WebRequestMethods.Http.Head;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
pageExists = response.StatusCode == HttpStatusCode.OK;
}
// Download image
if (pageExists)
{
string localFilename = #"C:\Users\Giri\Desktop\giri" + id + ".jpg";
using (WebClient client = new WebClient())
{
client.DownloadFile("http://image.tmdb.org/t/p/w780" + imagePath, localFilename);
}
}
For now, I have just been saving this image on my Desktop.
My question is how do I go about storing this image in my WPF application programmatically within a resources folder or a folder I have generated myself? The images should persist in that the next time the application is run, the added images should remain.
Is there an accepted place I should be storing my images?
Thanks for your help.
Please use AppDomain.CurrentDomain.BaseDirectory. Which will give you the directory of your executable. Even in deployed code this should give you the right value. But other values like Environment.CurrentDirectory can give different value based on from where you are calling it etc.
See this question Best way to get application folder path

Upload file to skydrive through SkyDrive API

I try to upload a text file to my skydrive or at least create new text file in SD and edit it's content, through SkyDrive API in my Windows 8 application.
How can I do that?
I tried to do something like that:
LiveConnectClient client = new LiveConnectClient(session);
var fileData = new Dictionary<string, object>();
fileData.Add("name", "new_file.txt");
try
{
LiveOperationResult fileOperationResult = await client.PutAsync("me/skydrive", fileData);
this.infoTextBlock.Text = fileOperationResult.ToString();
}
catch (LiveConnectException exception)
{
this.infoTextBlock.Text = exception.Message;
}
but I get error
"The provided request is not valid. The root SkyDrive folder cannot be updated."
If I write something like "me/skydrive/" I get
"The provided URL is not valid. The requested path '' is not supported".
Method LiveConnectClient.PutAsync allows me only to update existing properties (but not it's content).
How it should be done properly?
Btw - Is content on LCDC(http://msdn.microsoft.com/en-us/library/live/hh826531.aspx) updated? I'm asking because some methods, which are in documentation, doesn't exist in dlls (f.e. LiveConnectClient.Upload. There's only BackgroundUploadAsync).
Thanks for help in advance,
Micheal
Close but as I wrote: I can't use client.upload method because LiveConnectClient class doesn't contain it. That's why I asked about site content update.
Anyway - I've got an answer:
//create a StorageFile (here is one way to do that if it is stored in your ApplicationData)
StorageFile file = awaitApplicationData.Current.LocalFolder.GetFileAsync("yourfilename.txt");
try {
client = new LiveConnectClient(session);
LiveOperationResult operationResult = await client.BackgroundUploadAsync("me/skydrive", file.Name, file, OverwriteOption.Overwrite);
}
catch (LiveConnectException exception) {
//handle exception
}
You should use the Upload method on LiveConnectionClient. For example, see the Uploading Files example in the Live SDK. Something like ...
LiveOperationResult fileOperationResult =
await client.Upload("me/skydrive", /*file name here*/, /*file stream here*/);
Here's another way to upload a file from a console application using a SkyDriveApiClient downloaded from http://skydriveapiclient.codeplex.com/releases/view/103081
static void Main(string[] args)
{
var client = new SkyDriveServiceClient();
client.LogOn("YourEmail#hotmail.com", "password");
WebFolderInfo wfInfo = new WebFolderInfo();
WebFolderInfo[] wfInfoArray = client.ListRootWebFolders();
wfInfo = wfInfoArray[0];
client.Timeout = 1000000000;
string fn = #"test.txt";
if (File.Exists(fn))
{
client.UploadWebFile(fn, wfInfo);
}
}

How to upload an image file to Active Directory user profile in C#?

I need a method which will take an *.jpg image file and upload it to a user profile in the Active Directory of Windows AD 2003.
Also a method to retrieve the photo as stream or expose it as secure web service to be called by cross platform apps in java etc (Damn! am I asking too much!!!)
The file being uploaded will be a *.jpg which is basically a visual signature file created by a user.
Does anyone having any experience working with Active Directory in C# provide some information as to how this can be done with minimum implication related to security.
From the point of view of the Windows Active Directory Administrator what does he have to
do to make this possible.Changes/provisions to schema of user profile etc.
The image is being uploaded so that it can be later retrieved from the AD to be inserted into PDF document for signature purposes.
Can this be done in C#? Or is there any done libraries etc?
Here's a series of blog postings with code that shows how to do it:
(The first shows how to get a photo in, the second shows how to get it out)
Using the jpegPhoto attribute in AD - Part I
Using the jpegPhoto attribute in AD - Part II
EDIT: Here's a generic function implementing the code from Part I:
void AddPictureToUser(
string strDN, // User Distinguished Name, in the form "CN=Joe User,OU=Employees,DC=company,DC=local"
string strDCName, // Domain Controller, ie: "DC-01"
string strFileName // Picture file to open and import into AD
)
{
// Open file
System.IO.FileStream inFile = new System.IO.FileStream(strFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
// Retrive Data into a byte array variable
byte[] binaryData = new byte[inFile.Length];
int bytesRead = inFile.Read(binaryData, 0, (int)inFile.Length);
inFile.Close();
// Connect to AD
System.DirectoryServices.DirectoryEntry myUser = new System.DirectoryServices.DirectoryEntry(#"LDAP://" + strDCName + #"/" + strDN);
// Clear existing picture if exists
myUser.Properties["jpegPhoto"].Clear();
// Update attribute with binary data from file
myUser.Properties["jpegPhoto"].Add(binaryData);
myUser.CommitChanges();
}
EDIT: I found that in my organisation, the correct attribute to set was "thumbnailPhoto" like this:
myUser.Properties["thumbnailPhoto"].Add(binaryData);
This also seems to tbe the one that the commercial product Exclaimer is setting (but it might be only doing that in my organization)
The common AD attribute for a user photo is jpegPhoto but you can use what ever name you want
This sample shows the basic AD way to get and set an image stream. You need to flesh these methods out to be a useful class
Consider making your web service to just return the URL of the image. The request handler for that URL should then return the image with the correct content type etc. Much more useful in a web environment
using System;
using System.DirectoryServices;
using System.Collections;
using System.IO;
public class ADPhoto {
public void Set() {
try {
var de = new DirectoryEntry("LDAP://cn=username,cn=users,DC=domain, DC=com");
de.Username = "username";
de.Password = "password";
var forceAuth = de.NativeObject;
var fs = new FileStream("path\\photo.jpg", FileMode.Open);
var br = new BinaryReader(fs);
br.BaseStream.Seek(0, SeekOrigin.Begin);
byte[] ba = new byte[br.BaseStream.Length];
ba = br.ReadBytes((int)br.BaseStream.Length);
de.Properties["jpegPhoto"].Insert(0, ba);
de.CommitChanges();
}
catch(Exception ex) {
Console.WriteLine(ex.Message);
}
}
public Stream Get() {
var fs = new MemoryStream();
try {
var de = new DirectoryEntry("LDAP://cn=username,cn=users,DC=domain, DC=com");
de.Username = "username";
de.Password = "password";
var forceAuth = de.NativeObject;
var wr = new BinaryWriter(fs);
byte[] bb = (byte[])de.Properties["jpegPhoto"][0];
wr.Write(bb);
wr.Close();
}
catch (Exception e) {
Console.WriteLine(e.Message);
}
return fs;
}
}
Found an article that describes how to upload pictures to Active Directory and how to get them to show on the end-users computers.
http://blog.jocha.se/tech/ad-user-pictures-in-windows-10
Each Active Directory User Profile will have a home folder.
If you are not sure about this please checkout the below article
http://support.microsoft.com/kb/816313
I believe that you have to upload the image file to this directory.
Also if this doesn't solve your problem, please update if you find something else.
MNK...

Uploading files to Sharepoint (WSS 3.0) document library using HTTP PUT

Hi I have the following piece of code to upload a file to Sharepoint. It uses HTTP PUT:
public static string UploadFile(string destUrl, string sourcePath)
{
try
{
Uri destUri = new Uri(destUrl);
FileStream inStream = File.OpenRead(sourcePath);
WebRequest req = WebRequest.Create(destUri);
req.Method = "PUT";
req.Headers.Add("Overwrite", "F");
req.Timeout = System.Threading.Timeout.Infinite;
req.Credentials = CredentialCache.DefaultCredentials;
Stream outStream = req.GetRequestStream();
string status = CopyStream(inStream, outStream);
if (status == "success")
{
outStream.Close();
WebResponse ores = req.GetResponse();
return "success";
}
else
{
return status;
}
}
catch (WebException we)
{
return we.Message;
}
catch (System.Exception ee)
{
return ee.Message;
}
}
When I run this code I get the exception:
"The remote server returned an error: (409) Conflict."
Does anyone have any ideas as to where I am going wrong?
Thanks,
Alex
I've had this issue when I was referencing the url of the document library and not the destination file itself.
i.e. try http://server name/document library name/new file name.doc
No clue. But why dont you use Remote Procedure Calls (RPC) thats how i usually do it.
I found this example that might get you started http://geek.hubkey.com/2007/11/upload-file-to-sharepoint-document.html
Try:
void StorePlainFile(string target_url, string filename, byte[] file_bytes)
{
string url = target_url + "/" + filename;
System.Net.WebClient client = new System.Net.WebClient();
client.Credentials = System.Net.CredentialCache.DefaultCredentials;
client.Headers.Add("Overwrite", "F");
byte[] response = client.UploadData(url, "PUT", file_bytes);
}
I haven't solved my problem yet, that's why I'm here, but I know why you're getting this error.
The error results because you are not setting a hidden, but required, field. In my case, I had no columns, and certainly none that were required. However, there is a versioning field that is in conflict.
My intent is to 1) upload the document, and 2) set the document's metadata. 1) and 2) occur over separate HTTP calls. Ideally, I want to do this in a single call, but I don't know how to do this.
To accomplish this, 1) succeeds, so the document appears in the library. Then when I try to update the metadata, that's when I get the 409 error.
I'm pretty sure that I first need to insert a step in between 1) and 2) which first downloads the document's list (or manifest) which would in theory contain the needed versioning information. All I would need to do is set the metadata fields I need, and send back to the server.
No, we don't want to use the Sharepoint API because there are no libraries for it in Java. ;-)
Is there a paticular reason you can't just use the Sharepoint API (eg. SPFolder.Files.Add) to upload the file? As follows:
http://msdn.microsoft.com/en-us/library/ms454491.aspx
public void UploadFile(string srcUrl, string destUrl)
{
if (! File.Exists(srcUrl))
{
throw new ArgumentException(String.Format("{0} does not exist",
srcUrl), "srcUrl");
}
SPWeb site = new SPSite(destUrl).OpenWeb();
FileStream fStream = File.OpenRead(srcUrl);
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
EnsureParentFolder(site, destUrl);
site.Files.Add(destUrl, contents);
}
Alex,
This happened to me too. You probable should create another another lit or document library and upload files into it to test.
You may want to check the variable "destUri" to see if it points to exactly the expected sharepoint list.
My situation is I firstly created a document library "Requrements", there is a typo mistake, then i changed the title to "Requirements". You should notice that sharepoint still keeps the URL to this list as http://server:port/Requrements
This is an exeption. Hopefully it helps.

Categories

Resources