Monday, December 3, 2012

An internal database error occurred in the Business Data Connectivity Shared service (BDC)

Firstly i want to say that i run across on this error not quite (as i thought) relating to BDC.. but:

My initial goal was simple - create some custom list in SP2010 with Lookup (information already on this site) fields. When i tried to do that i got following message:

So.. BDC service is related with creating Lookup type fields in SharePoint. Time ago we moved our SharePoint databases to new SQL server, but we didn't move our BDC db.. so i started to realize where is the problem. I have to create new BDC service application with new db in our new sql server + delete old BDC application (relationships), point my web application to new BDC service application.

I looked in SP Central Adminstration page for Service Applications (Application management -> Manage Service Applications).

1. Deleted old BDC application.
2. Created new BDC.
3. Point web application to new BDC (Application management -> Service Applications -> Service Application Associations)

But unfortuneatlly when i tried to create Lookup field i got new error saying:
Entity (External Content Type) cannot be found with Namespace = '', Name = 'New external content Type'


Previously i had some (With old BDC application) External Lists with custom external content types in them, so when we are creating Lookup fields, SharePoitn is looking for those content types and they didn't exist any more, so i DELETED THOSE OLD EXTERNAL LISTS.

Friday, October 12, 2012

This item is no longer available. It may have been deleted by another user

There are many articles about this SharePoint error message: "This item is no longer available. It may have been deleted by another user"

Mike Smith's Tech Training Notes and

These solutions didn't work for me!

Thursday, August 30, 2012

SCSM Creating Manual Activity for Incident in C#

Some time ago I had to develope application that could connect two systems: Microsoft Dynamics CRM & SCSM (Microsoft System Center Service Manager). The main purpose of this application is to synchronize data between two applications.

In this article i will show you only some little part (but maybe one of the  toughest for me...) of my application code.
I will continue to post some other usefull parts from this project. 

The code consists of 3 main steps:

1. Create relationship between incident & manual activity
2. Create manual activity
3. Assign created activity to incident

There is good post about creating incident in SCSM which really helped me out:

//Create relationship between incident & manual acticvity
ManagementPackRelationship workItemContainsActivityRelationship =
mg.EntityTypes.GetRelationshipClass(new Guid("2DA498BE-0485-B2B2-D520-6EBD1698E61B"));
CreatableEnterpriseManagementRelationshipObject AssignedToIncident = 

new CreatableEnterpriseManagementRelationshipObject(mg, workItemContainsActivityRelationship);

//Create Manual Activity
CreatableEnterpriseManagementObject activityItemObject = 

new CreatableEnterpriseManagementObject(mg, classManualActivity);
Guid newActivityGuid = Guid.NewGuid();
activityItemObject[classManualActivity, "Id"].Value = newActivityGuid.ToString();                                              
activityItemObject[classManualActivity, "Title"].Value = "<Title>";
activityItemObject[classManualActivity, "Description"].Value = "<Description>";

EnterpriseManagementObjectGenericCriteria genericCr = 

new EnterpriseManagementObjectGenericCriteria("Id == '" + <SCSM Incident Id>.ToString() + "'");
IObjectReader<EnterpriseManagementObject> reader = mg.EntityObjects.GetObjectReader<EnterpriseManagementObject>(genericCr, ObjectQueryOptions.Default);

 if (reader != null && reader.Count > 0) {
foreach (EnterpriseManagementObject obj in reader) {


IncrementalDiscoveryData dd = new IncrementalDiscoveryData();

//Assign Manual Activity to Incident

Thursday, August 23, 2012

How to get all SharePoint Users with web services in c#

SPservice.UserGroup usergroup = new SPservice.UserGroup();
usergroup.Credentials = System.Net.CredentialCache.DefaultCredentials;

XmlNode allusers = usergroup.GetAllUserCollectionFromWeb();

foreach (XmlNode child in allusers.ChildNodes) {
                            foreach (XmlNode item in child) {
                                  foreach (XmlAttribute atr in item.Attributes) {
                                              if (atr.Name.ToString() == "LoginName") {

SPservice - name of web reference in your visual studio project with URL:
http://<your server name>/_vti_bin/usergroup.asmx

Friday, July 27, 2012

CRM 4 how to retrieve custom attribute value in C#

DynamicEntity someEntity;
TargetRetrieveDynamic retrieveTarget = new TargetRetrieveDynamic();

retrieveTarget.EntityId = <id of entity>;
retrieveTarget.EntityName = EntityName.<entity name>.ToString();
RetrieveRequest retrieveRequest = new RetrieveRequest();
retrieveRequest.ColumnSet = new ColumnSet(new string[] { "your_custom_attribute" });
retrieveRequest.ReturnDynamicEntities = true;
retrieveRequest.Target = retrieveTarget;

RetrieveResponse retrieveResponse = (RetrieveResponse)service.Execute(retrieveRequest);
someEntity = retrieveResponse.BusinessEntity as DynamicEntity;

String result = (String)someEntity["your_custom_attribute"];
String value = result.Value.ToString();

CRM 4 Workflow error message details

In CRM 4 to get more info from workflow error than "An error has occurred" run this command against CRM database:

select Message from AsyncOperationBase
order by CreatedOn desc

Thursday, January 5, 2012

CRM 2011 Create a new Case (incident) using C#

using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Discovery;
using System.Runtime.Serialization;
namespace CreateIncident
    class Program
        static void Main (string[] args)
ClientCredentials credentials = new ClientCredentials();
credentials.Windows.ClientCredential = new System.Net.NetworkCredential
("username", "passw", "domain");

Uri organizationUri = new Uri("http://crmservername:port/orgname/XRMServices/2011/Organization.svc");
Uri homeRealmUri = null;
OrganizationServiceProxy orgService = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null); 
IOrganizationService _service = (IOrganizationService)orgService;
Entity incident = new Entity(); 
incident.LogicalName = "incident";
incident["title"] = "Case subject..";
// Set customerid with some existing contact guid 
Guid customerid = new Guid("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}");
// Set customerid as contact to field "customerid" 
EntityReference CustomerId = new EntityReference("contact", customerid); 
incident["customerid"] = CustomerId;
// Set contactid with some existing contact guid 
Guid contactid = new Guid("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}");
// Set contactid as contact to field "casecontactid" 
EntityReference primaryContactId = new EntityReference("contact", contactid); 
incident["casecontactid"] = primaryContactId;

            catch (Exception e)

Monday, January 2, 2012

CRM 2011 Custom Email with Pdf report attachment

After migration from CRM 4 to CRM 2011 my plugin written for custom email with PDF report won't work anymore so i rebuild my previous solution from CRM 4 with necessary changes for new CRM 2011:

using System;
using System.Activities;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Workflow;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Crm.Sdk.Messages;
using SendReport.ReportService;
using Microsoft.Crm.Sdk;
using Microsoft.Xrm.Sdk.Query;

namespace SendReport
    public class SendReport : CodeActivity

        protected override void Execute(CodeActivityContext executionContext)

                IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
                IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                Guid incidentId = context.PrimaryEntityId;

                byte[] result = null;

                ReportService.ReportExecutionService rs = new ReportExecutionService();
                rs.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
                rs.Url = "http://crmserver/ReportServer/ReportExecution2005.asmx";

                string reportPath = "/Reports/reportname";
                string format = "PDF";
                string historyID = null;
                string devInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";

                ParameterValue[] parameters = new ParameterValue[1];
                parameters[0] = new ParameterValue();
                parameters[0].Name = "incidentid";
                parameters[0].Value = incidentId.ToString();

                DataSourceCredentials[] credentials = null;
                string showHideToggle = null;
                string encoding;
                string mimeType;
                string extension;
                Warning[] warnings = null;
                ParameterValue[] reportHistoryParameters = null;
                string[] streamIDs = null;

                ExecutionInfo execInfo = new ExecutionInfo();
                ExecutionHeader execHeader = new ExecutionHeader();
                rs.ExecutionHeaderValue = execHeader;
                execInfo = rs.LoadReport(reportPath, historyID);
                rs.SetExecutionParameters(parameters, "en-us");
                String SessionId = rs.ExecutionHeaderValue.ExecutionID;

                result = rs.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out

                catch (Exception err)
                    throw new Exception(err.Message.ToString());

                Entity email = new Entity();
                email.LogicalName = "email";

                EntityReference regardingObject = new EntityReference("incident", incidentId);
                email.Attributes.Add("regardingobjectid", regardingObject);

                Guid senderUserId = Sender.Get<EntityReference>(executionContext).Id;
                Guid recieverUserId = Recipient.Get<EntityReference>(executionContext).Id;
                Guid recieverCCUserId = RecipientCC.Get<EntityReference>(executionContext).Id;
                EntityReference from = new EntityReference("systemuser", senderUserId);
                EntityReference to = new EntityReference("contact", recieverUserId);
                EntityReference cc = new EntityReference("contact", recieverCCUserId);

                Entity fromParty = new Entity("activityparty");
                fromParty.Attributes.Add("partyid", from);

                Entity toParty = new Entity("activityparty");
                toParty.Attributes.Add("partyid", to);

                Entity ccParty = new Entity("activityparty");
                ccParty.Attributes.Add("partyid", cc);

                EntityCollection collFromParty = new EntityCollection();
                collFromParty.EntityName = "systemuser";

                EntityCollection collToParty = new EntityCollection();
                collToParty.EntityName = "systemuser";

                EntityCollection collccParty = new EntityCollection();
                collccParty.EntityName = "systemuser";

                var entity = service.Retrieve("incident", incidentId, new ColumnSet(new[] { "ticketnumber", "customerid", "title"}));
                var ticket = entity.GetAttributeValue<string>("ticketnumber");
                var customer = entity.GetAttributeValue<EntityReference>("customerid");
                var customername = customer.Name;
                var title = entity.GetAttributeValue<string>("title");

                email.Attributes.Add("from", collFromParty);
                email.Attributes.Add("to", collToParty);
                email.Attributes.Add("cc", collccParty);

                email.Attributes.Add("subject", "Here goes subject message.. : " + ticket);

                email.Attributes.Add("description", "Here goes description text..");

                Guid emailID = service.Create(email);

                // Attaching Pdf report
                CrmNumber crmNextActorID = new CrmNumber();

                RetrieveEntityRequest request = new RetrieveEntityRequest();
                request.LogicalName = "email";

                RetrieveEntityResponse response = (RetrieveEntityResponse)service.Execute(request);
                int objecttypecode = response.EntityMetadata.ObjectTypeCode.Value;               

                Entity attachment = new Entity("activitymimeattachment");

                attachment.Attributes.Add("subject", "Report");
                attachment.Attributes.Add("filename", "Report.pdf");
                attachment.Attributes.Add("body", Convert.ToBase64String(result));
                attachment.Attributes.Add("filesize", new CrmNumber(Convert.ToInt32(result.Length.ToString())));
                attachment.Attributes.Add("mimetype", "text/plain");
                attachment.Attributes.Add("attachmentnumber", crmNextActorID.Value);

                attachment.Attributes.Add("objectid", new EntityReference("email", new Guid(email.Id.ToString())));
                attachment.Attributes.Add("objecttypecode", objecttypecode);


                SendEmailRequest reqSendEmail = new SendEmailRequest();
                reqSendEmail.EmailId = emailID;
                reqSendEmail.TrackingToken = "";
                reqSendEmail.IssueSend = true;

                SendEmailResponse res = (SendEmailResponse)service.Execute(reqSendEmail);


            catch (Exception err)
                throw new Exception(err.ToString());


        [Input("Sender input")]
        public InArgument<EntityReference> Sender { get; set; }

        [Input("Recipient input")]
        public InArgument<EntityReference> Recipient { get; set; }

        [Input("RecipientCC input")]
        public InArgument<EntityReference> RecipientCC { get; set; }