The given key is not present in the dictionary - dynamics-crm-2011

Hi I am trying to fetch the accounts from CRM 2011. I am fetching the data in the EntityCollection . But when I am trying to read or access data from entityCollection it displayed first record but throwing an error after that record. Kindly have a look to below code and suggest me.
string fetch2 = #"
<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='account'>
<attribute name='name' />
<attribute name='address1_city' />
<attribute name='primarycontactid' />
<attribute name='telephone1' />
<attribute name='accountid' />
<order attribute='name' descending='false' />
<filter type='and'>
<condition attribute='accounttype' operator='eq' value='01' />
</filter>
</entity>
</fetch>";
try
{
EntityCollection fxResult = _service.RetrieveMultiple(new FetchExpression(fetch2));
foreach (var e in fxResult.Entities)
{
Console.WriteLine("Id:{0},Name:{1},City:{2}", e.Attributes ["accountid"].ToString(), e.Attributes["name"].ToString(), e.Attributes["address1_city"].ToString());
// Console.WriteLine("Id:{0},Name:{1},City:{2}", e.ToEntity["accountid"]);
}
}
catch (Exception e)
{
Console.WriteLine("Error:==" + e.Message);
}

Before access an attribute you need to ask if it is in the context:
e.Attributes.Contains("address1_city")
If the collection contains the attribute, then you can access it safe.
string accountid = (string)e.Attributes["address1_city"]
The reason the attribute doesn't come in the collection it's because it is null or you are not retrieving it. In this case maybe, one of your attributes is null. Maybe address1_city.

When retrieving attribute values of late-bound Entity objects, the recommended approach is to use method getAttributeValue<T>. When the attribute is not present in the entity's attribute collection, it returns default(T).
The primary key ('id') of the record is always present when it is returned by the OrganizationService.
So your code should look like this:
EntityCollection fxResult = _service.RetrieveMultiple(new FetchExpression(fetch2));
foreach (var e in fxResult.Entities)
{
Console.WriteLine(
"Id:{0},Name:{1},City:{2}",
e.Id,
e.GetAttributeValue<string>("name"),
e.GetAttributeValue<string>("address1_city"));
}
You can safely use the item selector when you need to assign a value to an attribute, regardless if it is already present or not.
E.g. the following code line is valid:
e["name"] = "Demo Accountname";

Related

XSD (bitwise) logic between two attributes

Is it possible for XSD to apply (bitwise) logic between two XML attributes?
I hope to catch the following schema violation:
<parent mask="0x0007">
<child id="1" value="0x0001"/>
<child id="2" value="0x0002"/>
<child id="x" value="0x0010"/> // catch this!
</parent>
child x can clearly not be masked by its parent.
In simple logic:
if ((value AND mask) != value) then
# child element is invalid
endif
My application can of course catch this during the loading of the XML.
But my application applies schema validation prior to that and it would be grand if we can catch this during that stage.

Incorrect / redundant where clause

I'm not the best a Linq and I have written the below query and it just seems my where clause is redundant and there has to be a better way?
Given the following XML structure:
<Views>
<Fulfillment>
<SecurityRoleName>ABCD</SecurityRoleName>
<SecurityRoleViews>
<RoleView name="A" />
<RoleView name="B" />
<RoleView name="C" />
<RoleView name="D" />
<RoleView name="E" />
<RoleView name="F" />
</SecurityRoleViews>
<PublicRoleViews>
<RoleView name="Z" />
<RoleView name="Y" />
<RoleView name="X" />
<RoleView name="W" />
<RoleView name="V" />
<RoleView name="U" />
</PublicRoleViews>
</Fulfillment>
</Views>
I wrote the following to get a single value (FulfillmentRoleName) and two List (SecuredViews, PublicViews) objects.
FulfillmentRoleName = configParms.Descendants("Fulfillment")
.Where(node => (string)node.Element("SecurityRoleName") == "SecurityRoleName")
.Select(node => node.Value.ToString())
.First();
SecuredViews = configParms.Descendants("SecurityRoleViews")
.Where(node => (string)node.Element("RoleView") == "RoleView")
.Select(node => node.Attribute("name").Value.ToString())
.ToList();
PublicViews = configParms.Descendants("PublicRoleViews")
.Where(node => (string)node.Element("RoleView") == "RoleView")
.Select(node => node.Attribute("name").Value.ToString())
.ToList();
I would want the following values:
FulfillmentRoleName = ABCD
SecuredViews = List of names A,B,C...
PublicViews = List of names Z,Y,X....
It is the where clause that I am unsure of:
.Where(node => (string)node.Element("RoleView") == "RoleView")
Seems there has to be a more elegant way to locate that node?
Thank you for taking the time to help
As per Ahmad Mageed recommendation I am using the more elegant Element("") approach. However I am getting an instantiation error...as if the element collection is not built yet??
However if I use configParms.Root.Value I get my SecurityRoleName value???
I would have thought that views would be the root....or is it the first node that has a value???
You can use the Elements method and provide the name to match. This would allow you to replace the where query with Elements("RoleView").
Some other observations:
You can simplify the first query by grabbing the "Fulfillment" element directly by using the Element method, instead of Descendants.
The Value property returns a string. The ToString() calls are redundant.
Here's an updated version of your queries:
// if configParms is an XDocument use configParms.Root
var securityRoleName = configParms.Element("Fulfillment")
.Element("SecurityRoleName").Value;
var securedViews = configParms.Descendants("SecurityRoleViews")
.Elements("RoleView")
.Select(node => node.Attribute("name").Value)
.ToList();
var publicViews = configParms.Descendants("PublicRoleViews")
.Elements("RoleView")
.Select(node => node.Attribute("name").Value)
.ToList();

Is it possible to have a while loop connected to the mouseover state in an OpenLaszlo app?

Is it possible to do something like this
while (view.mouseover == true) {
preform action
}
I want to have an action repeat for as long as the mouse is over a specific view.
(asked on the laszlo-user mailing list)
Well, it looks like you answered your own question while I was testing my solution to make sure it worked correctly, but here is an alternative solution that works under OpenLaszlo 4.9.0 SWF10 and OpenLaszlo 4.9.0 DHTML run-times:
<canvas width="1000" height="665" debug="true">
<view id="v" bgcolor="0xcccccc" width="200" height="200">
<!--- #param boolean mouseisover: true when the mouse is over -->
<attribute name="mouseisover" type="boolean" value="false" />
<!--- #keywords private -->
<!--- #param lz.Delegate dlgt_repeat: stores the lz.Delegate object -->
<attribute name="dlgt_repeat" type="expression" />
<!--
Called when the 'onmouseover' event occurs
-->
<handler name="onmouseover">
// Step 1) unregister any existing delegate
// mark it for garbage collection
// and prevent its event from triggering:
if (this['dlgt_repeat'])
this.dlgt_repeat.unregisterAll();
// Step 2) update this.mouseisover flag:
if (!this.mouseisover)
this.setAttribute('mouseisover', true);
// Step 3) create an event Delegate and call it
// on the next application idle event:
var objDlgt = new lz.Delegate(this, 'doSomething');
this.setAttribute('dlgt_repeat', objDlgt);
lz.Idle.callOnIdle(this.dlgt_repeat);
</handler>
<!--
Called when the 'onmouseout' event occurs
-->
<handler name="onmouseout">
// Step 1) unregister any existing delegate
// mark it for garbage collection
// and prevent its event from triggering:
if (this['dlgt_repeat'])
this.dlgt_repeat.unregisterAll();
// Step 2) Update this.mouseisover flag:
if (this.mouseisover)
this.setAttribute('mouseisover', false);
</handler>
<!--- #keywords private -->
<!---
Called on application idle event by lz.Idle repeatedly
when the mouse is down.
#param ??? objDummy: required for SWF9+ run-times for methods
called by delegates due to AS3 (ActionScript3 compiler
requirements). Just set default to null to make compiler
happy and ignore...
-->
<method name="doSomething" args="objDummy=null">
<![CDATA[
// Note: CDATA allows '&&' to be used in script below,
// alternatively omit CDATA and use '&&' instead
// of '&&'
// Step 1) Execute your code you want to run here:
if ($debug) Debug.debug('Do something...');
// Step 2): If mouse is still over and the event
// delegate exists then schedule the event to be
// executed upon the next application idle state:
if (this.mouseisover && this['dlgt_repeat'] != null)
lz.Idle.callOnIdle(this.dlgt_repeat);
]]>
</method>
<text text="Move mouse over" />
</view>
</canvas>
Since both ActionScript and JavaScript are single threaded, it's not possible to have a while loop with pauses between each loop iteration. In the SWF10/11 runtime, you need to make sure that the code within each method or function can be executed within one frame (duration depends on the framerate of the SWF clip) of your application.
As a workaround you can use a timer, here is an example:
<canvas debug="true">
<class name="mouseoverview" extends="view"> <attribute name="timer" type="object" value="null" />
<!-- lz.Delegate instance used by the timer -->
<attribute name="timerdel" type="object" value="null" />
<attribute name="timeractive" type="boolean" value="false" />
<!-- milliseconds to pause before each call to doWhileMouseover method -->
<attribute name="tick" type="number" value="500" />
<handler name="onmouseover">
Debug.info('mouseover');
if (this.timeractive == false) {
this.setAttribute('timeractive', true);
this.timerdel = new lz.Delegate( this, "timerCallback" );
this.timer = lz.Timer.addTimer( this.timerdel, this.tick );
// When the timer is activated, do one call to the method
// containing the loop logic. The following calls will be
// handled by the timer and delegate.
this.doWhileMouseover();
}
</handler>
<handler name="onmouseout">
Debug.info('mouseout');
if (this.timeractive) {
this.setAttribute('timeractive', false);
lz.Timer.removeTimer(this.timerdel);
}
</handler>
<method name="timerCallback" args="millis">
if (this.timeractive) {
lz.Timer.resetTimer(this.timerdel, this.tick);
this.doWhileMouseover();
}
</method>
<method name="doWhileMouseover">
Debug.info("This is your virtual while loop for mouseover");
</method>
</class>
<mouseoverview x="100"
y="100"
width="400"
height="400"
bgcolor="#33aaff"
tick="250">
</mouseoverview>
</canvas>
When a mouseover occurs, a timer is started using the timerdel (an instance of lz.Delegate). Then the doWhileMouseover() method is called once directly, and then repeatedly using the timer, as long as no onmouseout event happened.

Anyone configured apache solr FieldReaderDataSource?

I have a datbase column containing xml and I want to index using apache solr content in that column i have following data-config.xml (configuration). The database name is "solrdb" and columns name is "xmlfield", There seems to be some problem in it, the error is specified at the bottom.
<dataConfig>
<!--Data source to connect to database-->
<dataSource
name="XmlDocDS"
type="JdbcDataSource"
driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1/solrdb"
user="root"
password="root" />
<!-- Data Source for getting xml columne data-->
<dataSource
name="solrFieldReaderDS"
type="FieldReaderDataSource"/>
<document>
<entity
name="xmltable"
rootEntity="false"
datasource="XmlDocDS"
query="select xmlfield from xmltable">
<field column="xmldata" blob="true" />
<entity
name="page"
dataSource="solrFieldReaderDS"
dataField="xmltable.xmldata"
processor="XPathEntityProcessor"
forEach="/page">
<field column="id" xpath="/mediawiki/page/id"/>
<field column="Title" xpath="/mediawiki/page/title"/>
</entity>
</entity>
</document>
</dataConfig>
The error is following:
SEVERE: Exception while processing: xmltable document : null:org.apache.solr.handler.dataimport.DataImportHandlerException: Unable to execute query: select xmlfield from xmltable Processing Document # 1
The error is thrown in this part of JDBC importer code:
try {
Connection c = getConnection();
stmt = c.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
stmt.setFetchSize(batchSize);
stmt.setMaxRows(maxRows);
LOG.debug("Executing SQL: " + query);
long start = System.currentTimeMillis();
if (stmt.execute(query)) {
resultSet = stmt.getResultSet();
}
LOG.trace("Time taken for sql :"
+ (System.currentTimeMillis() - start));
colNames = readFieldNames(resultSet.getMetaData());
} catch (Exception e) {
wrapAndThrow(SEVERE, e, "Unable to execute query: " + query);
}
So there can be error in connection or query (smth wrong with DB?). Also grep logs for "Executing SQL" and "Time taken for sql :"
there was an error in connection, for some reason it was nto able to connect to my local machine, i changed the database host and it connected!, the problem is that I have the configuration in place and FieldReaderDataSource seems to work fine, but now when it completes everything it says documents indexed/updated = 0
here is my xml configuration
<dataSource
name="jdbcDataSource"
driver="com.mysql.jdbc.Driver"
url="xxxx"
user="yyyy"
password="zzzz" readOnly="true"/>
<dataSource
name="solrFieldReaderDS"
type="FieldReaderDataSource"/>
<document>
<entity
name="tabledata"
dataSource="jdbcDataSource"
query="select codeID,codeText from ArticlePoolState where codeID=3">
<entity
name="xmldata"
dataSource="solrFieldReaderDS"
forEach="/med"
dataField="tabledata.codeText"
processor="XPathEntityProcessor">
<field column="title" xpath="/title"/>
</entity>
</entity>
</document>
The query is fine.

Problem displaying custom property values for SharePoint custom field types

I'm trying to create a custom field type in SharePoint (WSS 3.0) that has custom properties. I have created my fldtypes*.xml file based on the SDK docs and this blog post and it seems to render fine and I can retrieve the custom property values inside my code. My problem is that after the initial field creation, if I go back to the list settings page and click on my newly added field, the form shows my custom properties with some value that I'm not providing it. For example, if my custom property's display name is "My Custom Prop" then the value in its textbox will be "My Custom Prop field value".
My question is this: how can I properly show the actual string values of my custom property types in these textboxes?
Here's my fldtypes*.xml file:
<?xml version="1.0" encoding="utf-8"?>
<FieldTypes>
<FieldType>
<Field Name="TypeName">MyCustomField</Field>
<Field Name="TypeDisplayName">My Custom Field</Field>
<Field Name="TypeShortDescription">MyCustomField</Field>
<Field Name="ParentType">Text</Field>
<Field Name="UserCreatable">TRUE</Field>
<Field Name="FieldTypeClass">MyCustomField.CustomFields.MyCustomField, MyCustomField, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d772gbab82fe6996</Field>
<PropertySchema>
<Fields>
<Field Name="MyCustomProp" DisplayName="My Custom Prop" Type="Text" MaxLength="50" DisplaySize="30" />
</Fields>
</PropertySchema>
</FieldType>
</FieldTypes>
And here's the code for my field type class:
public class MyCustomField : SPFieldText
{
private string propval;
public MyCustomField(SPFieldCollection fields, string fieldName)
: base(fields, fieldName)
{
}
public MyCustomField(SPFieldCollection fields, string typeName, string displayName)
: base(fields, typeName, displayName)
{
}
public override void Update()
{
// I can see any updated value here
propval = GetCustomProperty("MyCustomProp") as string;
base.Update();
}
public override Type FieldValueType
{
get { return typeof (string); }
}
}
What can I do to see the correct custom property values in my "Change Column" page (FldEditEx.aspx) in my SharePoint app?
There is a well known issue with saving and retrieving custom properties on a custom field type. Here is a direct link to the work around.
btw, some of the comments on the post purport the same problem.

Resources