Debugging VSTO with a Command Argument - vsto

I am developing an Excel Add-In, and I'm seeing some bugs that are coming up when people start Excel by opening a Workbook. If they start Excel and then open a Workbook, everything is fine, but otherwise there are issues.
The problem is, I don't know how to debug this, as I can't start the debugger with an Excel command argument (as far as I know).
I'll add some detail as requested:
Inside the ThisAddIn.cs, I have 2 blocks of code that are giving me problems.
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
try
{
if (isStarted) return;
var xl = this.Application;
xl.WorkbookOpen += WorkbookOpened;
xl.SheetActivate += Workbook_SheetActivate;
var workbook = Application.ActiveWorkbook;
WorkbookOpened(workbook);
isStarted = true;
}
catch (Exception ex)
{
logger.LogIt($"Error 01 - {ex.Message}");
}
}
and:
private void WorkbookOpened(Excel.Workbook workbook)
{
try
{
if (!isStarted)
{
var xl = this.Application;
xl.WorkbookOpen += WorkbookOpened;
xl.SheetActivate += Workbook_SheetActivate;
isStarted = true;
}
int key = Application.Hwnd;
dynamic srVers = null;
if (workbook.CustomDocumentProperties.Count == 0) return;
var srType = workbook.CustomDocumentProperties("InternalDocType");
try
{
srVers = workbook.CustomDocumentProperties("Version");
}
catch (Exception)
{
srVers = null;
}
if (srType.Value != "OurType") return;
Globals.Ribbons.prRibbon.WorkbookOpened(workbook);
}
catch (Exception ex)
{
logger.LogIt($"Error 06 - {ex.Message}");
}
}
When someone starts Excel and opens the workbook, there are no errors. However, if someone opens Excel by opening the workbook (double-click in File Explorer, or right click Excel and choosing the workbook) I get the Error 06 then Error 01, both with "Object reference not set to an instance of an object."
Any suggestions?

#ESDictor, you can directly pass the path of the excel file as command line argument in visual studio.

Related

Error: file doesn't exist

Now am working on a project where I need to create a folder in sdcard which am able to do. Also I need to hide/unhide it according to need. The code is working fine on emulator but not in device this is my code what went wrong ?
public class FolderCreate extends MIDlet {
private Form form;
private Display display;
FileConnection fc;
String path;
public void startApp() {
form = new Form("Hello World");
String msg = "Hello World!!!!!!!";
form.append(msg);
display = Display.getDisplay(this);
display.setCurrent(form);
System.out.println("WWWW");
try {
path = System.getProperty("fileconn.dir.memorycard");
System.out.println("Path : "+path+"/sample");
fc = (FileConnection)Connector.open(path+"/ABCD/");
if(!fc.exists())
{
fc.mkdir();
System.out.println("directory created");
}
} catch (IOException e) {
// TODO Auto-generated catch block
//System.out.println("ERROR "+e.getMessage());
Alert alert = new Alert("Alert");
alert.setString(e.getMessage());
display.setCurrent(alert);
}
try
{
//fc = (FileConnection)Connector.open(path+"/sample/");
if(fc.isHidden())
{
fc.setHidden(false);
}
else{
fc.setHidden(true);
}
fc.close();
}
catch (Exception e)
{
Alert alert = new Alert("Alert2");
alert.setString(e.toString());
display.setCurrent(alert);
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
System.out.println("Destroyed");
notifyDestroyed();
}
}
The error am getting is: java.io.IOException: file does not exist
Check if path starts with "file://". If not, add the suffix.
path = System.getProperty("fileconn.dir.memorycard");
if (path != null && !path.startsWith("file://")) {
path = "file://" + path;
}
I think you are doing mistake at following line,
path = System.getProperty("fileconn.dir.memorycard");
When you are working with phone and SD-Card you should use e: drive for referring to SD Card as follows,
path = file:///e:/<folder-name>/

CommunicationException in WCF Service

My problem is that AddExcursionAsync doesn't work, it shows CommunicationException.
In Console application this code works well. But in Silverlight it makes error. Functions
AddListOgTourNumbersAsync and GetListOfTourNumberAsync work correctly. Where I did the error?
Code:
private AdminServiceClient client;
public AddExcursionDialog()
{
InitializeComponent();
DurationElement.Value = new DateTime();
client = new AdminServiceClient();
client.GetListOfTourNumberCompleted += new EventHandler<GetListOfTourNumberCompletedEventArgs>(GetListOfTourNumber);
client.AddListOgTourNumbersCompleted += new EventHandler<AsyncCompletedEventArgs>(AddListOfTourNumbers);
client.AddExcursionCompleted += new EventHandler<AsyncCompletedEventArgs>(AddExcursion);
}
private void OKButton_Click(object sender, RoutedEventArgs e)
{
excursion = new Excursion();
excursion.Name = NameText.Text;
excursion.Cost = Convert.ToDouble(CostText.Text);
excursion.Place = PlaceText.Text;
excursion.Duration= (DateTime)DurationElement.Value;
excursion.Agency_id = tour_names[AgencyCB.SelectedValue.ToString()];
excursion.MaxPpl = Convert.ToInt32(MaxPplText.Text);
client.GetListOfTourNumberAsync();
client.AddExcursionAsync(excursion);
client.AddListOgTourNumbersAsync(tour_id, excursion.NumberOfList);
this.DialogResult = true;
}
I have also battled with CommunicationException(s). At that point, I believe the network were experiencing regular problems.
In my scenario I had to stabilise this call with a retry algorithm.
I'm not saying you should do this all the time, but use it to test.
In this code, the exception is allowed to be thrown if the 3rd attempt fails.
string[] Images64;
try { /* 1st try */
Images64 = _VideoClient.GetImagesStr(ImagePaths[0], ImagePaths[1], LFrame, RFrame);
}
catch (CommunicationException) {
try { /* 2nd try */
Images64 = _VideoClient.GetImagesStr(ImagePaths[0], ImagePaths[1], LFrame, RFrame);
}
catch (CommunicationException) {
try { /* 3rd try */
Images64 = _VideoClient.GetImagesStr(ImagePaths[0], ImagePaths[1], LFrame, RFrame);
}
catch (CommunicationException) {
throw;
}
}
}

Windows 8 Metro Style Clipboard Exception

I have developed an application which reads clipboard data in DispatcherTimer Tick() method.
Every second the clipboard data is read.
The application throws no exception in development machine (in debug or relase mode), however if I publish the application on a Win RT Tablet device, I have an exception while reading clipboard, but strangely only in "snap view" mode.
in full view mode, it works without any problem.
The exception is:
"Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))".
The code looks like;
private async Task Populate()
{
try
{
var clipboardText = await this.GetTextFromClipboard();
.....
}
catch (Exception ex)
{
this.HandleException("Error occured while reading clipboard: ", ex);
}
}
private async Task<string> GetTextFromClipboard()
{
var dataPackageView = Clipboard.GetContent(); // Exception occurs here!!!
if (dataPackageView.Contains(StandardDataFormats.Text))
{
var clipboardText = await dataPackageView.GetTextAsync();
return clipboardText;
}
return string.Empty;
}
What is wrong here and why it happens only at Snap View mode?

JavaMail - Pop3Folder accidentally gets closed

After successfully opening Pop3Folder, and retrieving messages from it, I then sometimes get to the point, when folder.isOpen returns false. At the same time, when looking at the Pop3Folder's fields in debug mode, I see that the field opened set to true.
Could somebody give me a hint, what might go wrong here?
Here is the code:
public void popMail(MessageProcessor messageProcessor) throws MessagingException {
Folder inboxFolder = null;
Store store = null;
try {
store = mailSession.getStore();
store.connect(mailSession.getProperty("mail.user"),
mailSession.getProperty("mail.password"));
// OK. Connected to POP3 Store.
inboxFolder = store.getFolder("inbox");
inboxFolder.open(Folder.READ_WRITE);
// The folder is successfully opened.
Message[] msgs = inboxFolder.getMessages();
// Messages are successfully retrieved.
if (msgs != null && msgs.length > 0) {
for (Message msg : msgs) {
if (messageProcessor != null) {
// Calling custom listener to process message
messageProcessor.processMessage(msg);
}
msg.setFlag(Flag.DELETED, true);
}
}
} finally {
// Oops, inboxFolder.isOpen returns false.
// Meanwhile I see in debug mode that inboxFolder#opened is set to true
if (inboxFolder != null && inboxFolder.isOpen()) {
try {
inboxFolder.close(true);
} catch (MessagingException e) {
log.warn("Error while closing folder");
}
} if (store != null) {
try {
store.close();
} catch (MessagingException e) {
log.warn("Error while closing store");
}
}
}
}
The server may be timing out the connection if your processMessage method takes too long. Turn on Session debugging and examine the protocol trace for clues.

excel file upload using apache file upload

I am developing an testing automation tool in linux system. I dont have write permissions for tomcat directory which is located on server. I need to develop an application where we can select an excel file so that the excel content is automatically stored in already existing table.
For this pupose i have written an form to select an file which is posted to a servlet CommonsFileUploadServlet where i am storing the uploaded file and then calling ReadExcelFile class which reads the file path and create a vector for data in file which is used to sstore data in database.
My problem is that i am not able to store the uploaded file in directory. Is it necessary to have permission rights for tomcat to do this. Can i store the file on my system and pass the path to ReadExcelFile.class
Please guide me
My code is as follows:
Form in jsp
CommonsFileUploadServlet class code:
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/plain");
out.println("<h1>Servlet File Upload Example using Commons File Upload</h1>");
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory ();
fileItemFactory.setSizeThreshold(1*1024*1024);
fileItemFactory.setRepository(new File("/home/example/Documents/Project/WEB-INF/tmp"));
ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
try {
List items = uploadHandler.parseRequest(request);
Iterator itr = items.iterator();
while(itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if(item.isFormField()) {
out.println("File Name = "+item.getFieldName()+", Value = "+item.getString());
} else {
out.println("Field Name = "+item.getFieldName()+
", File Name = "+item.getName()+
", Content type = "+item.getContentType()+
", File Size = "+item.getSize());
File file = new File("/",item.getName());
String realPath = getServletContext().getRealPath("/")+"/"+item.getName();
item.write(file);
ReadExcelFile ref= new ReadExcelFile();
String res=ref.insertReq(realPath,"1");
}
out.close();
}
}catch(FileUploadException ex) {
log("Error encountered while parsing the request",ex);
} catch(Exception ex) {
log("Error encountered while uploading file",ex);
}
}
}
ReadExcelFile code:
public static String insertReq(String fileName,String sno) {
//Read an Excel File and Store in a Vector
Vector dataHolder=readExcelFile(fileName,sno);
//store the data to database
storeCellDataToDatabase(dataHolder);
}
public static Vector readExcelFile(String fileName,String Sno)
{
/** --Define a Vector
--Holds Vectors Of Cells
*/
Vector cellVectorHolder = new Vector();
try{
/** Creating Input Stream**/
//InputStream myInput= ReadExcelFile.class.getResourceAsStream( fileName );
FileInputStream myInput = new FileInputStream(fileName);
/** Create a POIFSFileSystem object**/
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
/** Create a workbook using the File System**/
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
int s=Integer.valueOf(Sno);
/** Get the first sheet from workbook**/
HSSFSheet mySheet = myWorkBook.getSheetAt(s);
/** We now need something to iterate through the cells.**/
Iterator rowIter = mySheet.rowIterator();
while(rowIter.hasNext())
{
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator cellIter = myRow.cellIterator();
Vector cellStoreVector=new Vector();
short minColIndex = myRow.getFirstCellNum();
short maxColIndex = myRow.getLastCellNum();
for(short colIndex = minColIndex; colIndex < maxColIndex; colIndex++)
{
HSSFCell myCell = myRow.getCell(colIndex);
if(myCell == null)
{
cellStoreVector.addElement(myCell);
}
else
{
cellStoreVector.addElement(myCell);
}
}
cellVectorHolder.addElement(cellStoreVector);
}
}catch (Exception e){e.printStackTrace(); }
return cellVectorHolder;
}
private static void storeCellDataToDatabase(Vector dataHolder)
{
Connection conn;
Statement stmt;
String query;
try
{
// get connection and declare statement
int z;
for (int i=1;i<dataHolder.size(); i++)
{
z=0;
Vector cellStoreVector=(Vector)dataHolder.elementAt(i);
String []stringCellValue=new String[10];
for (int j=0; j < cellStoreVector.size();j++,z++)
{
HSSFCell myCell = (HSSFCell)cellStoreVector.elementAt(j);
if(myCell==null)
stringCellValue[z]=" ";
else
stringCellValue[z] = myCell.toString();
}
try
{
//inserting into database
}
catch(Exception error)
{
String e="Error"+error;
System.out.println(e);
}
}
stmt.close();
conn.close();
System.out.println("success");
}
catch(Exception error)
{
String e="Error"+error;
System.out.println(e);
}
}
POI will happily open from an old InputStream, it needn't be a File one.
I'd suggest you look at the Commons FileUpload Streaming API and consider just passing the excel part straight to POI without touching the disk