EPPLUS - Unable to save in different folder - visual-studio-2010

I'm trying to save the excel file. It working fine if i save the file in same location but if i wanted to save different location it throwm me error.
Error:
System.NotSupportedException was unhandled
Message=The given path's format is not supported.
Source=mscorlib
StackTrace:
at System.Security.Util.StringExpressionSet.CanonicalizePath(String path, Boolean needFullPath)
at System.Security.Util.StringExpressionSet.CreateListFromExpressions(String[] str, Boolean needFullPath)
at System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, Boolean checkForDuplicates, Boolean needFullPath, Boolean copyPathList)
at System.Security.Permissions.FileIOPermission..ctor(FileIOPermissionAccess access, AccessControlActions control, String[] pathList, Boolean checkForDuplicates, Boolean needFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
at System.IO.File.Create(String path)
at Report.Form1.ExportToExcelReport(DataTable Tbl, String ExcelFilePath) in C:\SMARTAG_PROJECT\SUREREACH\EXCEL\Report\Report\Form1.cs:line 142
at Report.Form1.button2_Click(Object sender, EventArgs e) in C:\SMARTAG_PROJECT\SUREREACH\EXCEL\Report\Report\Form1.cs:line 113
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at Report.Program.Main() in C:\SMARTAG_PROJECT\SUREREACH\EXCEL\Report\Report\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
My Code
FileInfo newFile = new FileInfo("C:\\Excel\\SampleStockTakeReport.xlsx");
ExcelPackage pck = new ExcelPackage(newFile);
ExcelWorksheet ws = pck.Workbook.Worksheets[1];
var path = "C:\\Excel\\Report\\SampleStockTakeExceptionReport" + DateTime.Now + ".xlsx";
ws.View.ShowGridLines = false;
ws.Cells["G13"].Value = "Rent";
ws.Cells["G14"].Value = "Level 1";
ws.Cells["G15"].Value = "Cell 1";
ws.Cells["V14"].Value = "Level 3";
ws.Cells["V15"].Value = "Cell 3";
ws.Cells["W12"].Value = "Bukit Raja";
ws.Cells["AJ13"].Value = "Row 1";
var tracksql = new TrackingSql();
var numberoftag = tracksql.getNumberofTag();
ws.Cells["S19"].Value = DateTime.Now;
ws.Cells["Y19"].Value = numberoftag.ToString();
var numberoftagscanned = 9;
var diff = numberoftag - numberoftagscanned;
ws.Cells["Q22"].Value = numberoftagscanned;
ws.Cells["X22"].Value = numberoftag;
ws.Cells["AD22"].Value = diff;
var thispath = "testing path for report";
Stream stream = File.Create(path); // throw error here
pck.SaveAs(stream);
System.Diagnostics.Process.Start(path);
MessageBox.Show("Report Generated at " + path + "");
Appreciated if anyone could advice/help on this.

This issue is not related to EPPlus. You get the NotSupportedException at
Stream stream = File.Create(path);
which is documented here: File.Create Method (String)
So this "path is in an invalid format." because of the colons in the time-part of DateTime.Now:
var path = "C:\\Excel\\Report\\SampleStockTakeExceptionReport" + DateTime.Now + ".xlsx";
So this should work:
var dayPart = DateTime.Now.ToString("yyyy-MM-dd");
var path = "C:\\Excel\\Report\\SampleStockTakeExceptionReport" + dayPart + ".xlsx";
If you need the time part, you could create a custom DateTimeFormatInfo:
var timeFormat = (DateTimeFormatInfo)CultureInfo.CurrentCulture.DateTimeFormat.Clone();
timeFormat.TimeSeparator = "_";
var dayPart = DateTime.Now.ToString(timeFormat); // replaces the colons with _ implicitely

You need to format DateTime.Now to something like DateTime.Now.ToString("MMddyyyy");

Related

'System.NullReferenceException' occurred in opennlp-tools-1.6.0.dll while training NER using OpenNLP

I am trying to train NER with OpenNLP and I got System.NullReferenceException in opennlp-tools-1.6.0. Here is the code.
public void Train()
{
Charset charset = Charset.forName("UTF-8");
var lineStream = new PlainTextByLineStream(new FileInputStream(trainingDataFilePath), charset);
var sampleStream = new NameSampleDataStream(lineStream);
TokenNameFinderModel model = null;
try
{
model = NameFinderME.train("en", "medicine", sampleStream, Collections.emptyMap());
BufferedOutputStream modelOut = null;
modelOut = new BufferedOutputStream(new FileOutputStream(onlpModelPath));
}
catch (Exception ex)
{
throw ex;
}
}
Error Message
An exception of type 'System.NullReferenceException' occurred in opennlp-tools-1.6.0.dll but was not handled in user code
StackTrace
at opennlp.tools.ml.maxent.GISTrainer.trainModel(Int32 , DataIndexer , Prior , Int32 , Int32 )
at opennlp.tools.ml.maxent.GIS.trainModel(Int32 iterations, DataIndexer indexer, Boolean printMessagesWhileTraining, Boolean smoothing, Prior modelPrior, Int32 cutoff, Int32 threads)
at opennlp.tools.ml.maxent.GIS.doTrain(DataIndexer indexer)
at opennlp.tools.ml.maxent.GIS.<bridge>doTrain(DataIndexer x0)
at opennlp.tools.ml.AbstractEventTrainer.train(ObjectStream events)
at opennlp.tools.namefind.NameFinderME.train(String languageCode, String type, ObjectStream samples, TrainingParameters trainParams, AdaptiveFeatureGenerator generator, Map resources)
at opennlp.tools.namefind.NameFinderME.train(String languageCode, String type, ObjectStream samples, TrainingParameters trainParams, Byte[] featureGeneratorBytes, Map resources)
at opennlp.tools.namefind.NameFinderME.train(String languageCode, String type, ObjectStream samples, Map resources)
at Notes.Models.OpenNLP.Training.PersonClassifierTraining.Train() in C:\Educational\Notes\Notes\App_Data\Training\PersonClassifierTraining.cs:line 29
at Notes.Controllers.HomeController..ctor() in C:\Educational\Notes\Notes\Controllers\HomeController.cs:line 18

How to get output value (customOut) from EnvDTE Commands.Raise method?

I am writing a Visual Studio 2012 add-in that needs to send a command to the built-in T-SQL Editor. The command in question, sqlEditorSqlDatabaseCommand, can be used to either set or get the name of the current database in the editor. Here is some (working) code that sets the database name:
const string guidSqlEditorCommandSet = "b371c497-6d81-4b13-9db8-8e3e6abad0c3";
const int sqlEditorSqlDatabaseCommand = 0x312;
object customIn = "myDatabaseName";
object customOut = null;
m_applicationObject.Commands.Raise(guidSqlEditorCommandSet, sqlEditorSqlDatabaseCommand, ref customIn, ref customOut);
The problem is, I need to get the current database name, which would require use of the customOut parameter, and I can't figure out how to make customOut work.
The implementation of sqlEditorSqlDatabaseCommand is as follows (via Reflector):
protected override int HandleExec(uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
{
AuxiliaryDocData auxiliaryDocDataForEditor = base.GetAuxiliaryDocDataForEditor();
if (auxiliaryDocDataForEditor != null)
{
QueryExecutor queryExecutor = auxiliaryDocDataForEditor.QueryExecutor;
if (queryExecutor != null)
{
if (pvaIn != IntPtr.Zero)
{
string objectForNativeVariant = (string) Marshal.GetObjectForNativeVariant(pvaIn);
this.SetDatabase(auxiliaryDocDataForEditor, objectForNativeVariant);
}
else if (pvaOut != IntPtr.Zero)
{
object database = string.Empty;
IDbConnection connection = queryExecutor.ConnectionStrategy.Connection;
if (((connection != null) && (connection.State == ConnectionState.Open)) && !string.IsNullOrEmpty(connection.Database))
{
database = connection.Database;
}
else
{
database = string.Empty;
}
Marshal.GetNativeVariantForObject(database, pvaOut);
}
}
}
return 0;
}
According to every marshaling example I've seen, I should be able to pass null for both customIn and customOut, and the database name should be placed in customOut. When I do this, I get an E_INVALIDARG exception from Commands.Raise:
System.ArgumentException: The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))
at EnvDTE.Commands.Raise(String Guid, Int32 ID, Object& CustomIn, Object& CustomOut)
at RDSVisualStudioAddIn.Exec(String commandName, vsCommandExecOption executeOption, Object& varIn, Object& varOut, Boolean& handled) in c:\RDS\RDSVisualStudioAddIn\Connect.cs:line 193
Has anyone used Commands.Raise with the customOut parameter?

PhoneCallTask fails

This is a really simple task but somehow it fails...
private void TextBlock_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
{
if (WasSwipe != true)
{
//JUST TO CHECK THAT CODE GETS HERE - RUNS PERFECT
MessageBox.Show("");
//FUNCTION
var phoneCallTask = new PhoneCallTask
{
DisplayName = "Kunal Chowdhury",
PhoneNumber = "0208795446322"
};
phoneCallTask.Show();
//FAILS HERE, AFTER SHOW
}
else
{
WasSwipe = false;
}
}
When i want to show task it fails with this:
Message: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
Source: Microsoft.Phone
Stack-trace: at Microsoft.Phone.Tasks.PhoneCallTask.NativeMethods.PhoneInitiateOutgoingPhoneCall_External(String
pDialString, String pDisplayName)
at Microsoft.Phone.Tasks.PhoneCallTask.PhoneDial(Object
phoneCallTask)
at
System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object
state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx)
at
System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
IN ADDITION:
Email task works:
EmailComposeTask emailComposeTask = new EmailComposeTask();
emailComposeTask.Subject = "message subject";
emailComposeTask.Body = "message body";
emailComposeTask.To = "recipient#example.com";
emailComposeTask.Cc = "cc#example.com";
emailComposeTask.Bcc = "bcc#example.com";
emailComposeTask.Show();
You probably didn't specify following permission in your app manifest file:
ID_CAP_PHONEDIALER

Unit testing a FileStreamResult

I have a Controller which returns a FileStreamResult via SharpZipLib (I have tried DotNetZip and there is no difference).
using (var buffer = new MemoryStream())
{
using (var zipStream = new ZipOutputStream(buffer))
{
zipStream.PutNextEntry(new ZipEntry("The Simpsons"));
var bart = Encoding.UTF8.GetBytes("Homer <3 donuts");
zipStream.Write(bart, 0, bart.Length);
zipStream.IsStreamOwner = false;
return File(buffer, MediaTypeNames.Application.Zip, fileName);
}
}
I am trying to unit test this as such:
var controller = new SimpsonsController();
var result = controller.ConfigurationReport(id);
Assert.IsInstanceOf<FileStreamResult>(result);
var streamResult = (FileStreamResult) result;
var zipInputStream = new ZipInputStream(streamResult.FileStream);
Assert.IsNotNull(zipInputStream);
var zipEntry = zipInputStream.GetNextEntry();
Assert.AreEqual("The Simpsons", zipEntry.Name);
Now the unit test fails with:
System.ObjectDisposedException : Cannot access a closed Stream.
at System.IO.__Error.StreamIsClosed()
at System.IO.MemoryStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputBuffer.Fill()
at ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputBuffer.ReadLeByte()
at ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputBuffer.ReadLeInt()
at ICSharpCode.SharpZipLib.Zip.ZipInputStream.GetNextEntry()
If I try to directly download via a browser, IIS 500s with a similar stacktrace:
Cannot access a closed Stream.
System.ObjectDisposedException: Cannot access a closed Stream.
at System.IO.MemoryStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at System.Web.Mvc.FileStreamResult.WriteFile(HttpResponseBase response)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
Has anyone tested this kind of stream-based file returning controllers? How did you succeed? Should I simply NOT dispose my classes? Really?
Try this, I think your problem is you are disposing of the stream that is being returned.
public FileStreamResult PDF()
{
MemoryStream buffer = new MemoryStream();
using (var zipStream = new ZipOutputStream(buffer))
{
zipStream.PutNextEntry(new ZipEntry("The Simpsons"));
var bart = Encoding.UTF8.GetBytes("Homer <3 donuts");
zipStream.Write(bart, 0, bart.Length);
zipStream.IsStreamOwner = false;
}
return File(buffer, MediaTypeNames.Application.Zip, fileName);
}
Take a look at this https://stackoverflow.com/a/10891136/985284 and follow other posts from Cheeso for more info.

IsolatedStorageFile giving exception

In windows phone 7, I am trying to write to a file and then trying to read from a file, but while reading it is giving the exception below.
public static void writeToFile(String videoUrl)
{
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
store.CreateDirectory("MyFolder");
IsolatedStorageFileStream stream = new IsolatedStorageFileStream("MyFolder\\data.txt", FileMode.Append,
FileAccess.Write, store);
StreamWriter writer = new StreamWriter(stream);
writer.WriteLine(videoUrl);
}
public static void readFromFile()
{
try
{
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream stream = new IsolatedStorageFileStream("MyFolder\\data.txt", FileMode.Open,
store);
StreamReader reader = new StreamReader(stream);
string line;
while ((line = reader.ReadLine()) != null)
{
Debug.WriteLine("kkkkkk-----------------" + line); // Write to console.
}
}
catch (Exception ex)
{
Debug.WriteLine("ESPNGoalsUtil::readFromFile : " + ex.ToString());
}
}
Exception:
System.IO.IsolatedStorage.IsolatedStorageException: Operation not permitted on IsolatedStorageFileStream.
at System.IO.IsolatedStorage.IsolatedStorageFileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, IsolatedStorageFile isf)
at System.IO.IsolatedStorage.IsolatedStorageFileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, IsolatedStorageFile isf)
at System.IO.IsolatedStorage.IsolatedStorageFileStream..ctor(String path, FileMode mode, IsolatedStorageFile isf)
at ESPNGoals.Utility.ESPNGoalsUtil.readFromFile()
I am writing the file and then reading the file in the same method and not closing the emulator.
You need to call Close on the StreamWriter before writeToFile returns (or better still wrap the code in a using block).
The same applies to StreamReader in readFromFile.

Resources