VS debugger does not close - wpf

I have the following code. can anyone tell me what would happen to ut, c2 instances? Would they be hanging around without being garbage-collected for a long time? The reason I ask is that after I close all the windows including the one that execute this code Visual Studio debugger is still on (I am running it in debug mode).
If I don't raise exception in Initializer() method in Class2, the debugger will close after I close all the windows.
Below is by code
namespace Test
{
public class Class1
{
private ICommand testCommand;
public ICommand TestCommand
{
get
{
return updCommand ?? (updCommand = new DelegateCommand(() =>
{
int nStatus = 0;
Class2 c2 = new Class2();
nStatus = c2.InitStatus;
if (nStatus == 0)
{
c2.doSth()
}
System.Windows.MessageBox.Show("Return status = " + nStatus.ToString());
c2 = null;
}
));
}
}
}
public class Class2
{
Utilities ut = new Utilities();
public int InitStatus { get; set; }
public Dbupdate()
{
Initializer();
}
private void Initializer()
{
try
{
throw new Exception("just test");
}
catch (Exception ex) { ErrHandler("Initializer(): " + ex.Message); InitStatus = -100; }
}
private void doSth()
{
ut.doWhateve();
}
}
}

Figured it out. I instantiated a window but didn't close before throwing the exception.

Related

How to generate report (Extent Report) in Specflow Project

Currently I am working designing my project in Specflow. I want to implement some reporting to my project. Currently I have created one separate .cs file and kept all my report setting. But these steps are getting unreachable. Can anyone please guide me how i can design my flow and how i can integrate with the feature file?
Please find the below BaseReport.cs file and my Step definition file.
namespace Verivox.CommonLib
{
public class BaseReport
{
public static ExtentReports extent;
public static ExtentTest test;
[BeforeFeature()]
public static void BasicSetUp()
{
//string pth = System.Reflection.Assembly.GetCallingAssembly().CodeBase;
string pth = System.IO.Directory.GetCurrentDirectory();
string actualPath = pth.Substring(0, pth.LastIndexOf("bin"));
string projectPath = new Uri(actualPath).LocalPath;
string reportPath = projectPath + "Reports\\" + FeatureContext.Current.FeatureInfo.Title + ".html";
extent = new ExtentReports(reportPath, true);
extent.LoadConfig(projectPath + "CommonLib\\Extent-config.xml");
}
[BeforeScenario()]
public static void BeforeScenarioSetUp()
{
test = extent.StartTest("Running Scenario -->" + ScenarioContext.Current.ScenarioInfo.Title);
}
[AfterScenario()]
public static void AfterScnario()
{
if (ScenarioContext.Current.TestError != null)
{
var error = ScenarioContext.Current.TestError;
var errormessage = "<pre>" + error.Message + "</pre>";
//Add capture screen shot line here
extent.EndTest(test);
}
}
[AfterFeature()]
public static void EndReport()
{
extent.Flush();
// extent.Close();
}
}
}
Steps
namespace Verivox.Steps
{
[Binding]
class CalculationVerificationSteps
{
[Given(#"I have navigate to Home Page")]
public void GivenIHaveNavigateToHomePage()
{
Browser.Current.Navigate().GoToUrl(ConfigurationManager.AppSettings["seleniumBaseUrl"]);
PropertyCollection.currentPage = new HomePage();
Browser.Current.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
}
[Given(#"Navigate to Mobile Calculator under All Comparison Section")]
public void GivenNavigateToMobileCalculatorUnderAllComparisonSection()
{
PropertyCollection.currentPage.As<HomePage>().MainCompItemClick("Telekommunikation");
PropertyCollection.currentPage.As<HomePage>().SubCompItemClick("Mobilfunk");
PropertyCollection.currentPage.As<HomePage>().CalculatorLinkClick("Mobiles Internet");
}
[Then(#"Mobile Calculator should appear")]
public void ThenMobileCalculatorShouldAppear()
{
Assert.IsTrue(PropertyCollection.currentPage.As<HomePage>().IsMobileInternetCalcExistance());
}
[Then(#"(.*) option and (.*) option is selected by default\.")]
public void ThenMonatsflatrateOptionAndSIMOptionIsSelectedByDefault_(string defaultTarif, string hardware)
{
try
{
Assert.IsTrue(PropertyCollection.currentPage.As<HomePage>().VerifyMobiIntSelectedItem(defaultTarif));
string colorCode = PropertyCollection.currentPage.As<HomePage>().VerifySelectedHardWare();
Assert.AreEqual(0, string.Compare("rgba(253, 138, 2, 1)", colorCode, StringComparison.OrdinalIgnoreCase));
}
catch (Exception)
{
BaseReport.test.Log(LogStatus.Fail, "Default selections are incorrect.");
}
}
You are missing the Binding- attribute on the BaseReport class. Without that, the hooks defined there are not called.

why Dispatcher.invoke() not working?

whenever a change is occured changes i call this set_filelist_inventory(). and send a new list to this function but UI is not upadating.
public partial class Inventory : UserControl
{
public List<String> file_list = new List<String>();
public void set_filelist_inventory(List<string> x)
{
if (file_list.SequenceEqual(x)) { }
else
{
file_list = x;
Dispatcher.Invoke(() =>
{
listview1.ItemsSource = file_list;
});
}
}
public Inventory()
{
InitializeComponent();
file_list = General.GetFileList();
Discover d = new Discover();
d.send(d);
listview1.ItemsSource = file_list;
}
}
I tried removing if else block. it still didn't worked.

Easy way to dynamically invoke web services (without JDK or proxy classes)

In Python I can consume a web service so easily:
from suds.client import Client
client = Client('http://www.example.org/MyService/wsdl/myservice.wsdl') #create client
result = client.service.myWSMethod("Bubi", 15) #invoke method
print result #print the result returned by the WS method
I'd like to reach such a simple usage with Java.
With Axis or CXF you have to create a web service client, i.e. a package which reproduces all web service methods so that we can invoke them as if they where normal methods. Let's call it proxy classes; usually they are generated by wsdl2java tool.
Useful and user-friendly. But any time I add/modify a web service method and I want to use it in a client program I need to regenerate proxy classes.
So I found CXF DynamicClientFactory, this technique avoids the use of proxy classes:
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.endpoint.dynamic.DynamicClientFactory;
//...
//create client
DynamicClientFactory dcf = DynamicClientFactory.newInstance();
Client client = dcf.createClient("http://www.example.org/MyService/wsdl/myservice.wsdl");
//invoke method
Object[] res = client.invoke("myWSMethod", "Bubi");
//print the result
System.out.println("Response:\n" + res[0]);
But unfortunately it creates and compiles proxy classes runtime, hence requires JDK on the production machine. I have to avoid this, or at least I can't rely on it.
My question:
Is there another way to dinamically invoke any method of a web service in Java, without having a JDK at runtime and without generating "static" proxy classes? Maybe with a different library? Thanks!
I know this is a really old question but if you are still interested you could use soap-ws github project: https://github.com/reficio/soap-ws
Here you have a sample usage really simple:
Wsdl wsdl = Wsdl.parse("http://www.webservicex.net/CurrencyConvertor.asmx?WSDL");
SoapBuilder builder = wsdl.binding()
.localPart("CurrencyConvertorSoap")
.find();
SoapOperation operation = builder.operation()
.soapAction("http://www.webserviceX.NET/ConversionRate")
.find();
Request request = builder.buildInputMessage(operation)
SoapClient client = SoapClient.builder()
.endpointUrl("http://www.webservicex.net/CurrencyConvertor.asmx")
.build();
String response = client.post(request);
As you can see it is really simple.
With CXF 3.x this could be possible with StaxDataBinding. Follow below steps to get the basics. Of course, this could be enhanced to your needs.
Create StaxDataBinding something like below. Note below code can be enhanced to your sophistication.
class StaxDataBinding extends AbstractInterceptorProvidingDataBinding {
private XMLStreamDataReader xsrReader;
private XMLStreamDataWriter xswWriter;
public StaxDataBinding() {
super();
this.xsrReader = new XMLStreamDataReader();
this.xswWriter = new XMLStreamDataWriter();
inInterceptors.add(new StaxInEndingInterceptor(Phase.POST_INVOKE));
inFaultInterceptors.add(new StaxInEndingInterceptor(Phase.POST_INVOKE));
inInterceptors.add(RemoveStaxInEndingInterceptor.INSTANCE);
inFaultInterceptors.add(RemoveStaxInEndingInterceptor.INSTANCE);
}
static class RemoveStaxInEndingInterceptor
extends AbstractPhaseInterceptor<Message> {
static final RemoveStaxInEndingInterceptor INSTANCE = new RemoveStaxInEndingInterceptor();
public RemoveStaxInEndingInterceptor() {
super(Phase.PRE_INVOKE);
addBefore(StaxInEndingInterceptor.class.getName());
}
public void handleMessage(Message message) throws Fault {
message.getInterceptorChain().remove(StaxInEndingInterceptor.INSTANCE);
}
}
public void initialize(Service service) {
for (ServiceInfo serviceInfo : service.getServiceInfos()) {
SchemaCollection schemaCollection = serviceInfo.getXmlSchemaCollection();
if (schemaCollection.getXmlSchemas().length > 1) {
// Schemas are already populated.
continue;
}
new ServiceModelVisitor(serviceInfo) {
public void begin(MessagePartInfo part) {
if (part.getTypeQName() != null
|| part.getElementQName() != null) {
return;
}
part.setTypeQName(Constants.XSD_ANYTYPE);
}
}.walk();
}
}
#SuppressWarnings("unchecked")
public <T> DataReader<T> createReader(Class<T> cls) {
if (cls == XMLStreamReader.class) {
return (DataReader<T>) xsrReader;
}
else {
throw new UnsupportedOperationException(
"The type " + cls.getName() + " is not supported.");
}
}
public Class<?>[] getSupportedReaderFormats() {
return new Class[] { XMLStreamReader.class };
}
#SuppressWarnings("unchecked")
public <T> DataWriter<T> createWriter(Class<T> cls) {
if (cls == XMLStreamWriter.class) {
return (DataWriter<T>) xswWriter;
}
else {
throw new UnsupportedOperationException(
"The type " + cls.getName() + " is not supported.");
}
}
public Class<?>[] getSupportedWriterFormats() {
return new Class[] { XMLStreamWriter.class, Node.class };
}
public static class XMLStreamDataReader implements DataReader<XMLStreamReader> {
public Object read(MessagePartInfo part, XMLStreamReader input) {
return read(null, input, part.getTypeClass());
}
public Object read(QName name, XMLStreamReader input, Class<?> type) {
return input;
}
public Object read(XMLStreamReader reader) {
return reader;
}
public void setSchema(Schema s) {
}
public void setAttachments(Collection<Attachment> attachments) {
}
public void setProperty(String prop, Object value) {
}
}
public static class XMLStreamDataWriter implements DataWriter<XMLStreamWriter> {
private static final Logger LOG = LogUtils
.getL7dLogger(XMLStreamDataWriter.class);
public void write(Object obj, MessagePartInfo part, XMLStreamWriter writer) {
try {
if (!doWrite(obj, writer)) {
// WRITE YOUR LOGIC HOW you WANT TO HANDLE THE INPUT DATA
//BELOW CODE JUST CALLS toString() METHOD
if (part.isElement()) {
QName element = part.getElementQName();
writer.writeStartElement(element.getNamespaceURI(),
element.getLocalPart());
if (obj != null) {
writer.writeCharacters(obj.toString());
}
writer.writeEndElement();
}
}
}
catch (XMLStreamException e) {
throw new Fault("COULD_NOT_READ_XML_STREAM", LOG, e);
}
}
public void write(Object obj, XMLStreamWriter writer) {
try {
if (!doWrite(obj, writer)) {
throw new UnsupportedOperationException("Data types of "
+ obj.getClass() + " are not supported.");
}
}
catch (XMLStreamException e) {
throw new Fault("COULD_NOT_READ_XML_STREAM", LOG, e);
}
}
private boolean doWrite(Object obj, XMLStreamWriter writer)
throws XMLStreamException {
if (obj instanceof XMLStreamReader) {
XMLStreamReader xmlStreamReader = (XMLStreamReader) obj;
StaxUtils.copy(xmlStreamReader, writer);
xmlStreamReader.close();
return true;
}
else if (obj instanceof XMLStreamWriterCallback) {
((XMLStreamWriterCallback) obj).write(writer);
return true;
}
return false;
}
public void setSchema(Schema s) {
}
public void setAttachments(Collection<Attachment> attachments) {
}
public void setProperty(String key, Object value) {
}
}
}
Prepare your input to match the expected input, something like below
private Object[] prepareInput(BindingOperationInfo operInfo, String[] paramNames,
String[] paramValues) {
List<Object> inputs = new ArrayList<Object>();
List<MessagePartInfo> parts = operInfo.getInput().getMessageParts();
if (parts != null && parts.size() > 0) {
for (MessagePartInfo partInfo : parts) {
QName element = partInfo.getElementQName();
String localPart = element.getLocalPart();
// whatever your input data you need to match data value for given element
// below code assumes names are paramNames variable and value in paramValues
for (int i = 0; i < paramNames.length; i++) {
if (paramNames[i].equals(localPart)) {
inputs.add(findParamValue(paramNames, paramValues, localPart));
}
}
}
}
return inputs.toArray();
}
Now set the proper data binding and pass the data
Bus bus = CXFBusFactory.getThreadDefaultBus();
WSDLServiceFactory sf = new WSDLServiceFactory(bus, wsdl);
sf.setAllowElementRefs(false);
Service svc = sf.create();
Client client = new ClientImpl(bus, svc, null,
SimpleEndpointImplFactory.getSingleton());
StaxDataBinding databinding = new StaxDataBinding();
svc.setDataBinding(databinding);
bus.getFeatures().add(new StaxDataBindingFeature());
BindingOperationInfo operInfo = ...//find the operation you need (see below)
Object[] inputs = prepareInput(operInfo, paramNames, paramValues);
client.invoke("operationname", inputs);
If needed you can match operation name something like below
private BindingOperationInfo findBindingOperation(Service service,
String operationName) {
for (ServiceInfo serviceInfo : service.getServiceInfos()) {
Collection<BindingInfo> bindingInfos = serviceInfo.getBindings();
for (BindingInfo bindingInfo : bindingInfos) {
Collection<BindingOperationInfo> operInfos = bindingInfo.getOperations();
for (BindingOperationInfo operInfo : operInfos) {
if (operInfo.getName().getLocalPart().equals(operationName)) {
if (operInfo.isUnwrappedCapable()) {
return operInfo.getUnwrappedOperation();
}
return operInfo;
}
}
}
}
return null;
}

The calling thread cannot access this object because a different thread owns it

I am getting the exception "The calling thread cannot access this object because a different thread owns it" inspite of using Dispatcher.Invoke.
Below is the code: _btnImage1 is an instance of ImageButton declared in xaml of LaneImageReview. Note that I used Dispatcher in the RefreshLiveVESImage method below.
public partial class LaneImageReview : Page
{
private void RefreshLiveVESImages(VESImagePackageInfo p_VesImageInfo)
{
this._btnImage1.RefreshLiveVESImage(p_VesImageInfo);
}
}
public class ImageButton : Button
{
public void RefreshLiveVESImage(VESImagePackageInfo p_VesImageInfo)
{
BitmapImage bitmap = null;
try
{
//load background if not photo available
//if (p_Image == null)
//{
// _imgPhoto.Source = null;
//}
//else
//{
foreach (VESCameraInfo camInfo in p_VesImageInfo.VESCameras)
{
if (camInfo.CameraImageSets[0].FullImage != null)
{
bitmap = DVASViewController.GetBitmapImageFromByteArray(camInfo.CameraImageSets[0].FullImage.VESImage);
this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action<BitmapImage>(SetImageSource), bitmap);
break;
}
}
//}
}
catch (Exception ex)
{
SecurityController.CatchException(ex);
}
finally
{
}
}
private void SetImageSource(BitmapImage p_Image)
{
this.imgFrontLeft.Source = p_Image;
}
}
Thanks.
you can try something like
Application.Current.Dispatcher.Invoke((ThreadStart)delegate
{
DoWork();
});

Problems sending message between Silverlight apps

Has anyone had any issues communicating between two Silverlight apps. When I try to send a message from one app, I get an error, "The message could not be delivered to receiver." My code for sending is below. I'm using the similar code that is in the samples for implementing Windows Live ID in a Silverlight App. I have this working when I'm running locally, but when I post to the server, I'm getting the delivery error.
#region Fields
private readonly LocalMessageSender sender = new LocalMessageSender("LiveIdAuthentication");
private int attempts = 0;
private const int MAX_ATTEMPTS = 10;
#endregion
#region Constructors
public MainPage()
{
InitializeComponent();
this.sender.SendCompleted += new EventHandler<SendCompletedEventArgs>(Sender_SendCompleted);
this.SendMessage("authenticated");
}
#endregion
#region Event Handlers
private void Sender_SendCompleted(object sender, SendCompletedEventArgs e)
{
if (e.Error != null)
{
if (attempts > MAX_ATTEMPTS)
{
MessageBox.Show(e.Error.Message);
CloseWindow();
}
else
{
SendMessage("authenticated");
}
}
else
{
attempts = 0;
CloseWindow();
}
}
#endregion
#region Methods
private void SendMessage(string message)
{
attempts++;
this.sender.SendAsync(message);
}
private void CloseWindow()
{
HtmlPage.Window.Eval("window.open(\"about:blank\", \"_self\")");
HtmlPage.Window.Eval("window.close()");
}
#endregion
Sorry about forgetting the receiver. This is mostly from the Live ID example.
private readonly WindowsLiveIdAuthentication _service;
private readonly AsyncCallback _asyncCallback;
private readonly object _asyncState;
private readonly LocalMessageReceiver _receiver = new LocalMessageReceiver("LiveIdAuthentication");
private bool _isCompleted;
private LoadUserResult _result;
#region Constructors
public LoginAsyncResult(WindowsLiveIdAuthentication service, AsyncCallback asyncCallback, object asyncState)
{
this._service = service;
this._asyncCallback = asyncCallback;
this._asyncState = asyncState;
this._receiver.MessageReceived += this.LocalMessageReceived;
}
#endregion
#region Properties
public object AsyncState
{
get { return this._asyncState; }
}
public System.Threading.WaitHandle AsyncWaitHandle
{
get { throw new NotImplementedException(); }
}
public bool CompletedSynchronously
{
get { return false; }
}
public bool IsCompleted
{
get { return this._isCompleted; }
}
public LoadUserResult Result
{
get { return this._result; }
}
#endregion
#region Methods
public void Cancel()
{
if (!this._isCompleted)
{
this._isCompleted = true;
}
}
public void Complete()
{
if (!this._isCompleted)
{
this._isCompleted = true;
this._receiver.Dispose();
Application.Current.RootVisual.Dispatcher.BeginInvoke(() =>
{
if (this._asyncCallback != null)
{
this._asyncCallback(this);
}
});
}
}
#endregion
#region Event Handlers
public void HandleLoadCallback(IAsyncResult asyncResult)
{
this._result = this._service.EndLoadUser(asyncResult);
if (!this._result.User.Identity.IsAuthenticated && !this._isCompleted && (this != asyncResult.AsyncState))
{
this._receiver.Listen();
}
else
{
this.Complete();
if (Globals.CurrentUser == null)
{
Globals.CurrentUser = _result.User as User;
Globals.SelectedDate = DateTime.Now;
(App.Current.RootVisual as MainPage).SetTheme(Globals.CurrentUser.CurrentTheme);
HtmlPage.Window.Navigate(new Uri("#UserHome", UriKind.Relative));
}
}
}
private void LocalMessageReceived(object sender, MessageReceivedEventArgs e)
{
this._service.BeginLoadUser(this.HandleLoadCallback, this);
}
#endregion
UPDATE:
OK, I found out that a RIA service call had failed, which resulted in not calling receiver.Listen(). So there wasn't a receiver for the sender to send messages. I'm still working on the failed RIA service call, but that's a different issue. I'll mark this as answered.
Please also add the code for the receiver. That is a very important part of this. If the receiver doesn't exist, for example, then it will fail.

Resources