Assuredly simple C# file saving issue - c#

We have a custom built web application built on ASP (2.0 it looks like) using C#. We recently moved it from an IIS6 environment to an IIS7. We have run into an issue where a page set up to view images that had been retrieved via a search is throwing an error. The code takes a copy of the image file and puts it into a work directory renaming the copy to the user's name.
bmpList[0].Save("c:\\inetpub\\wwwroot\\SiteName\\Work\\" + ((ImageUser)Session["ImageUser"]).Username + ".TIF", info, encParams);
I know that the wwwroot is no longer a valid directory in the path so I changed it to...
bmpList[0].Save("c:\\inetpub\\SiteName\\Work\\" + ((ImageUser)Session["ImageUser"]).Username + ".TIF", info, encParams);
Saved the file, did and IIS restart and cleared my browser cache and still receive an error...
A generic error occurred in GDI+.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.
Source Error:
Line 180:
Line 181: //bmpList[0].Save("c:\\pi\\" + ((ImageUser)Session["ImageUser"]).Username + ".TIF", info, encParams);
Line 182: bmpList[0].Save("c:\\inetpub\\wwwroot\\SiteName\\Work\\" + ((ImageUser)Session["ImageUser"]).Username + ".TIF", info, encParams);
Line 183:
Line 184: for (int a = 1; a < numFiles; a++)
Source File: c:\inetpub\Sitename\SiteApp\View.aspx.cs Line: 182
Stack Trace:
[ExternalException (0x80004005): A generic error occurred in GDI+.]
System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams) +615209
View.Page_PreRender(Object sender, EventArgs e) in c:\inetpub\SiteName\SiteApp\View.aspx.cs:182
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +25
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +42
System.Web.UI.Control.OnPreRender(EventArgs e) +11056766
System.Web.UI.Control.PreRenderRecursiveInternal() +108
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3394
It seems like a fairly straightforward thing but for some reason it is not updating (the path in the error remains exactly the same). What am I missing?

Almost all the time (i.e 99.9999% of the times), when using GDI, 'a generic error occured' means that the directory you are trying to save to doesn't have the proper permissions. Typically, you need to make sure that directory is allowing asp.net to modify files. Did you check the permission on the directory you are trying to save the files to?

So oddly enough the answer is actually as simple as it looks... almost.
Changing...
c:\inetpub\wwwroot\SiteName\Work\
to...
c:\inetpub\SiteName\Work\
worked. Why it was continuing to give me the same error from the browser after I changed the code on the .cs file was that the IP that they had bound to the site still belonged to a previous version of the machine so DNS was routing me over to that box instead. All said it ended up I was on the wrong OSI model layer. I only discovered it when I went to build a test version on the same box and went to unbind the IP from the broken site and bind it to my second test site and I found that the IP I wanted wasn't an option (so it must have been manually entered). Live and learn. Thanks for the input and advise.

Related

Specified cast is not valid. error shows in window server 2008 r2

I made a application in asp.net c# using linq and oracle database.This application is working fine on Widows 7 32 bit local host.But When I deployed this application in windows server 2008 r2.It gives a following error.Guide me what is the following error.How Can I check this error on deployment server and How can I resolved this error
Specified cast is not valid. Description: An unhandled exception
occurred during the execution of the current web request. Please
review the stack trace for more information about the error and where
it originated in the code.
Exception Details: System.InvalidCastException: Specified cast is not
valid.
Source Error:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidCastException: Specified cast is not valid.]
System.Data.UnboxT`1.ValueField(Object value) +54
sis.<>c__DisplayClass55.b__0(DataRow r) +38
System.Linq.WhereEnumerableIterator`1.MoveNext() +156
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +165
System.Linq.d__81`1.MoveNext() +472
System.Linq.Enumerable.Count(IEnumerable`1 source) +267
sis.regreport.Page_Load(Object sender, EventArgs e) +5015
System.Web.UI.Control.LoadRecursive() +71
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean
includeStagesAfterAsyncPoint) +3178
var vcolM = dt.AsEnumerable()
.Where(r => r.Field<string>("MAJ") == (string)vprglist
&& r.Field<string>("SPEC") == (string)vspecourse
&& r.Field<string>("L_ABR_CODE") == (string)genderEng[1]
&& r.Field<string>("reg") == (string)drRegion["reg"]
&& r.Field<decimal>("year") == syrcnt)
.Sum(r => Convert.ToInt32(r["strength"]));
All linq like above working fine in local pc.But giving error in windows server 2008.Where syrcnt is int.
The most likely cause of the InvalidCastException is the r.Field<string>("MAJ") , r.Field<decimal>("year") line. The Field<T> extension method will throw an InvalidCastException in the case where the actual type of the data doesn't match the type which was passed to Field<T>.
OR
lies in here Convert.ToInt32(r["strength"]), the strength might not be getting proper type
Honestly, I think you issues lies in the line r.Field<decimal>("year"). I may be wrong as there is not much information about the datatype of your variable syrcnt
Hence giving you the exception System.InvalidCastException: Specified cast is not valid

"Length cannot be less than zero." after database manipulation

First of all, I'd like to apologize in advance for my lack of proficiency in the area of C#.
Although I have very little knowledge of the subject I was in a situation where I needed to create an exact copy of a website. The website is using .NET 4.0, runs on IIS 7 with MSSQL Server 2008. The new website is set up as a subdomain of the old one.
I did a full backup of the original database, created a new database and "restored" it with the orginal's backup. The only thing I changed was the .mdf and .ldf files.
I then copied and pasted the actual files to the new folder and changed the config files with the new database.
Everything works perfectly until you add/delete news to/from the database. At that point, the front page of the website renders the following message:
Server Error in '/' Application.
Length cannot be less than zero.
Parameter name: length
Stack trace:
[ArgumentOutOfRangeException: Length cannot be less than zero.
Parameter name: length]
System.String.InternalSubStringWithChecks(Int32 startIndex, Int32 length, Boolean fAlwaysCopy) +10082776
Tang.Core.Utility.HtmlHelper.CutText(String rawText, Int32 length) +242
Tang.Website.UC.ArticleItems.GetLegacyDataTable(Int32 collectionId, Int32 maxRecord) +2172
Tang.Website.UC.ArticleItems.Page_Load(Object sender, EventArgs e) +150
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +25
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +42
System.Web.UI.Control.OnLoad(EventArgs e) +132
System.Web.UI.Control.LoadRecursive() +66
System.Web.UI.Control.LoadRecursive() +191
System.Web.UI.Control.LoadRecursive() +191
System.Web.UI.Control.LoadRecursive() +191
System.Web.UI.Control.LoadRecursive() +191
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2428
Another error is when a user is logged in (again "length cannot be zero"):
<%-- <p class="news_date"><%# Eval("collectionitemdatetime", "{0:d}") %></p>--%>
<p class="news_cont">
**<%# Tang.Core.Utility.HtmlHelper.CutText( Eval("collectionitemtext").ToString(), 450) %>** --> THIS IS WHERE THE PROBLEM IS, OBVIOUSLY STRING IS EMPTY?</p>
</div>
</ItemTemplate>
I am totally lost as nothing "major" has been edited from the original. I must be doing something wrong with the database.
EDIT: The thing is, as soon as I change the datbase from the webconfig file [to the original database], everything works, I can add/remove/edit items and they are shown on the home page. So it's gotta be something between the website & the database and not code-related
EDIT 2, Found a solution: I deleted the database, created a new one and instead of doing a "restore", I did "Export" from the original one. I had to set the primary keys manually and change some of them to (Is Identify) - Yes because I was getting the same error. Not the most elegant solution but at least everything seems to be working now.
Thank you all for your help!
Looks like length parameter comes with -1 value to CutText function. Is there an ORM tool you use? If you use Entity framework, you must set your connection string proper. Maybe your sql security properties doesn't let you to add. Sure look at your db when you add a news.

Response.BinaryWrite gives error on Production

I'm using localReport to print PDF (SQL REPORTVIEWER). It works fine on localhost. When I move the application to Production (64 bits windows 2008) it gives me an error. (see below)
I put the renderedbytes in a Session in USERCONTROL and I do window.open('Program1.aspx')...
In page load of Program1.aspx I try to retrieve the Session variable and process....
I think this statement cause the error "Response.BinaryWrite (...) etc".
It works on my local pc (Vista 32bits)...
Can someone please what the errors says? and How can I solve this on production??????
thank you..
USERCONTROL1.ASCX
byte[] renderedBytes;
renderedBytes = localReport.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
Session["report"] = Print.RenderReport(listEnt, Language);
PROGRAM2.ASPX
protected void Page_Load(object sender, EventArgs e)
{
string extension = "PDF";
Response.ContentType = "application/pdf";
// set the MIME type here
Response.AddHeader("content-disposition", "inline: filename=Test." + extension);
Response.BinaryWrite((byte[])Session["report"]);
Response.End();
}
Server Error in '/' Application.
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.HttpResponse.BinaryWrite(Byte[] buffer) +13
ConfederatieBouw.CustomModules.Controle_InhoudingsPlicht.WebForm1.Page_Load(Object sender, EventArgs e) +191
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsync
Are you running a web farm in production? If so, how are you storing session state? The default is InProc, which means the session will only exist on one server in the farm, and if the follow up request goes to another server, that would explain the issue. The fix this scenario, you will need to setup some sort of session state that can be shared across servers (such as a session state server or SQL Server session state).
Here is some info on the various session state providers:
http://msdn.microsoft.com/en-us/library/ms178586.aspx
Session["report"] is null. You're not setting it to renderBytes in the user control.
Also, it's a really bad idea to store this in a Session. Your binary data has to be serialized/encoded and then deserialized/unencoded whenever you set the Session[] value, which performs poorly. Create a property on the user control to accept the report object and write it to the output stream there, or just do it in the page itself. I'm not sure that it makes sense to put this in a user control instead of a regulat class, anyway.

Downloading file from server for user logged in as guest

I have a code which allows you to download any file from server to your local host.
This code works fine when i log in as administrator but when i log in as guest user it does not let me download.. and i get an error message saying..
External component has thrown an exception.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Runtime.InteropServices.SEHException: External component has thrown an exception.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
My code is as follows
string filepath = restoredFilename.ToString();
// Create New instance of FileInfo class to get the properties of the file being downloaded
FileInfo myfile = new FileInfo(filepath);
// Checking if file exists
if (myfile.Exists)
{
// Clear the content of the response
Response.ClearContent();
// Add the file name and attachment, which will force the open/cancel/save dialog box to show, to the header
Response.AddHeader("Content-Disposition", "attachment; filename=" + myfile.Name);
//Response.AddHeader("Content-Disposition", "inline; filename=" + myfile.Name);
// Add the file size into the response header
Response.AddHeader("Content-Length", myfile.Length.ToString());
// Set the ContentType
Response.ContentType = ReturnExtension(myfile.Extension.ToLower());
//// Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
Response.TransmitFile(myfile.FullName);
// End the response
Response.End();
}
I have to download the file using guest.. please help thanks
Stack Trace:
[SEHException (0x80004005): External component has thrown an exception.]
xyzgui.Guest.DriveContents.RestoreOneFileForGUI(Int32 machineID_Download, Int64 fileID, StringBuilder restoredFilename, UInt32 restoredFilenameBufsize) +0
xyzgui.Guest.DriveContents.file_Click(Object sender, EventArgs e) in C:\Users\jagmit\Documents\Visual Studio 2008\Projects\xyzgui\xyzgui\Guest\DriveContents.aspx.cs:341
System.Web.UI.WebControls.LinkButton.OnClick(EventArgs e) +111
System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +79
System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +175
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565
What authentication mechanism are you using: Forms, or Windows?
Do you have impersonation turned on?
I believe that the error you are seeing is generally thrown when there's a security issue - which sounds likely when you say "when I log in as administrator".
Is there more to the method RestoreOneFileForGUI that we're not seeing - because it looks like something is throwing a security exception outside of .NET - if it was as simple as the guest account (the account the website is running under) not having access to the file path then you'd see a standard SecurityException or UnauthorizedException from the FileInfo constructor.

Exception error message with incorrect line number

When an exception is thrown in an Asp.Net web page, an error message is displayed with the complete stack trace.
Example below:
Stack Trace:
IndexOutOfRangeException: Index was outside the bounds of the array.
MyNameSpace.SPAPP.ViewDetailsCodeBehind.LoadView() +5112
MyNameSpace.SPAPP.ViewDetailsCodeBehind.Page_Load(Object sender, EventArgs e) +67
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +13
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +43
System.Web.UI.Control.OnLoad(EventArgs e) +98
... ...
The problem is that the Line number displayed does not correspond to the line in my code that originated the exception.
In the example above, the stack shows line number 5111, yet my code behind .cs file only has 250 lines!
The aspx page is stored in a SharePoint site and the Assembly with the code behind has been deployed to GAC. Also, I've compiled in Debug mode.
Given the settings above, how can I find out what line in my code caused the Exception?
Clarification as pointed out by strelokstrelok:
In Release mode the number in front of the exception is NOT the line of code. Instead it's an offset to the native compiled code, which doesn't have any meaning to humans. More about this here: http://odetocode.com/Blogs/scott/archive/2005/01/24/963.aspx
In debug mode the PDB file will automatically map the native code offset to your .cs line in code and the number displayed WILL be the corresponding line in code.
Those numbers are NOT line numbers. In Release mode the stack trace contains the offsets into the native compiled code instead of line numbers. You can read some more about it here:
http://odetocode.com/Blogs/scott/archive/2005/01/24/963.aspx
The only way to get line numbers in a stack trace is if you built you code in debug mode with the PDB files available.
Your code behind file is not the complete class, it's only a portion that is used when the class as a whole is compiled by ASP.NET. To find what is truly on that line, take a look at the compiled class / assembly using a tool like Reflector.
Maybe the running code is not what you see on your screen. Some mate might have refactored it for you. :)

Categories

Resources