WordPerfect COM Automation Error - c#-4.0

In c# .Net 4.0 I am attempting to automate WordPerfect.
To do this I add a reference in my project to the wpwin14.tlb file that lives in the WordPerfect program folder.
That has the effect of creating the COM interfaces within my project.
Next I should be able to write code that instantiates a WordPerfect.PerfectScript object that I can use to automate WordPerfect.
However, when I try to instantiate the WordPerfect.PerfectScript object c# throws the error:
"Unable to cast COM object of type 'System.__ComObject' to interface
type 'WordPerfect.PerfectScript'. This operation failed because the
QueryInterface call on the COM component for the interface with IID
'{C0E20006-0004-1000-0001-C0E1C0E1C0E1}' failed due to the following
error: The RPC server is unavailable. (Exception from HRESULT:
0x800706BA)."
The thing to zero in on in that message (I do believe) is that the RPC server is unavailable.
I have tried this with WordPerfect running in the background and without. And I have gone to my services and made sure that RPC services were all running and restarting everything.
Is it possible that I am getting blocked by a firewall? That is my only faintest guess

I just wrap it as an OLE call and clean up my COM object with FinalReleaseComObject.
Here's a simple wrapper class I've been using to open Wp docs and convert them to pdf. It cleans up nicely in our automated process:
public class WpInterop : IDisposable
{
private bool _disposed;
private PerfectScript _perfectScript;
public PerfectScript PerfectScript
{
get
{
if (_perfectScript == null)
{
Type psType = Type.GetTypeFromProgID("WordPerfect.PerfectScript");
_perfectScript = Activator.CreateInstance(psType) as PerfectScript;
}
return _perfectScript;
}
}
protected void Dispose(bool disposing)
{
if (disposing)
{
Marshal.FinalReleaseComObject(_perfectScript);
}
_disposed = true;
}
public void Dispose()
{
if (_disposed == false)
{
GC.SuppressFinalize(this);
Dispose(true);
}
}
}

Make sure your version of WordPerfect has all of the service packs and hot fixes installed. This step has fixed many random-sounding issues for me over the years. Looks like you are using X4, which is no longer supported by Corel, which means that the updates are no longer on its web site. You should be running version 14.0.0.756 (SP2 plus 2 hotfixes).
I just uninstalled WPX4 and re-installed it, without the service pack updates. Running this code gave the exact error as the OP:
using System.Runtime.InteropServices;
using WordPerfect;
namespace WP14TLB
{
class Program
{
static void Main(string[] args)
{
PerfectScript ps = new PerfectScript();
ps.WPActivate();
ps.KeyType("Hello WP World!");
Marshal.ReleaseComObject(ps);
ps = null;
}
}
}
Installing the service packs "magically" fixed the problem.
BTW, for future reference, you can also try the WPUniverse forums. There are quite a few WP experts who regularly answer difficult questions.
There is also a link to the X4 updates here:

Related

BeforeFeature/AfterFeature does not work using SpecFlow and Coded UI

I am not able to define a [BeforeFeature]/[AfterFeature] hook for my feature file. The application under test is WPF standalone desktop applications.
If I use [BeforeScenario]/[AfterScenario] everything works fine, the application starts without any problem, the designed steps are performed correctly and the app is closed.
Once I use the same steps with [BeforeFeature]/[AfterFeature] tags the application starts and the test fails with:
The following error occurred when this process was started: Object reference not set to an instance of an object.
Here is an example:
[Binding]
public class Setup
{
[BeforeScenario("setup_scenario")]
public static void BeforeAppScenario()
{
UILoader.General.StartApplication();
}
[AfterScenario("setup_scenario")]
public static void AfterAppScenario()
{
UILoader.General.CloseApplication();
}
[BeforeFeature("setup_feature")]
public static void BeforeAppFeature()
{
UILoader.General.StartApplication();
}
[AfterFeature("setup_feature")]
public static void AfterAppFeature()
{
UILoader.General.CloseApplication();
}
}
StartApplication/CloseApplication were recorded and auto-generated with Coded UI Test Builder:
public void StartApplication()
{
// Launch '%ProgramFiles%\...
ApplicationUnderTest Application = ApplicationUnderTest.Launch(this.StartApplicationParams.ExePath, this.StartApplicationParams.AlternateExePath);
}
public class StartApplicationParams
{
public string ExePath = "C:\\Program Files..."
public string AlternateExePath = "%ProgramFiles%\\..."
}
Noteworthy: I'm quite new with SpecFlow.
I can't figure it out why my test fails with [BeforeFeature] and works fine with [BeforeScenario].
It would be great if somebody could help me with this issue. Thanks!
I ran into a similar problem recently. Not sure if this can still help you, but it may be of use for people who stumble upon this question.
For BeforeFeature\AfterFeature to work, the feature itself needs to be tagged, tagging just specific scenarios will not work.
Your feature files should start like this:
#setup_feature
Feature: Name Of Your Feature
#setup_scenario
Scenario: ...

SSJS to call a method in java class (in java library)

I've created a java library (named: invoke) with a java class (Invoke). Its seen when expanding Script libraries under code in the designer navigation pane.
The code is:
package com.kkm.vijay;
public class Invoke {
public static void main(String[] args) {
Runtime r = Runtime.getRuntime();
Process p = r.exec("C://some.exe");
}
}
Used the following ssjs to an onclick event of a button shows Error:500 when previewed in browser.
importPackage(com.kkmsoft.vijay);
var v=new Invoke();
v.main();
Even i used a function inside the class and changed the last line of ssjs to v.fn(). Yet the same problem.
There are a number of things wrong, and as Fredrik mentions you should switch on the standard Error page.
Your first code won't run because it is not correctly capturing the Exception. You are also using a main() method, which is normally used to execute a program. But you are calling it without any arguments. Avoid using that method unless it is for executing an application.
So change it to this:
package com.kkm.vijay;
import java.io.IOException;
public class Invoke {
public void mainCode() {
Runtime r = Runtime.getRuntime();
try {
Process p = r.exec("C://WINDOWS//notepad.exe");
} catch (IOException e) {
e.printStackTrace();
}
}
}
You should put that code in the new Java view in Designer.
Next your button code needs to change.
var v=new com.kkm.vijay.Invoke();
v.mainCode();
Testing that it should work fine. The issue next is, as it is SSJS the application will execute on the server. There may be security implications in this, and it may need you to modify the java.policy file in order to do this.
The related permission will be java.io.FilePermission.

Code Contracts trying to get build errors instead of warnings

I'm trying to get VS2010 Ultimate with Code Contracts to generate Errors instead of Warnings.
I have this simple test program:
using System.Diagnostics.Contracts;
namespace MyError
{
public class Program
{
static void Main(string[] args)
{
Program prog = new Program();
prog.Log(null);
}
public void Log(string msg)
{
Contract.Requires(msg != null);
}
}
}
It correctly determines there is a violation of the contract:
C:\...\Program.cs(10,13): warning : CodeContracts: requires is false: msg != null
In my csproj file there is this property field for Debug:
TreatWarningsAsErrors>true
Is there something else I have to set in the project settings to turn these into errors?
It looks like at this point Microsoft has elected not to make this possible, but they are considering it for the future:
http://connect.microsoft.com/VisualStudio/feedback/details/646880/code-contracts-dont-listen-to-treat-warnings-as-errors-setting
The problem is that the code contracts use a rewriter. they show as warnings because they are only calculated after the build completes.
Well i don't really know how it works, but unless you built code contracts into the compiler i do not see how they could be anything but warnings / messages.

Sharepoint Webpart custom properties get default values on server reboot

I have noticed that the custom properties of a webpart I developed return to their default values when I reboot my machine.
Is that a normal behavior? are the properties saved as far as the server is up, or there is some parameters I am missing.
Thank you.
EDIT: code:
namespace TestWebpart
{
[ToolboxItemAttribute(false)]
[XmlRoot(Namespace = "TestWebpart")]
public class GraphWebpart : Microsoft.SharePoint.WebPartPages.WebPart
{
// Visual Studio might automatically update this path when you change the Visual Web Part project item.
private const string _ascxPath = #"~/_CONTROLTEMPLATES/Test_Graph/TestWebpart/GraphWebpartUserControl.ascx";
protected override void CreateChildControls()
{
ReloadElements();
}
protected void ReloadElements()
{
Controls.Clear();
GraphWebpartUserControl control = (GraphWebpartUserControl)Page.LoadControl(_ascxPath);
control.xmlDataUrl = XMLFileUrl;
Controls.Add(control);
}
private static string _xmlFileUrl;
[WebBrowsable(true),
Personalizable(PersonalizationScope.Shared),
DefaultValue(""),
Description("xml"),
DisplayName("xml"),
WebDisplayName("xml")]
public string XMLFileUrl
{
get { return _xmlFileUrl; }
set {
_xmlFileUrl = value;
ReloadElements();
}
}
}
}
EDIT2:
Deleting static from the fields throws the flowing exception:
Web Part Error: An error occurred while setting the value of this property: TestWebpart:XMLFileUrl - Exception has been thrown by the target of an invocation.
Hide Error Details
[WebPartPageUserException: An error occurred while setting the value of this property: Blue_Graph.GraphWebpart.GraphWebpart:XMLFileUrl - Exception has been thrown by the target of an invocation.]
at Microsoft.SharePoint.WebPartPages.BinaryWebPartDeserializer.ApplyPropertyState(Control control)
at Microsoft.SharePoint.WebPartPages.BinaryWebPartDeserializer.Deserialize()
at Microsoft.SharePoint.WebPartPages.SPWebPartManager.CreateWebPartsFromRowSetData(Boolean onlyInitializeClosedWebParts)
First of all you should not have
private static string _xmlFileUrl;
it should be
private string _xmlFileUrl;
This static variable will be lost on IISRESET - won't work in a farm and has the potential to cause all sort of 'thread safe' issues if used multi-threaded environment (like a web server) so only use them if they are really needed.
When SharePoint loads a web part (or after you click Save/Apply in the toolpart) it uses reflection to find your properties (the [Browsable... attribute) and then serialization to load/save the value of the property to the database. One of these two is failing.
I would suspect that is some problem with the attribute - try this one and work backwards until it stops working ;)
[Browsable(true),
Category("Miscellaneous"),
DefaultValue(defaultText),
WebPartStorage(Storage.Personal),
FriendlyName("Text"),
Description("Text Property")]

Spec fails when run by mspec.exe, but passes when run by TD.NET

I wrote about this topic in another question.
However, I've since refactored my code to get rid of configuration access, thus allowing the specs to pass. Or so I thought. They run fine from within Visual Studio using TestDriven.Net. However, when I run them during rake using the mspec.exe tool, they still fail with a serialization exception. So I've created a completely self-contained example that does basically nothing except setup fake security credentials on the thread. This test passes just fine in TD.Net, but blows up in mspec.exe. Does anybody have any suggestions?
Update: I've discovered a work-around. After researching the issue, it seems the cause is that the assembly containing my principal object is not in the same folder as the mspec.exe. When mspec creates a new AppDomain to run my specs, that new AppDomain has to load the assembly with the principal object in order to deserialize it. That assembly is not in the same folder as the mspec EXE, so it fails. If I copied my assembly into the same folder as mspec, it works fine.
What I still don't understand is why ReSharper and TD.Net can run the test just fine? Do they not use mspec.exe to actually run the tests?
using System;
using System.Security.Principal;
using System.Threading;
using Machine.Specifications;
namespace MSpecTest
{
[Subject(typeof(MyViewModel))]
public class When_security_credentials_are_faked
{
static MyViewModel SUT;
Establish context = SetupFakeSecurityCredentials;
Because of = () =>
SUT = new MyViewModel();
It should_be_initialized = () =>
SUT.Initialized.ShouldBeTrue();
static void SetupFakeSecurityCredentials()
{
Thread.CurrentPrincipal = CreatePrincipal(CreateIdentity());
}
static MyIdentity CreateIdentity()
{
return new MyIdentity(Environment.UserName, "None", true);
}
static MyPrincipal CreatePrincipal(MyIdentity identity)
{
return new MyPrincipal(identity);
}
}
public class MyViewModel
{
public MyViewModel()
{
Initialized = true;
}
public bool Initialized { get; set; }
}
[Serializable]
public class MyPrincipal : IPrincipal
{
private readonly MyIdentity _identity;
public MyPrincipal(MyIdentity identity)
{
_identity = identity;
}
public bool IsInRole(string role)
{
return true;
}
public IIdentity Identity
{
get { return _identity; }
}
}
[Serializable]
public class MyIdentity : IIdentity
{
private readonly string _name;
private readonly string _authenticationType;
private readonly bool _isAuthenticated;
public MyIdentity(string name, string authenticationType, bool isAuthenticated)
{
_name = name;
_isAuthenticated = isAuthenticated;
_authenticationType = authenticationType;
}
public string Name
{
get { return _name; }
}
public string AuthenticationType
{
get { return _authenticationType; }
}
public bool IsAuthenticated
{
get { return _isAuthenticated; }
}
}
}
Dan,
thank you for providing a reproduction.
First off, the console runner works differently than the TestDriven.NET and ReSharper runners. Basically, the console runner has to perform a lot more setup work in that it creates a new AppDomain (plus configuration) for every assembly that is run. This is required to load the .dll.config file for your spec assembly.
Per spec assembly, two AppDomains are created:
The first AppDomain (Console) is created
implicitly when mspec.exe is
executed,
a second AppDomain is created by mspec.exe for the assembly containing the specs (Spec).
Both AppDomains communicate with each other through .NET Remoting: For example, when a spec is executed in the Spec AppDomain, it notifies the Console AppDomain of that fact. When Console receives the notification it acts accordingly by writing the spec information to the console.
This communiciation between Spec and Console is realized transparently through .NET Remoting. One property of .NET Remoting is that some properties of the calling AppDomain (Spec) are automatically included when sending notifications to the target AppDomain (Console). Thread.CurrentPrincipal is such a property. You can read more about that here: http://sontek.vox.com/library/post/re-iprincipal-iidentity-ihttpmodule-serializable.html
The context you provide will run in the Spec AppDomain. You set Thread.CurrentPrincipal in the Because. After Because ran, a notification will be issued to the Console AppDomain. The notification will include your custom MyPrincipal that the receiving Console AppDomain tries to deserialize. It cannot do that since it doesn't know about your spec assembly (as it is not included in its private bin path).
This is why you had to put your spec assembly in the same folder as mspec.exe.
There are two possible workarounds:
Derive MyPrincipal and MyIdentity from MarshalByRefObject so that they can take part in cross-AppDomain communication through a proxy (instead of being serialized)
Set Thread.CurrentPrincipal transiently in the Because
(Text is required for formatting to work -- please ignore)
Because of = () =>
{
var previousPrincipal = Thread.CurrentPrincipal;
try
{
Thread.CurrentPrincipal = new MyPrincipal(...);
SUT = new MyViewModel();
}
finally
{
Thread.CurrentPrincipal = previousPrincipal;
}
}
ReSharper, for example, handles all the communication work for us. MSpec's ReSharper Runner can hook into the existing infrastructure (that, AFAIK, does not use .NET Remoting).

Resources