File.CopyTo error - c#

I have a C# program that queries a remote database for an image file based on a key number. When it finds a match, it locates the file locally (on the server where the program is run) and copies it to a temporary local directory, from where the image is served up in the user's browser. However, I am getting a COM error directed at the file.CopyTo line of the program. The program DOES successfully locate the file and copy it to the temp directory, so it actually works, but for some reason, it apparently doesn't get a success message back or something, and so it stops before returning the filename back to the module that would serve it up in the browser. My apologies if this is too vague. Below is the Error, and then I have put the line of code it points to. There is really not much more to add, as it apparently has what it needs to be successful, but doesn't seem to acknowledge it. Let me know if I need to post more Anyway...
Server Error in '/Indus' Application.
DB-0039 An error occurred while copying a file.
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.COMException:
DB-0039 An error occurred while copying a file.
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:
[COMException (0x80004005): DB-0039 An error occurred while copying a
file.] XtenderSolutions.interop.AEXDBLib.IObjectFile.CopyTo(Object
FileName) +0 ip_axdb.AXNetConnect.GetAXDocuments(String FieldValue)
in C:\IndusAXProject2013\IP_AXDb\AXDB\AXNetConnect.cs:67
IP_EDMSforVentyx._Default.Page_Load(Object sender, EventArgs e) in
C:\IndusAXProject2013\IP_EDMSforVentyx\EDMSforVentyx_Default.cs:21
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) +91
System.Web.UI.Control.LoadRecursive() +74
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
+2207
And the line of code is simply:
file.CopyTo(filepath + filename);
which is part of this:
for (int j = 1; j <= ((int) pages.Count); j++)
{
PAGE page = (PAGE) pages[j];
PageVersions versions = (PageVersions) page.Versions;
int num4 = 0;
num4 = (int) versions.Count;
if (num4 < 1)
{
break;
}
PAGEVERSION pageversion = (PAGEVERSION) versions[num4];
ObjectFile file = (ObjectFile) app.FileObject;
filename = i.ToString() + "_" + j.ToString() + ".tif";
file.ObjectId = pageversion.ObjectId;
file.PathId = (pageversion.PathId);
file.GenerateNewFileName();
file.CopyTo(filepath + filename);
if (IsJpegHeader(filepath, filename))
{
this.DeleteImgFile(filepath, filename);
file.CopyTo(filepath + (i.ToString() + "_" + j.ToString() + ".jpg"));
}
}
Anyway, thanks if anyone has any ideas.

Related

c# Rotativa issue in production server using user built template pdf generation

i am developing a enterprise app in c# .net. There are many pdf documents generated in the system. I use Rotativa for pdf handling. There is one pdf which uses user created template in the system. System fetches data from the system and replaces the template variables with the dynamic values from server and downloads the pdf. This particular pdf is working fine in my local and development server, but fails in the production server. Will be glad if somebody could help. i have attached the error and the code. please have a look.
public ActionResult GenerateRedemptionLetterGift(int id, int templateId)
{
try
{
int RedTempId = templateId; //Convert.ToInt32(Request.QueryString["templateId"]);
int type = 2;
RedemptionCode RedemptionObj = new RedemptionCode();
RedemptionObj = BlObj.GetRedemptionDetail(id);
return new Rotativa.MVC.ActionAsPdf("ReturnTemplate", new { id, RedTempId, type }) { FileName = "Redemption_Letter_" + RedemptionObj.Id.ToString() + ".pdf" };
}
catch (Exception ex)
{
throw new Exception("Main Method", ex);
}
}
here i call a function ReturnTemplate as ActionAsPdf where all the data is fetched and replaced in the user created template.
public ActionResult ReturnTemplate(int id, int RedTempId, int type)
{
try
{
RedemptionTemplateBO RedTemp = new RedemptionTemplateBO();
RedTemp = BlObj.GetRedemptionTemplateForEdit(RedTempId);
Hashtable TempStrings = new Hashtable();
if (type == 1)
{
TempStrings = GenerateRedemptionHashTable(id);
}
else if (type == 2)
{
TempStrings = GenerateRedemptionHashTableGift(id);
}
StringBuilder builder = new StringBuilder();
builder.Append("<html><head><title>Redemption Letter</title></head><body><style> #font-face {font-family: myFirstFont;src: url(~/fonts/Roboto-Regular.ttf);} p{font-family: 'Roboto', sans-serif;color: #3e3e3e;font-size: 15px;font-weight: 400;margin-bottom: 10px}</style>");
builder.Append(RedTemp.TemplateContent);
builder.Append("</body></html>");
foreach (string key in TempStrings.Keys)
{
builder.Replace("[" + key + "]", (string)TempStrings[key]);
}
return Content(builder.ToString());
}
catch( Exception ex)
{
throw new Exception("Return Template", ex);
}
}
I have checked in the local using a break point, if i am getting the correct data in the string for returning in the second method. Its coming fine.
Its running fine in both local and development server. I am getting the expected pdf.
But when i run it in production. i am running into an error, and it doesnt seem to be hitting the try catch block also.
Server Error in '/' Application.
Error: Failed loading page http://app.com/Redemption/ReturnTemplate/185?RedTempId=3&type=2 (sometimes it will work just to ignore this error with --load-error-handling ignore)
Exit with code 1 due to network error: RemoteHostClosedError
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.Exception: Error: Failed loading page http://app.com/Redemption/ReturnTemplate/185?RedTempId=3&type=2 (sometimes it will work just to ignore this error with --load-error-handling ignore)
Exit with code 1 due to network error: RemoteHostClosedError
This is the last few stack trace
Rotativa.Core.WkhtmltopdfDriver.Convert(DriverOptions options, String html) +793
Rotativa.MVC.AsPdfResultBase.CallTheDriver(ControllerContext context) +27
Rotativa.MVC.AsPdfResultBase.BuildPdf(ControllerContext context) +203
Rotativa.MVC.AsPdfResultBase.ExecuteResult(ControllerContext context) +27
WkhtmltopdfDriver takes too long to respond from production server.
Could it be due to some outgoing calls in Rotativa server. But still my other pdf generations work fine with rotativa in the production server.
We had a similar but different error: Failed loading page:...HostNotFoundError
Basically, rotativa was trying to resolve the domain name from within the intranet, but this particular network does not allow you to access their own public facing sites using its bound domain name. Switching to .UrlAsAPdf and using the intranet IP address, fixed this.
Also test the PDF view/ page locally first, to see that it is doing what you want.

Include full trace with stack trace / error output c#

I'm using the following code in my global.asax file:
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Exception objErr = Server.GetLastError().GetBaseException();
string err = "Error Caught in Application_Error event<hr />" + "Current User: " + HttpContext.Current.User.Identity.Name + "<hr />" +
"Error in: " + Request.Url.ToString() +
"<hr />Error Message:" + objErr.Message.ToString() +
"<hr />Stack Trace:" + objErr.StackTrace.ToString();
//EventLog.WriteEntry("Sample_WebApp", err, EventLogEntryType.Error);
doEmail.sendEmail("Application Error - Curato (" + System.Configuration.ConfigurationManager.AppSettings["OrganisationName"].ToString() + ")", err);
// We do not want the error handled by the web.config as well, so clear the error.
Server.ClearError();
// Now redirect ourselves...
Response.Redirect("~/error.aspx?aspxerrorpath=" + Server.UrlEncode(Request.Url.PathAndQuery));
}
This sends the stackTrace and current user to an admin email address, and redirects the user to a friendly error page.
How would I be able to include the full Trace information in err? That is, the same information as if I had set Trace="True" in the <%# Page directive.
I'm exploring the Trace object - and found how to read it from a 3rd party reader how to read trace but I'd like to read it just in native code.
You're already getting the full StackTrace of the exception, I believe you're looking at the wrong Exception object:
I think your error is in this line:
Exception objErr = Server.GetLastError().GetBaseException();
I think the correct one should be:
Exception objErr = Server.GetLastError();
You can also inspect the exception to see if there are InnerException:
if (objErr.InnerException != null)
err = err + "<hr/>Message:" + objErr.InnerException.Message;
See this question also:
Application_Error - GetLastError() or GetLastError().GetBaseException()

ASPX works locally but not on server

I have uploaded a web project on the server.
While it was running smoothly on my local pc where the development was made, it's not running at all on the server. As far as I can read the error, theres' a problem with an empty DataSet (fetches data from a SQL db). Again, when running the aspx locally everything is ok. Another issue I see on the errorlog is it points to my local drive "D:..." Shouldn't it point to the server address?
Error.
There is no row at position 0.
Exception Details: System.IndexOutOfRangeException: There is no row at position 0.
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:
[IndexOutOfRangeException: There is no row at position 0.]
System.Data.RBTree`1.GetNodeByIndex(Int32 userIndex) +2474798
System.Data.DataRowCollection.get_Item(Int32 index) +21
WEB.Default.Page_Load(Object sender, EventArgs e) in D:\dev\Visual Studio\Temp\WEB\Default.aspx.cs:59
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +25
System.Web.UI.Control.LoadRecursive() +71
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3064
Any idea? I use the publish tool from VS2010 and it succesfully uploads in the server. But it's not working.
Another thing I don't get is, why the webpage sends this error if I have a try/catch in the page load. If there's an error, it sets a Label with a friendly message.
Thanks.
EDIT
Here's the page load code.
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
Session["FlagOpen"] = false;
var windowsIdentity = WindowsIdentity.GetCurrent();
if (windowsIdentity != null)
{
var userName = windowsIdentity.Name;
userName = Regex.Replace(userName, ".*\\\\(.*)", "$1", RegexOptions.None);
var ds = _objUser.GetRanking(userName);
var ranking = ds.Tables[0].Rows[0][1].ToString();
_objPersona.Ranking = ranking;
_objPersona.UserName = userName;
_objPersona.RealName = ds.Tables[0].Rows[0][0].ToString();
Session["User"] = _objPersona;
LblUserName.Text = ds.Tables[0].Rows[0][0].ToString();
ds = _objUser.GetFAQ(userName);
var cant = ds.Tables[0].Rows.Count;
}
else
{
BtnAbrirBandeja.Enabled = false;
LblUserName.Text = "Not allowed.";
}
}
}
catch (Exception)
{
LblWarnings.Text = "Error. Please contact sysadmin.";
throw;
}
}
EDIT 2.
Page keeps working locally. But not on the server. It throws the original error pointing to a local folder (when it's already uploaded and running from the server).
The DataSet being null is a consequence of the web not being able to communicate with the SQL server. Hence the error.
Basically, it runs OK while debugging, but not on server.
Any ideas? Thanks.
You need to test your dataset for null before you try to access an element from the dataset, hence the error message:
if (ds!=null)
{
//continue and access the dataset
}
else
{
//you didn't get any data or ds is simply null (result set is null)
}
You are also misusing the var keyword, you don't need to use var for simple types like strings and datasets.
For whatever reason your data is inaccessible or doesn't exist:
[IndexOutOfRangeException: There is no row at position 0.]
var ranking = ds.Tables[0].Rows[0][1].ToString();
You need to be checking ds.Tables.length (or count as it may be) before performing that line.
May be when running on your local machine it was taking data from your local server and now its getting data from your server database engine..tables may be empty there or may be tables not exist there..
Check your dataset fetching method for any errors..your try catch might have hidden that error..
your another part of question:
It throws that exception because your catch block has a 'throw' statement, which will just through the same error catched by the catch block with all the inner exception details..
Note: if you write
catch(Exception ex)
{throw ex;}
inner exception details would be lost...

Publishing my asp.net web application gives 'Object reference not set to an instance of an object.'

My web app compiles and runs fine on my machine. However when I publish it to my IIS6 server, I get the infamous Object reference not set to an instance of an object. With the following stack trace
[NullReferenceException: Object reference not set to an instance of an object.]
ForYourInformation.LDAPDetails..ctor(IntPtr logonToken) in d:\documents\documents\visual studio 2010\Projects\ForYourInformation\ForYourInformation\Utils.cs:66
ForYourInformation._Default.Page_Load(Object sender, EventArgs e) in d:\documents\documents\visual studio 2010\Projects\ForYourInformation\ForYourInformation\Default.aspx.cs:24
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +24
System.Web.UI.Control.LoadRecursive() +70
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3047
The flagged file Utils.cs is as follows
_UserName = windowsId.Name.Substring(windowsId.Name.IndexOf('\\') + 1);
_DomainName = windowsId.Name.ToString().Remove(windowsId.Name.IndexOf('\\'));
//Get users information from active directory
DirectorySearcher search = new DirectorySearcher("LDAP://DCHS");
search.Filter = String.Format("(SAMAccountName={0})", _UserName);
SearchResult result = search.FindOne();
DirectoryEntry entry = result.GetDirectoryEntry();
_FullName = result.Properties["givenName"][0].ToString() + ' ' + result.Properties["sn"][0].ToString();
_Email = result.Properties["mail"][0].ToString();
_FirstName = result.Properties["givenName"][0].ToString();
_SSID = windowsId.User.ToString();
It goes and grabs the users active directory and security info. Line 66 is the DirectoryEntry line. I've got no idea whats going on here, since it works fine running locally.
Any help is appreciated thanks.
Here you go Matt, the result is return null. Check it out before you using it.
SearchResult result = search.FindOne();
if(result != null)
{
DirectoryEntry entry = result.GetDirectoryEntry();
How to tell from the report. In this line it tell you that the 66 line throw the first error, and its a null pointer. So in this line the only null can be the result, and here we go, you find it.
ForYourInformation.LDAPDetails..ctor(IntPtr logonToken) in d:\documents\documents\visual studio 2010\Projects\ForYourInformation\ForYourInformation\Utils.cs:66

C# - User Settings broken

We had a rare exception occur when reading the standard .Net user settings (this are the ones found in "project properties" in VS 2008):
System.Configuration.ConfigurationErrorsException was caught
Message="Configuration system failed to initialize"
Source="System.Configuration"
BareMessage="Configuration system failed to initialize"
Line=0
StackTrace:
at System.Configuration.ConfigurationManager.PrepareConfigSystem()
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at System.Configuration.PrivilegedConfigurationManager.GetSection(String sectionName)
at System.Diagnostics.DiagnosticsConfiguration.GetConfigSection()
at System.Diagnostics.DiagnosticsConfiguration.Initialize()
at System.Diagnostics.DiagnosticsConfiguration.get_IndentSize()
at System.Diagnostics.TraceInternal.InitializeSettings()
at System.Diagnostics.TraceInternal.get_Listeners()
InnerException: System.Configuration.ConfigurationErrorsException
Message="Unexpected end of file has occurred. The following elements are not closed: setting, SettingsTest.Properties.Settings, userSettings, configuration. Line 7, position 1. (C:\\Documents and Settings\\USER\\Local Settings\\Application Data\\Hitcents\\SettingsTest.vshost.exe_Url_ghwhc20utv4toanuinmj0pfsljthcugo\\1.0.0.0\\user.config line 7)"
Source="System.Configuration"
BareMessage="Unexpected end of file has occurred. The following elements are not closed: setting, SettingsTest.Properties.Settings, userSettings, configuration. Line 7, position 1."
Filename="C:\\Documents and Settings\\USER\\Local Settings\\Application Data\\Hitcents\\SettingsTest.vshost.exe_Url_ghwhc20utv4toanuinmj0pfsljthcugo\\1.0.0.0\\user.config"
Line=7
StackTrace:
at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
at System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors schemaErrors)
at System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
at System.Configuration.ClientConfigurationSystem.OnConfigRemoved(Object sender, InternalConfigEventArgs e)
InnerException: System.Xml.XmlException
Message="Unexpected end of file has occurred. The following elements are not closed: setting, SettingsTest.Properties.Settings, userSettings, configuration. Line 7, position 1."
Source="System.Xml"
LineNumber=7
LinePosition=1
SourceUri=""
StackTrace:
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
at System.Xml.XmlTextReaderImpl.Throw(Int32 pos, String res, String arg)
at System.Xml.XmlTextReaderImpl.ThrowUnclosedElements()
at System.Xml.XmlTextReaderImpl.ParseElementContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlTextReader.Read()
at System.Xml.XmlTextReaderImpl.Skip()
at System.Xml.XmlTextReader.Skip()
at System.Configuration.XmlUtil.StrictSkipToNextElement(ExceptionAction action)
at System.Configuration.BaseConfigurationRecord.ScanSectionsRecursive(XmlUtil xmlUtil, String parentConfigKey, Boolean inLocation, String locationSubPath, OverrideModeSetting overrideMode, Boolean skipInChildApps)
at System.Configuration.BaseConfigurationRecord.ScanSectionsRecursive(XmlUtil xmlUtil, String parentConfigKey, Boolean inLocation, String locationSubPath, OverrideModeSetting overrideMode, Boolean skipInChildApps)
at System.Configuration.BaseConfigurationRecord.ScanSections(XmlUtil xmlUtil)
at System.Configuration.BaseConfigurationRecord.InitConfigFromFile()
InnerException:
*NOTE: this is re-created from a test app.
I pulled up the user.config file, and half of it was missing.
I expect our application was terminated abruptly for some reason or another.
This seems very rare, here is how we interact with the settings:
//How we read
Settings settings = Settings.Default;
_ourStaticMemberVariable = settings.OurValue;
//How we save
Settings settings = Settings.Default;
settings.OurValue = "Our Value";
settings.Save();
Is there anything wrong with how we're using it? Both calls have a try-catch that place some default values, but the values need to be able to reset from our application.
When in this state, our application cannot save new settings--and I cannot figure out a good way to programmatically recover. I had to manually find the user.config and delete it.
I also tried calling Settings.Reset(), etc. but get the same exception.
Any ideas on how to fix this? Or are we better off writing our own settings system or saving persistent settings in another way?
EDIT: A workaround is to delete the file from code, if you get a ConfigurationErrorsException.
Anyone know how to get the full path of the user.config file?
Here's a solution that does not require you to exit the application with kudos to Jarle (http://www.codeproject.com/Articles/30216/Handling-Corrupt-user-config-Settings?msg=3608682#xx3608682xx). Early on, before Settings ever gets called, use this
public static bool CheckSettings()
{
var isReset = false;
try
{
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
}
catch (ConfigurationErrorsException ex)
{
string filename = string.Empty;
if (!string.IsNullOrEmpty(ex.Filename))
{
filename = ex.Filename;
}
else
{
var innerEx = ex.InnerException as ConfigurationErrorsException;
if (innerEx != null && !string.IsNullOrEmpty(innerEx.Filename))
{
filename = innerEx.Filename;
}
}
if (!string.IsNullOrEmpty(filename))
{
if (System.IO.File.Exists(filename))
{
var fileInfo = new System.IO.FileInfo(filename);
var watcher
= new System.IO.FileSystemWatcher(fileInfo.Directory.FullName, fileInfo.Name);
System.IO.File.Delete(filename);
isReset = true;
if (System.IO.File.Exists(filename))
{
watcher.WaitForChanged(System.IO.WatcherChangeTypes.Deleted);
}
}
}
}
return isReset;
}
Essentially, rather than relying on Sittings to throw the error, read the file with the ConfigurationManager, that way the system's version never gets into a bad state.
The way to programmatically recover is to do what you did manually - delete the user settings file. Then call Settings.Reset. (You could also write a new user settings file with default values instead of deleting it, but if you're using the configuration manager properly that's essentially the same thing.)
This is a pretty rare occurrence, but it's not totally unheard of. Not only can your program crash while writing the user settings file, the file itself is user-writeable, so other programs the user runs could mess with it.
To avoid this particular vulnerability, persist user settings in a durable store with transactional integrity, i.e. a database. (You'll still have vulnerabilities, just not this one.) That's a lot of work for what in most cases will be a marginal improvement in reliability. But "in most cases" doesn't mean "in all cases;" yours may warrant it.
[STAThread]
private static void Main(string[] args)
{
try
{
// ...
}
catch (System.Configuration.ConfigurationErrorsException ex)
{
var config = ((System.Configuration.ConfigurationErrorsException)ex.InnerException).Filename;
// notify user, ask them to restart
System.IO.File.Delete(config);
Application.Exit();
}
}

Categories