Adding content control throws an exception dynamically - c#-4.0

I am fairly new to Word Addin development. Fortunately I was able to do almost everything but stuck at some simple issue I belive.
I want to insert plain text controls dynamically at the selected range. For this I am using the following:
currentDocument = application.ActiveDocument;
foreach(var field in myFieldsList)
{
Microsoft.Office.Interop.Word.Range rng = currentDocument.ActiveWindow.Selection.Range;
object oRng = rng;
var contentControlPlain = application.ActiveDocument.ContentControls.Add(Microsoft.Office.Interop.Word.WdContentControlType.wdContentControlText, ref oRng);
contentControlPlain.Tag = formField.FormFieldId.ToString();
contentControlPlain.SetPlaceholderText(null, null, " <" + formField.FormFieldName + "> ");
contentControlPlain.LockContentControl = (formField.TypeName.Trim() == "Blank");
}
Code seems to be working fine but when I try to insert the second field it complains saying:
This method or property is not available because the current selection partially covers a plain text content control.
I understand that addin is trying to insert next content control into the previously inserted plain text control. But I tried giving some other range and could not fix it.
Any help is greatly appreciated.
Thanks.

After adding every content control use
Application.Selection.Start = lastControl.Range.End+1

Related

openxml sdk excel total sums

i am having difficulties with open xml sdk:
i am trying to generate excel file with several columns that have numbers and i want to have total sum at the end
i have tried to Generate Table Definition Part Content and inside define every column (id, name etC). If column has true for TotalColumn, it adds code (rough example)
var column = new TableColumn{
id = 1,
name = "example",
TotalsRowFunction = TotalsRowFunctionValues.Sum,
TotalsRowFormula = new TotalsRowFormula("=SUBTOTAL(109;[" + rowName + "])")
};
I can't get it to work, when i open excel it reports error, but it doesn't explicitly says what the problem is... I tried with microsoft validator but can't figure anything out...
I'd appreciate any help / example code since i can't google anything out
EDIT:
i use this at the end:
workbookPart.Workbook.CalculationProperties.ForceFullCalculation = true;
workbookPart.Workbook.CalculationProperties.FullCalculationOnLoad = true;
Why not use a cell formula?
E.g.
cell.DataType = new EnumValue<CellValues>(CellValues.Number);
cell.CellFormula = new CellFormula(string.Format("=SUBTOTAL({0};[{1}])", "109", rowName));
//This will force a full recalculation of all the cells
workbookPart.Workbook.CalculationProperties.ForceFullCalculation = true;
workbookPart.Workbook.CalculationProperties.FullCalculationOnLoad = true;
I ended using EPPlus for this as it seems to be working simple and efficient

Edit richtext field and paste it edited in another richtext field

I'm heaving problems with a specific task on Lotus Notes. I have to copy a rich text field edit it and paste inside another rich text field. But when I edit the content the text style disappears. I've tried to use this solution:
http://www.bobzblog.com/tuxedoguy.nsf/dx/geek-o-terica-15-easy-conversion-of-notes-documents-to-mime-format-part-1
to copy the html and then edit the content. But I got another problem with this:
java.lang.ClassCastException: lotus.domino.local.Item incompatible with lotus.domino.RichTextItem
Can anyone help me with my task?
Thank you.
You don't specify how you want to edit the richtext data. But if you by "edit" mean "programatically make changes to", you can do that in regular Lotusscript using the NotesRichTextItem class.
I wrote a mail-merge class a while back, and it is replacing content in a rich text field with other values, keeping the formatting. If you look at the code you can probably figure it out.
http://blog.texasswede.com/code-mail-mergeform-letters-in-lotuscript/
The relevant code is here:
Public Function MergedRichText() As NotesRichTextItem
Dim range As NotesRichTextRange
Dim cnt As Integer
Set tempbody = sourcefield
Set range = tempbody.CreateRange
Forall p In placeholder
Call p.ProcessPlaceHolder(sourcedoc, maindoc)
If p.text = "" Then
p.text = " -- "
End If
cnt = range.FindAndReplace(p.placeholderstring, p.text, 1+4+8+16)
End Forall
Call tempbody.Compact
Call tempbody.Update
Set targetfield = tempbody
Set MergedRichText = tempbody
End Function

How to get my VBA scraper to find the above row?

I have some experience with VBA but I am very new to web scraping with VBA. However I am very enthusiastic about it and thought of a 1000 ways how could I use it and make my job easier. :)
My problem is that I have a website with two input fields and one button. I can write in the input fields (they have ID so I can easily find them)
My code for the input fields:
.Document.getElementById("header_keyword").Value = my_first
.Document.getElementById("header_location").Value = my_last
But I am really stuck with clicking the button.
Here is the html code for the buttons:
<span class="p2_button_outer p2_button_outer_big"><input class="p2_button_inner" type="submit" value="Keresés" /></span>
<span class="p2_button_outer p2_button_outer_big light hide_floating"><a id="tour_det_search" class="p2_button_inner" href="http://www.profession.hu/kereses">Részletes keresés</a></span>
As you can see there are two different buttons near each other, and they share the same class. I am looking for the first/upper one. My problem is that it has no ID, only class, type and value. But I was not able to find getelementsbytype or getelementsbyvalue method.
Is there any solution to find the button by type or value (or both)?
Sorry if I am asking something stupid but as I said previously I am new in scraping...:)
Thank you in advance and have a nice weekend!
Fortunatelly I have worked out the solution. :)
What I did is the following. I made searched for the relevant classes and then using the getAttribute() method and looping thru the classes I searched for the specific value and clicked on it when found it.
Below is the working code:
Set my_classes = .Document.getElementsByClassName("p2_button_inner")
For Each class In my_classes
If class.getAttribute("value") = "Keresés" Then
Range("c4") = "Clicked"
class.Click
Exit For
End If
Next class
Thank you!
You can use the following function. It looks for a first HTML element with the given caption. You can also limit the searching by HTML tag.
(The code is compatible with IE <9 that doesn't contain getElementsByClassName method).
Public Function FindElementByCaption(dom As Object, Caption As String, _
Optional Tag As String, Optional Nested As Boolean = True) As Object
Dim ControlsSet As Variant
Dim Controls As Variant
Dim Control As Object
'------------------------------------------------------------------------------------
Set ControlsSet = VBA.IIf(Nested, dom.all, dom.childNodes)
If VBA.Len(Tag) Then
Set Controls = ControlsSet.tags(VBA.LCase(Tag))
Else
Set Controls = ControlsSet
End If
For Each Control In Controls
If VBA.StrComp(Control.InnerHtml, Caption, vbTextCompare) = 0 Then
Set FindElementByCaption = Control
Exit For
End If
Next Control
End Function
Here is how to apply it in your code:
Dim button As Object
Set button = FindElementByCaption(.Document, "Keresés", "INPUT", True)
If Not button Is Nothing Then
Call button.Click
Else
Call MsgBox("Button has not been found")
End If
CSS selector:
Use a CSS selector to target the element of:
input[value='Keresés']
This says element with input tag, having attribute value with value 'Keresés'.
CSS query:
VBA:
You apply the selector via the querySelector method of document.
ie.document.querySelector("input[value='Keresés']").Click

Hyperlink in Post entity's textfield

I'm creating a Post entity (Activity feed entity) within my custom C# code and I need to be able to add a hyperlink into its text field.
Creating a post entity
Entity post = new Entity();
post.LogicalName = "post";
I could simply write something like
post["text"] = "http://www.google.com"
and it would work as a hyperlink. I think there's jQuery (out of a box?) that handles formatting in that case.
But in my case I'd like to add a hyperlink with a custom title. Something similar to
Click
Is there a supported way to do this or do I need to write my own client side script for formatting purposes?
For your text box content to work as a hyperlink, the Format of the Textbox needs to be URL. If you can set the format of your textbox, then any text that you put in there ,provided it follows the rules of hyperlink, it will be displayed as one.
Are you creating the attribute, or is it an existing one that you're trying to fiddle with? If it's an existing one, you need to write your own javascript to render it on the form as a hyperlink; and this would be unsupported.
you can use hyperlink with custom title like this:
string link = "<a onclick='window.open(" + "http://localhost:49944/Default.aspx? surveyresponseid=" + SurveyResponseId.ToString() + "); ' href='" + "http://localhost:49944/Default.aspx?surveyresponseid=" + SurveyResponseId.ToString() + "' target='_blank' >click this</a>";
post["text"] = link;

Opening excel file prompts a message box "content recovery of the workbook"

While I'm trying to open excel file a message box is prompting like "We found a problem with some content in file name. Do you want us to try to recover as much as we can? If you trust the source of this workbook, click Yes.". What actually done is i have a excel template designed and copying the file to another file and created temp file I'm inserting data to temp file using OPEN XML and data is getting from the database.
i have tried the solutions provided in the net but those fixes are not resolving my issue.My excel is 2010
Anyone solution provided is much appreciated.
I had this problem. It was caused by the way I was storing numbers and strings in cells.
Numbers can be stored simply using cell.CellValue = new CellValue("5"), but for non-numeric text, you need to insert the string in the SharedStringTable element and get the index of that string. Then change the data type of the cell to SharedString, and set the value of the cell to the index of the string in the SharedStringTable.
// Here is the text I want to add.
string text = "Non-numeric text.";
// Find the SharedStringTable element and append my text to it.
var sharedStringTable = document.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First().SharedStringTable;
var item = sharedStringTable.AppendChild(new SharedStringItem(new Text(text)));
// Set the data type of the cell to SharedString.
cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
// Set the value of the cell to the index of the SharedStringItem.
cell.CellValue = new CellValue(item.ElementsBefore().Count().ToString());
This is explained in the documentation here: http://msdn.microsoft.com/en-us/library/office/cc861607.aspx
Another few cases that can cause this type of error:
Your sheet name is longer than 31 characters
You have invalid characters in sheet name
You have cells with values longer than 32k
The issue is due to using
package.Save();
and
package.GetAsByteArray();
at the same time
when we call
package.GetAsByteArray();
it will do following operations
this.Workbook.Save();
this._package.Close();
this._package.Save(this._stream);
Hence, removing
package.Save();
will solve this problem "We found a problem with some content in file name. Do you want us to try to recover as much as we can? If you trust the source of this workbook, click Yes."
Another possible cause could be exceeded maximum number of cell styles.
You can define:
up to 4000 styles in a .xls workbook
up to 64000 styles in a .xlsx workbook
In this case you should re-use the same cell style for multiple cells, instead of creating a new cell style for every cell.
I added the right cellReference and fixed this issue for me:
string alpha = "ABCDEFGHIJKLMNOPQRSTUVQXYZ";
for (int colInx = 0; colInx < reader.FieldCount; colInx++)
{
AppendTextCell(alpha[colInx] + "1", reader.GetName(colInx), headerRow);
}
private static void AppendTextCell(string cellReference, string cellStringValue, Row excelRow)
{
// Add a new Excel Cell to our Row
Cell cell = new Cell() { CellReference = cellReference, DataType = new EnumValue<CellValues>(CellValues.String) };
CellValue cellValue = new CellValue();
cellValue.Text = cellStringValue.ToString();
cell.Append(cellValue);
excelRow.Append(cell);
}
Same warning but the problem with me was that I was using a client input (name of wave) as sheet name for the file and when date was presented within the name, the character '/' used as date part separator was causing the issue.
I think Microsoft need to provide a better error log to save people time investigate such minor issues. Hope my answer will save someone else's time.
The issue was due to storing a string in the cell directly using cell.CellValue = new CellValue("Text"). It is possible to store numbers like this but not string. For string, define data type as string before assigning the text using Cell.DataType = CellValues.String;

Resources