Update ticket Field in zoho desk - zoho

I'm a beginner at using Custom Function on the Zoho desk. I'm trying to update a field in the ticket template.
I have 2 fields in the ticket template [KM, COST]. The cost should equal 2*KM. For example, if KM = 100, then Cost = 200.
I created a workflow that works if the KM is updated and attached the following custom function code, but the field doesn't update.
orgId = "718524341";
response = zoho.desk.getRecordById(orgId,"tickets",TicketID,"zohodesk");
cid = response.get('cf_km');
km_cost = cid * 2;
zoho.desk.update(orgId,"tickets",TicketID,{"cf":{"cf_cost":km_cost}},"zohodesk");

The correct API Name for the tickets module in zoho desk is Tickets.
If you still can't get it to work, then try executing the function independent of the workflow with fixed parameters. Make sure to do info response and post the output here.

Related

Web.Content calling API service and merging pages with List.Transform started to fail

I created PowerBI report which which is connecting to data source via API service. Returning json contains thousands of entities. API service is called via Web.Content function. API service returns always total record count and so we are able to calculate nr. of pages which has to be called to obtain whole dataset. This report is displaying data from our servicedesk app, which is deployed on many servers and for many customers and use Query parameters to connect to any of these servers.
Detail of Power query is below.
Why am I writing here. This report was working without any issue more than 1,5 year but on August 17th one of servers start causing erros in step Pages where are some random lines (pages) with errors - see attached picture labeled "Errors in step Pages". and this is reason that next step Entities (List.Union) in query is stopping refresh and generate errors with message:
Expression.Error: We cannot apply field access to the type List. Details: Value=[List] Key=requests
What is notable
API service si returning records in the same order but faulty lists are random when calling with same parameters
some times is refresh without any error
The same power query called on another server is working correctly , problem is only with one specific server.
This problem started without notice on the most important server after 1,5 year without any problem.
Here is full text power of query for this main source, which is used later in other queries to extract all necessary data. Json is really complicated and I extract from it list of requests, list of solvers, list of solver groups,.... and this base query and its output is input for many referenced queries.
Errors in step Pages
let
BaseAPIUrl = apiurl&"apiservice?", /*apiurl is parameter - name of server e.g. https://xxxx.xxxxxx.sk/ */
EntitiesPerPage = RecordsPerPage, /*RecordsPerPage is parameter and defines nr. of record per page - we used as optimum 200-400 record per pages, but is working also with 4000 record per page*/
ApiToken = FnApiToken(), /*this function is returning apitoken value which is returning value of another api service apiurl&"api/auth/login", which use username and password in body of call to get apitoken */
GetJson = (QParm) => /*definiton general function to get data from data source*/
let
Options =
[ Query= QParm,
Headers=
[
Accept="application/json",
ApiKeyName="apitoken",
Authorization=ApiToken
]
],
RawData = Web.Contents(BaseAPIUrl, Options),
Json = Json.Document(RawData)
in Json,
GetEntityCount = () => /*one times called function to get nr of records using GetJson, which is returned as a part of each call*/
let
QParm = [pp="1", pg="1" ],
Json = GetJson(QParm),
Count = Json[totalRecord]
in
Count,
GetPage = (Index) => /*repeatadly called function to get each page of json using GetJson*/
let
PageNr = Text.From(Index+1),
PerPage = Text.From(EntitiesPerPage),
QParm = [pg = PageNr, pp=PerPage],
Json = GetJson(QParm),
Value = Json[data][requests]
in Value,
EntityCount = List.Max({ EntitiesPerPage, GetEntityCount() }), /*setup of nr. of records to variable*/
PageCount = Number.RoundUp(EntityCount / EntitiesPerPage), /*setup of nr. of pages */
PageIndices = { 0 .. PageCount - 1 },
Pages = List.Transform(PageIndices, each GetPage(_) /*Function.InvokeAfter(()=>GetPage(_),#duration(0,0,0,1))*/), /*here we call for each page GetJson function to get whole dataset - there is in comment test with delay between getpages but was not neccessary*/
Entities = List.Union(Pages),
Table = Table.FromList(Entities, Splitter.SplitByNothing(), null, null, ExtraValues.Error)
I also tried another way of appending pages to list using List.Generate. This is also bringing random errors in list but
it is bringing possibility to transform to table in contrast with original way with using List.Transform, but other referenced queries are failing and contains on the last row errors
When I am exploring content of faulty page/list extracting it via Add as New Query there are always all record without any fail.....
Source = List.Generate( /*another way to generate list of all pages*/
() => [Page = 0, ReqPageData = GetPage(0) ],
each [Page] < PageCount,
each [ReqPageData = GetPage( [Page] ),
Page = [Page] + 1 ],
each [ReqPageData]
),
#"Converted to Table" = Table.FromList(Source, Splitter.SplitByNothing(), null, null, ExtraValues.Error), /*here i am able to generate table from list in contrast when is used List.Generate*/
#"Expanded Column1" = Table.ExpandListColumn(#"Converted to Table", "Column1"), /*here aj can expand list to column*/
#"Removed Errors" = Table.RemoveRowsWithErrors(#"Expanded Column1", {"Column1"}) /*here i try to exclude errors, but i dont know what happend and which records (if any) are excluded*/
Extracting errored page
and finnaly I am tottaly clueless not able to find the cause of this behavior on this specific server. I tested to call pages which are errored via POSTMAN, I discused this issue with author of API service and He also tried to call this API service with all parameters but server is returning every page OK, only Power query is not able to List.Transform ...
I will be grateful and appreciate any tips or advice or if somebody solved the same issue in the past ....
Kuby
No, each error line of list in step List.Transform coud by extracted as new query and there are all records from one page OK. hmmmm
Finnaly, problem described in this issue was caused by "corrupted" content of returning json. The provider of core system informed me that they found bug and after fixing on the side of servisdesk is everything OK again. I tried to find problem in Power query and problem was in servisdesk. :(

Max number of classroom id retrieved

I have aprox 520 classrooms archived in my account, if I try to select them with
var courseList = Classroom.Courses.list({"courseStates":["ARCHIVED"]}).courses;
I get only 300 of them. Is this normal?
How can I select them all? Actually I'm writing a script to delete the oldest, but if I can't retrieve them, I can't delete them.
I understand that you got so many courses that the Courses.list() response is splitted in separate pages. In that case you can very easily navigate them by using tokens. First of all, make sure that you specify the pageSize in your request. That would set the desired amount of responses per page. Please keep in mind that the server may return fewer than the specified number of results, as it declared on the docs. In case that your response got divided into pages, the response would include the nextPageToken field. Then, to obtain the rest of courses, you have to repeat your request including that nextPageToken into the pageToken property. Please don't hesitate to ask me any doubt about this approach.
Thanks a lot Jaques, I found the solution:
var parametri = {"courseStates": "ARCHIVED"};
var page = Classroom.Courses.list(parametri);
var listaClassi = page.courses;
if (page.nextPageToken !== '') {
parametri.pageToken = page.nextPageToken;
page = Classroom.Courses.list(parametri);
listaClassi = listaClassi.concat(page.courses);
}
Anyway, I didn't need to change the pageSize, nor I found any tutorial about it.

Plugin performance in Microsoft Dynamics CRM 2013/2015

Time to leave the shy mode behind and make my first post on stackoverflow.
After doing loads of research (plugins, performance, indexes, types of update, friends) and after trying several approaches I was unable to find a proper answer/solution.
So if possible I would like to get your feedback/help in a Microsoft Dynamics CRM 2013/2015 plugin performance issue (or coding technique)
Scenario:
Microsoft Dynamics CRM 2013/2015
2 Entities with Relationship 1:N
EntityA
EntityB
EntityB has the following columns:
Id | EntityAId | ColumnDemoX (decimal) | ColumnDemoY (currency)
Entity A has: 500 records
Entity B has: 150 records per each Entity A record. So 500*150 = 75000 records.
Objective:
Create a Post Entity A Plugin Update to "mimic" the following SQL command
Update EntityB
Set ColumnDemoX = (some quantity), ColumnDemoY = (some quantity) * (some value)
Where EntityAId = (some id)
One approach could be:
using (var serviceContext = new XrmServiceContext(service))
{
var query = from a in serviceContext.EntityASet
where a.EntityAId.Equals(someId)
select a;
foreach (EntityA entA in query)
{
entA.ColumnDemoX = (some quantity);
serviceContext.UpdateObject(entA);
}
serviceContext.SaveChanges();
}
Problem:
The foreach for 150 records in the post plugin update will take 20 secs or more.
While the
Update EntityB Set ColumnDemoX = (some quantity), ColumnDemoY = (some quantity) * (some value) Where EntityAId = (some id)
it will take 0.00001 secs
Any suggestion/solution?
Thank you all for reading.
H
You can use the ExecuteMultipleRequest, when you iterate the 150 entities, save the entities you need to update and after that call the request. If you do this, you only call the service once, that's very good for the perfomance.
If your process could be bigger and bigger, then you should think making it asynchronous as a plug-in or a custom activity workflow.
This is an example:
// Create an ExecuteMultipleRequest object.
requestWithResults = new ExecuteMultipleRequest()
{
// Assign settings that define execution behavior: continue on error, return responses.
Settings = new ExecuteMultipleSettings()
{
ContinueOnError = false,
ReturnResponses = true
},
// Create an empty organization request collection.
Requests = new OrganizationRequestCollection()
};
// Add a UpdateRequest for each entity to the request collection.
foreach (var entity in input.Entities)
{
UpdateRequest updateRequest = new UpdateRequest { Target = entity };
requestWithResults.Requests.Add(updateRequest);
}
// Execute all the requests in the request collection using a single web method call.
ExecuteMultipleResponse responseWithResults =
(ExecuteMultipleResponse)_serviceProxy.Execute(requestWithResults);
Few solutions comes to mind but I don't think they will please you...
Is this really a problem ? Yes it's slow and database update can be so much faster. However if you can have it as a background process (asynchronous), you'll have your numbers anyway. Is it really a "I need this numbers in the next second as soon as I click or business will go down" situation ?
It can be a reason to ditch 2013. In CRM 2015 you can use a calculated field. If you need this numbers only to show up in forms (eg. you don't use them in reporting), you could also do it in javascript.
Warning this is for the desesperate call. If you really need your update to be synchronous, immediate, you can't use calculated fields, you really know what your doing etc... Why not do it directly in the database? I know this is a very bad advice. There are a lot of reason not to do it this way (you can read a few here). It's unsupported and if you do something wrong it could go really bad. But if your real situation is as simple as your example (just a calculated field, no entity creation, no relation modification), you could do it this way. You'll have to consider many things: you won't have any audit on the fields, no security, caching issues, no modified by, etc. Actually I pretty much advise against this solution.
1 - Put it this logic to async workflow.
OR
2 - Don't use
serviceContext.UpdateObject(entA);
serviceContext.SaveChanges();.
Get all the records (150) from post stage update the fields and ExecuteMultipleRequest to update crm records in one time.
Don't send update request for each and every record

Grab System Created Values CRM 2011

I'm facing a problem when I try to grab the Extended Amount Attribute inside the Opportunity Product Line Entity.
As follows my requirements are that upon creation of a an Opportunity Product Line I have a post-create plugin on it which applies a discount onto the extended amount and creates another line, with the new discounted extended amount. When I try to output the value on another field just to check what it gets, I keep getting 0 strangley. My code is as follows:
// Part where I grab the value
Entity entity = (Entity)context.InputParameters["Target"];
Money extenedAmount = (Money)entity["baseamount"];
//Create new line
Entity oppportunity_product = new Entity("opportunityproduct");
oppportunity_product["manualdiscountamount"] = extenedAmount;
service.Create(oppportunity_product);
Is it even possible to grab the amount? Would really much appreciate if someone could help me out here. Thanks in advanace.
After creation, you want to add a post image. Then reference the post image instead of the target.
if (context.PostEntityImages.Contains("PostImage") &&
context.PostEntityImages["PostImage"] is Entity)
{
postMessageImage = (Entity)context.PostEntityImages["PostImage"];
}
else
{
throw new Exception("No Post Image Entity in Plugin Context for Message");
}

How do I retrieve just recurring event masters using Exchange Web services?

I'm using a CalendarItemType view to retrieve calendar items. The only items I care about are those that I've created and I know that they are all weekly recurring items. I'm able to get each individual occurrence and, from any one of them the recurring master item, but I'd like to narrow the scope of my search to just those items that would match my pattern.
I've trying using the Restriction property on the FindItemType to specify a NotEqualTo restriction with a null constant for calenderRecurrenceId. This caused my request to time out. So far I've been unable to load the recurrences with the FindItemType at all and need to use a subsequent GetItemType call when I find an event that is an occurence in a recurring series.
Here's the code that I'm starting with. The code needs to work with both Exchange 2007 and Exchange 2010.
var findItemRequest = new FindItemType();
findItemRequest.ParentFolderIds = new DistinguishedFolderIdType[]
{
new DistinguishedFolderIdType()
};
((DistinguishedFolderIdType)findItemequest.ParentFolderIds[0]).Id = DistinguishedFolderIdNameType.calendar;
findItemRequest.Traversal = ItemQueryTraversalType.Shallow;
var itemShapeDefinition = new ItemResponseShapeType(
{
BaseShape = DefaultShapeNamesType.AllProperties;
}
findItemRequest.Item = calenderView;
findItemRequest.ItemShape = itemShapeDefinition;
var findItemResponse = this.esb.FindItem( findItemRequest );
Also, if you know of any good source of examples (beyond the ones in MSDN), I'd welcome them. I'm picking up someone else's code in an emergency and trying to learn Exchange Web Services on the fly.
Maybe I'm misunderstanding you, in which case I apologize.
You do NOT use the CalendarView - you use the normal IndexedPageItemView if all you want is Master Recurring Calendar items.
You use the CalendarView to expand the recurrences to individual items. However the compromise with CalendarView is NO restrictions are permitted besides Start and End Date. None.
You can search for a RecurrenceMaster by using the recurrence PidLid with an ExtendedPropertyDefinition. This works because, according to their documentation, "this property must not exist on single instance calendar items."
https://msdn.microsoft.com/en-us/library/cc842017.aspx
// https://msdn.microsoft.com/en-us/library/cc842017.aspx
ExtendedPropertyDefinition apptType = new ExtendedPropertyDefinition(
DefaultExtendedPropertySet.Appointment,
0x00008216, //PidLidAppointmentRecur
MapiPropertyType.Binary);
var restriction = new SearchFilter.Exists(apptType);
var iView = new ItemView(10);
var found = folder.FindItems(restriction, iView);
I just confirmed this works, today, when revisiting some old code that works with Office365 EWS in the cloud.
Found only property you need is RecurrenceStart property. Because EWS has limitations it is not possible to use all properties in restriction. This one working as expected.
Reference: Find master recurring appointments
You can create custom searchfilters. If you search from specific startdate OR isRecurring property you have most easy way...(SearchItems returns recurring masters)
List<SearchFilter> searchFilterCollection = new List<SearchFilter>();
SearchFilter.IsGreaterThanOrEqualTo startDatumFilter = new SearchFilter.IsGreaterThanOrEqualTo(AppointmentSchema.Start, new DateTime(2012, 9, 16));
SearchFilter.IsEqualTo masterRecurringFilter = new SearchFilter.IsEqualTo(AppointmentSchema.IsRecurring, true);
searchFilterCollection.Add(startDatumFilter);
searchFilterCollection.Add(masterRecurringFilter);
SearchFilter finalFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, searchFilterCollection);
ItemView itemView = new ItemView(100000);
itemView.PropertySet = new PropertySet(BasePropertySet.FirstClassProperties, AppointmentSchema.AppointmentType);
FindItemsResults<Item> items = _service.FindItems(WellKnownFolderName.Calendar, finalFilter, itemView);

Resources