Best practice for co-ordinating a SyncAdapter and GCM within the same app [closed] - google-cloud-messaging

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
My app uses a SyncAdapter to periodically sync server data with SQLite. It also syncs this data in response to a GCM message that indicates new/updated server data; via. an IntentService.
These components each do their work in different background threads and are created by different system processes (SyncManager/GCM broadcast) and have different lifecycles; unpredictably!
What is the best approach to fault-tolerantly co-ordinate these components: e.g.
for an Activity to signal to each that they should do no work
to signal to the SyncAdapter to do no work when the GCM IntentService is working, and vice versa.

You should
Put all your syncing code into the SyncAdapter
Remove the IntentService
In the GcmBroadcastReceiver you start the SyncAdapter instead of the IntentService.
Below is example code copied from the SyncAdapter documentation.
public class GcmBroadcastReceiver extends BroadcastReceiver {
...
// Constants
// Content provider authority
public static final String AUTHORITY = "com.example.android.datasync.provider"
// Account type
public static final String ACCOUNT_TYPE = "com.example.android.datasync";
// Account
public static final String ACCOUNT = "default_account";
// Incoming Intent key for extended data
public static final String KEY_SYNC_REQUEST =
"com.example.android.datasync.KEY_SYNC_REQUEST";
...
#Override
public void onReceive(Context context, Intent intent) {
// Get a GCM object instance
GoogleCloudMessaging gcm =
GoogleCloudMessaging.getInstance(context);
// Get the type of GCM message
String messageType = gcm.getMessageType(intent);
/*
* Test the message type and examine the message contents.
* Since GCM is a general-purpose messaging system, you
* may receive normal messages that don't require a sync
* adapter run.
* The following code tests for a a boolean flag indicating
* that the message is requesting a transfer from the device.
*/
if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)
&&
intent.getBooleanExtra(KEY_SYNC_REQUEST)) {
/*
* Signal the framework to run your sync adapter. Assume that
* app initialization has already created the account.
*/
ContentResolver.requestSync(ACCOUNT, AUTHORITY, null);
...
}
...
}
...
}

Related

How to implement an integration test to check if my circuit breaker fallback is called?

In my application, I need to call an external endpoint and if it is too slow a fallback is activated.
The following code is an example of how my app looks like:
#FeignClient(name = "${config.name}", url = "${config.url:}", fallback = ExampleFallback.class)
public interface Example {
#RequestMapping(method = RequestMethod.GET, value = "/endpoint", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
MyReturnObject find(#RequestParam("myParam") String myParam);
}
And its fallback implementation:
#Component
public Class ExampleFallback implements Example {
private final FallbackService fallback;
#Autowired
public ExampleFallback(final FallbackService fallback) {
this.fallback = fallback;
}
#Override
public MyReturnObject find(final String myParam) {
return fallback.find(myParam);
}
Also, a configured timeout for circuit breaker:
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 5000
How can I implement an integration test to check if my circuit break is working, i.e, if my endpoint (mocked in that case) is slow or if it returns an error like 4xx or 5xx?
I'm using Spring Boot 1.5.3 with Spring Cloud (Feign + Hystrix)
Note i donot know Feign or Hystrix.
In my opinion it is problematic to implement an automated integrationtest that simulates different implementatondetails of Feign+Hystrix - this implementation detail can change at any time. There are many different types of failure: primary-Endpoint not reachable, illegal data (i.e. receiving a html-errormessage, when exprecting xml data in a special format), disk-full, .....
if you mock an endpoint you make an assumption of implementationdetail of Feign+Hystrix how the endpoint behaves in a errorsituation (i.e. return null, return some specific errorcode, throw an exception of type Xyz....)
i would create only one automated integration test with a real primary-enpoint that has a never reachable url and a mocked-fallback-endpoint where you verify that the processed data comes from the mock.
This automated test assumes that handling of "networkconnection too slow" is the same as "url-notfound" from your app-s point of view.
For all other tests i would create a thin wrapper interface around Feign+Hystrix where you mock Feign+Hystrix. This way you can automatically test for example what happens if you receive 200bytes from primary interface and then get an expetion.
For details about hiding external dependencies see onion-architecture

How do I get the correct headers passed to WebAPI telemetry?

First I tried the code from this Q&A: HttpContext and TelemetryInitializer, the part where it says "I could create an action filter to set the context each time, but this feels awful."
Using the linked code, I tested using debugger breakpoints to see if there was a problem with the Active field being global. I did this with just two incoming web requests.
It seemed TelemetryConfiguration.Active.TelemetryInitializers.OfType().Single() was different for each request instead of global. Which is what I wanted. But in production I saw a race condition in that the wrong headers were being attached to the wrong requests. This was done by inspecting the Azure Log Analytics in the dependencies table, specifically the operation_Name versus an HTTP header from the UI that I attached to customDimensions.
Given that the linked Stackoverflow Q&A had a low rating I decided to try alternate code and found some from the official documentation here: https://github.com/Microsoft/ApplicationInsights-aspnetcore/wiki/Configure#add-request-level-properties-for-all-telemetry-items.
I am still getting incorrect headers applied in customDimensions. Could this be due to telemetry sampling or some other reason that I'm not aware of?
A generic form of my ITelemetryInitializer:
public class TrackingTelemetryInitializer : ITelemetryInitializer
{
private readonly IHttpContextAccessor _httpContextAccessor;
public TrackingTelemetryInitializer(IHttpContextAccessor httpContextAccessor)
{
this._httpContextAccessor = httpContextAccessor;
}
public void Initialize(ITelemetry telemetry)
{
if (_httpContextAccessor.HttpContext == null)
{
return;
}
var headers = _httpContextAccessor.HttpContext.Request.Headers;
if (headers.ContainsKey("Foobar"))
{
telemetry.Context.Properties["Foobar"] = headers["Foobar"];
}
}
}

Plagiarism Checker C# based API [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I am looking for a plagiarism checker API that is based on C# code. I need to use it on my web service. I need to easily query plagiarism checking engine and get result for the originality of the text.
If you know any service that is similar to what I am asking it would be great!
I’m using an online plagiarism checker service called Copyleaks which offers an interface to integrate with their API (HTTP REST). It also provides interface which is fully compatible with C#.
Steps to integrate with Copyleaks API:
Register on Copyleaks website.
Create a new C# Console application project and install Copyleaks’ Nuget Package.
Use the following code which performs a webpage scan.
This code was taken from its SDK (GitHub):
public void Scan(string username, string apiKey, string url)
{
// Login to Copyleaks server.
Console.Write("User login... ");
LoginToken token = UsersAuthentication.Login(username, apiKey);
Console.WriteLine("\t\t\tSuccess!");
// Create a new process on server.
Console.Write("Submiting new request... ");
Detector detector = new Detector(token);
ScannerProcess process = detector.CreateProcess(url);
Console.WriteLine("\tSuccess!");
// Waiting to process to be finished.
Console.Write("Waiting for completion... ");
while (!process.IsCompleted())
Thread.Sleep(1000);
Console.WriteLine("\tSuccess!");
// Getting results.
Console.Write("Getting results... ");
var results = process.GetResults();
if (results.Length == 0)
{
Console.WriteLine("\tNo results.");
}
else
{
for (int i = 0; i < results.Length; ++i)
{
Console.WriteLine();
Console.WriteLine("Result {0}:", i + 1);
Console.WriteLine("Domain: {0}", results[i].Domain);
Console.WriteLine("Url: {0}", results[i].URL);
Console.WriteLine("Precents: {0}", results[i].Precents);
Console.WriteLine("CopiedWords: {0}", results[i].NumberOfCopiedWords);
}
}
}
Call the function with your Username, API-Key and the URL of the content you wish to scan for plagiarism.
You can read more about its server in "How To" tutorial.

7" GPS with wince 6 cf 3.5 can't open com port [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
i am using vb 2008 and the serialport object from the system.IO.Ports.SerialPort to connect to com2 serial port on my device to read data from the gps.But when i try to open the port windows troughs an IO Exception. My first thinking was that some other program is using the port but do be sure i tried to open the port with pocket-putty (COM2:) including the colon and all functions and the gps data is flowing. In the documentation of the device the manufacturer writes this:
Pls note for GPS virtual serial port using, Data read not rely on the ComState. CbInQue, read serial data need to specify the length. To test the normal In the Sygic, Igo8, Careland map, detailed methods please use reference in CommTest ReadPortThread.
I don't understand what exactly he means.
My code functions on another Wince device but with wince 5.0 and CF 2.0
i am thankful for every answer
Your port name is wrong. Windows CE requires port names to be suffixed with a colon. The exception message probably told you that the requested port name was not found.
Change the code to this:
mySerialPort.PortName = "COM2:"
Some device do not offer SerialPort access to GPS but a streamed access. Try to open the GPS port as file:
You may need this interop: http://code.google.com/p/win-mobile-code/source/browse/trunk/gps8/Gps8/GPS_Sample8/ReadFile.cs?r=89
and then try opening as file:
#region CN50raw
bgThread2 myStreamReaderThread;
private void OpenStream()
{
//background thread already running?
if (myStreamReaderThread == null)
{
string szPort="";
szPort = GetGPSPort();
if (szPort != "")
{
AddRawText("Start reading stream at '" + szPort +"'");
//start a new thread
myStreamReaderThread = new bgThread2(szPort);
myStreamReaderThread.bgThread2Event += new bgThread2.bgThread2EventHandler(myStreamReaderThread_bgThread2Event);
}
else
AddRawText("No raw GPS port found");
}
}
private void OpenStream(string szPort)
{
//background thread already running?
if (myStreamReaderThread == null)
{
if (szPort != "")
{
AddRawText("Start reading stream at '" + szPort + "'");
//start a new thread
myStreamReaderThread = new bgThread2(szPort);
myStreamReaderThread.bgThread2Event += new bgThread2.bgThread2EventHandler(myStreamReaderThread_bgThread2Event);
}
else
AddRawText("No raw GPS port found");
}
}
void myStreamReaderThread_bgThread2Event(object sender, bgThread2.BgThreadEventArgs bte)
{
AddRawText(bte.sString);
}
private void CloseStream()
{
if (myStreamReaderThread != null)
{
myStreamReaderThread.Dispose();
Application.DoEvents();
myStreamReaderThread = null;
}
Application.DoEvents();
mnuRAWStart.Enabled = true;
mnuRAWStop.Enabled = false;
}
#endregion
the getGpsPort function above uses MS GPSID registry setting to find the raw port name. If your devcice does support GPSID, you do not need all the above and can use GPSID API to get location data of GPS.
Check your device's registry:
private string GetGPSPort()
{
string szStr="";
if (Registry.GetStringValue(Registry.HKLM,
"System\\CurrentControlSet\\GPS Intermediate Driver\\Multiplexer",
"DriverInterface",
ref szStr)
== 0)
{
return szStr;
}
else
{
if (Registry.GetStringValue(Registry.HKLM,
"System\\CurrentControlSet\\GPS Intermediate Driver\\Drivers",
"CurrentDriver",
ref szStr) == 0)
{
string szPath = "System\\CurrentControlSet\\GPS Intermediate Driver\\Drivers\\" + szStr;
if (Registry.GetStringValue(Registry.HKLM, szPath, "CommPort", ref szStr) == 0)
{
return szStr;
}
}
}
return "";
}
The above code lines are sources of my GpsSample application for Windows Mobile (Compact Framework)
Article: http://www.hjgode.de/wp/2010/06/11/enhanced-gps-sample-update/
Code http://code.google.com/p/win-mobile-code/source/browse/trunk/gps8/Gps8/GPS_Sample8/?r=89

BlackBerry: How to use PersistableRIMKeyStore?

I need to securely store private user data so it can persist across my app starts as well as device resets.
This will be a String I guess about 1000 chars at maximum.
I was told I can use RIM KeyStore API for this.
Well, I spent hours googling out any gide on RIM KeyStore API usage. JDE samples do not contain anything useful on this.
Looks like this is a rare thing in BB development, so there's almost no official info on this.
I read this and this. From those I understood the best choice for me is to use PersistableRIMKeyStore (it persists across device resets). However I am not able to figure out what exactly should the implementation be.
Can anyone help with sample code or point me to some guide? Also maybe there's a better/simpler way/approach for my task, so, please, let me know about it.
Thanks a lot in advance!!!
If you use the store in the same was as the "PersistentStoreDemo" which if you don't know you can get by going to File -> Import -> Blackberry Samples, you can encrypt the info in the store. On top of this, if the user has content protection on, you can use a ContentProtectedHashtable to automatically know that that information would be encrypted. So, without content protection, the info would be encrypted once, with it on, it would be doubly encrypted as well as stored with a hard to guess long hash of the app namespace (obviously, since to register the store you need it). Below is what I use:
package ca.dftr.phillyd.lib.persistables;
import net.rim.device.api.system.ApplicationDescriptor;
import net.rim.device.api.util.ContentProtectedHashtable;
import net.rim.device.api.util.Persistable;
/**
* Basic class for storing application specific information.
* Information such as application settings or whether the license agreement was accepted.
* For more complex and specific classes they should be implemented separately and implement persistable
* #author deforbes
*/
public class AppInfo extends ContentProtectedHashtable implements Persistable {
private String _appName = null;
private String _version = null;
/**
* Constructs the application info, creates and persists a hashtable for application settings.
* #param uniqueHexAppIdentifier Can be automatically created in resource class (BUNDLE_ID) or generated using other unique information.
*/
public AppInfo() {
ApplicationDescriptor appDesc = ApplicationDescriptor.currentApplicationDescriptor();
_appName = appDesc.getName();
_version = appDesc.getVersion();
}
/**
* Get the Name of the application
* #return The application name from the app descriptor
*/
public String getName()
{
return _appName;
}
/**
* Get the Version of the application
* #return The application version from the app descriptor
*/
public String getVersion()
{
return _version;
}
}
Along with a class of constants (which could be included in the above if you want). For example, From my PhillyD app:
package ca.dftr.phillyd.lib.persistables;
/**
* Keys for the AppInfo array
* #author deforbes
*/
public class AppInfoKeys {
public static final String QUALITY = "Quality";
public static final String CHANNEL = "Channel";
public static final String CHANNEL_NAME = "Channel_Name";
public static final String SEARCH = "Search";
public static final String LICENSE_ACCEPTED = "isLicenseAccepted";
public static final String VIDEOS_PER_PAGE = "NumPerPage";
public static final Boolean DOWNLOAD_THUMBS = new Boolean(true);
}
The PersistableRIMKeyStore is used to persist the RIM Key Store. To persist user data accross resets you only need to use the PersistentStore, if you want the deta to be protected you could use the ContentProtectedHashtable or ContentProtectedVector.