Mark an appointment as Scheduled in CRM 2011 - dynamics-crm-2011

I have a Silverlight application that creates an appointment but since it's not marked as "Scheduled" it will not show up in the Calendar. I am using the SOAP service for this, and here is some sample code that fires on a button click that creates an appointment but it does not show up in the Calendar:
TestCommand = new RelayCommand(() =>
{
var soapCtx = ServiceHelper.GetSingletonSoapService();
var activityId = Guid.NewGuid();
var appt = new Entity()
{
Id = activityId,
LogicalName = "appointment"
};
appt["activityid"] = activityId;
appt["scheduledstart"] = DateTime.Now.Date;
appt["scheduledend"] = DateTime.Now.Date.AddHours(1);
appt["description"] = "Test 1 2 3";
appt["subject"] = "Test Command Button Appointment";
appt["location"] = "Location 1 2 3";
soapCtx.BeginCreate(appt, ar =>
{
var response = soapCtx.EndCreate(ar);
var bookRequest = new OrganizationRequest();
bookRequest.RequestName = "Book";
bookRequest["Target"] = appt;
soapCtx.BeginExecute(bookRequest,
new AsyncCallback(OnBookRequestedCompleted), soapCtx);
}, null);
});
void OnBookRequestedCompleted(IAsyncResult ar)
{
var soapCtx = (IOrganizationService)ar.AsyncState;
var response = soapCtx.EndExecute(ar);
}
I keep getting "NotFound" exception in the OnBookRequestedCompleted method. Is there a different way of doing this?

Use Fiddler to debug your HTTP request/response and this will give you details about the 'Not Found' exception.

You should not be setting the ActivityId field it is returned by the BookRequest. if BookResponse.ValidationResult.ValidationSuccess == true, apptId = BookResponse.ValidationResult.ActivityId
You need to call SetStateRequest with the id returned by the BookRequest to set the state to Scheduled
For example:
SetStateRequest state = new SetStateRequest();
state.State = new OptionSetValue(3); // Scheduled
state.Status = new OptionSetValue(5); // Busy
state.EntityMoniker = new EntityReference("appointment", apptId);
SetStateResponse stateSet = (SetStateResponse)this.orgService.Execute(state);

Related

How add some content to Mockito mocked Pageable class?

I want testing pagination.
I want add some fake content to my Page mocked class.
How can I?
This is my test (refactoring it from a previous test), I'm using Junit5 and of course I get that No valut at JSON path $.content.lenght() and so on (of course, Page is empty):
/**
* index
*/
#WithMockUser("username")
#Test
void testCanIndex() throws Exception {
var transaction01 = BankAccountTransactionsControllerTest.validBankAccountTransactionsEntity(1L,
new BigDecimal(99.99), "First Transaction");
var transaction02 = BankAccountTransactionsControllerTest.validBankAccountTransactionsEntity(2L,
new BigDecimal(150.00), "Second Transaction");
var result = new ArrayList<BankAccountTransactionsEntity>();
result.add(transaction01);
result.add(transaction02);
Page<BankAccountTransactionsEntity> items = mock(Page.class);
when(bankAccountTransactionsService.index(0, 1, "id", "desc")).thenReturn(items);
mvc.perform(get("/api/v1/bank-account-transactions/")).andExpect(status().isOk())
.andExpect(jsonPath("$.content.length()", is(2))).andExpect(jsonPath("$[0].id", is(1)))
.andExpect(jsonPath("$.content[1].id", is(2))).andExpect(jsonPath("$[0].amount", is(new BigDecimal(99.99))))
.andExpect(jsonPath("$.content[1].amount", is(150)))
.andExpect(jsonPath("$.content[0].purpose", is("First Transaction")))
.andExpect(jsonPath("$.content[1].purpose", is("Second Transaction")))
.andExpect(jsonPath("$.content[0]", Matchers.hasKey("transactionDate")))
.andExpect(jsonPath("$.content[1]", Matchers.hasKey("transactionDate")));
}
Edit
I made a change, calling directly a PageImpl
#Test
void testCanIndex() throws Exception {
var transaction01 = BankAccountTransactionsControllerTest.validBankAccountTransactionsEntity(1L,
new BigDecimal(99.99), "First Transaction");
var transaction02 = BankAccountTransactionsControllerTest.validBankAccountTransactionsEntity(2L,
new BigDecimal(150.00), "Second Transaction");
var result = new ArrayList<BankAccountTransactionsEntity>();
result.add(transaction01);
result.add(transaction02);
Page<BankAccountTransactionsEntity> items = new PageImpl<>(result);
when(bankAccountTransactionsService.index(0, 1, "id", "desc")).thenReturn(items);
mvc.perform(get("/api/v1/bank-account-transactions/")).andExpect(status().isOk())
.andExpect(jsonPath("$.content.length()", is(2)));
}
But body returned is empty
MockHttpServletRequest:
HTTP Method = GET
Request URI = /api/v1/bank-account-transactions/
Parameters = {}
Headers = []
Body = null
Session Attrs = {}
Handler:
Type = com.bitbank.controllers.BankAccountTransactionsController
Method = com.bitbank.controllers.BankAccountTransactionsController#index(Integer, Integer, String, String)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []

Upload CSV to BigQuery in C#

Basically what I want to do is to submit a job to BigQuery (Asynchronously), check job status after and print out corresponding status info or error info. I created a frame as below. But I need help on:
GoogleApiException: Not Found Job exception when "BigQueryService.Jobs.Get(jobReference.ProjectId, jobReference.JobId).Execute()" was called. My gut is that the job wasn't submit correctly, but I don't know how to do it correctly.
How should I handle GoogleApiExceptions?
Firt step: create a Job (uploading CSV file into BigQuery), return the JobReference
TableReference DestTable = new TableReference();
DestTable.ProjectId = project;
DestTable.DatasetId = dataset;
DestTable.TableId = tableId;
Job Job = new Job();
JobConfiguration Config = new JobConfiguration();
JobConfigurationLoad ConfigLoad = new JobConfigurationLoad();
ConfigLoad.Schema = schema;
ConfigLoad.DestinationTable = DestTable;
ConfigLoad.Encoding = "ISO-8859-1";
ConfigLoad.CreateDisposition = "CREATE_IF_NEEDED";
ConfigLoad.WriteDisposition = createDisposition;
ConfigLoad.FieldDelimiter = delimiter.ToString();
ConfigLoad.AllowJaggedRows = true;
Config.Load = ConfigLoad;
Job.Configuration = Config;
//set job reference (mainly job id)
JobReference JobRef = new JobReference();
JobRef.JobId = GenerateJobID("Upload");
JobRef.ProjectId = project;
Job.JobReference = JobRef;
using(FileStream fileStream = new FileStream(filePath,FileMode.Open)){
var JobInfo = BigQueryService.Jobs.Insert(Job,project,fileStream,"text/csv");//application/octet-stream
JobInfo.UploadAsync();
Console.WriteLine(JobInfo.GetProgress().Status.ToString());
}
return JobRef;
Then, Pull Job status using projectId and jobId in the returned JobReference from the first step:
while (true)
{
pollJob = BigQueryService.Jobs.Get(jobReference.ProjectId, jobReference.JobId).Execute();
i = 0;
Console.WriteLine("Job status" + jobReference.JobId + ": " + pollJob.Status.State);
if (pollJob.Status.State.Equals("DONE"))
{
return pollJob;
}
// Pause execution for pauseSeconds before polling job status again,
// to reduce unnecessary calls to the BigQuery API and lower overall
// application bandwidth.
Thread.Sleep(pauseSeconds * 1000);
}
There's hardly any useful sample code out there showing how to upload a local CSV file to Bigquery table. I eventually get something to work. It might not be the best solution, but it at least works. It's open to any improvement.
private JobReference JobUpload(string project, string dataset, string tableId, string filePath, TableSchema schema, string createDisposition, char delimiter)
{
TableReference DestTable = new TableReference();
DestTable.ProjectId = project;
DestTable.DatasetId = dataset;
DestTable.TableId = tableId;
Job Job = new Job();
JobConfiguration Config = new JobConfiguration();
JobConfigurationLoad ConfigLoad = new JobConfigurationLoad();
ConfigLoad.Schema = schema;
ConfigLoad.DestinationTable = DestTable;
ConfigLoad.Encoding = "ISO-8859-1";
ConfigLoad.CreateDisposition = "CREATE_IF_NEEDED";
ConfigLoad.WriteDisposition = createDisposition;
ConfigLoad.FieldDelimiter = delimiter.ToString();
ConfigLoad.AllowJaggedRows = true;
ConfigLoad.SourceFormat = "CSV";
Config.Load = ConfigLoad;
Job.Configuration = Config;
//set job reference (mainly job id)
JobReference JobRef = new JobReference();
JobRef.JobId = GenerateJobID("Upload");
JobRef.ProjectId = project;
Job.JobReference = JobRef;
using(FileStream fileStream = new FileStream(filePath,FileMode.Open)){
JobsResource.InsertMediaUpload InsertMediaUpload = new JobsResource.InsertMediaUpload(BigQueryService,Job,Job.JobReference.ProjectId,fileStream,"application/octet-stream");
var JobInfo = InsertMediaUpload.UploadAsync();
Console.WriteLine(JobInfo.Status);
while (!JobInfo.IsCompleted)
{
//wait for the job to be activated and run
Console.WriteLine(JobInfo.Status);
}
}
return JobRef;
}
After this, you can actually use the returned JobRef to pull job status, almost the same as we do with Java API:
while(true)
{
PollJob = BigQueryService.Jobs.Get(jobReference.ProjectId, jobReference.JobId).Execute();
Console.WriteLine("Job status" + jobReference.JobId + ": " + PollJob.Status.State);
if (PollJob.Status.State.Equals("DONE"))
{
return PollJob;
}
}

SearchRequest and SearchReponse Classes are not present for silverlight application in CRM 2011?

i want to search all the available time slots for given resources in CRM 2011. Now CRM 2011 sdk provices a sammple for that in console application which is working fine but i want to do the same thing in silverlight applciation. In my silverlight application i am unable to find the SearchRequest and SearchReponse Classes.
Can any one help me how to do this in silverlight applciation?
First prepare the AppointmentRequest object
private void checkButton_Click(object sender, RoutedEventArgs e)
{
AppointmentRequest appReq = new AppointmentRequest
{
Objectives = new ObservableCollection<ObjectiveRelation>(),
RequiredResources = new ObservableCollection<RequiredResource>(),
AppointmentsToIgnore = new ObservableCollection<AppointmentsToIgnore>(),
Constraints = new ObservableCollection<ConstraintRelation>(),
Sites = new ObservableCollection<Guid>(),
Duration = 60,
Direction = SearchDirection.Forward,
NumberOfResults = 5,
ServiceId = new Guid("DD535FD0-F84B-E111-8F2F-00505688095F"),
SearchWindowStart = DateTime.UtcNow,
SearchWindowEnd = DateTime.UtcNow.AddDays(7.0),
AnchorOffset = 300
};
OrganizationRequest req = new OrganizationRequest() { RequestName = "Search" };
req["AppointmentRequest"] = appReq;
IOrganizationService service = SilverlightUtility.GetSoapService();
service.BeginExecute(req, new AsyncCallback(GetAppReqResult), service);
}
Following is the Asynchromus callback function
private void GetAppReqResult(IAsyncResult res)
{
try
{
OrganizationResponse resp =
((IOrganizationService)res.AsyncState).EndExecute(res);
SearchResults results = (SearchResults)resp["SearchResults"];
this.Dispatcher.BeginInvoke(() => ProcessAppointments(results));
}
catch (Exception)
{
MessageBox.Show("Error Occurred");
}
}
results object will contains the all possible time slots for an appointment request object passed.
Hope this help to the people like me

Subsonic 3 Saving into different databases

Using subsonic 3 I have a project with a bit of a weird scenario. I have a .net windows service that needs to connect to a master database which stores connections to other database servers and also a set of tables for processing automated SMS messages. Then I have identical databases on the other servers (the connection string table is empty on the other db's) that handle the messages for other applications.
So, subsonic can call to all of the DB's just fine using the connection string/provider name options.
public static List<SMSRequestWithResponseList> SMSRequestListGetAll(string applicationName)
{
string connStr = GetConnectionStringByApplicationName(applicationName);
List<SMSRequestWithResponseList> response = new List<SMSRequestWithResponseList>();
List<DAL.CDYNESMSRequest> lst = DAL.CDYNESMSRequest.All(connStr, providerName).ToList();
foreach (DAL.CDYNESMSRequest mitm in lst)
{
SMSRequestWithResponseList itm = new SMSRequestWithResponseList(mitm, mitm.CDYNESMSResponses.ToList(), string.Empty);
response.Add(itm);
}
return response;
}
The issue is saving...Insert seems to be working.
DAL.CDYNESMSRequest itm = new DAL.CDYNESMSRequest(connStr, providerName).;
itm.KeyCode = KeyCode;
itm.ApplicationName = ApplicationName;
itm.BatchTransaction = BatchTransaction;
itm.AssignedDID = GetParameter("AssignedDID");
itm.PhoneNumber = PhoneNumber;
itm.MessageDetail = MessageText;
itm.MessageCancelled = false;
itm.MessageQueued = false;
itm.MessageSent = false;
itm.IsImmediate = SendImmediate;
itm.InQueue = false;
itm.ScheduledDateTime = ScheduledDateTime;
itm.CreateDT = dt;
itm.ModifiedDT = dt;
itm.Save();
But it doesn't seem to want to update...
DAL.CDYNESMSRequest itm = DAL.CDYNESMSRequest.SingleOrDefault(x => x.RequestID == requestID, connStr, providerName);
if (itm != null)
{
itm.MessageID = messageGUID;
itm.MessageCancelled = messageCancelled;
itm.MessageQueued = messageQueued;
itm.ReferenceID = messageReferenceID;
itm.MessageSent = messageSent;
if (messageSentDT < new DateTime(1753, 1, 1, 0, 0, 0))
itm.MessageSentDT = null;
else
itm.MessageSentDT = messageSentDT;
itm.MessageSMSError = messageSMSError;
itm.ModifiedDT = dt;
itm.Save();
}
I'm calling using the connection string from the correct database but it doesn't update the record.
If I'm saving it incorrectly please let me know. I did try to create a new provider and set it on the save but it barked at me saying it already had an open connection.
Thanks!
Don't use ActiveRecord pattern, but the SimpleRepository which allows you to setup multiple repos and you can specify a connectionstring per repo.
// not sure if this is the right constructor or if it's providerName, connectionString
var repo1 = new SimpleRepository(connectionString1, providerName);
var repo2 = new SimpleRepository(connectionString2, providerName);
var item = repo1.Single<Product>(1);
if (repo2.Exists<Product>(x => x.Id == item.Id))
repo2.Update(item);
else
repo2.Add(item);

How to get current Item in Custom Form Action Sharepoint Designer

On custom edit page of list item, I want to do the following
- On clicking Form Action Hyperlink [DataView Control], custom form action will fire to update
a item hidden field [Status].
I already tried the following
- Passing #ID to the work flow but didnt work
- Create a duplicate ID column and updated it with the ID on Item Creation. and then tried to access in "Update Item in" Action but getting "An unexpected error has occurred" while running it.
[Remember i can only use sharepoint designer]
Try to use these javascript functions:
function GetQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
}
function GetCurrentItem() {
var itemId = GetQueryVariable("ID");
try {
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle('list-title');
this.currItem = list.getItemById(itemId);
context.load(currItem);
context.executeQueryAsync(Function.createDelegate(this, this.funcSuccess), Function.createDelegate(this, this.funcFailed));
}
catch (e) {
alert(e);
}
}
function funcSuccess() {}
function funcFailed() {}

Resources