Cannot open a word doc and reference it without locking it - c#-4.0

Hello I know how to open and get plain text from a word file for a bit of code. However I am having a bad effect occur from this. The word doc becomes locked and I am not aware how to de allocate whatever is locking it. What I ultimately want would like to open a file that will be in a UNC path and read part of it, whether someone else has it open or not, parse lines from it, close it, don't save anything or lock the file. The closest I can get is I can open a file, parse it, it will lock, but when I open it and close it(same machine running the code) it magically unlocks it.
I know almost nothing on COM so I hunted for a while and found something out about the Marshall object and added that. I have tried to turn on and off the reference 'ReadOnly: True', 'ReadOnly: False'. I feel there is just something simple I am missing so I thought I would ask here. Any suggestions feel free, I am coding in .NET 4.0 so you don't have pass in all those annoying obj = null, obj = null for opening the Doc.
public static string ReadWordDoc(string loc)
{
Word.Application wordApp = new Word.Application();
Word.Document Doc = wordApp.Documents.Open(loc, ReadOnly: true);
sb = "";
foreach (Word.Paragraph objParagraph in Doc.Paragraphs)
{
try
{
sb += objParagraph.Range.Text + "\n";
}
catch (Exception ex)
{
throw ex;
}
}
return sb;
Doc.Close(SaveChanges: false);
Marshal.ReleaseComObject(Doc);
wordApp.Quit(SaveChanges: false);
}

I figured it out for some reason a lock was being kept. I made sure I quit the Word app with 'Do Not Save Changes' as well as running the Garbage Collector as well. It may be a little overkill but it essentially ensures that no lock is left on my file I am targeting.
Word._Application wordApp = new Word.Application();
Word._Document Doc = wordApp.Documents.Open(loc, ReadOnly: true);
try
{
sb = "";
foreach (Word.Paragraph objParagraph in Doc.Paragraphs)
{
try
{
sb += objParagraph.Range.Text + "\n";
}
catch (Exception ex)
{
throw ex;
}
}
}
catch (COMException) { }
finally
{
//FileInfo finfo = new FileInfo(loc);
//finfo.IsReadOnly = false;
if (Doc != null)
{
Doc.Close();
Doc = null;
}
if (wordApp != null)
{
wordApp.Quit(Word.WdSaveOptions.wdDoNotSaveChanges);
wordApp = null;
}
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
return sb;

Related

Pdf jumps to page 2 when opening

I used the C# sample of PDFViewSimpleTest
When opening a pdf, it automatically jumps to the second page.
Foxit does it too (so i guess they also use pdfTron), Adobe starts from page 1
I haven't got a clue why. The pdf can be found here: http://docdro.id/EDsbCcH
The code is really simple:
public bool OpenPDF(String filename)
{
try
{
PDFDoc oldDoc = _pdfview.GetDoc();
_pdfdoc = new PDFDoc(filename);
if (!_pdfdoc.InitSecurityHandler())
{
AuthorizeDlg dlg = new AuthorizeDlg();
if (dlg.ShowDialog() == DialogResult.OK)
{
if(!_pdfdoc.InitStdSecurityHandler(dlg.pass.Text))
{
MessageBox.Show("Incorrect password");
return false;
}
}
else
{
return false;
}
}
_pdfview.SetDoc(_pdfdoc);
_pdfview.SetPagePresentationMode(PDFViewCtrl.PagePresentationMode.e_single_page);
filePath = filename;
if (oldDoc != null)
{
oldDoc.Dispose();
}
}
catch(PDFNetException ex)
{
MessageBox.Show(ex.Message);
return false;
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
return false;
}
this.Text = filename; // Set the title
return true;
}
Technically you can achieve by an OpenAction inside the Catalog directory of the PDF, that a PDF opens at a page, which is not the first page. But that isn't the case in your PDF. The PDF itself seems to be very trivial, without anything special.
My Foxit Reader version 8.2.1 does open this PDF normally at the first page.
Please try the latest version.
Official: https://www.pdftron.com/pdfnet/downloads.html
Nightly Stable/Production: http://www.pdftron.com/nightly/?p=stable/

lotus.domino.local.Item cannot be cast to lotus.domino.RichTextItem

I try to put a file into a richtext but it crashes !
In my first code, I try to use directly "getFirstItem", in first time it was ok but now i try to use it again and it crashed.
In second time i pass with an object and it find my obj doesn't an richtextItem (instanceof) ???
I don't understand.
I have the message : "lotus.domino.local.Item cannot be cast to lotus.domino.RichTextItem" ?
Could you help me ?
public void copieFichierDansRichText(String idDocument, String nomRti, File file,
String nameFichier, String chemin) throws NotesException {
lotus.domino.Session session = Utils.getSession();
lotus.domino.Database db = session.getCurrentDatabase();
lotus.domino.Document monDoc = db.getDocumentByUNID(idDocument);
lotus.domino.RichTextItem rtiNew = null;
try {
try {
if (monDoc != null) {
// if (monDoc.getFirstItem(nomRti) != null) {
// rtiNew = (lotus.domino.RichTextItem)
// monDoc.getFirstItem(nomRti);
// } else {
// rtiNew = (lotus.domino.RichTextItem)
// monDoc.createRichTextItem(nomRti);
// }
Object obj = null;
if (monDoc.getFirstItem(nomRti) != null) {
obj = monDoc.getFirstItem(nomRti);
if (obj instanceof lotus.domino.RichTextItem) {
rtiNew = (lotus.domino.RichTextItem) obj;
}
} else {
obj = monDoc.createRichTextItem(nomRti);
if (obj instanceof lotus.domino.RichTextItem) {
rtiNew = (lotus.domino.RichTextItem) obj;
}
}
PieceJointe pieceJointe = new PieceJointe();
pieceJointe = buildPieceJointe(file, nameFichier, chemin);
rtiNew.embedObject(EmbeddedObject.EMBED_ATTACHMENT, "", pieceJointe.getChemin()
+ pieceJointe.getNomPiece(), pieceJointe.getNomPiece());
monDoc.computeWithForm(true, false);
monDoc.save(true);
}
} finally {
rtiNew.recycle();
monDoc.recycle();
db.recycle();
session.recycle();
}
} catch (Exception e) {
e.printStackTrace();
}
}
EDIT : I try to modify my code with yours advices but the items never considerate as richtextitem. It is my problem. I don't understand why, because in my field it is a richtext ! For it, the item can't do :
rtiNew = (lotus.domino.RichTextItem) item1;
because item1 not be a richtext !!!
I was trying to take all the fields and pass in the item one by one, and it never go to the obj instance of lotus.domini.RichTextItem....
Vector items = doc.getItems();
for (int i=0; i<items.size(); i++) {
// get next element from the Vector (returns java.lang.Object)
Object obj = items.elementAt(i);
// is the item a RichTextItem?
if (obj instanceof RichTextItem) {
// yes it is - cast it as such // it never go here !!
rt = (RichTextItem)obj;
} else {
// nope - cast it as an Item
item = (Item)obj;
}
}
A couple of things. First of all I would set up a util class method to handle the object recycling in a neater way:
public enum DominoUtil {
;
public static void recycle(Base... bases) {
for (Base base : bases) {
if (base != null) {
try {
base.recycle();
} catch (Exception e) {
// Do nothing
}
}
}
}
}
Secondly I would remove the reduntants try/catch blocks and simplify it like this:
private void copieFichierDansRichText(String idDocument, String nomRti, File file,
String nameFichier, String chemin) {
Session session = DominoUtils.getCurrentSession();
Database db = session.getCurrentDatabase();
Document monDoc = null;
try {
monDoc = db.getDocumentByUNID(idDocument);
Item item = monDoc.getFirstItem(nomRti);
if (item == null) {
item = monDoc.createRichTextItem(nomRti);
} else if (item.getType() != Item.RICHTEXT) {
// The item is not a rich text item
// What are you going to do now?
}
RichTextItem rtItem = (RichTextItem) item;
PieceJointe pieceJointe = new PieceJointe();
pieceJointe = buildPieceJointe(file, nameFichier, chemin);
rtItem.embedObject(EmbeddedObject.EMBED_ATTACHMENT, "", pieceJointe.getChemin()
+ pieceJointe.getNomPiece(), pieceJointe.getNomPiece());
monDoc.computeWithForm(true, false);
monDoc.save(true);
} catch (NotesException e) {
throw new FacesException(e);
} finally {
DominoUtil.recycle(monDoc);
}
}
Finally, apart from the monDoc, you need not recycle anything else. Actually Session would be automatically recycled and anything beneath with it (so no need to recycle db, let alone the session!, good rule is don't recycle what you didn't instantiate), but it's not bad to keep the habit of keeping an eye on what you instantiate. If it were a loop with many documents you definitively want to do that. If you also worked with many items you would want to recycle them as early as possible. Anyway, considered the scope of the code it's sufficient like this. Obviously you would call DominoUtil.recycle directly from the try block. If you have multiple objects you can recycle them at once possibly by listing them in the reverse order you set them (eg. DominoUtil.recycle(item, doc, view)).
Also, what I think you miss is the check on the item in case it's not a RichTextItem - and therefore can't be cast. I put a comment where I think you should decide what to do before proceeding. If you let it like that and let the code proceed you will have the code throw an error. Always better to catch the lower level exception and re-throw a higher one (you don't want the end user to know more than it is necessary to know). In this case I went for the simplest thing: wrapped NotesException in a FacesException.

Getting code from all (closed) files in solution in Visual Studio SDK

I'm trying to get and edit the code of all the html-files in the project
i found a way to loop over all ProjectItems
IEnumerator Projects = _applicationObject.Solution.Projects.GetEnumerator();
while (Projects.MoveNext())
{
IEnumerator Items = ((Project)Projects.Current).ProjectItems.GetEnumerator();
Queue<ProjectItem> ProjectItems = new Queue<ProjectItem>();
while (Items.MoveNext())
{
ProjectItem SubItem = (ProjectItem)Items.Current;
try
{
if (SubItem.Document != null) DocumentIndex.Add(SubItem.Document);
}
catch (Exception Exception)
{
Console.WriteLine(Exception.Message);
//ignore
}
ProjectItems.Enqueue(SubItem);
}
//follow the tree down
while (ProjectItems.Count != 0)
{
ProjectItem ProjectItem = ProjectItems.Dequeue();
if (ProjectItem.ProjectItems != null)
{
foreach (ProjectItem SubItem in ProjectItem.ProjectItems)
{
ProjectItems.Enqueue(SubItem);
try
{
try
{
SubItem.Open(SubItem.Kind);
DocumentIndex.Add(SubItem.Document);
}catch(Exception Ex){
Console.WriteLine(Ex.Message);
}
}
catch (Exception Exception)
{
Console.WriteLine(Exception.Message);
//ignore
}
}
}
}
}
now i can't get to the code of the files that are not open in an editor window.
how do i get and edit the code of "not opened" projectItems?
how do i detect if a file is a code file? (eg: .cs, .html, .htm, .asp, ....
You must open the ProjectItem that you want to read or edit
DTE dte = (DTE)Package.GetGlobalService(typeof(DTE));
var project = dte.Solution.Projects.Item(1);
var projectItems = project.ProjectItems;
var anyItem = projectItems.Item(0);
Window anyItemWindow = anyItem.open()
var selection = anyItem.Document.Selection as TextSelection;
selection.SelectAll();
Console.WriteLine(selection.Text) // All code
anyItem.Document.Close() //Close Document
if you don't open the ProjectItem anyItem.Doument is null.
Note: selection.Insert("") can be used to change the code

Activated Solution on Sharepoint 2010 is not visible

I have activated a WSP file which includes a website template. This works and I can see the solution int he solution gallery. When I try to create a website, based on that template, its not showing up. But it says "Status: Activated".
Then I tried to deactivate it and activate it again manually. Out of a sudden, there is a new template showing up, which takes the name of my template appended by a "2".
So whats happening here exactly? The code to activate my solution is:
System.IO.MemoryStream input = new System.IO.MemoryStream(System.IO.File.ReadAllBytes(rootDirectory + "\\Templates\\Project.wsp"), true);
SPDocumentLibrary solutionGallery = (SPDocumentLibrary)web.Site.GetCatalog(SPListTemplateType.SolutionCatalog);
try
{
SPFile solutionFile = solutionGallery.RootFolder.Files.Add("Project.wsp", input);
SPUserSolution newUserSolution = web.Site.Solutions.Add(solutionFile.Item.ID);
}
catch { ... }
Ok, I found the answer myself and want to share it here. The solution is, not to provide the solution in the catalog, but also to enable the features! It works like this:
System.IO.MemoryStream input = new System.IO.MemoryStream(System.IO.File.ReadAllBytes(rootDirectory + "\\Templates\\Project.wsp"), true);
SPDocumentLibrary solutionGallery = (SPDocumentLibrary)web.Site.GetCatalog(SPListTemplateType.SolutionCatalog);
try
{
SPFile solutionFile = solutionGallery.RootFolder.Files.Add("Project.wsp", input);
SPUserSolution newUserSolution = web.Site.Solutions.Add(solutionFile.Item.ID);
Guid solutionId = newUserSolution.SolutionId;
SPFeatureDefinitionCollection siteFeatures = web.Site.FeatureDefinitions;
var features = from SPFeatureDefinition f
in siteFeatures
where f.SolutionId.Equals(solutionId) && f.Scope == SPFeatureScope.Site
select f;
foreach (SPFeatureDefinition feature in features)
{
try
{
web.Site.Features.Add(feature.Id, false, SPFeatureDefinitionScope.Site);
}
catch { }
}
SPWebTemplateCollection webTemplates = web.Site.RootWeb.GetAvailableWebTemplates(1033);
SPWebTemplate webTemplate = (from SPWebTemplate t
in webTemplates
where t.Title == "Projekt"
select t).FirstOrDefault();
if (webTemplate != null)
{
try
{
web.Site.RootWeb.ApplyWebTemplate(webTemplate.Name);
}
catch { }
}
}
catch { ... }

Is it possible to use IMAP Query Terms in Javamail with GMail?

I am trying to programmatically retrieve the Call Log messages that are backup up from my android phone by a little application called SMSBackup (highly recommended).
What I want to do is to be able to retrieve the call logs for a particular day. I have tried the following program, using JavaMail:
public List<CallLogEntry> getCallLog(String username, String password, Date date, TimeZone tz) {
Store store = null;
try {
store = MailUtils.getGmailImapStore(username, password);
Folder folder = store.getDefaultFolder();
if (folder == null)
throw new Exception("No default folder");
Folder inboxfolder = folder.getFolder("Call log");
if (inboxfolder == null)
throw new Exception("No INBOX");
inboxfolder.open(Folder.READ_ONLY);
Date fromMidnight = new Date(TimeUtils.fromMidnight(date.getTime(), tz));
Date toMidnight = new Date(TimeUtils.toMidnight(date.getTime(), 0, tz));
SentDateTerm fromTerm = new SentDateTerm(SentDateTerm.GT, fromMidnight);
SentDateTerm toTerm = new SentDateTerm(SentDateTerm.LT, toMidnight);
AndTerm searchTerms = new AndTerm(fromTerm, toTerm);
Message[] msgs = inboxfolder.search(searchTerms);
FetchProfile fp = new FetchProfile();
fp.add("Subject");
fp.add("Content");
fp.add("From");
fp.add("SentDate");
inboxfolder.fetch(msgs, fp);
List<CallLogEntry> callLog = new ArrayList<CallLogEntry>();
for (Message message : msgs) {
CallLogEntry entry = new CallLogEntry();
entry.subject = message.getSubject();
entry.body = (String) message.getContent();
callLog.add(entry);
}
inboxfolder.close(false);
store.close();
return callLog;
} catch (NoSuchProviderException ex) {
ex.printStackTrace();
} catch (MessagingException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (store != null)
store.close();
} catch (MessagingException ex) {
ex.printStackTrace();
}
}
return null;
}
My two utility methods (fromMidnight / toMidnight):
public static final long fromMidnight(long time, TimeZone tz) {
Calendar c = Calendar.getInstance(tz);
c.setTimeInMillis(time);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 1);
return c.getTimeInMillis();
}
public static final long toMidnight(long time, int nDays, TimeZone tz) {
Calendar c = Calendar.getInstance(tz);
c.setTimeInMillis(time + nDays*MILLIS_IN_DAY);
c.set(Calendar.HOUR_OF_DAY, 23);
c.set(Calendar.MINUTE, 59);
c.set(Calendar.SECOND, 59);
c.set(Calendar.MILLISECOND, 999);
return c.getTimeInMillis();
}
However, for some reason:
while eventually executing, it takes about 3 minutes to complete
I'm getting back the entire Call log, i.e. the entire content of the "Call Log" folder in my mailbox
What am I missing?
The main thing that you're missing is that the underlying IMAP SEARCH syntax supports only dates, not date-times. So your query will result in JavaMail issuing the command:
A001 SEARCH SENTBEFORE 16-JAN-2011 SENTSINCE 16-JAN-2011 ALL
(Put a breakpoint in IMAPProtocol.issueSearch() to see this.)
GMail appears to freak out on this query, which logically cannot match any messages. Try switching your logic to a single term using SentDateTerm.EQ (which maps to SENTON) and it should work:
SentDateTerm term = new SentDateTerm(SentDateTerm.EQ, date.getTime());
Message[] msgs = inboxfolder.search(term);

Resources