Using cfpop to access gmail in CF8 - coldfusion

So I need to use ColdFusion 8 to check a GMail account for emails, eventually I'll download the attachments. I've Googled and not found much except for the following code. What bugs me is that, that's all I've found.
So is this the best way to go?
Here is the code. I've included the link but there is not much more information.
<cfscript>
javaSystem = createObject( "java", "java.lang.System" );
jProps = javaSystem.getProperties();
jProps.setProperty( "mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory" );
jProps.setproperty( "mail.pop3.port", 995 );
jProps.setProperty( "mail.pop3.socketFactory.port", 995 );
</cfscript>
<cfpop action="getheaderonly" name="rsEmail" startrow="1? maxrows="50" server="pop.gmail.com" port="995" username="your#username.com.au" password="yourpassword">
Using CFPOP to check mail on GMail

Is there a reason you need to use POP in particular? If you're on CF9, then you can use CFIMAP which ought to work with gmail. The docs even use gmail as an example.
Alternatively, you could use the javamail API directly:
<cfscript>
props = CreateObject("java","java.util.Properties").init();
props.setProperty("mail.store.protocol", "imaps");
sessClass = CreateObject("java","javax.mail.Session");
sess = sessClass.getDefaultInstance(props);
store = sess.getStore("imaps");
store.connect("imap.googlemail.com","you#gmail.com", "password");
folder = store.getFolder("inbox");
if(!folder.isOpen()){
folder.open(folder.READ_WRITE)
}
messageCount = folder.getMessageCount();
dump(messageCount);
if (!IsNull(folder) && folder.isOpen()) { folder.close(true); }
if (!IsNull(store)) { store.close(); }
</cfscript>

This will work but you should know that it sets the GLOBAL SSL socketfactory for POP3. I believe this will have a serverwide affect - which may be irrelevant to your process but it is worth noting.

You could possibly use the opensource cfgmail project on Riaforge:
http://cfgmail.riaforge.org/
It works both in CF 7 and up.

Related

Best way to dynamically set host server in ColdFusion 10

I use the following to dynamically detect the host server. The importance for making it dynamic is that currently there are too many hard coded redirect such as:
http:s//mysite.com/hr/index.cfm
within my app.
When I'm moving from production site to development site and then back to production site, I have to manually change/comment out this http/https one by one and it is not only time consuming but also dangerous.
Here is the code I found that can detect the host server. Then I do the following:
<CFSET inet = CreateObject("java", "java.net.InetAddress")>
<CFSET inet = inet.getLocalHost()>
<CFSET HostServer = "#inet.getHostName()#">
<CFSET ThisHostServer = "#LEFT(HostServer,6)#">
<CFSWITCH expression="#Trim(ThisHostServer)#"><!--- Prod or Dev server --->
<CFCASE value="myprodsite.com">
<CFSET UseThisURL = "http://myprodsite.com">
</CFCASE>
<CFCASE value="mydevsite.com">
<CFSET UseThisURL = "http://myDevsite.com">
</CFCASE>
</CFSWITCH>
Then on each page where links or redirection exist, I just need to use:
#UseThisURL#/hr/index.cfm
My question is:
Where is the best way to set #UseThisURL# in the application?
I'm using ColdFusion 10 and Application.cfc in Linux env.
Should I set it as an application or a session scope?
Since everything will be in an application or session scope, when users are idle on a certain page and the application/session scope is expired, when user click on a link will it generate an error? How to prevent users from seeing error caused by using this technique? Please advice, thank you!
Best practice that I used is creating config.cfc which can contain function like getServerSpecificVariables() to return structure. this structure will be saved in your application scope since you don't want to create USEThisURL for every session start. When you need to reset simply clear your application scope. instantiate below config component inside onApplicationStart event in Application.cfc
Example
Config.cfc:
component{
public struct function getServerSpeceficVariables(){
var config = {};
var inet = CreateObject("java", "java.net.InetAddress");
inet = inet.getLocalHost();
HostServer = inet.getHostName();
ThisHostServer = LEFT(HostServer,6);
switch(Trim(ThisHostServer)){
case 'myprodsite.com':{
config.useThisURL = '';
break;
}
case 'mydevsite.com':{
config.useThisURL = '';
break;
}
}
return config;
}
}

How to get Expiration Date of access token in Facebook SDK for Unity

I am using parse sdk for backend management for my game. For user signup/login parse api ask for parameter tokenExpiration. I have no idea how to get it from facebook unity sdk.
https://www.parse.com/docs/unity_guide#fbusers-signup
Task<ParseUser> logInTask = ParseFacebookUtils.LogInAsync(accessToken, userId, tokenExpiration);
Got this problem solved by myself using debug_token. Here is the right code on how to do it.
FB.API("/debug_token?input_token="+FB.AccessToken+"&access_token="+FB.AccessToken,Facebook.HttpMethod.GET, AccessTokenCallback);
function AccessTokenCallback(response:String){
Debug.Log(response);
var access = JSON.Parse(response);
Debug.Log("Token Expiration is: "+access["data"]["expires_at"].Value);
}
If you will print the response it will give you a JSON with all information about the access token and you can take whatever info you need about an access token.
Open FacebookAccessTokenEditor.cs and replace original line 81:
formData["batch"] = "[{\"method\":\"GET\", \"relative_url\":\"me?fields=id\"},{\"method\":\"GET\", \"relative_url\":\"app?fields=id\"}]";
by these two:
string getExpiresAt = ",{\"method\":\"GET\", \"relative_url\":\"debug_token?input_token="+accessToken+"\"}";
formData["batch"] = "[{\"method\":\"GET\", \"relative_url\":\"me?fields=id\"},{\"method\":\"GET\", \"relative_url\":\"app?fields=id\"}"+getExpiresAt+"]";
Then open FacebookEditor.cs and in method MockLoginCallback, just before line 220:
isLoggedIn = true;
insert the following lines:
var tokenData = (Dictionary<string, object>)MiniJSON.Json.Deserialize(responses[2]);
var expiresAt = (long)((Dictionary<string, object>)tokenData["data"])["expires_at"];
accessTokenExpiresAt = FromTimestamp((int)expiresAt);
also, add the missing function FromTimestamp which you can copy from AndroidFacebook.cs or IOSFacebook.cs or jus copy from here:
private DateTime FromTimestamp(int timestamp)
{
return new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(timestamp);
}
Finally, you can call the parse method like you do on IOS or Android or Web:
Task<ParseUser> logInTask = ParseFacebookUtils.LogInAsync(FB.UserId, FB.AccessToken, FB.AccessTokenExpiresAt);
Note: As I have worked on the code, I am not sure of the original line numbers, but I think they are correct. Also, this does not reflect the best coding practices, but since it is used only in a debug context, they're good enough for me.

Using Apache HttpComponents for http requests with NTLM authentication

Quick background.
CFHTTP doesn't support Windows NTLM/Authenticate authentication, only basic authentication. I need to make http requests that will have to authenticate against NTLM, so I've ended up rolling my own version of CFHTTP.
I found Terry Ryan's article that uses the apache httpclient version 3.1 to perform digest authentication and have built upon that using version 4.1.2 instead which includes NTLM functionality.
I have a function that will perform a get request and then other functions to handle returning a structure that looks like the cfhttp result set. The changes I made are based on the authentication tutorial example.
public any function httpRequest(url,username,password,domain) {
var httpClient = createObject("java","org.apache.http.impl.client.DefaultHttpClient");
var authScope = createObject("java","org.apache.http.auth.AuthScope");
var httpCredentials = createObject("java","org.apache.http.auth.NTCredentials");
var httpGet = createObject("java","org.apache.http.client.methods.HttpGet");
var jURL = createObject("java", "java.net.URL").init(arguments.url);
var host = jURL.getHost();
var path = jURL.getPath();
var httpHostTarget = createObject("java","org.apache.http.HttpHost").init(host,80,"http");
var localContext = createObject("java","org.apache.http.protocol.BasicHttpContext");
var httpContent = {};
var response = '';
if (len(arguments.username) and len(arguments.password) gt 0){
httpCredentials.init(arguments.Username, arguments.password, cgi.remote_host,arguments.domain);
httpClient.getCredentialsProvider().setCredentials(authScope.ANY, httpCredentials);
}
if (!Len(path)) path = "/";
httpGet.init(path);
response = httpClient.execute(httpHostTarget, httpget, localContext);
httpContent = convertHttpClientResponseToCFHTTPFormat(response);
httpClient.getConnectionManager().shutdown();
return httpContent;
}
This was working fine until I altered the function to perform the authentication.
Unfortunately I'm now getting :
The execute method was not found.
Either there are no methods with the specified method name and argument types or the execute method is overloaded with argument types that ColdFusion cannot decipher reliably. ColdFusion found 2 methods that match the provided arguments. If this is a Java object and you verified that the method exists, use the javacast function to reduce ambiguity.
As far as I can tell there is only one matching execute() function in HttpClient for the object classes passed to it, so I'm a little confused. JavaCast doesn't allow you to cast to complex objects or super types, so that didn't work.
Can anyone suggest how I can get this to work? How can I reduce the ambiguity?
Looking at the error, it's getting confused between two execute methods that have the same number of parameters. Although I don't know why it is...
Anyway, I found a way around the error. It involves pulling the method you're after out of the class and invoking it directly. If ColdFusion was happier with casting Java objects life might be easier.
//response = httpClient.execute(httpHostTarget, httpget, localContext);
classes = [httpHostTarget.getClass(), CreateObject('java', 'org.apache.http.HttpRequest').getClass(), CreateObject('java', 'org.apache.http.protocol.HttpContext').getClass()];
method = httpClient.getClass().getMethod('execute', classes);
params = [httpHostTarget, httpget, localContext];
response = method.invoke(httpClient, params);
There may be another way of doing this (casting instead) but it's all I've got ;)
As a guess, could you be loading the wrong version of the .jars ? You don't seem to be using JavaLoader like Ryan did...

SBL-ODU-01007 The HTTP request did not contain a valid SOAPAction header

I am hoping someone can help get me in the right direction...
I am using Powerbuilder 12 Classic and trying to consume a Oracle CRM OnDemand web service.
Using Msxml2.XMLHTTP.4.0 commands, I have been able to connect using https and retrieve the session id, which I need to send back when I invoke the method.
When I run the code below, I get the SBL-ODU-01007 The HTTP request did not contain a valid SOAPAction header error message. I am not sure what I am missing??
OleObject loo_xmlhttp
ls_get_url = "https://secure-ausomxxxx.crmondemand.com/Services/Integration?command=login"
try
loo_xmlhttp = CREATE oleobject
loo_xmlhttp.ConnectToNewObject("Msxml2.XMLHTTP.4.0")
loo_xmlhttp.open ("GET",ls_get_url, false)
loo_xmlhttp.setRequestHeader("UserName", "xxxxxxx")
loo_xmlhttp.setRequestHeader("Password", "xxxxxxx")
loo_xmlhttp.send()
cookie = loo_xmlhttp.getResponseHeader("Set-Cookie")
sesId = mid(cookie, pos(cookie,"=", 1)+1, pos(cookie,";", 1)-(pos(cookie,"=", 1)+1))
ls_post_url = "https://secure-ausomxxxx.crmondemand.com/Services/Integration/Activity;"
ls_response_text = "jsessionid=" + sesId + ";"
ls_post_url = ls_post_url + ls_response_text
loo_xmlhttp.open ("POST",ls_post_url, false)
loo_xmlhttp.setRequestHeader("COOKIE", left(cookie,pos(cookie,";",1)-1) )
loo_xmlhttp.setRequestHeader("COOKIE", left(cookie,pos(cookie,";",1)-1) )
ls_post_url2 = "document/urn:crmondemand/ws/activity/10/2004:Activity_QueryPage"
loo_xmlhttp.setRequestHeader("SOAPAction", ls_post_url2)
loo_xmlhttp.send()
ls_get_url = "https://secure-ausomxxxx.crmondemand.com/Services/Integration?command=logoff"
loo_xmlhttp.open ("POST",ls_get_url, false)
loo_xmlhttp.send()
catch (RuntimeError rte)
MessageBox("Error", "RuntimeError - " + rte.getMessage())
end try
I believe you are using incorrect URL for Login and Logoff;
Here is the sample:
https://secure-ausomxxxx.crmondemand.com/Services/Integration?command=login
https://secure-ausomxxxx.crmondemand.com/Services/Integration?command=logoff
Rest of the code looks OK to me.
I have run into similar issues in PB with msxml through ole. Adding this may help:
loo_xmlhttp.setRequestHeader("Content-Type", "text/xml")
you need to make sure that the your value for ls_post_url2 is one of the values that is found in the wsdl file. Just search for "soap:operation soapAction" in the wsdl file to see the valid values for SOAPAction.

Sitecore Clear Cache Programmatically

I am trying to publish programmatically in Sitecore. Publishing works fine. But doing so programmatically doesn't clear the sitecore cache. What is the best way to clear the cache programmatically?
I am trying to use the webservice that comes with the staging module. But I am getting a Bad request exception(Exception: The remote server returned an unexpected response: (400) Bad Request.). I tried to increase the service receivetimeout and sendtimeout on the client side config file but that didn't fix the problem. Any pointers would be greatly appreciated?
I am using the following code:
CacheClearService.StagingWebServiceSoapClient client = new CacheClearService.StagingWebServiceSoapClient();
CacheClearService.StagingCredentials credentials = new CacheClearService.StagingCredentials();
credentials.Username = "sitecore\adminuser";
credentials.Password = "***********";
credentials.isEncrypted = false;
bool s = client.ClearCache(true, dt, credentials);
I am using following code to do publish.
Database master = Sitecore.Configuration.Factory.GetDatabase("master");
Database web = Sitecore.Configuration.Factory.GetDatabase("web");
string userName = "default\adminuser";
Sitecore.Security.Accounts.User user = Sitecore.Security.Accounts.User.FromName(userName, true);
user.RuntimeSettings.IsAdministrator = true;
using (new Sitecore.Security.Accounts.UserSwitcher(user))
{
Sitecore.Publishing.PublishOptions options = new Sitecore.Publishing.PublishOptions(master, web,
Sitecore.Publishing.PublishMode.Full, Sitecore.Data.Managers.LanguageManager.DefaultLanguage, DateTime.Now);
options.RootItem = master.Items["/sitecore/content/"];
options.Deep = true;
options.CompareRevisions = true;
options.RepublishAll = true;
options.FromDate = DateTime.Now.AddMonths(-1);
Sitecore.Publishing.Publisher publisher = new Sitecore.Publishing.Publisher(options);
publisher.Publish();
}
In Sitecore 6, the CacheManager class has a static method that will clear all caches. The ClearAll() method is obsolete.
Sitecore.Caching.CacheManager.ClearAllCaches();
Just a quick note, in Sitecore 6.3, that is not needed anymore. Caches are being cleared automatically after a change happens on a remote server.
Also, if you are on previous releases, instead of clearing all caches, you can do partial cache clearing.
There is a free shared source component called Stager that does that.
http://trac.sitecore.net/SitecoreStager
If you need a custom solution, you can simply extract the source code from there.
I got this from Sitecore support. It clears all caches:
Sitecore.Context.Database = this.WebContext.Database;
Sitecore.Context.Database.Engines.TemplateEngine.Reset();
Sitecore.Context.ClientData.RemoveAll();
Sitecore.Caching.CacheManager.ClearAllCaches();
Sitecore.Context.Database = this.ShellContext.Database;
Sitecore.Context.Database.Engines.TemplateEngine.Reset();
Sitecore.Caching.CacheManager.ClearAllCaches();
Sitecore.Context.ClientData.RemoveAll();
Out of the box solution provided by Sitecore to clean caches (ALL of them) is utilized by the following page: http://sitecore_instance_here/sitecore/admin/cache.aspx and code behind looks like the following snippet:
foreach (var cache in Sitecore.Caching.CacheManager.GetAllCaches())
cache.Clear();
Via the SDN:
HtmlCache cache = CacheManager.GetHtmlCache(Context.Site);
if (cache != null) {
cache.Clear();
}