Input output stream not working in Web Forms function - io

Can someone tell me why I keep getting a read and write timeout on this function? I have this as a code behind function on click even from a button. Everything as far as the data looks good until I get to the stream section and it still steps through, but when I check the Stream object contents after stepping into that object it states Read Timeout/Write Timeout: System invalid Operation Exception.
protected void SubmitToDB_Click(object sender, EventArgs e)
{
if (FileUploader.HasFile)
{
try
{
if (SectionDropDownList.SelectedValue != null)
{
if (TemplateDropDownList.SelectedValue != null)
{
// This gets the full file path on the client's machine ie: c:\test\myfile.txt
string strFilePath = FileUploader.PostedFile.FileName;
//use the System.IO Path.GetFileName method to get specifics about the file without needing to parse the path as a string
string strFileName = Path.GetFileName(strFilePath);
Int32 intFileSize = FileUploader.PostedFile.ContentLength;
string strContentType = FileUploader.PostedFile.ContentType;
//Convert the uploaded file to a byte stream to save to your database. This could be a database table field of type Image in SQL Server
Stream strmStream = FileUploader.PostedFile.InputStream;
Int32 intFileLength = (Int32)strmStream.Length;
byte[] bytUpfile = new byte[intFileLength + 1];
strmStream.Read(bytUpfile, 0, intFileLength);
strmStream.Close();
saveFileToDb(strFileName, intFileSize, strContentType, bytUpfile); // or use FileUploader.SaveAs(Server.MapPath(".") + "filename") to save to the server's filesystem.
lblUploadResult.Text = "Upload Success. File was uploaded and saved to the database.";
}
}
}
catch (Exception err)
{
lblUploadResult.Text = "The file was not updloaded because the following error happened: " + err.ToString();
}
}
else
{
lblUploadResult.Text = "No File Uploaded because none was selected.";
}
}

Try something like this:
using (var fileStream = FileUploader.PostedFile.InputStream)
{
using (var reader = new BinaryReader(fileStream))
{
byte[] bytUpfile = reader.ReadBytes((Int32)fileStream.Length);
// SAVE TO DB...
}
}

Related

OpenXml Cannot Read or Write To Azure Blob Storage with FileMode or FileAccess value is invalid for the stream

We are working with DocumentFormat.OpenXml.WordDocument and opening a template of a Wordfile inside the Azure Blob, writing to it and saving it. There are two issues:
During the opening of the Document
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(streamToWrite, true))
Here the issue is like this ->
DocumentFormat.OpenXml.Packaging.OpenXmlPackageException: 'The stream was not opened for writing.'
If I replaces the IsEditable=trueto false, the issue will go. But the another issue occurs subsequently during the reading of the stream, after the changing the texts.
// Writing the changed document using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.OpenOrCreate)))
The Error is like this-> System.ArgumentException: 'Stream was not writable.'
Final Code is like this, which is referred from this link : -https://learn.microsoft.com/en-us/office/open-xml/how-to-search-and-replace-text-in-a-document-part
public async Task<IActionResult> UpdateDocumentAsync([FromBody] ProcessingQuery query)
{
BlobClient readblob = new BlobClient(new Uri("https://XXXXXX/docxviewer/outputviewer/blob.docx?sp=racwd"));
using (HttpClient client = new HttpClient())
{
using (Stream streamToWrite = await client.GetStreamAsync(readblob.Uri))
{
try
{
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(streamToWrite, false))
{
string docText = null;
using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
docText = sr.ReadToEnd();
}
//Writing of Single Queries this will become dictionary key-value pair
Regex regexText1 = new Regex("{first_name}");
docText = regexText1.Replace(docText, query?.first_Name);
Regex regexText2 = new Regex("{last_name}");
docText = regexText2.Replace(docText, query?.last_Name);
Regex regexText3 = new Regex("{phone}");
docText = regexText2.Replace(docText, query?.phone);
// Writing the changed document
using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.OpenOrCreate)))
{
sw.Write(docText);
sw.Flush();
sw.Close();
}
wordDoc.Close();
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
streamToWrite.Close();
}
}
return Ok(readblob);
}
Please help us on this codes with relevant codes and documents. If there is any issue in blob storage token Kindly help us in that too.. :)

cannot access the file because it is using by another program Error

I have been fighting with this issue since last week.still not able to solve.
i am sending file to client machine once i get in server automatically.but so many time when i handle file it throw an error that Cannot access the file because it is using by another program.
below my code
private static string SaveFileStream(string filePath, Stream stream, string Filename1)
{
string localresponse;
try
{
//this.SaveFileStream(System.Configuration.ConfigurationSettings.AppSettings[fileToPush.FileType].ToString() + "\\" + fileToPush.FileName, new MemoryStream(fileToPush.Content));
if (File.Exists(filePath))
{
File.Delete(filePath);
}
using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
stream.CopyTo(fileStream);
fileStream.Flush();
fileStream.Dispose();
}
FileInfo info = new FileInfo(filePath);
ExtractFile(info);
localresponse = "Successful";
}
catch (Exception ex)
{
localresponse = ex.Message;
}
return localresponse;
}

How to save image to the database after it is scanned

I have developed a windows application to scan images.After the image is scanned i want to save it directly to the database not in local machine...The code which i have used is as follows
try
{
String str = string.Empty;
WIA.CommonDialogClass scanner;
ImageFile imageObject;
scanner = new CommonDialogClass();
imageObject = scanner.ShowAcquireImage
(WiaDeviceType.ScannerDeviceType,
WiaImageIntent.ColorIntent,
WiaImageBias.MinimizeSize,
ImageFormat.Jpeg.Guid.ToString("B"),
false,
true,
true);
str = DateTime.Now.ToString();
str = str.Replace("/", "");
str = str.Replace(":", "");
Directory.CreateDirectory("D:\\scanned1");
// MessageBox.Show(string.Format("File Extension = {0}\n
//\nFormat = {1}", imageObject.FileExtension, imageObject.FormatID));
imageObject.SaveFile(#"D:\scanned1\lel" + str + ".jpg");
MessageBox.Show("Scanning Done");
}
catch (Exception ex)
{
MessageBox.Show("Please check if the scanner is connected properly.");
}
Instead of saving it to D drive i want to save it to database.....How can i do it?Plz reply...
I've got no idea what "ImageFile" is really, but there should be a way to transform it into the byte array (byte[]). Afterwards you would need to insert that array to varbinary field in your sql.
something like this:
using(SqlCommand cmd = new SqlCommand("INSERT INTO MyTable (myvarbinarycolumn) VALUES (#myvarbinaryvalue)", conn))
{
cmd.Parameters.Add("#myvarbinaryvalue", SqlDbType.VarBinary, myarray.length).Value = myarray;
cmd.ExecuteNonQuery();
}
ofc sqlcommand should be opened and valid.
myarray is of type byte[]

Downloading bulk files from sharepoint library

I want to download the files from a sharepoint document library through code as there are thousand of files in the document library.
I am thinking of creating console application, which I will run on sharepoint server and download files. Is this approach correct or, there is some other efficient way to do this.
Any help with code will be highly appreciated.
Like SigarDave said, it's perfectly possible to achieve this without writing a single line of code. But if you really want to code the solution for this, it's something like:
static void Main(string[] args)
{
// Change to the URL of your site
using (var site = new SPSite("http://MySite"))
using (var web = site.OpenWeb())
{
var list = web.Lists["MyDocumentLibrary"]; // Get the library
foreach (SPListItem item in list.Items)
{
if (item.File != null)
{
// Concat strings to get the absolute URL
// to pass to an WebClient object.
var fileUrl = string.Format("{0}/{1}", site.Url, item.File.Url);
var result = DownloadFile(fileUrl, "C:\\FilesFromMyLibrary\\", item.File.Name);
Console.WriteLine(result ? "Downloaded \"{0}\"" : "Error on \"{0}\"", item.File.Name);
}
}
}
Console.ReadKey();
}
private static bool DownloadFile(string url, string dest, string fileName)
{
var client = new WebClient();
// Change the credentials to the user that has the necessary permissions on the
// library
client.Credentials = new NetworkCredential("Username", "Password", "Domain");
var bytes = client.DownloadData(url);
try
{
using (var file = File.Create(dest + fileName))
{
file.Write(bytes, 0, bytes.Length); // Write file to disk
return true;
}
}
catch (Exception)
{
return false;
}
}
another way without using any scripts is by opening the document library using IE then in the ribbon you can click on Open in File Explorer where you can then drag and drop the files right on your desktop!

GDI+ Generic Error

When my images are being loaded from my database on my web server, I see the following error:
A generic error occurred in GDI+. at
System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder,
EncoderParameters encoderParams) at
System.Drawing.Image.Save(Stream stream, ImageFormat format) at
MyWeb.Helpers.ImageHandler.ProcessRequest(HttpContext context)
All my code is attempting to do is load the image, can anybody take a look and let me know what I'm doing wrong?
Note - This works if I test it on my local machine, but not when I deploy it to my web server.
public void ProcessRequest(HttpContext context)
{
context.Response.Clear();
if (!String.IsNullOrEmpty(context.Request.QueryString["imageid"]))
{
int imageID = Convert.ToInt32(context.Request.QueryString["imageid"]);
int isThumbnail = Convert.ToInt32(context.Request.QueryString["thumbnail"]);
// Retrieve this image from the database
Image image = GetImage(imageID);
// Make it a thumbmail if requested
if (isThumbnail == 1)
{
Image.GetThumbnailImageAbort myCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
image = image.GetThumbnailImage(200, 200, myCallback, IntPtr.Zero);
}
context.Response.ContentType = "image/png";
// Save the image to the OutputStream
image.Save(context.Response.OutputStream, ImageFormat.Png);
}
else
{
context.Response.ContentType = "text/html";
context.Response.Write("<p>Error: Image ID is not valid - image may have been deleted from the database.</p>");
}
}
The error occurs on the line:
image.Save(context.Response.OutputStream, ImageFormat.Png);
UPDATE
I've changed my code to this, bit the issue still happens:
var db = new MyWebEntities();
var screenshotData = (from screenshots in db.screenshots
where screenshots.id == imageID
select new ImageModel
{
ID = screenshots.id,
Language = screenshots.language,
ScreenshotByte = screenshots.screen_shot,
ProjectID = screenshots.projects_ID
});
foreach (ImageModel info in screenshotData)
{
using (MemoryStream ms = new MemoryStream(info.ScreenshotByte))
{
Image image = Image.FromStream(ms);
// Make it a thumbmail if requested
if (isThumbnail == 1)
{
Image.GetThumbnailImageAbort myCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
image = image.GetThumbnailImage(200, 200, myCallback, IntPtr.Zero);
}
context.Response.ContentType = "image/png";
// Save the image to the OutputStream
image.Save(context.Response.OutputStream, ImageFormat.Png);
} }
Thanks.
Probably for the same reason that this guy was having problems - because the for a lifetime of an Image constructed from a Stream, the stream must not be destroyed.
So if your GetImage function constructs the returned image from a stream (e.g. a MemoryStream) and then closes the stream before returning the image then the above will fail. My guess is that your GetImage looks a tad like this:
Image GetImage(int id)
{
byte[] data = // Get data from database
using (MemoryStream stream = new MemoryStream(data))
{
return Image.FromStream(data);
}
}
If this is the case then try having GetImage return the MemoryStream (or possibly the byte array) directrly so that you can create the Image instance in your ProcessRequest method and dispose of the stream only when the processing of that image has completed.
This is mentioned in the documentation but its kind of in the small print.

Resources