Word automation with C++ Builder 5 - c++

I'm trying to control Word through a c++ builder 5 application. I would like to
open a ".dot" model file created with Word and modify it. In the ".dot" model file
there are some fields. For example, Title, LastName, FirstName, Address
and so on, and I would like to modify these fields putting text into them and then
saving file with a new name, for example "Warning.doc" leaving the ".dot" file
unaltered.
I can open the file, count the number of fields it contains, but then
when it comes to replacing each field with a string I don't know how to do because
I don't have a complete documentation on OleFunction and OlePropertyGet methods. I attach my source code to this message, can anybody help me to solve this problem please?
try
{
my_word = Variant::CreateObject("word.application");
}
catch (...)
{
Application->MessageBox("Unable to obtain Word automation object",
"Error:",MB_OK | MB_ICONERROR);
}
my_word.OlePropertySet("Visible", (Variant)true);
void __fastcall TForm1::Button2Click(TObject *Sender)
{
Variant this_doc;
Variant my_fields;
Variant test;
int k,field_count;
AnsiString test1;
AnsiString filename = "d:\\ProgrammaWord\\1-Avviso.dot";
my_docs = my_word.OlePropertyGet("Documents");
this_doc = my_docs.OleFunction("Open", filename);
my_fields = this_doc.OlePropertyGet("Fields");
field_count = my_fields.OlePropertyGet("Count");
for(k = 1; k <= field_count; k++)
{
test = my_fields.OleFunction("Item",(Variant)k);
test1 = test.OleFunction("Value"); //This instruction throws an exception
// "Value" is not a recognized parameter
// in this case
Memo1->Lines->Add(test1);
}
}

I never used word Ole but I used it for Outlook and Excel, I can't try it with word since I'm currently on OSX but you should try something similar as what I did.
The generic way of using Ole was to OleGetproperty() while you get the targeted field then OleSetProperty("action", ...).
for example when I wanted to change the color of the text in a particular cell of my excel document I used:
Variant _excel = Variant::CreateObject("Excel.Application");
Variant _workbook = _excel.OlePropertyGet("WorkBooks").OleFunction("Open", filename);
Variant _worksheet = _workbook.OlePropertyGet("WorkSheets", sheet);
_worksheet.OlePropertyGet("Cells", row, col).OlePropertyGet("Font").OlePropertySet("Color", color);
Here I instanciate an excel object, then I load a file into it (_workbook), then I select the _worksheet from the _workbook and I start my business.
Here comes the interesting part:
It concist of getting to a particular cell, getting the font object from it, and then setting the color of this font object.
Disclaimer: This is an example from my sources for excel, it's not directly related to your example, but maybe you can understand the principe with it. I can't try to figure out what you need because I have no windows right now.
Hope this can help you. Finding ressources for OLE can be fierce if you don't have the good patterns to look for.

Related

C++ How to use Range parameter with InlineShapes AddPicture() method

There is very limited documentation on using this method with C++. Most of the documentation is for VB. Please help me to 1) create a range object 2) use this range object with the AddPicture() method.
Here is the AddPicture definition for C++:
LPDISPATCH InlineShapes::AddPicture(LPCTSTR FileName, VARIANT* LinkToFile, VARIANT* SaveWithDocument, VARIANT* Range)
Below is working code that inserts an image into a word document. It inserts at top of doc because the range parameter(4th parameter, currently 'covOptional') is not specified. There is other code that sets up m_disp to interact with document of interest.
_Document objDoc;
COleVariant covOptional;
//instantiate the document object
objDoc.AttachDispatch(m_disp);
//adding image to doc
InlineShapes objInlineShapes(objDoc.GetInlineShapes())
objInlineShapes.AddPicture("C:\\QR.png", covOptional, covOptional, covOptional);
Here is more info on what I am trying to do incase there are alternative ways. I have a word document that I need to add a png image to. I see a couple ways of doing this: 1) hardcode range objects that specify the position in the document of the png to be inserted into 2) add anchor strings (ex. %pngLocation%) to the document. Find a way to return a range that represents this string's location. Use that range with the AddPicture() method.
I had to use a different msword library, but I got this to work with the following code.
#import "C:\Program Files (x86)\Microsoft Office\root\Office16\MSWORD.OLB" named_guids raw_native_types rename("ExitWindows", "WordExitWindows") rename("FindText", "WordFindText"), rename("VBE", "testVBE")
#include "path\debug\msword.tlh"
//setting up
Word::WindowPtr pWindow = w_app.GetActiveWindow();
Word::Range* pRange = pWindow->Selection->GetRange();
pRange->Start = 20;
pRange->End = 20;
VARIANT vTargetRange;
vTargetRange.vt = VT_DISPATCH;
vTargetRange.pdispVal = pRange;
I was able to use '&vTargetRange' as the range parameter in AddPicture().
Thank you to Castorix31.

cross site scripting issues with Fullwidth unicode characters

I have developed an application in Asp.net mvc 5.I am facing cross site scripting issues with Full width unicode characters.
Attack value:-%uff1cinput/onclick=alert(1)%uff1e
%uff1c = <
%uff1e = >
I know Antixss library can be used to resolve the issue.But anybody can show a sample code on how to implement Antixss for input filtering and output encoding
Please suggest a solution for this.
I had the same issue, and finally found a fix for it. Hopefully this will help anyone else that has the same problem.
Basically, you need to extend the RequestValidator base class that's part of System.Web.Util. Here's my class that will filter out both the unicode values and the actual full width less than and greater than symbols:
using System.Web;
using System.Web.Util;
namespace Common.Extensions
{
public class RequestValidatorExtension : RequestValidator
{
private const string UNICODE_LESS_THAN = "%uff1c";
private const string UNICODE_GREATER_THAN = "%uff1e";
public RequestValidatorExtension() { }
protected override bool IsValidRequestString(
HttpContext context,
string value,
RequestValidationSource requestValidationSource,
string collectionKey,
out int validationFailureIndex
)
{
validationFailureIndex = -1;
if (value.Contains(UNICODE_LESS_THAN))
value = value.ReplaceWith(UNICODE_LESS_THAN, "<");
else if (value.Contains("<"))
value = value.ReplaceWith("<", "<");
if (value.Contains(UNICODE_GREATER_THAN))
value = value.ReplaceWith(UNICODE_GREATER_THAN, ">");
else if (value.Contains(">"))
value = value.ReplaceWith(">", ">");
return base.IsValidRequestString(context, value, requestValidationSource, collectionKey, out validationFailureIndex);
}
}
}
In my case, when the "malicious" code was added into a text box, it would be passed in as the unicode value. However, when the query string was intercepted by Fiddler and modified, the value would be in the full width symbol. That is why there's a check for both.
You also have to register this new RequestValidationType in the web.config or in your global.asax page. Here's an example of both:
// Web.config
<httpRuntime requestValidationMode="2.0" requestValidationType="namespace.class" />
// Global.asax.cs
protected void Application_Start(object sender, EventArgs e)
{
RequestValidator.Current = new RequestValidatorExtension();
}
Also, here's a link to the MS documentation on how to utilize and extend the class.
Hope this helps, cheers!
Based on the Article below, the issue happened because the SQL server will try to convert the Unicode <> to Ascii version of <> if your database column dost not support nvarchar or nchar. As a result, when the same <> are queried from the database, it becomes XSS injection.
So essentially there are two ways to fix this.
1st as #Alec Zorn's answer, you can block them at input. This is a simple and effective approach.
The 2nd approach is you can change the DB column to use nvarchar or nchar. But this approach will require you to change a lot of columns.
https://www.gosecure.net/blog/2016/03/22/xss-for-asp-net-developers/

Search Dialogs in Epicor

Hopefully someone here is familiar with creating customizations in Epicor 9. I've posted this to the Epicor forums as well, but unfortunately that forum seems pretty dead. Any help I can get would be much appreciated.
I've created a customization on the Order Entry form to display and store some extra information about our orders. One such field is the architect on the job. We store the architects in the customer table using a GroupCode of AR to distinguish them from regular customers. I have successfully added a button that launches a customer search dialog and filters the results to only display the architects (those with GroupCode AR). Here's where the problems come in. I have two questions:
1: On the customer search, there is a customer type field that defaults to a value of Customer. Other choices are < all>, Suspect, or Prospect. How can I make the search form default to < all>?
2: How do I take the architect (customer) I select through the search dialog and populate its CustID into the ShortChar01 field on my Order Entry customization? Here's the code I have:
private void SearchOnCustomerAdapterShowDialog()
{
// Wizard Generated Search Method
// You will need to call this method from another method in custom code
// For example, [Form]_Load or [Button]_Click
bool recSelected;
//string whereClause = string.Empty;
string whereClause = "GroupCode = 'AR'";
System.Data.DataSet dsCustomerAdapter = Epicor.Mfg.UI.FormFunctions.SearchFunctions.listLookup(this.oTrans, "CustomerAdapter", out recSelected, true, whereClause);
if (recSelected)
{
System.Data.DataRow adapterRow = dsCustomerAdapter.Tables[0].Rows[0];
// Map Search Fields to Application Fields
EpiDataView edvOrderHed = ((EpiDataView)(this.oTrans.EpiDataViews["OrderHed"]));
System.Data.DataRow edvOrderHedRow = edvOrderHed.CurrentDataRow;
if ((edvOrderHedRow != null))
{
edvOrderHedRow.BeginEdit();
edvOrderHedRow["ShortChar01"] = adapterRow["CustID"];
edvOrderHedRow.EndEdit();
}
}
}
When I select a record and click OK, I get an unhandled exception.
I think the problem you are/were having is that you aren't adding the CustNum to the Sales Order first. In my mind I would do it this way first, but there is might be ChangeCustomer BO method in oTrans that you could call to make sure everything defaults correct.
EpiDataView edvOrderHed = ((EpiDataView)(this.oTrans.EpiDataViews["OrderHed"]));
if (edvOrderHed.HasRow)
{
edvOrderHed[edvOrderHed.Row].BeginEdit();
edvOrderHed[edvOrderHed.Row]["CustNum"] = adapterRow["CustNum"];
edvOrderHed[edvOrderHed.Row]["ShortChar01"] = adapterRow["CustID"];
edvOrderHed[edvOrderHed.Row].EndEdit();
}
Hope that is helpful, even if late.

Finding the phone company of a cell phone number?

I have an application where people can give a phone number and it will send SMS texts to the phone number through EMail-SMS gateways. For this to work however, I need the phone company of the given number so that I send the email to the proper SMS gateway. I've seen some services that allow you to look up this information, but none of them in the form of a web service or database.
For instance, http://tnid.us provides such a service. Example output from my phone number:
Where do they get the "Current Telephone Company" information for each number. Is this freely available information? Is there a database or some sort of web service I can use to get that information for a given cell phone number?
What you need is called a HLR (Home Location Register) number lookup.
In their basic forms such APIs will expect a phone number in international format (example, +15121234567) and will return back their IMSI, which includes their MCC (gives you the country) and MNC (gives you the phone's carrier). The may even include the phone's current carrier (eg to tell if the phone is roaming). It may not work if the phone is currently out of range or turned off. In those cases, depending on the API provider, they may give you a cached result.
The site you mentioned seems to provide such functionality. A web search for "HLR lookup API" will give you plenty more results. I have personal experience with CLX's service and would recommend it.
This would be pretty code intensive, but something you could do right now, on your own, without APIs as long as the tnid.us site is around:
Why not have IE open in a hidden browser window with the URL of the phone number? It looks like the URL would take the format of http://tnid.us/search.php?q=########## where # represents a number. So you need a textbox, a label, and a button. I call the textbox "txtPhoneNumber", the label "lblCarrier", and the button would call the function I have below "OnClick".
The button function creates the IE instance using MSHtml.dll and SHDocVW.dll and does a page scrape of the HTML that is in your browser "object". You then parse it down. You have to first install the Interoperability Assemblies that came with Visual Studio 2005 (C:\Program Files\Common Files\Merge Modules\vs_piaredist.exe). Then:
1> Create a new web project in Visual Studio.NET.
2> Add a reference to SHDocVw.dll and Microsoft.mshtml.
3> In default.aspx.cs, add these lines at the top:
using mshtml;
using SHDocVw;
using System.Threading;
4> Add the following function :
protected void executeMSIE(Object sender, EventArgs e)
{
SHDocVw.InternetExplorer ie = new SHDocVw.InternetExplorerClass();
object o = System.Reflection.Missing.Value;
TextBox txtPhoneNumber = (TextBox)this.Page.FindControl("txtPhoneNumber");
object url = "http://tnid.us/search.php?q=" + txtPhoneNumber.Text);
StringBuilder sb = new StringBuilder();
if (ie != null) {
ie.Navigate2(ref url,ref o,ref o,ref o,ref o);
ie.Visible = false;
while(ie.Busy){Thread.Sleep(2);}
IHTMLDocument2 d = (IHTMLDocument2) ie.Document;
if (d != null) {
IHTMLElementCollection all = d.all;
string ourText = String.Empty;
foreach (object el in all)
{
//find the text by checking each (string)el.Text
if ((string)el.ToString().Contains("Current Phone Company"))
ourText = (string)el.ToString();
}
// or maybe do something like this instead of the loop above...
// HTMLInputElement searchText = (HTMLInputElement)d.all.item("p", 0);
int idx = 0;
// and do a foreach on searchText to find the right "<p>"...
foreach (string s in searchText) {
if (s.Contains("Current Phone Company") || s.Contains("Original Phone Company")) {
idx = s.IndexOf("<strong>") + 8;
ourText = s.Substring(idx);
idx = ourText.IndexOf('<');
ourText = ourText.Substring(0, idx);
}
}
// ... then decode "ourText"
string[] ourArray = ourText.Split(';');
foreach (string s in ourArray) {
char c = (char)s.Split('#')[1];
sb.Append(c.ToString());
}
// sb.ToString() is now your phone company carrier....
}
}
if (sb != null)
lblCarrier.Text = sb.ToString();
else
lblCarrier.Text = "No MSIE?";
}
For some reason I don't get the "Current Phone Company" when I just use the tnid.us site directly, though, only the Original. So you might want to have the code test what it's getting back, i.e.
bool currentCompanyFound = false;
if (s.Contains("Current Telephone Company")) { currentCompanyFound = true }
I have it checking for either one, above, so you get something back. What the code should do is to find the area of HTML between
<p class="lt">Current Telephone Company:<br /><strong>
and
</strong></p>
I have it looking for the index of
<strong>
and adding on the characters of that word to get to the starting position. I can't remember if you can use strings or only characters for .indexOf. But you get the point and you or someone else can probably find a way to get it working from there.
That text you get back is encoded with char codes, so you'd have to convert those. I gave you some code above that should assist in that... it's untested and completely from my head, but it should work or get you where you're going.
Did you look just slightly farther down on the tnid.us result page?
Need API access? Contact sales#tnID.us.
[Disclosure: I work for Twilio]
You can retrieve phone number information with Twilio Lookup.
If you are currently evaluating services and functionality for phone number lookup, I'd suggest giving Lookup a try via the quickstart.

NSDictionary from P-list with UIPickerView

I'm having a problem with my picker in one of my apps. I have an NSDictionary obtained from a property list that contains a bunch of keys, which in turn contain a bunch of strings. I have two components, each one should have the same list of strings within. I also have a slider that I want to use to allow the user to change keys. So when the slider's value goes from 0 to 1 the key at index 1 in the dictionary should load its contents into the pickerview's components.
It's working as far as loading the new contents into the picker based on the slider. I've been using the slider's tag as the variable to dictate which contents get loaded. The problem is that after loading a new list of items the program crashes, I'm thinking that the number of rows needed isn't getting update or something but I'm just not experienced enough with UIPickerView to isolate the problem myself without spending more hours than I've already used trying to figure this out myself.
Here are my delegate/data methods for the picker:
#pragma mark -
#pragma mark Picker Delegate/Data Methods
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 2;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
//aryNames is an NSArray instance variable that contains the values for the components of the picker
if (component == 0)
return [self.aryNames count];
return [self.aryNames count];
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row
forComponent:(NSInteger)component
{
//I think this is where my problem is
//I'm using a string to select the object
// at the index of the slider's location to
// fill up the instance variable with new data.
//Anyway, it works fine if I have two different arrays hardcoded
//but I'd really like to have this load dynamically because
//there are a lot of keys and this way I could add and remove keys without
//worrying about changing code
NSString *selectedType = [self.aryKeys objectAtIndex:slideUnitTypes.tag];
NSArray *newNames = [dictAllNames objectForKey:selectedType];
self.aryNames = newNames;
return [aryNames objectAtIndex:row];
}
//I'm pretty sure that the method below is not the problem
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:
(NSInteger)component
{
if (component == 0)
{
[firstValueHeading setText:[aryNames objectAtIndex:row]];
}
else
{
[secondValueHeading setText:[aryNames objectAtIndex:row]];
}
}
If it wasn't descriptive enough or you need to see more of my code please tell me. This problem has been a real bugger in an otherwise smooth project. Thanks.
I am still fairly new to this myself, but in Troy Brant's book (chapter 9) he does this. You should grab the book from the library/bookstore and review the source code at http://troybrant.net/iphonebook/chapter9/Ruralfork-done.zip
It should help.
i've actually solved this long since. here is the code for that delegate if it helps:
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
NSUInteger index = slideUnitTypes.value;
NSString *placeString = [self.aryKeys objectAtIndex:index];
NSArray *returnThisArray = [dictAllNames objectForKey:placeString];
return [returnThisArray objectAtIndex:row];
}
if anyone out there needs to see any of my other delegates just comment on this answer and hopefully SO should send me an email.