httpContext.Current.Session is null (Inside WebService) Asp.net [duplicate] - c#

This question already has an answer here:
ASP.NET + C# HttpContext.Current.Session is null (Inside WebService)
(1 answer)
Closed 9 years ago.
I have an web service.And i am using some session variables in that service.
Code:
[WebMethod(EnableSession = true)]
public static string UploadFiles_Local(Dictionary<int, string> accFile)
{
string FilePath = "";
Dictionary<int, string> dicStatus = new Dictionary<int, string>();
Dictionary<int, string> dicUpload = new Dictionary<int, string>();
System.Web.HttpContext.Current.Session["uLocal"] = System.Web.HttpContext.Current.Server.MapPath("UplodedFiles") + "\\" + DateTime.Now.Ticks.ToString();
foreach (var f_l in accFile)
{
FilePath = f_l.Value;
string fName = FilePath.Substring(FilePath.LastIndexOf("\\") + 1, FilePath.Length - FilePath.LastIndexOf("\\") + 1);
//File reading
FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
//Directory Existens checking
if (!Directory.Exists(System.Web.HttpContext.Current.Session["uLocal"].ToString()))
{
Directory.CreateDirectory(System.Web.HttpContext.Current.Session["uLocal"].ToString());
}
try
{
//Upload files
long FileSize = new FileInfo(FilePath).Length; // File size of file being uploaded.
string uploadFileName = new FileInfo(FilePath).Name; // File name
Byte[] buffer = new Byte[FileSize];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
fs = null;
fs = File.Open(System.Web.HttpContext.Current.Session["uLocal"].ToString() + "\\" + fName, FileMode.OpenOrCreate);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(buffer);
bw.Close();
dicStatus.Add(f_l.Key, "File " + fName + ". Successfuly uploded to:" + System.Web.HttpContext.Current.Session["uLocal"].ToString() + "\\" + fName);
dicUpload.Add(f_l.Key, System.Web.HttpContext.Current.Session["uLocal"].ToString() + "\\" + fName);
}
catch (Exception ex)
{
if (fs != null)
{
fs.Close();
}
dicStatus.Add(f_l.Key, "File " + fName + ". Error in uploding to:" + System.Web.HttpContext.Current.Session["uLocal"].ToString() + "\\" + fName + "\r\nError :" + ex.Message);
}
finally
{
if (fs != null)
{
fs.Close();
}
}
}
if (dicUpload.Count > 0)
{
//Making rar of uploded files
ClsClass.RarFilesT(System.Web.HttpContext.Current.Session["uLocal"].ToString() + ".rar", dicUpload);
FilePath = System.Web.HttpContext.Current.Session["uLocal"].ToString() + ".rar";
}
else
{
FilePath = "Error";
}
return FilePath;
}
I have already enabled session in that web service but stile i get error message :-
Error message:-
'System.Web.HttpContext.Current' is null
And one more ting i need to call this service from globle.ashx file.

Maybe this can help:
http://www.codeproject.com/Articles/35119/Using-Session-State-in-a-Web-Service
But let me tell you that a Web Service should not stored any session states, that is just wrong.

Related

ZIP download is blocking because of organisation policy in asp.net

As am having my ZIP file in the folder and if I click download report button am blocking to download based on my organization policy.
But I need to download this ZIP file from the code how can we achieve this.
The code which I used as below
string[] filenames = Directory.GetFiles(SourceFolder);
ZipFilePath = DestinationFolder + #"\" + ZipFileName;
using (ZipOutputStream s = new
ZipOutputStream(File.Create(ZipFilePath)))
{
s.SetLevel(6);
byte[] buffer = new byte[4096];
foreach (string file in filenames)
{
if (Path.GetFileName(file).Contains(SubString) || Path.GetFileName(file).Contains("logfile"))
{
ZipEntry entry = new
ZipEntry(Path.GetFileName(file));
entry.DateTime = DateTime.Now;
s.PutNextEntry(entry);
using (FileStream fs = File.OpenRead(file))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0,
buffer.Length);
s.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
}
}
s.Finish();
s.Close();
}
string DownloadFileName = ZipFilePath;
DownloadFileName = DownloadFileName.Replace("\\", "~");
RadAjaxManager1.ResponseScripts.Add("setTimeout(function(){ document.location.href = 'DownloadHandler.ashx?FileName=" + DownloadFileName + "'; return false; },300);");
The DownloadHandler.ashx page as below
public void ProcessRequest(HttpContext context)
{
try
{
HttpResponse rspns = context.Response;
string FileToDownload = context.Request.QueryString["FileName"];
string FileName = string.Empty;
if (context.Request.QueryString["Name"] != null)
{
FileName = context.Request.QueryString["Name"];
}
if (FileToDownload!=null)
{
FileToDownload = FileToDownload.Replace("~", "\\");
FileName = System.IO.Path.GetFileName(FileToDownload);
}
else
{
//FileName = Convert.ToString(iTAPSession.UserData);
}
rspns.AppendHeader("content-disposition", "attachment; filename=\"" + FileName.Replace(" ", "%20"));
rspns.TransmitFile(FileToDownload);
rspns.End();
}
catch (Exception e)
{
}
}
public bool IsReusable
{
get
{
return false;
}
}
am getting the below exception
Based on your organization's access policies, access to this website or download ( http://xxxxxxx/ITAADemo/DownloadHandler.ashx?FileName=D:~ITAADemo~Files~SuperAdmin~bn4wgrusef1xgmjhqokd2yo2~~TextAnalytics~~zipdownload~Report_2018-Jul-19-11-39-31.zip ) has been blocked because the file type "application/zip" is not allowed.

C# How to get file/ copy file from a bzip2 (.bz2) file without extracting the file

I have a .bz2 compressed file, and i want to copy the inside file to another location, without decompressing it.
I use .net 4.5 with C#.
i tried like this, but this is for zip files (.zip):
using (var zip = ZipFile.Read(_targetPathComplete + "\\" + file[0].ToUpper() + "_" + file[1].ToUpper() + ".bz2"))
{
Stream s = zip[file[0].ToUpper() + "_" + file[1].ToUpper()].OpenReader();
// fiddle with stream here
using (var fileStream = File.Create(_targetPathComplete + "\\" + file[0].ToUpper() + "_" + file[1].ToUpper() + ".HDC"))
{
s.Seek(0, SeekOrigin.Begin);
s.CopyTo(fileStream);
}
}
Or compress a file with bzip2 algorithm and give an extension .HDC to it.
I think i solved it like this, at least the file i have wit this method is the same as when i copy the file from winrar.
var fname = _targetPathComplete + "\\" + file[0].ToUpper() + "_" + file[1].ToUpper() + ".bz2";
using (var fs = File.OpenRead(fname))
{
using (var decompressor = new Ionic.BZip2.BZip2InputStream(fs))
{
var outFname = _targetPathComplete + "\\" + file[0].ToUpper() + "_" + file[1].ToUpper() + ".HDC";
using (var output = File.Create(outFname))
{
var buffer = new byte[2048];
int n;
while ((n = decompressor.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, n);
}
}
}
}

Unzip files in Windows Phone 8 - 'System.OutOfMemoryException'

I used the UnZipper class from this (How to unzip files in Windows Phone 8) post in my app for zips with images, but in some rare cases it gives me this error:
A first chance exception of type 'System.OutOfMemoryException' occurred in System.Windows.ni.dll System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown. at System.Windows.Application.GetResourceStreamInternal(StreamResourceInfo zipPackageStreamResourceInfo, Uri resourceUri) at System.Windows.Application.GetResourceStream(StreamResourceInfo zipPackageStreamResourceInfo, Uri uriResource) at ImperiaOnline.Plugins.UnZipper.GetFileStream(String filename) at ImperiaOnline.Plugins.IOHelpers.unzip(String zipFilePath, String zipDestinationPath)
The device has more then twice needed free memory. Can somebody help me with this. Here is my code:
public static void unzip(string zipFilePath,string zipDestinationPath) {
using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
var dirNames = isolatedStorage.GetDirectoryNames(zipDestinationPath);
bool doesFolderExists = (dirNames.Length > 0) ? true : false;
if (!doesFolderExists)
{
Debug.WriteLine("Folder does not exists");
isolatedStorage.CreateDirectory(zipDestinationPath);
}
try
{
using (IsolatedStorageFileStream zipFile = isolatedStorage.OpenFile(zipFilePath, FileMode.Open, FileAccess.ReadWrite))
{
UnZipper unzip = new UnZipper(zipFile);
bool isModuleFolderDeleted = false;
foreach (string currentFileAndDirectory in unzip.FileNamesInZip())
{
string[] fileLocations = currentFileAndDirectory.Split('/');
string prefix = zipDestinationPath + '/';
int locationsCount = fileLocations.Length;
string fileName = fileLocations.Last();
string currentPath = prefix;
for (int i = 0; i < locationsCount - 1; i++)
{
dirNames = isolatedStorage.GetDirectoryNames(currentPath + fileLocations[i]);
doesFolderExists = (dirNames.Length > 0) ? true : false;
if (!doesFolderExists)
{
isolatedStorage.CreateDirectory(currentPath + fileLocations[i]);
if (i == 2)
{
isModuleFolderDeleted = true;
}
}
else if (i == 2 && !isModuleFolderDeleted)
{
Debug.WriteLine(currentPath + fileLocations[i] + " is deleted and recreated");
DeleteDirectoryRecursively(isolatedStorage, currentPath + fileLocations[i]);
isolatedStorage.CreateDirectory(currentPath + fileLocations[i]);
isModuleFolderDeleted = true;
}
currentPath += fileLocations[i] + '/';
}
var newFileStream = isolatedStorage.CreateFile(currentPath + fileName);
byte[] fileBytes = new byte[unzip.GetFileStream(currentFileAndDirectory).Length];
unzip.GetFileStream(currentFileAndDirectory).Read(fileBytes, 0, fileBytes.Length);
unzip.GetFileStream(currentFileAndDirectory).Close();
try
{
newFileStream.Write(fileBytes, 0, fileBytes.Length);
}
catch (Exception ex)
{
Debug.WriteLine("FILE WRITE EXCEPTION: " + ex);
newFileStream.Close();
newFileStream = null;
zipFile.Close();
unzip.Dispose();
}
newFileStream.Close();
newFileStream = null;
}
zipFile.Close();
unzip.Dispose();
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
isolatedStorage.DeleteFile(zipFilePath);
}
}
This error appears here:
var newFileStream = isolatedStorage.CreateFile(currentPath + fileName);
byte[] fileBytes = new byte[unzip.GetFileStream(currentFileAndDirectory).Length]; unzip.GetFileStream(currentFileAndDirectory).Read(fileBytes, 0, fileBytes.Length);
unzip.GetFileStream(currentFileAndDirectory).Close();
I debugged it and it fails on
byte[] fileBytes = new byte[unzip.GetFileStream(currentFileAndDirectory).Length];
I checked GetFileStream method
public Stream GetFileStream(string filename)
{
if (fileEntries == null)
fileEntries = ParseCentralDirectory(); //We need to do this in case the zip is in a format Silverligth doesn't like
long position = this.stream.Position;
this.stream.Seek(0, SeekOrigin.Begin);
Uri fileUri = new Uri(filename, UriKind.Relative);
StreamResourceInfo info = new StreamResourceInfo(this.stream, null);
StreamResourceInfo stream = System.Windows.Application.GetResourceStream(info, fileUri);
this.stream.Position = position;
if (stream != null)
return stream.Stream;
return null;
}
It throws OutOfMemory exception on this row:
StreamResourceInfo stream = System.Windows.Application.GetResourceStream(info, fileUri);

Images corrupting in FTP, Binary mode on

I made a post back in january about this, but it was never solved. I have been working on a program to ftp to my Youtube Teams website. For some odd reason, the HTML code generated works and is transferred successfully, but the images come through corrupted. I've made sure that Binary mode is set to true and permissions are all correct. Nothing seems to work.
Can somebody help me?
This is our part of the Code which is relevant to my question:
namespace TMNGP_FTP
{
partial class Form1
{
// some functions and properties for the form
UriBuilder ftpurl;
String ftpurlstr = "ftp://tmngp.heliohost.org";
static String ftpusername = "*******";
static String ftppassword = "*******";
public static string GenerateFileName(string context)
{
return context + DateTime.Now.ToString("yyyyMMddHHmmss") + ".html";
}
public void openpic_Click(object sender, System.EventArgs e)
{
//Wrap the creation of the OpenFileDialog instance in a using statement,
//Rather than manually calling the dispose method to ensure proper disposal
using (OpenFileDialog dlg = new OpenFileDialog())
{
dlg.Title = "Open Image";
dlg.Filter = "png files (*.png)|*.png";
if (dlg.ShowDialog() == DialogResult.OK)
{
string folderName = #"c:\TMNGP_Web_Files";
string pathString = folderName + #"\htTemp";
pathString = pathString + #"\imgs";
if (!System.IO.Directory.Exists(pathString))
{
System.IO.Directory.CreateDirectory(pathString);
}
string destFileName = pathString + #"\" + dlg.SafeFileName.ToString();
System.IO.File.Copy(dlg.FileName, destFileName, true);
DisplImg.Image = new Bitmap(dlg.OpenFile());
DisplImg.ImageLocation = destFileName;
}
}
}
private FtpClient ftpnew = null;
public void textgen_Click(object sender, System.EventArgs e)
{
string folderName = #"c:\TMNGP_Web_Files";
string pathString = folderName + #"\htTemp";
if (!System.IO.Directory.Exists(pathString))
{
System.IO.Directory.CreateDirectory(pathString);
}
string fileName = GenerateFileName("HT");
pathString = pathString + #"\" + fileName;
Console.WriteLine("Path to my file: {0}\n", pathString);
if (!System.IO.File.Exists(pathString))
{
//System.IO.FileStream fs = System.IO.File.Create(pathString);
using (System.IO.StreamWriter file = new System.IO.StreamWriter(pathString))
{
file.WriteLine("<div class='simple_overlay' id='news_archive/" + DisplImg.ImageLocation.Substring(31) + "' style='display:none;'>");
file.WriteLine("<a class='close'></a>");
file.WriteLine("<img src='news_archive/" + DisplImg.ImageLocation.Substring(31) + "'/>");
file.WriteLine("<div class='details'>");
file.WriteLine("<h3> " + txtTitle.Text + " </h3>");
file.WriteLine("<h4> " + TxtInfo.Text + " </h4>");
file.WriteLine("<p>" + Desctext.Text + "</p>");
file.WriteLine("</div>");
file.WriteLine("</div>");
}
if(radioButton1.Checked)
{
ftpurl = new UriBuilder("ftp", "tmngp.heliohost.org", 21, "NGP/news_archive/");
ftpurlstr = "/public_html/NGP/news_archive";
}
else
{
ftpurl = new UriBuilder("ftp", "tmngp.heliohost.org", 21, "TM/news_archive/");
ftpurlstr = "/public_html/TM/news_archive";
}
try
{
//string filenametwo = System.IO.Path.GetFullPath(#"c:\TMNGP_Web_Files\htTemp\"+fileName);
string filenamethree = System.IO.Path.GetFullPath(DisplImg.ImageLocation.ToString());
Console.WriteLine("{0}", filenamethree);
Console.WriteLine(pathString);
//string ftpfullpath = ftpurl;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create((#"ftp://tmngp.heliohost.org" + ftpurlstr + fileName).ToString());
Console.WriteLine("{0}", ftpurl + fileName);
ftp.Credentials = new NetworkCredential(ftpusername, ftppassword);
ftp.KeepAlive = true;
ftp.UseBinary = true;
ftp.Method = WebRequestMethods.Ftp.UploadFile;
StreamReader sourceStreamone = new StreamReader(#"c:\TMNGP_Web_Files\htTemp\" + fileName);
byte[] fileContentsone = Encoding.UTF8.GetBytes(sourceStreamone.ReadToEnd());
sourceStreamone.Close();
ftp.ContentLength = fileContentsone.Length;
Stream requestStreamone = ftp.GetRequestStream();
requestStreamone.Write(fileContentsone, 0, fileContentsone.Length);
requestStreamone.Close();
FtpWebResponse ftpresponseone = (FtpWebResponse)ftp.GetResponse();
Console.WriteLine("Upload File Complete, status {0}", ftpresponseone.StatusDescription);
ftpresponseone.Close();
}
catch (WebException ex)
{
throw ex;
}
try
{
string imgfile = DisplImg.ImageLocation.Substring(31);
FtpWebRequest ftp2 = (FtpWebRequest)FtpWebRequest.Create((#"ftp://tmngp.heliohost.org" + ftpurlstr + imgfile).ToString());
ftp2.Credentials = new NetworkCredential(ftpusername, ftppassword);
ftp2.KeepAlive = true;
ftp2.UseBinary = true;
ftp2.Method = WebRequestMethods.Ftp.UploadFile;
StreamReader sourceStreamtwo = new StreamReader(DisplImg.ImageLocation.ToString());
byte[] fileContentstwo = Encoding.UTF8.GetBytes(sourceStreamtwo.ReadToEnd());
sourceStreamtwo.Close();
ftp2.ContentLength = fileContentstwo.Length;
Stream requestStreamtwo = ftp2.GetRequestStream();
requestStreamtwo.Write(fileContentstwo, 0, fileContentstwo.Length);
requestStreamtwo.Close();
FtpWebResponse ftpresponsetwo = (FtpWebResponse)ftp2.GetResponse();
Console.WriteLine("Upload File Complete, status {0}", ftpresponsetwo.StatusDescription);
ftpresponsetwo.Close();
}
catch (Exception ex)
{
throw ex;
}
MessageBox.Show("FTP Complete");
}
else
{
Console.WriteLine("File \"{0}\" already exists.", fileName);
return;
}
}
// a bunch of Windows Form Designer generated code ...
}
}
Ok this code is hard to read, BUT, it looks like you are using Encoding.UTF8.GetBytes() on the image (sourceStreamTwo) when you declare Byte[] fileContentTwo.
Edit - forgot to mention, you don't need the StreamReader - use a FileStream instead:
FileStream sourceStreamtwo = new FileStream(DisplImg.ImageLocation.ToString(), FileMode.Open);
Change that to
Byte[] fileContentTwo;
using (BinaryReader br = new BinaryReader(sourceStreamtwo))
{
fileContentsTwo = br.ReadBytes((int)sourceStreamtwo.Length);
// rest of code that deals with sourceStreamTwo
}
Note this assumes you aren't reading from a network where you might not have the whole stream available, see Creating a byte array from a stream
In .net 4 or higher you can use Stream.CopyTo() which is safer as it handles interruptions in the stream - again see above question and answers for more info.
And you should be good. Encoding is meant for text, images are binary.
Also please consider some different naming conventions for your variables :)

How to decompress .bz2 file in C#?

I am developing wpf application. I am using sharpziplib to compress and decompress files. I am easily decompress the .zip files using following code
public static void UnZip(string SrcFile, string DstFile, string safeFileName, int bufferSize)
{
//ICSharpCode.SharpZipLib.Zip.UseZip64.Off;
FileStream fileStreamIn = new FileStream(SrcFile, FileMode.Open, FileAccess.Read);
ZipInputStream zipInStream = new ZipInputStream(fileStreamIn);
string rootDirectory = string.Empty;
if (safeFileName.Contains(".zip"))
{
rootDirectory = safeFileName.Replace(".zip", string.Empty);
}
else
{
rootDirectory = safeFileName;
}
Directory.CreateDirectory(App.ApplicationPath + rootDirectory);
while (true)
{
ZipEntry entry = zipInStream.GetNextEntry();
if (entry == null)
break;
if (entry.Name.Contains("/"))
{
string[] folders = entry.Name.Split('/');
string lastElement = folders[folders.Length - 1];
var folderList = new List<string>(folders);
folderList.RemoveAt(folders.Length - 1);
folders = folderList.ToArray();
string folderPath = "";
foreach (string str in folders)
{
folderPath = folderPath + "/" + str;
if (!Directory.Exists(App.ApplicationPath + rootDirectory + "/" + folderPath))
{
Directory.CreateDirectory(App.ApplicationPath + rootDirectory + "/" + folderPath);
}
}
if (!string.IsNullOrEmpty(lastElement))
{
folderPath = folderPath + "/" + lastElement;
WriteToFile(DstFile + rootDirectory + #"\" + folderPath, bufferSize, zipInStream, rootDirectory, entry);
}
}
else
{
WriteToFile(DstFile + rootDirectory + #"\" + entry.Name, bufferSize, zipInStream, rootDirectory, entry);
}
}
zipInStream.Close();
fileStreamIn.Close();
}
private static void WriteToFile(string DstFile, int bufferSize, ZipInputStream zipInStream, string rootDirectory, ZipEntry entry)
{
FileStream fileStreamOut = new FileStream(DstFile, FileMode.OpenOrCreate, FileAccess.Write);
int size;
byte[] buffer = new byte[bufferSize];
do
{
size = zipInStream.Read(buffer, 0, buffer.Length);
fileStreamOut.Write(buffer, 0, size);
} while (size > 0);
fileStreamOut.Close();
}
But the same code is not working with .bz2 files. It is giving error at line
ZipEntry entry = zipInStream.GetNextEntry();
The error is - Wrong Local header signature: 0x26594131. How should I decompress the .bz2 file ? Can you please provide me any code or link through which I can resolve the above issue ?
While you use a ZipInputStream for .zip files, you should use a BZip2InputStream for .bz2 files (and GZipInputStream for .gz files etc.).
Unlike Zip (and RAR and tar), bz2 and gzip are just byte stream compressors. They have no concept of a container format like the aforementioned, and hence why it fails on GetNextEntry. (In other words, bz2 and gzip will only have 1 entry at most).

Categories

Resources