Quantcast
Channel: CRM Development forum
Viewing all 465 articles
Browse latest View live

Creating Email Activity + ActivityMimeAttachment with oData in Offline mode - Help !

$
0
0

Hi guys,

I wrote some javascript code that creates an email activity with a PDF attachment. It's functional from the CRM web client (On-Premise) and using the Outlook client when I'm in online mode, but when I go OFFLINE I get the following error "The activitymimeattachment with id xxxxxxx Does Not Exist".

I make 2 ajax calls, the first to create the Email Activity (which returns the newly created ActivityId) which I then send to my second Ajax call to create the ActivityMimeAttachment and associate it with the activity. As I said, when I'm online, it's all fine, and if I look at the ajax responses in the screenshots attached, the one that fails is looking for a ActivityMimeAttachmentId = "13F85C43-2E26-E311-96FB-005056C00008" which doesn't exist in the ActivityMimeAttachment Table. The attachment does get saved but with an id of "15F85C43-2E26-E311-96FB-005056C00008" (the SECOND number in the guid is different). If I look at the JSON response for the successfull call (when online), the value of activitymimeattachmentId is correct. 

This is driving me NUTS ! Is there a difference between the oData service on the CRM server and service that is running on the local pc ?

I've also included a snippet of my code.

var ODATA_ActivityMimeAttachmentCollection = "/ActivityMimeAttachmentSet";
var ODATA_EmailCollection = "/EmailSet";	

var RegardingEntity = new Object();
RegardingEntity.LogicalName = "contact";
RegardingEntity.Id = customerid[0].id; 

var objEmail = new Object();

objEmail.RegardingObjectId = RegardingEntity;
objEmail.Subject = "Contract email";

var jsonEntity = window.JSON.stringify(objEmail);

//* Create an email record *//
$.ajax({
	
	async : true,
	type: "POST",
	contentType: "application/json; charset=utf-8",
	datatype: "json",
	url: serverUrl + ODATA_ENDPOINT + ODATA_EmailCollection,
	data: jsonEntity,
	beforeSend: function (XMLHttpRequest) {
		XMLHttpRequest.setRequestHeader("Accept", "application/json");
	},
	success : function (data) {
		//** Create the email attachment **//
		emailId = data.d.ActivityId;
		if (emailId) {
			var refEntity = new Object();
			refEntity.LogicalName = "email";
			refEntity.Id = emailId;
			//refEntity.Name = "Subject";
			var objAnnotation = new Object();
			//objAnnotation.ObjectTypeCode = "email";
			objAnnotation.Subject = "PDF Contract Document";
			objAnnotation.ActivityId = refEntity
			//objAnnotation.ObjectId = refEntity;
			objAnnotation.MimeType= "application/pdf";
			objAnnotation.Body = binaryFileToString();
			objAnnotation.FileName = "Signed_Contract.pdf";
			//Parse the entity object into JSON 
			var jsonEntity2 = window.JSON.stringify(objAnnotation);
			//AJAX function to Create a CRM record using OData 
			$.ajax({
				async : true,
				type: "POST",
				contentType: "application/json; charset=utf-8",
				datatype: "json",
				url: serverUrl + ODATA_ENDPOINT + ODATA_ActivityMimeAttachmentCollection,
				data: jsonEntity2,
				beforeSend: function (XMLHttpRequest) {
					XMLHttpRequest.setRequestHeader("Accept", "application/json");
				}
			});
		}							
	},


How to make chart's legends wider?

$
0
0

Hello,

I have a pipeline type chart as a part of my dashboard. The chart has labels (or legends) docked to the right. The problem is that by default the text is cut at some point and three dots are added to the end. I'd like to make the legend area wider so that the text would be displayed entirely.

Here's my XML right now. I tried to use Legend.MaximumAutoSize property but I doesn't do anything? I've tried almost everything I can imagine so I decided to ask help here.

<visualization><visualizationid>{DAB9876F-5DD3-E211-89F1-78E3B519B0A5}</visualizationid><name>Projects (euro)</name><primaryentitytypecode>cre_project</primaryentitytypecode><datadescription><datadefinition><fetchcollection><fetch mapping="logical" aggregate="true"><entity name="cre_project"><attribute groupby="true" alias="_CRMAutoGen_groupby_column_Num_0" name="cre_projectstate" /><attribute alias="_CRMAutoGen_aggregate_column_Num_0" name="cre_value" aggregate="sum" /></entity></fetch></fetchcollection><categorycollection><category alias="_CRMAutoGen_groupby_column_Num_0"><measurecollection><measure alias="_CRMAutoGen_aggregate_column_Num_0" /></measurecollection></category></categorycollection></datadefinition></datadescription><presentationdescription><Chart Palette="None" PaletteCustomColors="55,118,193; 197,56,52; 149,189,66; 117,82,160; 49,171,204; 255,136,35; 97,142,206; 209,98,96; 168,203,104; 142,116,178; 93,186,215; 255,155,83"><Series><Series ShadowOffset="0" IsValueShownAsLabel="True" Font="{0}, 9.5px" LabelForeColor="59, 59, 59" ChartType="Funnel" CustomProperties="FunnelLabelStyle=Outside, FunnelNeckHeight=0, FunnelPointGap=1, FunnelNeckWidth=5 "><SmartLabelStyle Enabled="True" /></Series></Series><ChartAreas><ChartArea><Area3DStyle Enable3D="True" /></ChartArea></ChartAreas><Legends><Legend Alignment="Center" LegendStyle="Table" Docking="right" IsTextAutoFit="True" IsEquallySpacedItems="True" ShadowColor="0, 0, 0, 0" ForeColor="59, 59, 59" MaximumAutoSize="50" TextWrapThreshold="30" /></Legends><Titles><Title Alignment="TopLeft" DockingOffset="-3" Font="{0}, 13px" ForeColor="0, 0, 0"></Title></Titles></Chart></presentationdescription><isdefault>false</isdefault></visualization>

Thank you in advance.

Add multiple Custom views in Party Lookup (Regarding)

$
0
0

I have set up the Regarding lookup (in Email entity) to show only Incidents and a custom entity, called Problem.

I can set up through JavaScript a custom view (filtered) only for one of these entities, but not for both.

How can I have multiple custom views for this lookup?

document.getElementById("regardingobjectid").setAttribute("defaulttype", "112");
document.getElementById("regardingobjectid").setAttribute("lookuptypenames", "Incident:112:Case,aux_problem:10036:Problem");
document.getElementById("regardingobjectid").setAttribute("lookuptypes", "112,10036");
document.getElementById("regardingobjectid").setAttribute("lookuptypeIcons", "/_imgs/ico_18_112.gif:../WebResources/aux_problem_icon_16");

setCasesView("aux_account", "regardingobjectid", false);

 I call here to setProblemsView, the same as setCasesView but not setting it as default (with the false at the end)

Xrm.Page.getControl(lookupFieldName).addCustomView(viewId, entityName, viewDisplayName, fetchXml, layoutXml, false);

But is not applying my filtered view when I choose problems Problems

function setCasesView(entityFieldName, lookupFieldName, resetSelection) {

    // use randomly generated GUID Id for the view
    var viewId = "{xxxxxxxx-xxxx-0000-9FB6-58E69E4C81AA}";

    var entityName = "incident";

    // give the custom view a name
    var viewDisplayName = "Cases in Account: " + accname + "";

    // find all cases where account is the account selected
    var fetchXml = ...
    var layoutXml = ...

    Xrm.Page.getControl(lookupFieldName).addCustomView(viewId, entityName, viewDisplayName, fetchXml, layoutXml, true);
    document.getElementById(lookupFieldName).setAttribute("disableViewPicker", "1");
}

Programmatically remove resources for Service Appointment

$
0
0

I am adding the resource to the SA in the following manner:

ActivityParty resParty = new ActivityParty();
resParty.PartyId = new EntityReference() { LogicalName = "systemuser", Id = appt.new_PhysicianAssigned.Id };

resParty.ActivityId = new EntityReference() { LogicalName = "serviceappointment", Id = appt.ActivityId };

resParty.ParticipationTypeMask = new OptionSetValue() { Value = 10 }; //resource

myContext.AddToActivityPartySet(resParty);
appt.serviceappointment_activity_parties.Add(resParty);
How would I remove all the resources and only the resources for a given Service Activity?


returning target ID on crm 4 custom activity

$
0
0

I just want a simple custom workflow activity to return the accounted (guid value) so I can pass it to another activity like an email. this is the code that I am using . it is pretty simple but is not working

I need to run it "ON DEMAND", so, I would expect it would get at least the accountId of my selected record

the activity is appearing on the workflow wizard but when I use it, my workflow fails.

am I doing something wrong?

[CrmWorkflowActivity("Return accountid")]
    public partial class RetrieveContactIDActivity : Activity
    {

        public static DependencyProperty ResponseProperty = DependencyProperty.Register("Response", typeof(string), typeof(RetrieveContactIDActivity));
        [CrmOutput("ResponseId")]
        [CrmReferenceTarget("account")]
        public string Response
        {
            get
            {
                return (string)base.GetValue(ResponseProperty);
            }
            set
            {
                base.SetValue(ResponseProperty, value);
            }
        }
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {

            // Get the context service.
            IContextService contextService = (IContextService)executionContext.GetService(typeof(IContextService));
            IWorkflowContext context = contextService.Context;
            ICrmService crmService = context.CreateCrmService(true);

           
            try
            {

                if (context.InputParameters.Properties.Contains("Target") && context.InputParameters.Properties["Target"] is DynamicEntity)
                {
                    DynamicEntity entity = context.InputParameters.Properties["Target"] as DynamicEntity;

                    if (entity.Properties.Contains("contactid"))
                    {
                        Response = ((Key)entity.Properties["contactid"]).Value.ToString();

                    }
                    

                    if (entity.Properties.Contains("id"))
                    {
                        Response = ((Key)entity.Properties["contactid"]).Value.ToString();

                    }                    
                }
            }
            catch (SoapException ex)            {
               
                //logger.LogError(ex.Detail.InnerText);
            }
            catch (Exception ex)            {
                
                //logger.LogError(ex.Message);
            }

            return base.Execute(executionContext);
        }
    }

Call localhost endpoints on IFD deployment

$
0
0

We have a loadbalanced deployment with 3 front end servers. While processing async plugins we make calls out to other organizations on the same deployment, but the IFD url is load balanced (https://orgname.domain.com) thus causing a hit out to the loadbalancer and back (unnecessary). I would like to be able to make a call directly to the server the process is running on (http://localhost/orgname) however I run into a few issues:

1) When initializing the service the server redirects from http -> https so the resulting url is https://localhost/orgname, not a huge problem, except...

2) Causes invalid server certificate...

easy enough to get around

ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) =>
{
	var request = sender as HttpWebRequest;
	return (request != null && (request.Host == "localhost" || request.Host == "127.0.0.1")) || sslPolicyErrors == SslPolicyErrors.None;
};

3) This is the show stopper, I receive an exception saying it cannot authenticate:

System.InvalidOperationException: The user authentication failed! 
   at Microsoft.Xrm.Sdk.ClientExceptionHelper.Assert(Boolean condition, String message) 
   at Microsoft.Xrm.Sdk.Client.ServiceProxy`1.AuthenticateCore() 
   at Microsoft.Xrm.Sdk.Client.ServiceProxy`1.ValidateAuthentication() 
   at Microsoft.Xrm.Sdk.Client.ServiceContextInitializer`1.Initialize(ServiceProxy`1 proxy) 
   at Microsoft.Xrm.Sdk.Client.OrganizationServiceContextInitializer..ctor(OrganizationServiceProxy proxy) 
   at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.ExecuteCore(OrganizationRequest request) 

So I can get around 1 and 2... anyone have any suggestions for #3?

One alternative is to resolve the local machine name and fqdn and use that, but I'd still like to see why I'm getting the Unable to authenticate. Below is the code to generate the service:

public IOrganizationService LocalHostOrganizationService(string orgUrlName, TimeSpan timeout, bool enableProxyTypes = true)
{
	var organizationUri = new Uri(string.Format(OrganizationServiceUrl(AuthenticationProviderType.ActiveDirectory), orgUrlName, "localhost"));

	var creds = new ClientCredentials();
	creds.Windows.ClientCredential = new NetworkCredential();
	creds.Windows.ClientCredential.UserName = _auth.Domain + "\\" + _auth.UserName;
	creds.Windows.ClientCredential.Password = _auth.Password;
	var serviceProxy = new OrganizationServiceProxy(organizationUri, null, creds, null);

	if (enableProxyTypes)
		serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
	serviceProxy.Timeout = timeout;
	return serviceProxy;
}

private string OrganizationServiceUrl(AuthenticationProviderType authType)
{
	var url = (_auth.UseSSL ? "https" : "http");
	switch (authType)
	{
		case (AuthenticationProviderType.ActiveDirectory):
			url += "://{1}/{0}/XRMServices/2011/Organization.svc";
			break;
		default:
			url += "://{0}.{1}/XRMServices/2011/Organization.svc";
			break;
	}
	return url;
}


Thank you in advance for your help. If you think you may be able to help with any of my unanswered threads please look at them here

Accessing the CRM lookup window from an external application

$
0
0

I have some nice JavaScript code that allows you to access the lookupinfo.aspx page when deploying a solution as an html web resource.  

var surl = "http://mycrmtest.crm.dynamics.com/_controls/lookup/lookupinfo.aspx?AllowFilterOff=1&DefaultType=2&DefaultViewId=%7bA2D479C5-53E3-4C69-ADDD-802327E67A0D%7d&DisableQuickFind=0&DisableViewPicker=0&LookupStyle=single&ShowNewButton=1&ShowPropButton=1&browse=0&objecttypes=2";
var oLookupItems = window.showModalDialog(surl, window, "dialogwidth: 450; dialogheight: 300; resizable: yes");
            if (oLookupItems != null) {
                if (oLookupItems.items.length > 0) {
                    var name = oLookupItems.items[0].name;
                    alert('name: ' + name);
                    document.getElementById('new_actionby').textContent = name;
                    var Id = oLookupItems.items[0].id;
                    Id = Id.replace("{", "");
                    Id = Id.replace("}", "");
                    alert('Id: ' + Id);
                }

I ran into a problem using this code when attempting to access it from an external .aspx page.  
The first issue I noticed was the inability to script across domains.  I found a solution that utilizes a local proxy:  http://www.sharepointjohn.com/aspnet-proxy-page-cross-domain-requests-from-ajax-and-javascript/
This solution works great when authentication is NOT involved, but does not work when authenticating to onPremise or online.  I even tried wrapping the proxy code in my OrganizationServiceProxy authentication, but that does not work.
Is there a way to authenticate to CRM when passing code via a proxy?
Is there a way to  legally script across domains?
Is there a better way to access the lookupinfo.aspx page when hosted on another domain?

Thank you for reading.

CRM 2011 Getting System.TypeLoadException after plugin build

$
0
0

Hi!

Fixed an error in a plugin(EmailFilterPlugin which treats emails) and build it With success(Visual Studio 2010). Then updated the plugin with Plugin registration Tool(as usual) and suddenly we get the error below... I have also tried with no change in code, same problem. I believe there must be something with my develop environment but can't see what it is... when I update with an old build it Works fine!  

Please help me, I'm stuck:-)

Log Name:      MSCRMEmailLog
Source:        MSCRMEmailLog
Date:          18.09.2013 11:05:09
Event ID:      9628
Task Category: None
Level:         Error
Keywords:      Classic
User:          N/A
Computer:      _server.local
Description:
#9628 - An error occurred while delivering the e-mail message with subject "bla bla bla" in mailbox testskjema@bla.no for delivery to http://_server/MSCRMOrg. System.ServiceModel.FaultException`1[Microsoft.Xrm.Sdk.OrganizationServiceFault]: System.TypeLoadException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #D06FF112 (Fault Detail is equal to Microsoft.Xrm.Sdk.OrganizationServiceFault).
Event Xml:<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event"><System><Provider Name="MSCRMEmailLog" /><EventID Qualifiers="0">9628</EventID><Level>2</Level><Task>0</Task><Keywords>0x80000000000000</Keywords><TimeCreated SystemTime="2013-09-18T09:05:09.000000000Z" /><EventRecordID>12712398</EventRecordID><Channel>MSCRMEmailLog</Channel><Computer>_server.local</Computer><Security /></System><EventData><Data>#9628 - An error occurred while delivering the e-mail message with subject "bla bla bla" in mailbox testskjema@bla.no for delivery to http://_server/MSCRMOrg. System.ServiceModel.FaultException`1[Microsoft.Xrm.Sdk.OrganizationServiceFault]: System.TypeLoadException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #D06FF112 (Fault Detail is equal to Microsoft.Xrm.Sdk.OrganizationServiceFault).</Data></EventData></Event>
BR Knut Myre


Serialization Exception in WorkFlow 4.5 with WorkflowInstanceUnhandledExceptionRecord

$
0
0

Hi, I have configured my WorkFlowApplication to emit tracking records. And, in the overridden Track() method Im trying to convert the TrackingRecord to XML and storing it somewhere.

Im able to parse all the type of Tracking Record except UnhandledExceptionRecord and FaultPropogationRecord.

It throws SerializationException. 

Here is my Track() method,

  protected override void Track(TrackingRecord record, TimeSpan timeout)
        {
            string _xmlData = string.Empty;
            WorkFlowTrackingEntity trackEntity = null;
            if (record != null)
            {
                using (TextWriter textWriter = new StringWriter())
                {
                    XmlTextWriter xmlWriter = new XmlTextWriter(textWriter);
                    DataContractSerializer serializer = new DataContractSerializer(record.GetType());
                    serializer.WriteObject(xmlWriter, record);
                    _xmlData = textWriter.ToString();
                    xmlWriter.Flush();
                    textWriter.Flush();
                }
                trackEntity = new WorkFlowTrackingEntity(record.InstanceId.ToString(), record.EventTime);
                trackEntity.XMLContent = _xmlData;
                WorkFlowTrackingHandler.GetInstance.LogTrackingRecord(trackEntity);
            }
        }

This is how i convert the record to XML.

Can anyone pls tell where I'm going wrong.

xpathevaluator' is undefined

$
0
0

I got error on this line... (IE10)

var result = window.showModalDialog(Xrm.Page.context.getServerUrl() + "/WebResources/ser_constituentdialog", obj, 'dialogWidth=380px,dialogHeight=380px,resizable:yes');

Full description is attach below.

Add multiple Custom views in Party Lookup (Regarding)

$
0
0

I have set up the Regarding lookup (in Email entity) to show only Incidents and a custom entity, called Problem.

I can set up through JavaScript a custom view (filtered) only for one of these entities, but not for both.

How can I have multiple custom views for this lookup?

document.getElementById("regardingobjectid").setAttribute("defaulttype", "112");
document.getElementById("regardingobjectid").setAttribute("lookuptypenames", "Incident:112:Case,aux_problem:10036:Problem");
document.getElementById("regardingobjectid").setAttribute("lookuptypes", "112,10036");
document.getElementById("regardingobjectid").setAttribute("lookuptypeIcons", "/_imgs/ico_18_112.gif:../WebResources/aux_problem_icon_16");

setCasesView("aux_account", "regardingobjectid", false);

 I call here to setProblemsView, the same as setCasesView but not setting it as default (with the false at the end)

Xrm.Page.getControl(lookupFieldName).addCustomView(viewId, entityName, viewDisplayName, fetchXml, layoutXml, false);

But is not applying my filtered view when I choose problems Problems

function setCasesView(entityFieldName, lookupFieldName, resetSelection) {

    // use randomly generated GUID Id for the view
    var viewId = "{xxxxxxxx-xxxx-0000-9FB6-58E69E4C81AA}";

    var entityName = "incident";

    // give the custom view a name
    var viewDisplayName = "Cases in Account: " + accname + "";

    // find all cases where account is the account selected
    var fetchXml = ...
    var layoutXml = ...

    Xrm.Page.getControl(lookupFieldName).addCustomView(viewId, entityName, viewDisplayName, fetchXml, layoutXml, true);
    document.getElementById(lookupFieldName).setAttribute("disableViewPicker", "1");
}

Creating Opportunity with Silverlight

$
0
0

Hi all,

I'm trying to just create a simple shell Opportunity so I can further it once I know I can create one.  My issue is that I've been able to create Accounts and Contacts through similar code to the Opportunity.  The problem is the Opportunity throws an error in the EndCreate SOAP call.

private void btnCreateContact_Click(object sender, RoutedEventArgs e) { // Get IOrganizationService instance IOrganizationService myOrgService = SilverlightUtility.GetSoapService(); Entity myContact = new Entity(); myOpp.LogicalName = "opportunity"; // Create the AttributeCollection myOpp.Attributes = new AttributeCollection(); // Specify Last Name and First Name for the contact to be created KeyValuePair<string, object> oppName = new KeyValuePair<string, object>(); oppName.Key = "name"; oppName.Value = "CreateMe";myOpp.Attributes.Add(oppName); OrganizationRequest myOrgRequest = new OrganizationRequest(); myOrgRequest.RequestName = "Create"; // call the Create method myOrgService.BeginCreate(myOpp, myCreateHandler, myOrgService); }

public System.Guid EndCreate(System.IAsyncResult result) { object[] _args = new object[0]; System.Guid _result = ((System.Guid)(base.EndInvoke("Create", _args, result))); return _result; }

So I've followed the code by attaching the solution to a running instance in CRM and the only issue is that at the line "System.Guid _result = ((System.Guid)(base.EndInvoke("Create", _args, result)));" it gives me a very generic error message; even though the data in the call for opportunity is pretty well identical to the opportunity endInvoke.

So does anyone know if either I'm missing something? Should use some other method? Or know the reason/solution to why it is giving me an error while attempting to create the record?

Any help is really appreciated.


Silverlight CRM Context Best Practice

$
0
0

I have a Silverlight application that I use to schedule, update and cancel Service Activities. Every once in awhile I'll get strange behavior from certain users that I can't explain. For instance, every time a user edits an appointment subject they'll get an error saying the Scheduled Start time must be less than or equal to the Scheduled End time, even though it is and they did not adjust that.

My question is how to set up my Service Agent in Silverlight to connect to CRM.

Currently I am declaring the context once in my class:

public string orgUri = Connections.orgUri();
public string CRMUrl = Connections.crmUrl();

private mySrvc.myContext _myContext; 

public mySrvc.myContext MyContext  
{
   get
   {
      if (_myContext == null)
      {
         _myContext = new mySrvc.myContext(new Uri(string.Format("{0}/xrmservices/2011/organizationdata.svc/", CRMUrl), UriKind.Absolute));

         _myContext.IgnoreMissingProperties = true;
   
         _myContext.UseDefaultCredentials = true;
         _myContext.MergeOption = MergeOption.OverwriteChanges;
         _myContext.IgnoreResourceNotFoundException = true;
      }
      return _myContext;
   }
}

And in my update/Createfunctions I have the following to update/create for a retrievedSA that is populated:

MyContext.UpdateObject(retrievedSA);
MyContext.BeginSaveChanges(OnUpdatedServiceAppointmentCompleted, retrievedSA);
private void OnUpdatedServiceAppointmentCompleted(IAsyncResult result)
{
   try
   {
      MyContext.EndSaveChanges(result);


   }
}

Is this acceptable? It works but should I be creating a new context before every MyContext.UpdateObject / MyContext.AddToServiceAppointmentSet(retrievedSA)? Before I call the MyContext.UpdateObject should I always set _myContext = null?

For example:

_myContext = null;

MyContext.AddToServiceAppointmentSet(newSA);
MyContext.BeginSaveChanges(OnCreatedServiceAppointmentCompleted, newSA);

Just curious about this approach to see why I might be having the issues that I am having.

Thanks,

Tim

The system cannot find the file specified. (Exception from HRESULT: 0x80070002)

$
0
0

If i am using consoleapplication i am getting that project template under the solution.

But I failed to get custom webapplication into the specified solution.

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using EnvDTE; using EnvDTE80; using EnvDTE90; using EnvDTE100; using EnvDTE90a; using Extensibility; namespace TestWinForm { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { // string GetProjectTemplate( //string TemplateName, //string Language); // Solution2.getprojecttemplate("TestWebApplication.Zip|FrameworkVersion=4.5", "CSharp"); EnvDTE.Solution soln = System.Activator.CreateInstance(Type.GetTypeFromProgID("VisualStudio.Solution")) as EnvDTE.Solution; soln.DTE.MainWindow.Visible = true; EnvDTE80.Solution2 soln2 = soln as EnvDTE80.Solution2; // string csTemplatePath = @"C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\ProjectTemplatesCache\Web\CSharp\1033\TestWebApp.zip\MyTemplate.vstemplate"; string csTemplatePath = soln2.GetProjectTemplate("WebApplication.zip", @"Web\CSharp"); soln.AddFromTemplate(csTemplatePath, @"D:\SolutionTest2", "Foo", false); int x = soln.AddIns.Count; } } }



Karthik

how to get the name of a solution component in MS dynamics CRM

$
0
0

Hi,

  I trying to retrieve the list of default solution solution components. I don't find an attribute to get the names of solution components of default solution...

Following is the code I am using to retrieve solution components of default solution. This code is retrieving the solution component name but not the solution component logical name

 Entity solutionComponentEntity = new Entity("solutioncomponent");

         
  solutionComponentEntity["solutionid"] = "{fd140aaf-4df4-11dd-bd17-0019b9312238}" //default solution id


QueryExpression querySolutionComponent = new QueryExpression
            {
                EntityName = "solutioncomponent",
                ColumnSet = new ColumnSet("componenttype", "solutioncomponentid"),//specify whatever columns you want to retrieve
                Criteria = new FilterExpression()
            };
            querySolutionComponent.Criteria.AddCondition("solutionid", ConditionOperator.Equal, solutionComponentEntity["solutionid"]);

            EntityCollection querySolutionComponentResults = osp.RetrieveMultiple(querySolutionComponent);
            if (querySolutionComponentResults.Entities.Count > 0)
            {
                obj.rtb.AppendText("\t\n****Existing Solutions Components****\n");
                for (int i = 0; i < querySolutionComponentResults.Entities.Count; i++)
                {

                    if (true)//Here you need to do the filtering. I mean enities, webresources etc.
                    {
                        obj.rtb.AppendText("\n"+ querySolutionComponentResults.Entities[i]["componenttype"]);
                    }
                }
            }                     


Karthik


Entity created from action won't update

$
0
0

Hi Everyone,

I tried writing a simple code to utilize Actions in CRM 2013. The following code is registered on post-execute phase of a custom action:

EntityReference ent = localContext.PluginExecutionContext.OutputParameters["TaskEntity"] as EntityReference;
Entity task = service.Retrieve("task", ent.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet(true));
task["description"] = "test description";                
service.Update(feladat);

The custom action creates a task from an e-mail, then sets its entityreferece output parameter to the created task. The post plugin only adds description to the task (I know, I could have done this from the Action, it is just for testing purposes).

I am getting the reference and the task correctly, but it is not getting updated with the given description.

Any ideas what might cause the problem?

Regards,

Adam

MS CRM 2011 online - setting appointment's set regarding field automatically

$
0
0

I have a form where is a subgrid pointing to appointments. When I add appointment via the subgrid, I want to set the appointment's regarding field to populate automatically and pointing to originating entity.

function EventOnLoad()
{
    // is this a create form?
    if (Xrm.Page.ui.getFormType() == 1)
    {
        // The query string has the parent's id and object type code
        var queryStringObject = Xrm.Page.context.getQueryStringParameters();

        if (queryStringObject != null)
        {
            // let's go get the event's object type code.  
            var eventOTC = getEntityOTC('mpxrm_project'); 
			alert("stage 1");

            // If the parent is an event, then we need to set the regarding object.
            // NOTE: If this appointment was created from the left navigation _CreateFromType will be null and the code won't execute (which we want)
            if (eventOTC == queryStringObject._CreateFromType)
            {
                var eventName = "";
				alert("stage 2");
				var root = Xrm.Page.context.getClientUrl();
				alert(root);

                  var sQuery = root + "/XRMServices/2011/organizationData.svc/mpxrm_projectSet?$select=mpxrm_name,mpxrm_project_id&$filter=mpxrm_project_id eq guid'"+ queryStringObject._CreateFromId +"'";

            alert("stage 3");
				alert(sQuery);
				var request = new XMLHttpRequest();
                request.open("GET", sQuery, false); //sync
                request.setRequestHeader("Accept", "application/json");
                request.setRequestHeader("Content-Type", "application/json; charset=utf-8");
                request.send();

                var retrievedData = JSON.parse(request.responseText).d;
				alert("stage 4");
				alert(retrievedData);
                if (retrievedData.results[0].mpxrm_project_id != null)
                {
				alert("stage 5");
                    eventName = retrievedData.results[0].mpxrm_project_id;

                    var olookup = new Object();
                    olookup.id = queryStringObject._CreateFromId;
                    olookup.entityType = 'mpxrm_project';
                    olookup.name = eventName;
                    var olookupValue = new Array();
                    olookupValue[0] = olookup;

                    Xrm.Page.getAttribute('regardingobjectid').setValue(olookupValue);
                } 
            }
        }
    }
}

// This funtion gets the Object Type Code for any entity
function getEntityOTC(entityName)
{
    var lookupService = new RemoteCommand("LookupService", "RetrieveTypeCode");
    lookupService.SetParameter("entityName", entityName);

    var result = lookupService.Execute();
    if (result.Success && typeof result.ReturnValue == "number")
    {
        return result.ReturnValue;
    }
    else
    {
        return null;
    }
}

I managed to get this on alert("stage 4");. Then I managed to get this to alert(retrievedData); but with this i get answer undefined.

After that I get error message:

There was an error with this field's customizes event.
Field:window
Event:onload
Error: unable to get property 'results' of undefined or null reference

Any helps. This is working on another environment where only fieldnames and entity's name are different.

Javascript-only way of adding event and passing event context?

$
0
0

I'm faced with the daunting task of adding "on change" events to hundreds of fields, a large amount of which require passing the execution context.   I know that this is the way to add an "on change" event to a particular field:

Xrm.Page.data.entity.attributes.get('particularfield').addOnChange(functiontorun);

But I cannot seem to find a way to also pass any information from the control that calls the event without going through CRM and manually adding it via the web interface.  Is there a Javascript-only solution for this?  I tried traversing arguments[0] but found that arguments[0].getContext.getName() is always equal to "".  I've search all over and haven't found an answer to this yet.

We are using CRM 2011 UR11.

CRM2013 / window.open / problem

$
0
0

We have developed a Silverlight application in CRM2011 .
In this application, a Silverlight DataGrid is included. When the user double-clicks on the DataRow, a new 
window (detail-data) opens.
Uri-Pattern: 

"main.aspx?id={0}&etn={1}&pagetype=entityrecord"

Opening the detailed dataset doesn't work in CRM2013 in the same way as in CRM2011.
Instead of the detailed data(popup) the Silverlight application is shown.

function OpenCrmForm(url) {
    /// <summary>Open CrmUrl(DetailData) in new window</summary>
    /// <param name="path" type="string"></param>
    if (!url) return;

    var _Uri = (Mscrm != null && Mscrm.CrmUri != null)
                    ? Mscrm.CrmUri.create(url).toString()
                    : Xrm.Page.context.prependOrgName(url);
    var _getUri = function (uri) {
        return (Custom.MyContext.isAvailable)
                ? Xrm.Page.context.getClientUrl() +"/" + uri
                : uri
    };

    var crmUri = _getUri(_Uri);

    window.open(crmUri, "", "status=0,resizable=1,width=1000px,height=600px");
    //Xrm.Utility.openEntityForm("account", "75b1ffef-5224-e311-93f8-0050568e7857");
    //My.WindowOpen(_getUri(_Uri));
}

How can I solve this problem?

Thank you in advance,

Sven Honert


linq to sql using crm early bound classes

$
0
0

Hi all,

i am using subselect query for  salesorder entity has new_sefer field. My query is

(from d in context.SalesOrderDetailSetwhere context.SalesOrderSet.Where(s => s.new_Sefer.Id==Id).Select(i => i.SalesOrderId).Contains(d.SalesOrderId.Id)select d).Count();

it throws this exception : "Invalid 'where' condition. An entity member is invoking an invalid property or method."

 I have also question about subselect queries

how can i write this sql query using linq to sql

select count(*)from salesorderdetail where salesorderId in(select salesorderId from salesorder where new_sefer ='750FEB6F-F742-E311-8F56-000C29F3049E')


Any help appreciated :-)


Viewing all 465 articles
Browse latest View live


Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>