VMWare VIM SDK. List all VM's working, but list all datasources does not. Am I missing something? - vmware

My goal is to get a listing of all the DataStores in a specific datacenter. I'm able to list all of the Hosts, and VM's, but not the Datastores, and I don't understand why (I'm still learning the API's). Any insight would be appreciated.
Here's the code for grabbing all of the VM's (this works as expected):
public List<VM> getVMsInDatacenter(String datacenter, IEnumerable<String> properties)
{
List<VM> VMs = null;
this.joinConnection((appUtil) =>
{
var svcUtil = appUtil.getServiceUtil();
var dcMoRef = svcUtil.GetDecendentMoRef(null, "Datacenter", datacenter);
var typeinfo = buildTypeInfo("VirtualMachine", properties.ToList());
VMs = buildVMsFromObjectContent(svcUtil.GetContentsRecursively(null, dcMoRef, typeinfo, true));
});
return VMs;
}
Here is the analogous code for the Datastore (which does not work as expected):
public List<DataStore> getDataStoresInDatacenter(String datacenter, IEnumerable<String> properties)
{
List<DataStore> DataStores = null;
this.joinConnection((appUtil) =>
{
var svcUtil = appUtil.getServiceUtil();
var dcMoRef = svcUtil.GetDecendentMoRef(null, "Datacenter", datacenter);
var typeinfo = buildTypeInfo("Datastore", properties.ToList());
DataStores = buildDataStoresFromObjectContent(svcUtil.GetContentsRecursively(null, dcMoRef, typeinfo, true));
});
return DataStores;
}
appUtil is an instantiation of the AppUtil class that came with the VIM SDK samples. It houses functionality for connecting, querying, etc.
joinConnection is a method for connecting, or re-using a connection if we've already connected.
If there are any other questions about the code, please let me know.
Also, if there's a better way, I'd like to know that too :)

Found the problem. The method getContentsRecursively is calling a method called 'buildFullTraversal' that builds a traversal/selection spec. This method was not adding a traversal for the datastore. I added one that like so:
TraversalSpec vmToDs = new TraversalSpec();
vmToDs.name = "vmToDs";
vmToDs.type = "VirtualMachine";
vmToDs.path = "datastore";
HToVm.skip = false;
HToVm.skipSpecified = true;
And then I modified the visitFolders traversal like so:
// Recurse through the folders
TraversalSpec visitFolders = new TraversalSpec();
visitFolders.name = "visitFolders";
visitFolders.type = "Folder";
visitFolders.path = "childEntity";
visitFolders.skip = false;
visitFolders.skipSpecified = true;
visitFolders.selectSet = new SelectionSpec[] { new SelectionSpec(), new SelectionSpec(), new SelectionSpec(), new SelectionSpec(), new SelectionSpec(), new SelectionSpec(), new SelectionSpec(), new SelectionSpec() };
visitFolders.selectSet[0].name = "visitFolders";
visitFolders.selectSet[1].name = "dcToHf";
visitFolders.selectSet[2].name = "dcToVmf";
visitFolders.selectSet[3].name = "crToH";
visitFolders.selectSet[4].name = "crToRp";
visitFolders.selectSet[5].name = "HToVm";
visitFolders.selectSet[6].name = "rpToVm";
visitFolders.selectSet[7].name = "vmToDs";
return new SelectionSpec[] { visitFolders, dcToVmf, dcToHf, crToH, crToRp, rpToRp, HToVm, rpToVm, vmToDs };
Now, calls to getContentsRecursively will also include the datastores that belong to a VM, so the method in the question will works as expected.

Related

Dynamics GP Web Services: Changing policy behavior at runtime

I am creating a payables invoices using Web Services on GP2013. Optionally, my users can provide line item distributions. I can create invoices, but unless I modify the CreatePayablesInvoice policy to "Distributions Will Be Provided" in the dynamics security console, the invoice gets both the system provided distributions as well as the distribution lines I am creating. I want to have the ability to provide distributions if necessary, otherwise I want the system to handle it.
The documentation suggests I should be able to alter the policy in code, but when I get the policy object back from GetPolicyByOperation, the Behaviors array is empty. I have tried creating the behavior manually in code and it doesn't alter what happens when the invoice is created. The only thing that impacts the result is editing the property in the security console.
My code for altering the the policy is below:
payablesInvoiceCreatePolicy = wsDynamicsGP.GetPolicyByOperation("CreatePayablesInvoice", context);
BehaviorKey bk = new BehaviorKey();
bk.Id = new Guid("e476a157-ecf0-4dae-8cef-317dd2cfbe41");
Behavior b = new Behavior();
b.Key = bk;
BehaviorOption opt0 = new BehaviorOption();
opt0.Key = new BehaviorOptionKey();
opt0.Key.Id = 0;
opt0.Name = "Distributions Will Be Provided";
BehaviorOption opt1 = new BehaviorOption();
opt1.Key = new BehaviorOptionKey();
opt1.Key.Id = 1;
opt1.Name = "Automatically Create Distributions";
b.Options = new BehaviorOption[] { opt0, opt1 };
b.SelectedOption = b.Options[1];
payablesInvoiceCreatePolicy.Behaviors = new Behavior[]{b};
wsDynamicsGP.CreatePayablesInvoice(payablesInvoice, context, payablesInvoiceCreatePolicy);
Documentation seems to be sparse on what should or shouldn't work here. I have to assume I should be able to update the policy as I see fit at runtime based on whether or not my user has decided to provide line item distributions.
Does anyone know what I am missing?
Yes. It took me 2 days to fix this myself. After adding the behaviour to the policy object UpdatePolicy before calling the create invoice as below:
wsDynamicsGP.UpdatePolicy(payablesInvoiceCreatePolicy, new RoleKey { Id = "00000000-0000-0000-0000-000000000000" }, context)
wsDynamicsGP.CreatePayablesInvoice(payablesInvoice, context, payablesInvoiceCreatePolicy);
Note that you selected the behavior that automatically creates distribution lines on invoice creation. The behavior's Internal property also must be set to true.
Here is a working example also utilizing FlowerKing's answer:
BehaviorKey bk = new BehaviorKey();
bk.Id = new Guid("e476a157-ecf0-4dae-8cef-317dd2cfbe41");
bk.PolicyKey = payablesInvoiceCreatePolicy.Key;
Behavior b = new Behavior();
b.Key = bk;
b.Internal = true;
BehaviorOption opt0 = new BehaviorOption();
opt0.Key = new BehaviorOptionKey();
opt0.Key.Id = 0;
opt0.Name = "Distributions Will Be Provided";
BehaviorOption opt1 = new BehaviorOption();
opt1.Key = new BehaviorOptionKey();
opt1.Key.Id = 1;
opt1.Name = "Automatically Create Distributions";
b.Options = new BehaviorOption[] { opt0, opt1 };
b.SelectedOption = b.Options[0];
policy.Behaviors = new Behavior[] { b };
client.UpdatePolicy(payablesInvoiceCreatePolicy, new RoleKey { Id = "00000000-0000-0000-0000-000000000000" }, context);
client.CreatePayablesInvoice(payablesInvoice, context, payablesInvoiceCreatePolicy);

Invoking AX web service via C#

I am trying to connect to the AX web services. What I will do it to fetch the right price given a product and a customer.
I realised the right webservice to use is PriceListServiceClient and I am able to log in to it using windows authentication, but I cannot retrieve any data from it.
Here is my code:
PriceListServiceClient priceListServiceClient = new PriceListServiceClient();
priceListServiceClient.ClientCredentials.Windows.ClientCredential.UserName = "yyy";
priceListServiceClient.ClientCredentials.Windows.ClientCredential.Password = "zzz!";
priceListServiceClient.ClientCredentials.Windows.ClientCredential.Domain = "xxx";
CriteriaElement[] criteriaElement = new CriteriaElement[1];
criteriaElement[0] = new CriteriaElement();
criteriaElement[0].DataSourceName = "SalesPrice";
criteriaElement[0].FieldName = "ItemId";
criteriaElement[0].Operator = Operator.NotEqual;
criteriaElement[0].Value1 = "5637153175";
QueryCriteria queryCriteria = new QueryCriteria();
queryCriteria.CriteriaElement = criteriaElement;
CallContext callContext = new CallContext();
var found = priceListServiceClient.find(callContext, queryCriteria);
Console.WriteLine(found.Currency);
priceListServiceClient.Close();
Any idea about why this is happening?
Try filling in the properties in the CallContext (company and language).
new CallContext { Company = "zzz", Language = "nl" };
I found the answer here: http://community.dynamics.com/ax/f/33/p/118741/246784.aspx
The Ax class for Price List document is AxPriceDiscTmpPrintout Class. This class wraps the TmpPriceDiscPrintout table, which is a TMP table. That's why you are not getting anything in return.

Windows Phone 7 Consuming Webservice WSDL

Ok I have written some basic generic webservices before but I have never tried to consume a 3rd party one.
The one I am trying to consume is
http://opendap.co-ops.nos.noaa.gov/axis/webservices/predictions/wsdl/Predictions.wsdl
I am not getting any results back from this what so ever and cannot figure out why.
More odd is it is not even reaching PredictionsClient_getPredictionsAndMetadataCompleted when I put a break point in the code it doesn't even reach it.
Any suggestions would be greatly appreciated
public void Bouy(double meters)
{
PredictionService.Parameters PredictionParams = new PredictionService.Parameters();
PredictionService.PredictionsPortTypeClient PredictionsClient = new PredictionService.PredictionsPortTypeClient();
GeoCoordinateWatcher gc = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
//gc.Position.Location.Latitude, gc.Position.Location.Longitude
GeoCoordinate myLocation = new GeoCoordinate(27.931631,-82.802582);
foreach (var bl in BouyLocation.GetAll())
{
GeoCoordinate otherLocation = new GeoCoordinate(bl.Lat, bl.Lon);
PredictionParams.beginDate = DateTime.Now.ToString("yyyyMMdd");
PredictionParams.endDate = DateTime.Now.AddDays(1.0).ToString("yyyyMMdd");
PredictionParams.stationId = bl.LocationID;
PredictionParams.timeZone = 0;
PredictionParams.unit = 1;
PredictionParams.dataInterval = 6;
PredictionsClient.getPredictionsAndMetadataCompleted += new EventHandler<PredictionService.getPredictionsAndMetadataCompletedEventArgs>(PredictionsClient_getPredictionsAndMetadataCompleted);
PredictionsClient.getPredictionsAndMetadataAsync(PredictionParams);
double mymeters = myLocation.GetDistanceTo(otherLocation);
if (mymeters < meters)
{
TextBlock DynTextBlock = new TextBlock
{
Name = "Appearance" + bl.LocationID,
Text = bl.LocationName + PredictionResult,
TextWrapping = System.Windows.TextWrapping.Wrap,
Margin = new Thickness(12, -6, 12, 0),
Style = (Style)Resources["PhoneTextSubtleStyle"]
};
DynamicAppearance.Children.Add(DynTextBlock);
this.nearByLocations.Add(new BouyLocationModel() { LocationName = bl.LocationName, LocationID = bl.LocationID, Lat = bl.Lat, Lon = bl.Lon });
}
}
var test = nearByLocations;
}
void PredictionsClient_getPredictionsAndMetadataCompleted(object sender, PredictionService.getPredictionsAndMetadataCompletedEventArgs e)
{
string err = e.Error.ToString();
PredictionResult = e.Result.ToString();
}
Loooking at the code you have here I think that you have used the importing of a ServiceReference to auto build the classes for you?
Unfortunately I have found that this is rather temperamental on WP7 and the only way I actually got it to work was when I connected it to a Microsoft WCF service. Connecting to anything else just doesn't work.
If you do google searches there are various pages talking about the fact it doesn't work and ways around it (which I couldn't get to work).
However, there are ways around it but it isn't as simple as the auto-generated stuff. Basically you do things manually.
Although there are other ways to manually create the web service what I did was follow the information in the following which worked well: http://zetitle.wordpress.com/2010/10/14/using-reactive-extensions-with-webrequest/
You will need to parse the response yourself but XML to LINQ works really well for this.
Hope that helps, or maybe someone will have the solution as it is something I am interested in knowing how to get working too

Subsonic 3 Save() then Update()?

I need to get the primary key for a row and then insert it into one of the other columns in a string.
So I've tried to do it something like this:
newsObj = new news();
newsObj.name = "test"
newsObj.Save();
newsObj.url = String.Format("blah.aspx?p={0}",newsObj.col_id);
newsObj.Save();
But it doesn't treat it as the same data object so newsObj.col_id always comes back as a zero. Is there another way of doing this? I tried this on another page and to get it to work I had to set newsObj.SetIsLoaded(true);
This is the actual block of code:
page p;
if (pageId > 0)
p = new page(ps => ps.page_id == pageId);
else
p = new page();
if (publish)
p.page_published = 1;
if (User.IsInRole("administrator"))
p.page_approved = 1;
p.page_section = staticParent.page_section;
p.page_name = PageName.Text;
p.page_parent = parentPageId;
p.page_last_modified_date = DateTime.Now;
p.page_last_modified_by = (Guid)Membership.GetUser().ProviderUserKey;
p.Add();
string urlString = String.Empty;
if (parentPageId > 0)
{
urlString = Regex.Replace(staticParent.page_url, "(.aspx).*$", "$1"); // We just want the static page URL (blah.aspx)
p.page_url = String.Format("{0}?p={1}", urlString, p.page_id);
}
p.Save();
If I hover the p.Save(); I can see the correct values in the object but the DB is never updated and there is no exception.
Thanks!
I faced the same problem with that :
po oPo = new po();
oPo.name ="test";
oPo.save(); //till now it works.
oPo.name = "test2";
oPo.save(); //not really working, it's not saving the data since isLoaded is set to false
and the columns are not considered dirty.
it's a bug in the ActiveRecord.tt for version 3.0.0.3.
In the method public void Add(IDataProvider provider)
immediately after SetIsNew(false);
there should be : SetIsLoaded(true);
the reason why the save is not working the second time is because the object can't get dirty if it is not loaded. By adding the SetIsLoaded(true) in the ActiveRecord.tt, when you are going to do run custom tool, it's gonna regenerate the .cs perfectly.

Virtual Server IIS WMI Problem

I have been tasked with finding out what is causing an issue with this bit of code:
public static ArrayList GetEthernetMacAddresses()
{
ArrayList addresses = new ArrayList();
ManagementClass mc = new ManagementClass("Win32_NetworkAdapter");
// This causes GetInstances(options)
// to return all subclasses of Win32_NetworkAdapter
EnumerationOptions options = new EnumerationOptions();
options.EnumerateDeep = true;
foreach (ManagementObject mo in mc.GetInstances(options)) {
string macAddr = mo["MACAddress"] as string;
string adapterType = mo["AdapterType"] as string;
if (!StringUtil.IsBlank(macAddr) && !StringUtil.IsBlank(adapterType))
{
if (adapterType.StartsWith("Ethernet")) {
addresses.Add(macAddr);
}
}
}
return addresses;
}
On our (Win2003) virtual servers, this works when run as part of a console application but not from a web service running on IIS (on that same machine).
Alternatively, I can use this code in a web service on IIS (on the virtual server) and get the correct return values:
public static string GetMacAddresses()
{
ManagementClass mgmt = new ManagementClass(
"Win32_NetworkAdapterConfiguration"
);
ManagementObjectCollection objCol = mgmt.GetInstances();
foreach (ManagementObject obj in objCol)
{
if ((bool)obj["IPEnabled"])
{
if (sb.Length > 0)
{
sb.Append(";");
}
sb.Append(obj["MacAddress"].ToString());
}
obj.Dispose();
}
}
Why does the second one work and not the first one?
Why only when called through an IIS web service on a virtual machine?
Any help would be appreciated.
UPDATE: After much telephone time with all different levels of MS Support, the've come to the conclusion that this is "As Designed".
Since it is on a driver level for the virtual network adapter driver, the answer was that we should change our code "to work around the issue".
This means that you cannot reliable test code on virtual servers unless you with the same code that you use on physical servers, since we can't guarantee that the servers are exact replicas...
Okay, so I wrote this code to test the issue:
public void GetWin32_NetworkAdapter()
{
DataTable dt = new DataTable();
dt.Columns.Add("AdapterName", typeof(string));
dt.Columns.Add("ServiceName", typeof(string));
dt.Columns.Add("AdapterType", typeof(string));
dt.Columns.Add("IPEnabled", typeof(bool));
dt.Columns.Add("MacAddress", typeof(string));
//Try getting it by Win32_NetworkAdapterConfiguration
ManagementClass mgmt = new ManagementClass("Win32_NetworkAdapter");
EnumerationOptions options = new EnumerationOptions();
options.EnumerateDeep = true;
ManagementObjectCollection objCol = mgmt.GetInstances(options);
foreach (ManagementObject obj in objCol)
{
DataRow dr = dt.NewRow();
dr["AdapterName"] = obj["Caption"].ToString();
dr["ServiceName"] = obj["ServiceName"].ToString();
dr["AdapterType"] = obj["AdapterType"];
dr["IPEnabled"] = (bool)obj["IPEnabled"];
if (obj["MacAddress"] != null)
{
dr["MacAddress"] = obj["MacAddress"].ToString();
}
else
{
dr["MacAddress"] = "none";
}
dt.Rows.Add(dr);
}
gvConfig.DataSource = dt;
gvConfig.DataBind();
}
When it's run on a physical IIS box I get this:
Physical IIS server http://img14.imageshack.us/img14/8098/physicaloutput.gif
Same code on Virtual IIS server:
Virtual server http://img25.imageshack.us/img25/4391/virtualoutput.gif
See a difference? It's on the first line. The virtual server doesn't return the "AdapterType" string. Which is why the original code was failing.
This brings up an interesting thought. If Virtual Server is supposed to be an "virtual" representation of a real IIS server, why doesn't it return the same values?
Why are the two returning different results? It's possible that due to the different user accounts, you'll get different results running from the console and from a service.
Why does (1) fail and (2) work? Is it possible that a null result for adapterType return a null value? If so, would the code handle this condition?