Search in agresso Query Engine - web-services

Is it possible to search/filter on columns with Agresso's QueryEngineService? I've been playing around with SearchCriteria.SearchCriteriaPropertiesList and TemplateResultOptions.Filter but without any luck. I havn't been able to locate any documentation on this matter either.
QueryEngineService.TemplateList templateList = QueryEngineService.GetTemplateList(null, null, Credentials);
var template = templateList.TemplateHeaderList.FirstOrDefault(x => x.Name == strViewName);
if (template == null)
return null;
QueryEngineService.SearchCriteria searchProp = QueryEngineService.GetSearchCriteria(template.TemplateId, false, Credentials);
QueryEngineService.TemplateResultOptions options = QueryEngineService.GetTemplateResultOptions(Credentials);
options.RemoveHiddenColumns = true;
QueryEngineService.InputForTemplateResult input = new QueryEngineService.InputForTemplateResult();
input.TemplateResultOptions = options;
input.TemplateId = template.TemplateId;
input.SearchCriteriaPropertiesList = searchProp.SearchCriteriaPropertiesList;
QueryEngineService.TemplateResultAsDataSet result = QueryEngineService.GetTemplateResultAsDataSet(input, Credentials);
return result.TemplateResult;

You can try to start with this:
List<SearchCriteriaProperties> searchCriteriaProperties = searchCriteria.getSearchCriteriaPropertiesList().getSearchCriteriaProperties();
SearchCriteriaProperties columnFilter = null;
for (SearchCriteriaProperties criteria : searchCriteriaProperties) {
if(criteria.getColumnName().equalsIgnoreCase("ColumnNameHere")) {
columnFilter = criteria;
columnFilter.setRestrictionType("=");
columnFilter.setFromValue("valueToAssign");
}
}
Next is add the columnFilter variable to an instance of the ArrayOfSearchCriteriaProperties() object by using the getSearchCriteriaProperties().add()
ArrayOfSearchCriteriaProperties filter = new ArrayOfSearchCriteriaProperties();
filter.getSearchCriteriaProperties().add(columnFilter);
You can now add the filter object to an instance of the InputForTemplateResult() object.

Working solution (for me)
QueryEngineService.SearchCriteria searchProp = QueryEngineService.GetSearchCriteria(template.TemplateId, false, Credentials);
foreach (QueryEngineService.SearchCriteriaProperties criteria in searchProp.SearchCriteriaPropertiesList)
{
if(criteria.ColumnName.Equals("column_name", StringComparison.OrdinalIgnoreCase))
{
criteria.RestrictionType = "=";
criteria.FromValue = "value";
}
}
//Rest of the code from question above

Related

SPAlert.Filter not working

Can anybody help with SPAlert filters on Sharepoint 2013?
If I set Filter property on SPAlert instance the alert has not been sent
SPAlert newAlert = user.Alerts.Add();
SPAlertTemplateCollection alertTemplates = new SPAlertTemplateCollection(
(SPWebService)(SPContext.Current.Site.WebApplication.Parent));
newAlert.AlertType = SPAlertType.List;
newAlert.List = list;
newAlert.Title = alertTitle;
newAlert.DeliveryChannels = SPAlertDeliveryChannels.Email;
newAlert.EventType = eventType;
newAlert.AlertFrequency = SPAlertFrequency.Immediate;
newAlert.AlertTemplate = alertTemplates[Constants.AlertTemplates.GenericListCustom];
var wsm = new WorkflowServicesManager(web);
var wss = wsm.GetWorkflowSubscriptionService();
var subscriptions = wss.EnumerateSubscriptionsByList(list.ID);
bool assotiationExist = false;
var guid = Constants.Workflows.ApprovalWF.Guid;
foreach (var subs in subscriptions)
{
assotiationExist = subs.DefinitionId == guid;
if (assotiationExist)
{
newAlert.Filter = "<Query><Eq><FieldRef Name=\"ApprovalStatus\"/><Value type=\"string\">Approved</Value></Eq></Query>";
}
}
newAlert.Update(false);
If I set Filter property on SPAlert instance the alert has not been sent
What do you need exactly ?
If you just want to change the filter (alert condition), did you simply try :
newAlert.AlertType = SPAlertType.List;
newAlert.List = list;
newAlert.Title = alertTitle;
newAlert.DeliveryChannels = SPAlertDeliveryChannels.Email;
newAlert.EventType = eventType;
newAlert.AlertFrequency = SPAlertFrequency.Immediate;
newAlert.AlertTemplate = alertTemplates[Constants.AlertTemplates.GenericListCustom];
newAlert.Filter = "<Query><Eq><FieldRef Name=\"ApprovalStatus/New\"/><Value type=\"string\">Approved</Value></Eq></Query>";
newAlert.Update(false);
I have just added a /New in your filter query. Query filter in alert need to get a /New or a /Old in your field.
If your alert still doesn't work, it might be something else than the filter.
The problem was in line newAlert.EventType = eventType. eventType was SPEventType.Add. That was the reason of not sending alert after Workflow set the ApprovalStatus field to «Approved».
I’ve modified algourithm. Now eventType is SPEventType.Modify and I added new field "IsNewAlertSent" to list. When event fires the first time then I send email and set the "IsNewAlertSent" field
Final code is shown below.
class UserAlertManager:
..
newAlert.EventType = (eventType == SPEventType.Add? SPEventType.Modify: eventType);
newAlert.AlertFrequency = SPAlertFrequency.Immediate;
newAlert.AlertTemplate = alertTemplates[Constants.AlertTemplates.GenericListCustom];
..
if (assotiationExist)
{
newAlert.Filter = "<Query><Eq><FieldRef name=\"ApprovalStatus\"/><Value type=\"Text\">Approved</Value></Eq></Query>";
newAlert.Properties.Add("grcustomalert", "1");
}
..
newAlert.Update(false);
class GRCustomAlertHandler:
...
string subject = string.Empty;
string body = string.Empty;
bool grCustomAlert = Utils.IsSPAlertCustom(ahp.a);
if (ahp.eventData[0].eventType == (int)SPEventType.Modify && grCustomAlert)
{
SPListItem item = list.GetItemById(ahp.eventData[0].itemId);
var isNewAlertSentField = item.Fields.GetFieldByInternalName(Constants.Fields.IsNewAlertSent);
if (isNewAlertSentField != null && (item[Constants.Fields.IsNewAlertSent] == null || !(bool)item[Constants.Fields.IsNewAlertSent]))
{
...
Utils.SendMail(web, new List<string> { ahp.headers["to"].ToString() }, subject, body);
item[Constants.Fields.IsNewAlertSent] = true;
using (new DisabledItemEventScope())
{
item.SystemUpdate(false);
}
}
}
...

Updating Location and ShipQty in Acumatica Shipment Lines

I'm having this weird problem in acumatica webservices, I'm updating existing Shipments in acumatica using webservices. My code is supposed to update the Location and ShippedQty but for no reason it updates all the items except the last one. It happens when the Shipment has multiple items. Please help me solve this problem, below is my code and an image of the Shipment screen with the last item not updated.
Thanks.
var commands = new List<Acumatica_LSOne_Integration.SO302000.Command>();
commands.Add(new SO302000.Value { Value = shipmentNbr, LinkedCommand = shipmentSchema.ShipmentSummary.ShipmentNbr });
commands.Add(new SO302000.Value { Value = shipmentType, LinkedCommand = shipmentSchema.ShipmentSummary.Type });
commands.Add(shipmentSchema.DocumentDetails.ShipmentNbr);
commands.Add(shipmentSchema.DocumentDetails.LineNbr);
commands.Add(shipmentSchema.DocumentDetails.InventoryID);
commands.Add(shipmentSchema.DocumentDetails.Warehouse);
commands.Add(shipmentSchema.DocumentDetails.Location);
commands.Add(shipmentSchema.DocumentDetails.OrderedQty);
var soLines = context.Submit(commands.ToArray());
List<Acumatica_LSOne_Integration.SO302000.Command> commandList = new List<Acumatica_LSOne_Integration.SO302000.Command>();
for (int index = 0; index < soLines.Length; index++)
{
string sShipNbr = soLines[index].DocumentDetails.ShipmentNbr.Value;
string sLineNbr = soLines[index].DocumentDetails.LineNbr.Value;
string sInventoryID = soLines[index].DocumentDetails.InventoryID.Value;
string sWarehouse = soLines[index].DocumentDetails.Warehouse.Value;
string sLocation = soLines[index].DocumentDetails.Location.Value;
string sOrderedQty = soLines[index].DocumentDetails.OrderedQty.Value;
commandList.Add(new SO302000.Key
{
ObjectName = shipmentSchema.DocumentDetails.ShipmentNbr.ObjectName,
FieldName = shipmentSchema.DocumentDetails.ShipmentNbr.FieldName,
Value = sShipNbr.Trim(), Commit = true
});
commandList.Add(new SO302000.Key
{
ObjectName = shipmentSchema.DocumentDetails.LineNbr.ObjectName,
FieldName = shipmentSchema.DocumentDetails.LineNbr.FieldName,
Value = sLineNbr.Trim(), Commit = true
});
commandList.Add(new SO302000.Value
{
Value = vLocation.Trim(),
LinkedCommand = shipmentSchema.DocumentDetails.Location
});
commandList.Add(new SO302000.Value { Value = sOrderedQty, LinkedCommand = shipmentSchema.DocumentDetails.ShippedQty,IgnoreError = true, Commit = true });
}
commandList.Add(shipmentSchema.Actions.ConfirmShipmentAction);
context.Submit(commandList.ToArray());
Sample Output:
I guessed that you have allowed negative quantity on your inventory, by default when an item has zero quantity on a particular warehouse the location will set as and a shipped quantity of zero and as I've seen you're code, check this line code
string sLocation = soLines[index].DocumentDetails.Location.Value;
if this soLine retreives a value as I guess this line is the cause why it won't update.
I've actually come up with a solution that works well using the Contract Based Web Services. Below is my sample code:
using (DefaultSoapClient soapClient = new DefaultSoapClient())
{
InitializeWebService(soapClient,sAUser,sAPass,vCompany,vBranchID);
Shipment shipmentToBeFound = new Shipment
{
Type = new StringSearch { Value = shipmentType },
ShipmentNbr = new StringSearch { Value = shipmentNbr },
};
Shipment shipment = (Shipment)soapClient.Get(shipmentToBeFound);
int iLineNbr = Int32.Parse(sLineNbr);
ShipmentDetail shipmentLine = shipment.Details.Single(
orderLineToBeUpdated =>
orderLineToBeUpdated.LineNbr.Value == iLineNbr);
shipmentLine.LocationID = new StringValue { Value = vLocation.Trim() };
shipmentLine.ShippedQty = new DecimalValue { Value = decimal.Parse(sOrderedQty) };
shipment = (Shipment)soapClient.Put(shipment);
soapClient.Logout();
}

How to unit test unformatted method in mvc?

I have to unit test one of the very big and unformatted method in ASP.NET MVC 4.0.
Below is the code of action method :-
public ActionResult GetDetails(string ProdName, int ProdArea, int ProdAreaId= 0)
{
if (ProdAreaId == 0 && ProdArea == 1 && System.Web.HttpContext.Current.Session["ResponseProdAreaId"] != null)
{
ProdAreaId = (int)System.Web.HttpContext.Current.Session["ResponseProdAreaId"];
}
if (string.IsNullOrEmpty(ProdName))
{
if (System.Web.HttpContext.Current.Session["ProdName"] == null)
{
ProdName = Guid.NewGuid().ToString();
System.Web.HttpContext.Current.Session["ProdName"] = ProdName;
}
else
{
ProdName = System.Web.HttpContext.Current.Session["ProdName"].ToString();
}
}
else
{
ProdName = ProdName.Replace("___", " ");
}
List<StateDetail> stateList = ProductService.GetAllStates().Where(n => n.FKCountryID == (int)Countries.UnitedStates).ToList();
ProductAddressViewModel model = new ProductAddressViewModel
{
ProdArea = ProdArea,
FKProductID = CurrentProductId
};
model.States = stateList != null ? new SelectList(stateList, "StateID", "StateCode") : null;
if (System.Web.HttpContext.Current.Session[“ProdAddresses”] != null && ProdAreaId == 0 && ProdArea == 1)
{
List<ProductAddressDto> lstprodaddresses = (List<ProductAddressDto>)System.Web.HttpContext.Current.Session[“ProdAddresses”];
if (lstprodaddresses.Count > 0)
{
AddressDto addrDto = lstprodaddresses.First().Address;
//save address in DB
model.Address1 = addrDto.Address1;
model.Address2 = addrDto.Address2;
model.ProdArea = 1;
model.City = addrDto.City;
model.IsDefault = true;
model.ProdName = model.ProdName;
model.SelectedAddressTypeID = (int)AddressType.Street;
model.ZIPCode = addrDto.ZIPCode;
model.SelectedStateId = addrDto.FKStateID;
model.AddressTypes = GetAddressTypes();
}
}
else if (model.FKProductID > 0)
{
ToolDto tool = ToolService.GetToolDetails(model.FKProductID);
if (ProdAreaId > 0)
{
model.AddressTypes = GetAddressTypes();
ProductAddressDto prodaddr = tool.ToolAddresses.First(n => n.Tool_AddressID == ProdAreaId);
model.Address1 = prodaddr.Address.Address1;
model.Address2 = prodaddr.Address.Address2;
model.City = prodaddr.Address.City;
model.SelectedStateId = prodaddr.Address.FKStateID;
model.ZIPCode = prodaddr.Address.ZIPCode;
model.SelectedAddressTypeID = prodaddr.Address.FKAddressTypeID;
model.IsDefault = prodaddr.IsDefault;
model.FKAddressID = prodaddr.FKAddressID;
model.Tool_AddressID = prodaddr.Tool_AddressID;
model.FKProductID = prodaddr.FKProductID;
model.AddressTypes = GetAddressTypes();
}
else
{
//address types
List<int> excludeAddrTypes = new List<int>();
foreach (ProductAddressDto prodadrdto in tool.ToolAddresses)
{
if (prodadrdto.Tool_AddressID != ProdAreaId)
{
excludeAddrTypes.Add(prodadrdto.Address.FKAddressTypeID);
}
}
if (System.Web.HttpContext.Current.Session[“ProdAddresses”] != null)
{
excludeAddrTypes.Add((int)AddressType.Street);
}
var addrtypes = from AddressType e in Enum.GetValues(typeof(AddressType))
where !excludeAddrTypes.Contains((int)e)
select new { Id = (int)e, Name = e.ToString() };
model.AddressTypes = addrtypes.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name
});
if (tool.ToolAddresses.Count == 0)
{
model.IsDefault = (ProdArea == 1);
}
}
}
else
{
//filter out address types if responsed tool is there
if (System.Web.HttpContext.Current.Session[“ProdAddresses”] != null)
{
List<int> excludeAddrTypes = new List<int>();
excludeAddrTypes.Add((int)AddressType.Street);
var addrtypes = from AddressType e in Enum.GetValues(typeof(AddressType))
where !excludeAddrTypes.Contains((int)e)
select new { Id = (int)e, Name = e.ToString() };
model.AddressTypes = addrtypes.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name
});
}
else
{
model.AddressTypes = GetAddressTypes();
}
model.IsDefault = (ProdArea == 1);
}
model.ProdName = ProdName;
return PartialView("_AddUpdateAddress", model);
}
May be the method is not in correct format.But i have to do it's unit testing.I have do that in several different ways.But i am not sure about its correctness.
I want to know that how should we do unit test for such a big and unformatted method like this.
Can anyone help me out on this ?
Below is the piece of code of my unit testing method :-
[TestMethod]
public void GetDetailsTest_NotEmpty()
{
var ProdName = random.ToString();
var ProdArea = random.Next();
var ProdAreaId = 0;
var _toolServiceMock = new Mock<IToolService>();
var _lookupServiceMock = new Mock<ILookupService>();
var stateList = new List<StateDto> {
new StateDto() { StateID = random.Next(), StateCode = Guid.NewGuid().ToString(), Description = random.ToString(), FKCountryID = 1 },
new StateDto() { StateID = random.Next(), StateCode = Guid.NewGuid().ToString(), Description = random.ToString(), FKCountryID = random.Next() },
};
_lookupServiceMock.Setup(s => s.GetAllStates()).Returns(stateList); // .Returns(stateList);
//Arrange
CustomerDto cust = _toolService.LookupCustomers("", "").FirstOrDefault();
if (cust != null)
{
ToolDto tool = _toolService.GetToolDetails(cust.Tool.toolId);
if (tool.ToolAddresses.Count > 0 && tool.ToolAddresses.First().Address != null)
{
HttpContext.Current.Session["FKToolID"] = cust.FKToolID;
var controller = new ToolController(_toolServiceMock.Object);
PartialViewResult result = controller.SelectAddress(cust.Tool.Name, 1, tool.ToolAddresses.First().Tool_AddressID) as PartialViewResult;
var viewmodel = (ToolAddressViewModel)((ViewResultBase)(result)).Model;
if (viewmodel != null)
{
//Act
Assert.AreEqual(tool.ToolAddresses.First().Address.Address1, viewmodel.Address1);
Assert.AreEqual("_AddUpdateAddress", result.ViewName);
Assert.IsInstanceOfType(viewmodel, typeof(ToolAddressViewModel));
}
//Act
_lookupServiceMock.VerifyAll();
}
}
}
First of all, your method is a way too complicated and too long.
Make your actions short and with one responsability to respect SOLID principle (http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)).
It will make your methods easier to test.
To help you with your problem, you can do something quick with your code :
Split your actions in internal virtual methods with one concern each (internal to be testable in you unit test project, virtual to be able to mock them).
Put the [assembly: InternalsVisibleTo("YourTestAssembly")] on your controller
In your unit test project, you will be able to test any of your internal methods separately.
Finally, to test your action, use a mocking framework (RhinoMock, Moq) to mock all your internal virtual methods and test the logic of your action (proxies generated by mocking framework will let you mock virtual methods).
It's the easiest way you can test your logic without breaking the existing application.
The inconvenient is that your logic is in internal methods wich let the whole assembly able to use it.

Zend Regex route reverse with paginator

I have following regex route, which allows me to use pagination - to parse URL and also build it:
; route "product-{brand}"
product.type = "Zend_Controller_Router_Route_Regex"
product.route = "product-([a-z\-]+)(?:/page/(\d+)/?)?"
product.defaults.module = "default"
product.defaults.controller = "products"
product.defaults.action = "product"
product.defaults.page = "1"
product.map.1 = "brand"
product.map.2 = "page"
product.reverse = "product-%s/page/%d"
Everything is working fine, however, I need to get the rid of default page. Currently we are migrating old web to the Zend and we need to preserve old links because of current google positions, etc.
With default "page", I'm getting always /page/1, without it Zend "cannot assemble" URL.
How to not display page 1 in URL ?
Finally, I've managed to achieve this, but only by rewriting Regex assemble method.
I'm simply overriding two methods.
Class extension:
class Utils_Router_Regex extends Zend_Controller_Router_Route_Regex
{
// instantiate
public static function getInstance(Zend_Config $config)
{
$defs = ($config->defaults instanceof Zend_Config) ? $config->defaults->toArray() : array();
$map = ($config->map instanceof Zend_Config) ? $config->map->toArray() : array();
$reverse = (isset($config->reverse)) ? $config->reverse : null;
return new self($config->route, $defs, $map, $reverse);
}
// in this case, we are using $this->_reverse as array from config
public function assemble($data = array(), $reset = false, $encode = false, $partial = false)
{
//// EXTENSION PART !!!
if( !isset( $data[(string) $this->_reverse->pagemap]) ) { // if not set url helper
$reverse = $this->_reverse->base;
} else { // if set in url helper
$reverse = $this->_reverse->paginator;
}
/// end of extension part
if ($reverse === null) {
require_once 'Zend/Controller/Router/Exception.php';
throw new Zend_Controller_Router_Exception('Cannot assemble. Reversed route is not specified.');
}
$defaultValuesMapped = $this->_getMappedValues($this->_defaults, true, false);
$matchedValuesMapped = $this->_getMappedValues($this->_values, true, false);
$dataValuesMapped = $this->_getMappedValues($data, true, false);
// handle resets, if so requested (By null value) to do so
if (($resetKeys = array_search(null, $dataValuesMapped, true)) !== false) {
foreach ((array) $resetKeys as $resetKey) {
if (isset($matchedValuesMapped[$resetKey])) {
unset($matchedValuesMapped[$resetKey]);
unset($dataValuesMapped[$resetKey]);
}
}
}
// merge all the data together, first defaults, then values matched, then supplied
$mergedData = $defaultValuesMapped;
$mergedData = $this->_arrayMergeNumericKeys($mergedData, $matchedValuesMapped);
$mergedData = $this->_arrayMergeNumericKeys($mergedData, $dataValuesMapped);
if ($encode) {
foreach ($mergedData as $key => &$value) {
$value = urlencode($value);
}
}
ksort($mergedData);
$return = #vsprintf($reverse, $mergedData);
if ($return === false) {
require_once 'Zend/Controller/Router/Exception.php';
throw new Zend_Controller_Router_Exception('Cannot assemble. Too few arguments?');
}
return $return;
}
}
Then you can define which sprintf string to use:
hodinky.type = "Utils_Router_Regex"
hodinky.route = "hodinky-([a-z\-]+)(?:/page/(\d+)/?)?"
hodinky.defaults.module = "default"
hodinky.defaults.controller = "products"
hodinky.defaults.action = "hodinky"
hodinky.map.1 = "znacka"
hodinky.map.2 = "page"
hodinky.reverse.paginator = "hodinky-%s/page/%d" ; assebmly with paginator
hodinky.reverse.base = "hodinky-%s/" ; assebmly without paginator
hodinky.reverse.pagemap = "page" ; "page" map key
If you have better solution, please let me know.

Getting VMWare DataStore inventory data (inventory traversal)

I'm attempting to get typical properties (capacity, free space, name) from the DataStores in my VMware ESXi server. I'm having trouble getting the TraversalSpec, ObjectSpec and PropertySpecs.
Can someone please tell me what I'm doing wrong?
public void GetDataStoreValues()
{
PropertyFilterSpec spec = GetDataStoreQuery();
ObjectContent[] objectContent = _service.RetrieveProperties(_sic.propertyCollector, new[] { spec } );
foreach (ObjectContent content in objectContent)
{
if (content.obj.type == "DataStore")
{
//... get values
}
}
}
private PropertyFilterSpec GetDataStoreQuery()
{
try
{
// Traversal to get to the host from ComputeResource
TraversalSpec tSpec = new TraversalSpec
{
name = "HStoDS",
type = "HostSystem",
path = "dataStore",
skip = false
};
// Now create Object Spec
var objectSpec = new ObjectSpec
{
obj = _sic.rootFolder,
skip = true,
selectSet = new SelectionSpec[] { tSpec }
};
var objectSpecs = new[] { objectSpec };
// Create PropertyFilterSpec using the PropertySpec and ObjectPec
// created above.
// Create Property Spec
string[] propertyArray = new[] {
"summary.capacity"
,"summary.freeSpace"
,"summary.name"
};
var propertySpec = new PropertySpec
{
all = true,
pathSet = propertyArray,
type = "DataStore"
};
var propertySpecs = new[] { propertySpec };
var propertyFilterSpec = new PropertyFilterSpec
{
propSet = propertySpecs,
objectSet = objectSpecs
};
return propertyFilterSpec;
}
catch (Exception)
{
}
return null;
}
Also, are object type names case sensitive? I seem to see all sorts of cases when I look at samples.
Thanks for any suggestions.
First question: You can use the following code to get properties of DataStore. I tested this code on vCenter 5.1
public void Test()
{
var properties = GetProperties(
new ManagedObjectReference { type = "Datastore", Value = "<your_datastore_key>" },
new[] {"summary.capacity", "summary.freeSpace", "summary.name"});
}
private List<DynamicProperty> GetProperties(ManagedObjectReference objectRef, string[] properties)
{
var typesAndProperties = new Dictionary<string, string[]> { { objectRef.type, properties } };
var objectContents = RetrieveResults(typesAndProperties, new List<ManagedObjectReference> { objectRef });
return ExtractDynamicProperties(objectRef, objectContents);
}
private List<ObjectContent> RetrieveResults(Dictionary<string, string[]> typesAndProperties, List<ManagedObjectReference> objectReferences)
{
var result = new List<ObjectContent>();
var tSpec = new TraversalSpec { path = "view", skip = false };
var oSpec = new ObjectSpec { skip = true, selectSet = new SelectionSpec[] { tSpec } };
oSpec.obj = service.CreateListView(serviceContent.viewManager, objectReferences.ToArray());
tSpec.type = "ListView";
var fSpec = new PropertyFilterSpec
{
objectSet = new[] { oSpec },
propSet = typesAndProperties.Keys.Select(typeName => new PropertySpec { type = typeName, pathSet = typesAndProperties[typeName] }).ToArray()
};
PropertyFilterSpec[] pfs = { fSpec };
var retrieveResult = service.RetrievePropertiesEx(serviceContent.propertyCollector, pfs, new RetrieveOptions());
if (retrieveResult != null)
{
result.AddRange(retrieveResult.objects);
while (!String.IsNullOrEmpty(retrieveResult.token))
{
retrieveResult = service.ContinueRetrievePropertiesEx(serviceContent.propertyCollector, retrieveResult.token);
result.AddRange(retrieveResult.objects);
}
service.DestroyView(oSpec.obj);
}
return result;
}
private static List<DynamicProperty> ExtractDynamicProperties(ManagedObjectReference objectRef, IEnumerable<ObjectContent> objectContents)
{
var result = new List<DynamicProperty>();
foreach (var objectContent in objectContents)
{
if (objectContent.propSet == null) continue;
if (objectContent.obj == null) continue;
if (objectContent.obj.type != objectRef.type || objectContent.obj.Value != objectRef.Value) continue;
result.AddRange(objectContent.propSet);
}
return result;
}
How to run the sample:
Initialize the service by object of VimService class and the serviceContent by object of ServiceContent class.
Login to vCenter or ESX using service.
Replace <your_datastore_key> with Key of your datastore. You can use the Managed Object Browser to find keys of their datastores. To get a description of datastore object, go to following links in MOB: content -> rootFolder -> childEntity -> datastoreFolder -> childEntity. Value of "Managed Object ID" on top of page is correct Key (like datastore-46).
Second question: Yes, the type of ManagedObjectReference is case sensitive.