Dynamics CRM Entity Data update from a custom Aspx Page - asp.net

I have found many sample to create data in dynamics crm from a custom aspx page, but i need to update entity data.
any sample will be helpful.
Thanks

It's quite simple, when you create a record normally you use the following code:
Entity newContact = new Entity("contact");
contact["firstname"] = "John";
contact["lastname"] = "Smith";
service.Create(newContact);
If you need to update a record, you need to retrieve it first (using a Retrieve if you have the Guid, or a RetrieveMultiple if you need to find it using a query), after just update the fields.
Entity retrievedContact = service.Retrieve("contact", GuidOfTheRecord, ColumnsYouWantToRetrieve);
retrievedContact["firstname"] = "My New First Name";
retrievedContact["lastname"] = "My New Last Name";
service.Update(retrievedContact);

Related

How To Use The RelatedEntities Collection To Create RelatedEntities

I'm attempting to follow the logic describe here: https://msdn.microsoft.com/en-us/library/gg309282.aspx for creating associated entities using the RelatedEntities Property. Problem is, no Associated Entities are getting created. I'm attempting to perform this action from within a Pre=Operation plugin... Is it not supported within a PreOperation Plugin? What am I doing wrong if it?
Here is the code:
var collection = new EntityCollection();
collection.Entities.AddRange(incentives.Select(e => e.ToSdkEntity()));
target.RelatedEntities.Add(new Relationship(new_LeadProduct.Fields.new_lead_new_leadproduct_LeadId), collection);
Since a pre-create plugin executes before the target entity has been created in the database you will not be able to create related entities referencing the target. You should execute related entity logic in a post-create plugin.
Edit:
This answer applies if you are trying to create related records associated with the Target in a plugin operation. Your question did not specify otherwise but based on the code in your answer it looks like this is not what you are trying to do.
Here is the code from the MSDN Example:
//Define the account for which we will add letters
Account accountToCreate = new Account
{
Name = "Example Account"
};
//Define the IDs of the related letters we will create
_letterIds = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
//This acts as a container for each letter we create. Note that we haven't
//define the relationship between the letter and account yet.
EntityCollection relatedLettersToCreate = new EntityCollection
{
EntityName = Letter.EntityLogicalName,
Entities =
{
new Letter{Subject = "Letter 1", ActivityId = _letterIds[0]},
new Letter{Subject = "Letter 2", ActivityId = _letterIds[1]},
new Letter{Subject = "Letter 3", ActivityId = _letterIds[2]}
}
};
//Creates the reference between which relationship between Letter and
//Account we would like to use.
Relationship letterRelationship = new Relationship("Account_Letters");
//Adds the letters to the account under the specified relationship
accountToCreate.RelatedEntities.Add(letterRelationship, relatedLettersToCreate);
//Passes the Account (which contains the letters)
_accountId = _service.Create(accountToCreate);
After some additional testing, the Related Entities Collection must be populated before the PreOperation stage. So registering this to run on PreValidation works as expected.

How to use SQL Server 2008 stored procedure in asp.net mvc

I have created a simple stored procedure in SQL Server 2008 as:
CREATE PROCEDURE viewPosts
AS
SELECT * FROM dbo.Post
Now, I have no idea how to use it in controller's action, I have a database object which is:
entities db = new entities();
Kindly tell me how to use stored procedure with this database object in Entity Framework.
For Details check this link:
http://www.entityframeworktutorial.net/data-read-using-stored-procedure.aspx
Hope this will help you.
See article about 30% in:
In the designer, right click on the entity and select Stored Procedure mapping.
Click and then click the drop down arrow that appears. This exposes the list of all Functions found in the DB metadata.
Select Procedure from the list. The designer will do its best job of matching the stored procedure’s parameters with the entity properties using the names. In this case, since all of the property names match the parameter names, it maps every one correctly so you don’t need to make any changes. Note: The designer is not able to automatically detect the name of the field being returned.
Under the Result Column Bindings section, click and enter variable name. The designer should automatically select the entity key property for this final mapping.
The following code is what I use to initialize the stored procedure, then obtain the result into variable returnedResult, which in this case is the record id of a newly created record.
SqlParameter paramResult = new SqlParameter("#Result", -1);
paramResult.Direction = System.Data.ParameterDirection.Output;
var addParameters = new List<SqlParameter>
{
new SqlParameter("#JobID", EvalModel.JobID),
new SqlParameter("#SafetyEvaluator", EvalModel.SafetyEvaluator),
new SqlParameter("#EvaluationGuid", EvalModel.EvaluationGuid),
new SqlParameter("#EvalType", EvalModel.EvalType),
new SqlParameter("#Completion", EvalModel.Completion),
new SqlParameter("#ManPower", EvalModel.ManPower),
new SqlParameter("#EDate", EvalModel.EDate),
new SqlParameter("#CreateDate", EvalModel.CreateDate),
new SqlParameter("#Deficiency", EvalModel.Deficiency.HasValue ? EvalModel.Deficiency.Value : 0),
new SqlParameter("#DeficiencyComment", EvalModel.DeficiencyComment != null ? EvalModel.DeficiencyComment : ""),
new SqlParameter("#Traffic", EvalModel.Traffic.HasValue ? EvalModel.Traffic.Value : 0),
paramResult
};
// Stored procedure name is AddEval
context.Database.ExecuteSqlCommand("AddEval #JobID, #SafetyEvaluator, #EvaluationGuid, #EvalType, #Completion, #ManPower, #EDate, #CreateDate, #Deficiency, #DeficiencyComment, #Traffic, #Result OUTPUT", addParameters.ToArray());
var returnedResult = paramResult.Value;
NewEvaluationID = Convert.ToInt32(returnedResult);

Entity Framework Update Time & Date Column with Parameterized

I have changed all my code from the raw ADO.NET SQLCommand to Entity Framework in order to have easier accessibility of changing my code in the future. However, I have realized there are many drawbacks in Entity Framework it is not as simple as injecting raw SQL commands into the database. Moreover, I have used Reverse Engineering to generate the Models & Mapping for MS Sql Server.
Currently, I am trying to do the following but none of the columns are getting updated.
string sql = #"UPDATE [ProductDB] SET CreatedProduct_Time=getdate(), CreatedProduct_Date=getdate()" + " WHERE [Material_No] = #Material_No";
db.Database.ExecuteSqlCommand(sql, new SqlParameter("#Material_No", materialnotxt));
The columns are not getting updated.
I am having a doubt whether Entity Framework will help me maintain my code for future use and is it worth the headache using it instead of the old raw SQL code? So far there are many constraints and it requires a higher learning curve.
Some confusing parts I have find online what is the difference between the context.Database.ExecuteSqlCommand and this MSDN http://msdn.microsoft.com/en-us/library/bb738684.aspx the code looks entirely different then my approach.
EDIT
I have used a different approach to insert the Date and Time while inserting all the info from the textbox.
using (var db = new ROGContext())
{
ProductDB product = new ProductDB
{
Material_No = long.Parse(MaterialNo_txtbox.Text),
Product_Line = ProductLineDropDownList1.SelectedItem.Text,
Product_Description = Description_txtbox.Text,
Size = Size_txtbox.Text,
UOM = UOM_txtbox.Text,
SupplierID = long.Parse(SupplierCountryListBox.SelectedItem.Value),
CreatedProduct_Date = DateTime.Parse(System.DateTime.Now.ToShortDateString()), //in the SQL database I have set the datatype as date to get yyyy/mm/dd
CreatedProduct_Time = DateTime.Now.TimeOfDay //in the SQL database I have set the datatype as time(0) to get hh:mm:ss
};
long queryselect = (from materialno in db.ProductDBs
where materialno.Material_No == product.Material_No
select materialno.Material_No).SingleOrDefault();
if (queryselect != long.Parse(materialnotxt))
{
Label1.Text = "Product successfully added in database";
Label1.Visible = true;
db.ProductDBs.Add(product);
db.SaveChanges();
}
You can use Context.ExecuteStoreCommand for Insert, Update and Delete.
See in Page 64 of Entity Framework 4.0 Recipes: A Problem-Solution Approach
Answer your edited part:
ExecuteStoreQuery for Select
ExecuteStoreCommand for Insert, Update and Delete
Entity Framework v4 – Tips and Tricks

EWS: How to Edit/Update an existing Appointment?

I created some Appointments in VB.NET with EWA. It works fine. Now i want to edit the appointment ( date or topic).
for every booking I saved the booking ID in a extended property from the appointment
' Create a definition for the extended property.
Dim extendedPropertyDefinition As New EWS.ExtendedPropertyDefinition(EWS.DefaultExtendedPropertySet.Appointment, EWS.MapiPropertyType.String)
' Add the extended property to an e-mail message object named "appointment".
appointment.SetExtendedProperty(extendedPropertyDefinition, buchungId)
How can I select a appointment with the correct bookingid and edit the topic for example?
you can search by items with the Extended property. Your code may look like this (hope c#-Code helps you too, I'm a bit out of practise in VB):
ExtendedPropertyDefinition prop = new ExtendedPropertyDefinition(Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet.PublicStrings, <Name>, MapiPropertyType.String);
SearchFilter filter = new SearchFilter.IsEqualTo(prop, "SearchValue");
FolderId folder = new FolderId(WellKnownFolderName.Inbox)
FindItemsResults<Item> result = service.FindItems(folder, filter, new ItemView(10));
If your "buchungid" is unique, result.Items should have one item if it's in the inbox.

MS CRM Dynamics in latest bound - how to discover all entities?

I am building a connector to CRM Dynamics.
I would like to get (discover) all the entities with their fields.
There for, I am using the IOrganizationService interface with RetrieveAllEntitiesRequest.
I do get all the entities names BUT I don't know how to get all fields (columns) of any entity.
please help...
hagai
It sounds like your almost there. This it taken from the MSDN sample: Dump Attribute Metadata to a File.
RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
{
EntityFilters = EntityFilters.Attributes,
RetrieveAsIfPublished = true
};
// Retrieve the MetaData.
RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(request);
foreach (EntityMetadata currentEntity in response.EntityMetadata)
{
foreach (AttributeMetadata currentAttribute in currentEntity.Attributes)
{
Console.WriteLine("LogicalName: " + currentAttribute.LogicalName);
}
}
We need to create RetrieveAllEntitiesRequest first
RetrieveAllEntitiesRequest entityRequest = new RetrieveAllEntitiesRequest();
Then call the service.execute() to retrieve results
there is a blog post which explains really well.

Resources