Server Date and Time on Action In SSJS - xpages

I want your help to get Server Date and Time when action is performed. e.g. Submit, Approve, Reject etc
var myDoc:NotesDocument = data_source.getDocument().
I have tried following but failed to get server time this always stores client date and time specially when its executed on client.
myDoc.replaceItemValue("ApprovedOn", session.createDateTime(#Now());
following generates error / exceptions.
myDoc.replaceItemValue("ApprovedOn", #Now());
OR
var curr_Date = #Now();
myDoc.replaceItemValue("ApprovedOn", curr_Date);
OR
var mDt:NotesDateTime = session.createDateTime(#Now());
myDoc.replaceItemValue("ApprovedOn", mDt.toJavaDate());
Error while executing JavaScript action expression
Script interpreter error, line=168, col=17: [TypeError] Exception
occurred calling method NotesDocument.replaceItemValue(string, Date)
null
Please guide me how can I store current server date in a date and time field when any action is performed. Thanks for your time and efforts.

AFAIK, SSJS can only run within the XPages runtime. For an XPages application accessed via a browser, the XPages runtime sits on top of the HTTP task on the server, so the date and time would be the server's. (That's why I asked the question above).
For setting a field value with the core Domino API, you need to pass a NotesDateTime. The NotesDocument SSJS class (mapping to the underlying Java Document class) doesn't allow you to pass a Java date. OpenNTF Domino API does allow you to pass a Java date and auto-converts the value.
Best approach for XPiNC (this came from Serdar Basegmez, I can't take credit) is access a server-based database in SSJS, call createDocument() method and access it's created date. In the getDatabase() method you'll have to explicitly name a server. This will have a performance impact, because XPiNC is running locally, so you're connecting from local to another server, but will work.

Related

Best practice for connections to CRM in web application

am sorry if this question will be a bit to broad but if this is question about normal ASP.NET MVC 5 Owin based application with default connection to MSSQL server i would not have such hard time but we use CRM as our database.
Ok as i mention am working on ASP.NET MVC5 application and am having hard time finding what is the best practice to create, keep open and to close connection to Dynamics CRM 365?
I found some many posts and blogs but everyone pulling on his side of the road.
Some say it's better for every request to open new connection in using statement so it could be closed right away (that's sounds good but it's a possible that requests will be slow because on every request it needs to open new connection to CRM).
Some say it' better to make singleton object on application scope, keep it open during application lifetime and reuse it on every request.
Normally i would use OrganizationServiceProxy in some simple console app but in this case am not sure should i use OrganizationServiceProxy or CrmServiceClient or something else?
If anyone have or had some similar problem, any hint would be great.
UPDATE:
#Nicknow
I downloaded SDK from SDK 365 and am using this dll-s.
Microsoft.Xrm.Sdk.dll, Microsoft.Crm.Sdk.Proxy.dll, Microsoft.Xrm.Tooling.Connector.dll and Microsoft.IdentityModel.Clients.ActiveDirectory.dll.
You mention
Microsoft.CrmSdk.XrmTooling.CoreAssembly 8.2.0.5.
if am correct this nuget package use official assembly that i downloaded, or there are some modification to this package?
About that test
proof test
if i got it right, no matter if i use using statement, implement Dispose() method or just use static class on application scope for a lifetime of application i will allways get same instance (If i use default settings RequireNewInstance=false)?
For code simplicity, I usually create a static class (a singleton could be used too, but would usually be overkill) to return a CrmServiceClient object. That way my code is not littered with new CrmServiceClient calls should I want to change anything about how the connection is being made.
So it would be good practice to create static class on application scope that lives for application lifetime? That means that every user that makes request would use same instance ? Wouldn't that be i performance issue for that one connection?
All of your method calls will execute to completion or throw an exception thus even if the GC takes a while there is no open connection sitting out there eating up resources and/or blocking other activity.
This one takes me back to section where i allways get same instance of CrmServiceClient and got the part that xrm.tooling handles cached connection o the other side but what happens on this side (web application).
Isn't the connection to CRM (i.e. CrmServiceClient) unmanaged resources, shouldn't i Dispose() it explicitly?
I found some examples with CrmServiceClient and pretty much in all examples CrmServiceClient is casted in IOrganizationService using CrmServiceClient.OrganizationWebProxyClient or CrmServiceClient.OrganizationServiceProxy.
Why is that and what are the benefits of that?
I got so many questions but this is already allot to ask, is there any online documentation that you could point me to it?
First, I'm assuming you are using the latest SDK DLLs from Nuget: Microsoft.CrmSdk.XrmTooling.CoreAssembly 8.2.0.5.
I never wrap the connection in a using statement and I don't think I've ever seen an example where that is done. There are examples from the "old days", before we had tooling library, where calls to create OrganizationServiceProxy were wrapped in a using statement, which caused a lot of inexperienced developers to release code with connection performance issues.
Luckily most of this has been fixed for us through the Xrm.Tooling library.
Create your connection object using CrmServiceClient:
CrmServiceClient crmSvc = new CrmServiceClient(#"...connection string goes here...");
Now if I create an OrganizationServiceContext (or an early-bound equivalent) object I do wrap that in a using so that it is determinedly disposed when I've completed my unit of work.
using (var ctx = new OrganizationServiceContext(crmSvc))
{
var accounts = from a in ctx.CreateQuery("account")
select a["name"];
Console.WriteLine(accounts.ToList().Count());
}
The Xrm.Tooling library handles everything else for you as far the connection channel and authentication. Unless you specify to create a new channel each time (by adding 'RequireNewInstance=true' to the connection string or setting the useUniqueInstance to true when calling new CrmServiceClient) the library will reuse the existing authenticated channel.
I used the following code to do a quick proof test:
void Main()
{
var sw = new Stopwatch();
sw.Start();
var crmSvc = GetCrmClient();
Console.WriteLine($"Time to get Client # 1: {sw.ElapsedMilliseconds}");
crmSvc.Execute(new WhoAmIRequest());
Console.WriteLine($"Time to WhoAmI # 1: {sw.ElapsedMilliseconds}");
var crmSvc2 = GetCrmClient();
Console.WriteLine($"Time to get Client # 2: {sw.ElapsedMilliseconds}");
crmSvc2.Execute(new WhoAmIRequest());
Console.WriteLine($"Time to WhoAmI # 2: {sw.ElapsedMilliseconds}");
}
public CrmServiceClient GetCrmClient()
{
return new CrmServiceClient("...connection string goes here...");
}
When I run this with RequireNewInstance=true I get the following console output:
Time to get Client # 1: 2216
Time to WhoAmI # 1: 2394
Time to get Client # 2: 4603
Time to WhoAmI # 2: 4780
Clearly it was taking about the same amount of time to create each connection.
Now, if I change it to RequireNewInstance=false (which is the default) I get the following:
Time to get Client # 1: 3761
Time to WhoAmI # 1: 3960
Time to get Client # 2: 3961
Time to WhoAmI # 2: 4145
Wow, that's a big difference. What is going on? On the second call the Xrm.Tooling library uses the existing service channel and authentication (which it cached.)
You can take this one step further and wrap your new CrmServiceClient calls in a using and you'll get the same behavior, because disposing of the return instanced does not destroy the cache.
So this will return times similar to above:
using (var crmSvc = GetCrmClient())
{
Console.WriteLine($"Time to get Client # 1: {sw.ElapsedMilliseconds}");
crmSvc.Execute(new WhoAmIRequest());
Console.WriteLine($"Time to WhoAmI # 1: {sw.ElapsedMilliseconds}");
}
using (var crmSvc2 = GetCrmClient())
{
Console.WriteLine($"Time to get Client # 2: {sw.ElapsedMilliseconds}");
crmSvc2.Execute(new WhoAmIRequest());
Console.WriteLine($"Time to WhoAmI # 2: {sw.ElapsedMilliseconds}");
}
For code simplicity, I usually create a static class (a singleton could be used too, but would usually be overkill) to return a CrmServiceClient object. That way my code is not littered with new CrmServiceClient calls should I want to change anything about how the connection is being made.
To fundamentally answer the question about using, we don't need to use it because there is nothing to be released. All of your method calls will execute to completion or throw an exception thus even if the GC takes a while there is no open connection sitting out there eating up resources and/or blocking other activity.

OpenNTF Domino API: "org.openntf.domino.utils.Factory is not initialized for this thread"

I'm trying to implement OpenNTF Domino API as a replacement in our project but it fails with this message:
"OpenNTF Domino API: org.openntf.domino.utils.Factory is not initialized for this thread!"
Code snippet:
boolean init = Factory.isInitialized(); // false
Database db = Factory.getSession().getCurrentDatabase(); // This fails of course because no Session
I'm implementing the call in a JAVA DAO behind a EXTLib Servlet in XPages.
So it's not called by an XPage but as an REST API call.
The Domino API Demo DB is working so the server install seems to be OK.
Is there a setup, properties I'm missing to init it ?
Yes, there is specific setup require for non-XPages access, as done in OsgiWorlds on OpenNTF. Nathan has added a DAS extension specifically for REST access from Graph database. You basically need to initialise the session for the Factory before trying to access it, generally done in the Servlet when it initiates the HTTP connection. Please contact me on Twitter (Paulswithers) so the team can work with you. Also it's worth you having a look at the OsgiWorlds source code. Although that's for a Vaadin servlet and allows defining a development user to run as, in production mode it also uses the logged on user name and the configuration class and calls to it from the servlet are effectively what you need from the REST servlet.

Azure Mobile Service (node backend) __updatedAt property not automatically set after edit

After reading the documentation I was expecting that this field is automatically set by Azure Mobile Services. Apparently it isn't.
Should I configure something extra?
Other options that I see (to do for each table):
* add an axtra line to the node js update(item, user, request) function:
item.__updatedAt = new Date();
* create an update trigger in the database
Anybody experience with this?
Thx!
The __updatedAt column is updated by a trigger created in the underlying SQL Server database, so it should be updated any time a row is updated. Note that this requires a database operation to occur for it to be updated.

Uploading photos using Grails Services

I would like to ask, What would be the most suitable scope for my upload photo service in Grails ? I created this PhotoService in my Grails 2.3.4 web app, all it does is to get the request.getFile("myfile") and perform the necessary steps to save it on the hard drive whenever a user wants to upload an image. To illustrate what it looks like, I give a skeleton of these classes.
PhotoPageController {
def photoService
def upload(){
...
photoService.upload(request.getFile("myfile"))
...
}
}
PhotoService{
static scope="request"
def upload(def myFile){
...
// I do a bunch of task to save the photo
...
}
}
The code above isn't the exact code, I just wanted to show the flow. But my question is:
Question:
I couldn't find the exact definition of these different grails scopes, they have a one liner explanation but I couldn't figure out if request scope means for every request to the controller one bean is injected, or each time a request comes to upload action of the controller ?
Thoughts:
Basically since many users might upload at the same time, It's not a good idea to use singleton scope, so my options would be prototype or request I guess. So which one of them works well and also which one only gets created when the PhotoService is accessed only ?
I'm trying to minimize the number of services being injected into the application context and stays as long as the web app is alive, basically I want the service instance to die or get garbage collect at some point during the web app life time rather than hanging around in the memory while there is no use for it. I was thinking about making it session scope so when the user's session is terminated the service is cleaned up too, but in some cases a user might not want to upload any photo and the service gets created for no reason.
P.S: If I move the "def photoService" within the upload(), does that make it only get injected when the request to upload is invoked ? I assume that might throw exception because there would be a delay until Spring injects the service and then the ref to def photoService would be n
I figured out that Singleton scope would be fine since I'm not maintaining the state for each request/user. Only if the service is supposed to maintain state, then we can go ahead and use prototype or other suitable scopes. Using prototype is safer if you think the singleton might cause unexpected behavior but that is left to testing.

Extending log4net - Adding additional data to each log

We're working on logging in our applications, using log4net. We'd like to capture certain information automatically with every call. The code calling log.Info or log.Warn should call them normally, without specify this information.
I'm looking for a way to create something we can plug into log4net. Something between the ILog applications use to log and the appenders, so that we can put this information into the log message somehow. Either into ThreadContext, or the LogEventInfo.
The information we're looking to capture is asp.net related; the request url, user agent, etc. There's also some information from the apps .config file we want to include (an application id).
I want to get between the normal ILog.Info and appender so that this information is also automatically included for 3rd party libraries which also use log4net (Nhibernate, NServiceBus, etc).
Any suggestions on where the extensibility I want would be?
Thanks
What you are looking for is called log event context. This tutorial explains how it works:
http://www.beefycode.com/post/Log4Net-Tutorial-pt-6-Log-Event-Context.aspx
In particular the chapter 'Calculated Context Values' will interesting for you.
Update:
My idea was to use the global context. It is easy to see how this works for something like application ID (in fact there you do not even need a calculated context object). Dynamic information like request url could be done like this:
public class RequestUrlContext
{
public override string ToString()
{
string url;
// retrieve url from request
return url;
}
}
The object is global but the method is called on the thread that handles the request and thus you get the correct information. I also recommend that you create one class per "information entity" so that you have a lot of flexibility with the output in the log destination.

Resources