Best method for initializling the Okuma API if I want a program that works for both lathe and mills? - api

I am writing a program that will run on both lathe and machining centers. How best can I initialize the API without doing during loading. Should I call a class for each machine type or can I call each (and close them) within the same class?
Added example of current method for just Lathe...
using Okuma.CLDATAPI.DataAPI;
using Okuma.CLDATAPI.Enumerations;
using Okuma.CLDATAPI.Structures;
using Okuma.CLDATAPI.DataAPI.MacMan;
public class LatheDutyOnline
{
private CMachine Objl;
private CVariables Objlv;
private CIO IO;
private CATC ObjAtc;
private CAxis objaxis;
private CBallScrew objBS;
private CProgram objProgram;
private CSpec objSpec;
private CSpindle objSpindle;
private void Form1_Load(System.Object sender, System.EventArgs e)
{
Objl = new CMachine();
Objl.Init();
Objlv = new CVariables();
IO = new CIO();
ObjAtc = new CATC();
objaxis = new CAxis();
objBS = new CBallScrew();
objProgram = new CProgram();
objSpec = new CSpec();
objSpindle = new CSpindle();
}

You need a routine to check the current machine type. Something like this:
Private Sub CheckMachineType()
If System.IO.File.Exists("C:\OSP-P\SHAREDDLL\LDATAPI.DLL") And System.IO.File.Exists("C:\OSP-P\VOLANTE\CRAD\LCMDAPI.EXE") Then
MachineType = Lathe
ElseIf System.IO.File.Exists("C:\OSP-P\SHAREDDLL\MDATAPI.DLL") And System.IO.File.Exists("C:\OSP-P\VOLANTE\CRAD\MCMDAPI.EXE") Then
MachineType = MachiningCenter
Else
MachineType = NonOSP
End If
End Sub
Then you can initialize the correct API type based on the value of MachineType.
UPDATE
We now have a standard machine agnostic library that is perfect for this.
Please have a look at the sample program for SCOUT.
https://github.com/OkumaAmerica/Open-API-SDK/tree/master/Scout

Take a look at c# intro to Interfaces and this video using .Net interfaces for machine neutral applications. Using interfaces allows you to program against the interface instead of directly against the API.

Related

signUpUrl returning nullpointerexception

SignupUrl signupUrl = androidManagementClient
.signupUrls()
.create()
.setProjectId(CLOUD_PROJECT_ID)
.setCallbackUrl(CALLBACKURL).execute();
causes the app to crash due to NPE
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.api.services.androidmanagement.v1.AndroidManagement$SignupUrls com.google.api.services.androidmanagement.v1.AndroidManagement.signupUrls()' on a null object reference
Has anyone seen this before? I've followed all the prerequisites to developing and am currently going of off the sample app, and this is the piece of code that crashes. What could be the reason?
https://developers.google.com/android/management/sample-app
Update as per request:
Code
EnterpriseHelperClass - I'd like to do this programmatically even though I know this can easily be executed via the quickstart guide.
public class EnterpriseCreationHelper {
private static final String CALLBACKURL =
"https://play.google.com/work/adminsignup?enterpriseToken";
private static final String TAG = "MainActivity";
private static String CLOUD_PROJECT_ID = "******-";
private static String SERVICE_ACCOUNT = "****#****-.iam.gserviceaccount.com";
private static String CREDENTIALS_FILE =
"/Users/****/appname/src/******.json";
private static String POLICY_ID = "samplePolicy";
private static AndroidManagement androidManagementClient;
public EnterpriseCreationHelper(AndroidManagement androidManagementClient){
EnterpriseCreationHelper.androidManagementClient = androidManagementClient;
}
public void run() throws IOException {
Your androidManagementClient value is null.
Kindly share the initialisation method of androidManagementClient it will be helpful for us to answer
Thanks
Looks like getAndroidManagementClient is returning a null object, which results in setting androidManagementClient to null. Make sure your credentials are correct, and that this method returns successfully.

javaparser Symbol solver: I can resolve inherited classes of a class but cannot resolve anything else

I have setup the JavaSymbolSolver like below:
Instance Variables:
private CombinedTypeSolver combinedTypeSolver = new CombinedTypeSolver();
private JavaSymbolSolver symbolSolver;
private ParserConfiguration parserConfiguration = new
ParserConfiguration();
private JavaParser parser;
private CompilationUnit compilationUnit = null;
private ParseResult<CompilationUnit> parseResultcompilationUnit = null;
from constructor:
this.combinedTypeSolver.add(new ReflectionTypeSolver());
this.combinedTypeSolver.add((new JavaParserTypeSolver("C:\\Users\\nfountou\\git\\TestingJavaParser\\rsc")));
this.combinedTypeSolver.add((new JavaParserTypeSolver("C:\\Users\\nfountou\\git\\TestingJavaParser")));
this.symbolSolver = new JavaSymbolSolver(this.combinedTypeSolver);
this.parserConfiguration.setSymbolResolver(this.symbolSolver);
this.parser = new JavaParser(parserConfiguration);
FileInputStream in = new FileInputStream(filepath);
this.parseResultcompilationUnit = this.parser.parse(in);
this.compilationUnit = parseResultcompilationUnit.getResult().get();
The test code seems to work fine and I am being able to resolve e.g. class B
of class A as can be seen below:
public class A extends B{
}
the problem is that it seems that I cannot resolve anything else and whatever I tried I receive the message below:
Exception in thread "main" java.lang.IllegalStateException: No data of this type found. Use containsData to check for this first.
For example the source code that I am running for resolving e.g an AssignExpr:
ResolvedType declaringType = ((AssignExpr) value).calculateResolvedType();
(where value is an object that holds an AssignExpr node)
Resolving a superclass works fine and returns the right values:
ResolvedClassDeclaration declaringType = ((ClassOrInterfaceType) value).resolve().getTypeDeclaration().asClass();
Any ideas what am I doing wrong?
I found what was the issue... Source code is fine and it passes the configuration to the parser in the right way. The problem was that as I was refactoring code, I created a class and named it "SymbolSolver" which was causing the problem as javaparser uses a class with that specific name...
Also another problem was that I was using wrapppedNode Nodes which do not hold the configuration from symbolsolver.

FakeItEasy VB.NET issues with parameters

Ok, I am trying to teach myself testing using a mock framework and I work in VB.NET, I am new to lambda expressions and all my previous applications were written in version 2005 or earlier. I now have 2010.
So I have tried Rhino.Mocks but found it difficult to get my head around it mostly because of the older syntax. Since, no-one seems to be bloggin in VB.NET these days, I have been looking at C# examples and trying to figure out what is going on.
So I have a situation where I pass an interface to the constructor of a class and hold a refrence to that interface. When an method is called on the object and event is raise that should be handled by the class that implements the inteface.
I was having trouble, so I tried to create a simple version in C# and repeat the steps in vb.net.
So my interface:
public interface IBroadcastClient
{
void MessageReceivedHandler(string msg);
}
The class that raises the events:
public class Broadcaster
{
public Broadcaster(IBroadcastClient c)
{
_client= c;
this.SendMessage += new MessageReceived(_client.MessageReceivedHandler);
}
private IBroadcastClient _client;
public event MessageReceived SendMessage;
public void SendMessageNow()
{
string _Message;
if (SendMessage != null)
{
_Message = #"Yay!";
SendMessage(_Message);
}
}
}
The test:
[TestMethod]
public void TestSendMessageWithIgnoreParameter()
{
//string msg = #"Yay!";
var client = A.Fake<IBroadcastClient>();
Broadcaster b = new Broadcaster(client);
b.SendMessageNow();
A.CallTo(() => client.MessageReceivedHandler(A<string>.Ignored)).MustHaveHappened();
}
This passes, no problems so far.
Now to try the same this in vb.net;
The same interface and broadcaster class, just in vb.net rather than C# with initially hte following unit test.
<TestMethod()>
Public Sub TestMethod1()
Dim client = A.Fake(Of IBroadcastClient)()
Dim b As New Broadcaster(client)
b.SendMessageNow()
NextCall.To(client).MustHaveHappened()
client.MessageReceivedHandler(A(Of String).Ignored)
End Sub
This fails with the following error message;
" Assertion failed for the following call:
TestFakeItEasyVB.IBroadcastClient.MessageReceivedHandler(msg: )
Expected to find it at least once but found it #0 times among the calls:
1: TestFakeItEasyVB.IBroadcastClient.MessageReceivedHandler(msg: "Yay!")"
Funnily enough writing it this way;
<TestMethod()>
Public Sub TestMethod3()
Dim client = A.Fake(Of IBroadcastClient)()
Dim b As New Broadcaster(client)
b.SendMessageNow()
A.CallTo(Sub() client.MessageReceivedHandler(A(Of String).Ignored)).MustNotHaveHappened()
End Sub
Will also fail with the same error message, however, this version of the test passes.
<TestMethod()>
Public Sub TestMethod2()
Dim client = A.Fake(Of IBroadcastClient)()
Dim b As New Broadcaster(client)
b.SendMessageNow()
NextCall.To(client).MustHaveHappened()
client.MessageReceivedHandler("Yay!")
End Sub
This variation also passes in C#, my quandry is what am I doing wrong to get the test to ignore the argument passed to the faked event handler?
The NextCall-syntax is there for legacy reasons, it's better to use the expression syntax:
A.CallTo(Sub() client.MessageReceivedHandler(A(Of String).Ignored)).MustNotHaveHappened()
In your tests above all others has MustHaveHappened, but this specific one has MustNotHaveHappened, I guess that's why your test is failing. I've compiled your code and run it and once it's changed to MustHaveHappened the test passes.
Currently you can not use argument constraints in the VB-specific "NextCall"-syntax. However you can use the method "WhenArgumentsMatch" to rewrite your first test like this:
<TestMethod()>
Public Sub TestMethod1()
Dim client = A.Fake(Of IBroadcastClient)()
Dim b As New Broadcaster(client)
b.SendMessageNow()
NextCall.To(client).WhenArgumentsMatch(Function(a) a.Get(Of String)(0) = "Yay!").MustHaveHappened()
client.MessageReceivedHandler(Nothing)
End Sub
Or you could use the extension "WithAnyArguments" to ignore all arguments:
<TestMethod()>
Public Sub TestMethod1()
Dim client = A.Fake(Of IBroadcastClient)()
Dim b As New Broadcaster(client)
b.SendMessageNow()
NextCall.To(client).WithAnyArguments().MustHaveHappened()
client.MessageReceivedHandler(Nothing)
End Sub

WCF List<> received as [] in client, how to work with []

I present a List from WCF and client receives DocTypes[]. No prob there.
current situation is where client my only accept 1,2 out of 100 DocTypes. What is best way to condense the [100 ] to only 2?
I have this code for marking what user checked off of grid.
foreach (GridViewRow rowItem in gvDocTypes.Rows)
{
chk = (CheckBox)(rowItem.Cells[0].FindControl("chk1"));
if (chk.Checked)
DFO[y].Process = true;
y++;
}
This is the schema for the data collection:
[System.NonSerializedAttribute()]
private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
private int DocTypeGroupField;
private System.Guid DocTypeIDField;
private string DocTypeNameField;
private int DocTypeNumberField;
private string ErrorMsgField;
private bool ProcessField;
Best practice I think is to name a clone of this object and add as needed in my iteration through the grid. I just can't get my starting point in a new array?
Have tried this:
Service.DocTypes dfo = new Service.DocTypes() ;
Service.DocTypes[] DFO = (Service.DocTypes[])Session["oDocTypes"];
Service.DocTypes[] oDFO = DFO.Clone();
What am I missing?
TIA
Stephen
If you use Add service reference to create service proxy for you, you can define what type of collection should be generated. Default is System.Array but you can choose System.Collections.Generic.List.
Best regards, Ladislav
In Visual Studio, right-click the added reference under Service References, then choose "Configure Service Reference". Change "Collection Type" from "System.Array" to "System.Collections.Generic.List" and you'll then be able to treat them as lists from the client.

how to save/restore a form and controls between program runs?

I have a complex form to allow the user to configure my app.
What's the best way to save the form state & reload when the program next runs.
I mean text he has entered in list boxes, the selected item of combo/list/radio, whether a checkbox is cheeked, etc
Lots of people here telling me when to save, but not many telling me how ...
In the end I went with WritePrivateProfileString()
You have a few options of where to save the entered settings - in a configuration file, or in the registry, maybe a database (maybe even "the cloud", but i won't go there).
You should have the user carry out a specific action (such as clicking an Apply button) before you save the settings - you shouldn't just save the settings when the user closes the form, as that is ultimately not good UX.
How you persist the settings is totally up to you - you can save them into a straight name/value pair style config file, you may want to use XML in the config file, or you save them as keys and values in a known spot in the registry (or you could save name/value pairs into a database table).
When your application is next run, one of the start up tasks can be to check the known location (whether it be the registry or a config file) for the settings, and then load them into a settings class. Make sure that you have logical default values for each setting in case it has either never been set, or for some reason you cannot read it back in. The settings class can then either be passed in to each form for it to apply whatever settings are relevant, or it could be a static class (globally visible single instance class) so that it can just be read from anywhere in the application.
Edit: after reading your comment to another answer, here is another option, slightly more advanced. Use the settings class i mentioned earlier, but also use binding - you can bind your settings object directly to your form, so any values entered will be updated directly into the settings object without you having to write code to do it (provided you use two way binding). The "streaming" can be achieved by serializing the settings object to a file (or a database), i suggest you look at the XmlSerializer.
Serialize the Form.
Implement ISerializable, and in serializable constructor and GetObject() method load/save your fields.
In OnClosing serialize the form.
///
/// try to obtain the las serialized main form with old data
MainForm mainForm = DeserializeMainForm("mainForm.data");
///
/// if any old data found, create a new(empty) main form
if (mainForm == null) mainForm = new MainForm();
static MainForm DeserializeMainForm(string filePath)
{
MainForm mf = null;
FileStream fileStream = null;
try
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
fileStream = new FileStream(filePath, FileMode.Open);
mf = (MainForm)binaryFormatter.Deserialize(fileStream);
}
catch { }
finally
{
if (fileStream != null)
{
fileStream.Close();
}
}
return mf;
}
MainForm:
[Serializable]
public partial class MainForm : Form, ISerializable
{
protected MainForm(SerializationInfo info, StreamingContext context)
: this()
{
if (info == null)
throw new System.ArgumentNullException("info");
this.tbxServerIp.Text = info.GetString("server ip");
this.tbxServerPort.Text = info.GetString("server port");
this.tbxEventFilter.Text = info.GetString("event filter");
this.tbxWallId.Text = info.GetString("wallId");
foreach (Control control in this.Controls)
{
if (control is EventSender)
{
EventSender eventSender = (control as EventSender);
eventSender.LoadFromSerializationInfo(info);
}
}
}
private void SerializeThis()
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
FileStream fileStream = new FileStream("mainForm.data", FileMode.Create);
try
{
binaryFormatter.Serialize(fileStream, this);
}
catch
{
throw;
}
finally
{
fileStream.Close();
}
}
protected override void OnClosing(CancelEventArgs e)
{
SerializeThis();
base.OnClosing(e);
}
}
Private Sub frm_Closing (sender as Object, e as CancelEventArgs) Handles MyBase.Closing
' save all the values you want'
End Sub
Private Sub frm_Load(sender as Object, e as EventArgs) Handles MyBase.Load
If SaveSettingsExist Then
' restore all the values you want'
End If
End Sub
I actually have a couple of generic routines I use like this for saving the form size/position and ListView column settings. So I have something like...
Private Sub frm_Closing (sender as Object, e as CancelEventArgs) Handles MyBase.Closing
SaveFormPos(Me)
SaveListview(Me, lvuInvoices)
End Sub
Private Sub frm_Load(sender as Object, e as EventArgs) Handles MyBase.Load
RestoreFormPos(Me)
RestoreListview(Me, lvuInvoices)
End Sub
The Me parameter (for the Listview routine) is used to create a key for the values to be saved to the registry. You have all sorts of options in front of you. You could put this functionality into a base class for all your Forms, create a SaveState class, or simply stick routines into a Module. You could save this data to the registry, a database, text files. You could have a generic routine that trawls through the Controls collection looking for TextBoxes, Checkboxes etc.
However, once you've created a useful set of save routines, you can then employ them on any subsequent form you want, so you only need to do the hard work once.
I also agree on having a LoadSettings/SaveSettings set of functions that are called when creating the form/ when closing the application.
As a store location for the application's settings I recommend using the Isolated Storage.
As an addition, depending on the controls you are using on your form, you could have the options of saving their status in XML format format and then restoring it next time.
For example Infragistics controls offer this possibility(e.g UltraDockManager, UltraToolbarManager have a SaveAsXml/LoadFromXml pair of functions).
You can somehow save everything in a hidden textbox in a hidden form.
When the user clicks the apply button, open the text file automatically and make the program read it line by line.
Example:
Line 1 could be the location of an image
Line 2 could be the text for a textbox
Line 3 could be a word or number that the program uses to determine if a
checkbox is true or false