I need to retrieve full name and parent account of contact in Dynamics CRM.
I am using following code:
ColumnSet cols = new ColumnSet(new String[] { "fullname", "parentcustomerid" });
Entity retrContact = (Entity)orgService.Retrieve("contact", contactID, cols);
fullName = retrContact.Attributes["fullname"];
parentAccount = retrContact.Attributes["parentcustomerid"];
nameStr = fullName.ToString();
companyStr = parentAccount.ToString();
My problem is that companyStr getting "Microsoft.Xrm.Sdk.EntityReference" instead of Name value.
parentAccount contains following:
LogicalName "account" string
Name "Microsoft Corp" string
RowVersion null string
How can I get Name string?
The parentcustomerid object is an EntityReference object which has the name you're looking for. This code works:
ColumnSet cols = new ColumnSet(new string[] { "fullname", "parentcustomerid" });
Entity retrContact = (Entity)orgService.Retrieve("contact", new Guid("{9DF2ACC2-0212-E611-80E4-6C3BE5A83B1C}"), cols);
var parentAccount = (EntityReference)retrContact.Attributes["parentcustomerid"];
var companyStr = parentAccount.Name;
You should probably fetch the parentAccount from server (please refer to EntityReference.Name Property
This property is not automatically populated unless the EntityReference object has been retrieved from the server.
E.g. you should fetch the data from server using the Id parentcustomerid, somewhat like
Entity Account = service.Retrieve(Account.EntityLogicalName, parentAccount.Id, new ColumnSet(true));
You can for sure replace Account.EntityLogicalName with "account" string.
Related
I want to get the all fields along with type/datatype of the metadata fields of a Metadata schema.
I have written below sample code to achieve the functionality and I am able to get Name, Description etc but could not find any property with type/dataType. If anyone of you have any idea, please suggest...
var client = new SessionAwareCoreService2010Client();
client.ClientCredentials.Windows.ClientCredential.UserName = "myUserName";
client.ClientCredentials.Windows.ClientCredential.Password = "myPassword";
client.Open();
if (client.State == System.ServiceModel.CommunicationState.Opened)
{
var schemaUri = "tcm:1-47-8";
var fields= client.ReadSchemaFields(schemaUri, true, new ReadOptions());
var fieldName = fields.MetadataFields[0].Name;
}
To know the type of a field, you only need to examine the .NET type of the field.
I typically use an "is" check, but you can also call GetType if you want.
For example:
var client = new SessionAwareCoreService2010Client();
client.ClientCredentials.Windows.ClientCredential.UserName = "myUserName";
client.ClientCredentials.Windows.ClientCredential.Password = "myPassword";
client.Open();
if (client.State == System.ServiceModel.CommunicationState.Opened)
{
var schemaUri = "tcm:1-47-8";
var fields= client.ReadSchemaFields(schemaUri, true, new ReadOptions());
foreach (var field in fields.MetadataFields)
{
if (field is SingleLineTextFieldDefinitionData)
{
// Do something specifically for single-line text fields
}
}
}
The ReadSchemaFields method exposes only the definition of the fields. So it is essentially a wrapper around the properties you enter while you define the field in a schema.
The Content and Metadata are exposed by ComponentData.Content and ComponentData.Metadata respectively. But those are exposed as XML strings, so you will have to do your own parsing of them.
If you (understandably) don't feel like that, have a look at this helper class: http://code.google.com/p/tridion-practice/wiki/ChangeContentOrMetadata
You might also want to read my answer to this question: Updating Components using the Core Service in SDL Tridion 2011
I am pretty new to Entity Framework. I am getting an error as
An object with a temporary EntityKey value cannot be attached to an
object context
I think I am doing something wrong.
I have a Customer table and Address table where the Address table has customer's ID as foreign key.
I want to add a new address to the customer entity and keep in session and in next call I want to save it. this is only an example.
using (var db = new MyModel())
{
Customer cust = db.Customers.SingleOrDefault(c => C.ID == 1);
Address addr = new Address();
addr.Street = "123 super st";
cust.Addresses.Add(addr);
Session["customer"] = cust;
}
Customer SessionCustomer = (Customer)Session["customer"];
Customer.Comments = "Added new address";
using (var db = new MyModel())
{
db.Customers.Attach(SessionCustomer); //This throws exception: An object with a temporary EntityKey value cannot be attached to an object context
db.ObjectStateManager.ChangeObjectState(SessionCustomer, System.Data.EntityState.Modified);
db.SaveChanges();
}
Any help is appreciated. thank you.
Try using db.Customers.AddObject() for reattaching object to datacontext.
Take also a look at this: http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.addobject.aspx
Cheers
I have a Soap service that I added to my .NET project via Service Reference.
problemReporting.soapClient s = new problemReporting.soapClient();
problemReporting.NullRequest nr = new NullRequest();
problemReporting.ProblemDescription[] getDescList = s.getProblemDescriptionList(nr);
if (!IsPostBack)
{
rbProblemList.DataSource = getDescList;
rbProblemList.DataTextField = "description";
rbProblemList.DataValueField = "code";
rbProblemList.DataBind();
}
This returns a DropDownList of 23 items. (This list could grow in the future.) The service is returning an array of objects, where each object contains Category, Code, and Description.
How can I create a separate method that will return ONLY the 4 categories that exists in this array? I am unable to find any examples of how to create a method that will filter the data from a soap service.
Thank you in advance for any assistance.
This is basically the same code from another question you asked:
ASP.NET C# Filter DropDownList based on specific Category of Items from Soap Service
problemReporting.soapClient s = new problemReporting.soapClient();
problemReporting.NullRequest nr = new NullRequest();
problemReporting.ProblemDescription[] getDescList = s.getProblemDescriptionList(nr);
List<string> categories = new List<string>();
categories.Add("Category1");
categories.Add("Category2");
categories.Add("Category3");
var filteredResults = FilterCategories(categories, getDescList);
if (!IsPostBack)
{
rbProblemList.DataSource = filteredResults;
rbProblemList.DataTextField = "description";
rbProblemList.DataValueField = "code";
rbProblemList.DataBind();
}
public ProblemDescription[] FilterCategories(List<string> categories, ProblemDescription[] data )
{
var cats = from desc in data
where categories.Contains(desc.category)
select desc;
return cats;
}
i was looking at an example of how to do an insert in Linq to SQL and here it was it said:
NorthwindDataContext context = new NorthwindDataContext();
context.Products.Add(new Product(..));
context.SubmitChanges();
but when i look at the below, (in my case the Table is UserInfo), the Table doesn't have an "Add" method:
public System.Data.Linq.Table<UserInfo> UserInfos
{
get
{
return this.GetTable<UserInfo>();
}
}
any clue what i am doing wrong here?
You should use the InsertOnSubmit method:
NorthwindDataContext context = new NorthwindDataContext();
context.Products.InsertOnSubmit(new Product(..));
context.SubmitChanges();
The Add method exist on the EntitySet members, is mostly used when adding Child entities to a Parent one, for example:
var category = new Category{ Name = "Breveages"};
category.Products.Add(new Product{ Name = "Orange Juice"});
category.Products.Add(new Product{ Name = "Tomato Juice"});
category.Products.Add(new Product{ Name = "Cola"});
//...
context.Categories.InsertOnSubmit(category);
// This will insert the Category and
// the three Products we associated to.
EDIT: To do update operations, you just need to retrieve the entity by doing a query, or attaching it, for example:
var customer = context.Customers.Single( c => c.CustomerID == "ALFKI");
customer.ContactName = "New Contact Name";
context.SubmitChanges();
The DataContext tracks the changes of its related entities and when the SubmitChanges method is called, it will detect that change, and generate an Update SQL statement behind the scenes to do the update operation...
I have a question that I'm struggling with in ADO.NET Data Services:
When assembling an Entity for storage I need to get a related value from a lookup file. For example a person has a status code assigned of 'Pending' which is in a table called StatusCodes.
In Entity Framework, I'd need to set the value of person.StatusCode equal to an instance of the StatusCode. In the Entity Framework or in LINQ2Sql I'd so something like this:
var person = Person.CreatePerson(stuff);
var statCode = myContext.StatusCodeSet.Where(sc => sc.Description == "Pending").FirstOrDefault();
person.StatusCode = statCode;
// ...more code here...
myContext.BeginSaveChanges(SaveChangesOptions.Batch,
new AsyncCallback(OnSaveAllComplete),
null);
The query for the statCode won't work in ADO.NET Data Services and I get a runtime error saying the function is not supported. I assume it's because the statCode lookup is not an Async call.
However,
var person = Person.CreatePerson(stuff);
var query = from stat in myContext.StatusCodeSet
where stat.Description == "Pending"
select stat;
var dsQuery = (DataServiceQuery<StatusCode>)query;
dsQuery.BeginExecute(
result => tutorApplication.StatusCode = dsQuery.EndExecute(result).FirstOrDefault(), null);
// ...more code here...
myContext.BeginSaveChanges(SaveChangesOptions.Batch,
new AsyncCallback(OnSaveAllComplete),
null);
doesn't work either due to the Async nature of the query, the result won't be back before the person save happens.
Am I approaching this correctly?
Thanks
After sleeping on this I came up with the following:
var person = Person.CreatePerson(stuff);
var appStatPending = new StatusCode()
{
StatusCodeId = (int)StatusCodes.Pending,
Code = "Pending",
Description = "Pending",
EffectiveDate = DateTime.Now,
EnteredBy = "",
EnteredDate = DateTime.Now
};
myContext.AttachTo("StatusCodeSet", appStatPending);
person.StatusCode = appStatPending;
myContext.SetLink(tutorApplication, "StatusCode", appStatPending);
// ...more code here...
myContext.BeginSaveChanges(SaveChangesOptions.Batch,
new AsyncCallback(OnSaveAllComplete),
null);
I can create a local copy of the status code and link it into the context. It's important to new up the appStatPending rather than doing a StatusCode.CreateStatusCode() since doing that will add a new StatusCode to the database when the person graph persisted. For the same reason it's important to do the AttachTo("StatusCodeSet", appStatPending) since doing myContext.AddToStatusCodeSet() will also add a new entry to the StatusCodes table in the database.