UserDataSvc_9aa58 can not disabled error(getlasterror) 87 args is wrong - visual-c++

the below code :
void changeStartType(string szSvcName, uint startType)
{
//
IntPtr schSCManager = OpenSCManager(
null, // local computer
null, // ServicesActive database
SCM_ACCESS.SC_MANAGER_ALL_ACCESS); // full access rights
if (schSCManager == IntPtr.Zero)
{
//appendLog(string.Format("OpenSCManager error : {0}:{1}", szSvcName, GetLastError()));
//throw new Exception("OpenSCManager error");
return;
}
// open
IntPtr schService = OpenService(
schSCManager, // SCM database
szSvcName, // name of service
SERVICE_ACCESS.SERVICE_CHANGE_CONFIG); // need change config access
if (schService == IntPtr.Zero)
{
//appendLog(string.Format("OpenService error : {0}:{1}", szSvcName, GetLastError()));
//throw new Exception("OpenService error");
return;
}
if (!ChangeServiceConfig(
schService, // handle of service
SERVICE_NO_CHANGE, // service type: no change
startType, // service start type
SERVICE_NO_CHANGE, // error control: no change
null, // binary path: no change
null, // load order group: no change
null, // tag ID: no change
null, // dependencies: no change
null, // account name: no change
null, // password: no change
null)) // display name: no change
{
//appendLog(string.Format("OpenService error : : {0}:{1}", szSvcName, GetLastError()));
//throw new Exception("OpenService error");
Debug.WriteLine($"OpenService error : : {szSvcName}:{GetLastError()}");
return;
}
// close
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
}
changeStartType("UserDataSvc_9aa58",4); // 4 mean disable .
Debug output:
OpenService error : UserDataSvc_9aa58:87
87 mean args is wrong , but why ?
I only want to disabled some of services .

Related

Send Push Notifications with Image Payload using Firebase Admin SDK

I am trying to send push notifications through the firebase admin sdk, but the image somehow is not displayed in the push notification.
What's weird is that when I use an invalid key in the notifications object (like image) I get an error. So I assume I got the right keys specified. Documentation for the Notification can be found here.
The following code successfully sends a push notification but there is no image displayed on the users phone:
const admin = require('firebase-admin');
const app = admin.initializeApp({...}); // authenticated with credentials json file
await app.messaging().sendMulticast({
notification: {
title: "hello User",
body: "This is a push notification with an image",
imageUrl: "https://example.com/myPublicImage.png",
},
tokens: ["device_token_1", "device_token_2","..."]
});
Change imageUrl key to image in notification being sent by Firebase Admin SDK. I checked with imageUrl key, it does not work, rather,
it gives null to remoteMessage.getNotification().getImageUrl() in app.
In node.js server, you can create post request to send the Firebase message using Firebase Admin SDK:
Request.post({
"headers": {"Authorization":auth_key_string, "content-type": "application/json" },
"url": "https://fcm.googleapis.com/fcm/send",
"body": JSON.stringify({
"registration_ids" :receiver_token ,
"notification" : {
"title": title,
"body" : message,
"image":imageUrlVal
}
})
}, (error, response, body) => {
if(error) {
return console.dir(error);
}
console.dir(JSON.parse(body));
});
Now, handle this message from FirebaseActivity in Android App code.
In onMessageReceived method add this lines.
if (remoteMessage.getNotification() != null) {
// Since the notification is received directly from
// FCM, the title and the body can be fetched
// directly as below.
Log.d(TAG, "Message Received: " + "YES");
Bitmap bitmap = null;
try {
bitmap = getBitmapfromUrl(remoteMessage.getNotification().getImageUrl().toString());
} catch (Exception e) {
e.printStackTrace(); }
try {
showNotification(
remoteMessage.getNotification().getTitle(),
remoteMessage.getNotification().getBody(),bitmap );
} catch (IOException e) {
e.printStackTrace();
}
}
Define getBitmapfromUrl() as below:
public Bitmap getBitmapfromUrl(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(input);
} catch (Exception e) {
Log.e("awesome", "Error in getting notification image: " + e.getLocalizedMessage());
return null;
}
}
showNotification() can be defined as:
public void showNotification(String title,
String message, Bitmap bitmap) throws IOException {
Intent intent
= new Intent(this, NextPageActivity.class);
// Assign channel ID
String channel_id = "notification_channel";
// Here FLAG_ACTIVITY_CLEAR_TOP flag is set to clear
// the activities present in the activity stack,
// on the top of the Activity that is to be launched
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Pass the intent to PendingIntent to start the
// next Activity
PendingIntent pendingIntent
= PendingIntent.getActivity(
this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder builder
= new NotificationCompat
.Builder(getApplicationContext(), channel_id)
.setSmallIcon(R.drawable.app_icon)
.setAutoCancel(true)
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
.setOnlyAlertOnce(true)
.setContentIntent(pendingIntent);
// A customized design for the notification can be
// set only for Android versions 4.1 and above. Thus
// condition for the same is checked here.
if (Build.VERSION.SDK_INT
>= Build.VERSION_CODES.JELLY_BEAN) {
Log.d(TAG, "Higher Version: ");
builder = builder.setContent(
getCustomDesign(title, message));
if (bitmap != null) {
builder.setLargeIcon(bitmap)
.setStyle(
new NotificationCompat.BigPictureStyle()
.bigPicture(bitmap)
.bigLargeIcon(null)
.setBigContentTitle(title)
.setSummaryText(message)
);
}
} // If Android Version is lower than Jelly Beans,
// customized layout cannot be used and thus the
// layout is set as follows
else {
Log.d(TAG, "Lower Version: ");
builder = builder.setContentTitle(title)
.setContentText(message)
.setSmallIcon(R.drawable.app_icon);
}
// Create an object of NotificationManager class to
// notify the
// user of events that happen in the background.
NotificationManager notificationManager
= (NotificationManager) getSystemService(
Context.NOTIFICATION_SERVICE);
// Check if the Android Version is greater than Oreo
if (Build.VERSION.SDK_INT
>= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel
= new NotificationChannel(
channel_id, "web_app",
NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(
notificationChannel);
}
notificationManager.notify(0, builder.build());
}
getCustomDesign() can be defined as:
private RemoteViews getCustomDesign(String title,
String message) {
#SuppressLint("RemoteViewLayout") RemoteViews remoteViews =
new RemoteViews(getApplicationContext().getPackageName(),
R.layout.notification);
remoteViews.setTextViewText(R.id.title, title);
remoteViews.setTextViewText(R.id.message, message);
remoteViews.setTextViewText(R.id.note_button, "Reply");
remoteViews.setImageViewResource(R.id.icon, R.drawable.app_icon);
//remoteViews.setImageViewResource(R.id.message_image, R.drawable.app_icon);
return remoteViews;
}

Electron - How to create deep-linking on linux

I have an ElectronJS project and I use the protocols (deep-link) in this one. It's work on MacOS and Windows but on Linux I can't understand how to create this protocol.
I have looked in the ElectronJS documentation as well as on the web for issues etc. but I can't figure out how to initialize protocol on Linux. All I want is to achieve, as I have succeeded on MacOS and Windows, a protocol to interact with the app in deep-link.
Code that works on MacOS and Windows :
// main.ts
// –– B ––– PROTOCOL HANDLER –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
ProtocolUtils.setDefaultProtocolClient();
// eslint-disable-next-line default-case
switch (process.platform) {
case 'darwin':
ProtocolUtils.setProtocolHandlerOSX();
break;
case 'win32':
ProtocolUtils.setProtocolHandlerWin32();
break;
}
// –– E ––– PROTOCOL HANDLER –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
// protocol.ts
export abstract class ProtocolUtils {
/**
* #description Create default protocole for call this app.
* Ex : in your browser => myapp://test
*/
public static setDefaultProtocolClient(): void {
if (!app.isDefaultProtocolClient('myapp')) {
// Define custom protocol handler.
// Deep linking works on packaged versions of the application!
app.setAsDefaultProtocolClient('myapp');
}
}
/**
* #description Create logic (WIN32) for open url from protocol
*/
public static setProtocolHandlerWin32(): void {
// Force Single Instance Application on win32
const gotTheLock = app.requestSingleInstanceLock();
app.on('second-instance', (e: Electron.Event, argv: string[]) => {
// Someone tried to run a second instance, we should focus our window.
if (MainWindow.mainWindow) {
if (MainWindow.mainWindow.isMinimized()) MainWindow.mainWindow.restore();
MainWindow.mainWindow.focus();
} else {
MainWindow.openMainWindow(); // Open main windows
}
app.whenReady().then(() => {
MainWindow.mainWindow.loadURL(this._getDeepLinkUrlForWin32(argv)); // Load URL in WebApp
});
});
if (gotTheLock) {
app.whenReady().then(() => {
MainWindow.openMainWindow(); // Open main windows
MainWindow.mainWindow.loadURL(this._getDeepLinkUrlForWin32()); // Load URL in WebApp
});
} else {
app.quit();
}
}
/**
* #description Create logic (OSX) for open url from protocol
*/
public static setProtocolHandlerOSX(): void {
app.on('open-url', (event: Electron.Event, url: string) => {
event.preventDefault();
app.whenReady().then(() => {
MainWindow.openMainWindow(); // Open main windows
MainWindow.mainWindow.loadURL(this._getUrlToLoad(url)); // Load URL in WebApp
});
});
}
/**
* #description Format url to load in mainWindow
*/
private static _getUrlToLoad(url: string): string {
// Ex: url = myapp://deep-link/test?params1=paramValue
// Ex: Split for remove myapp:// and get deep-link/test?params1=paramValue
const urlSplitted = url.split('//');
// Generate URL to load in WebApp.
// Ex: file://path/index.html#deep-link/test?params1=paramValue
const urlToLoad = format({
pathname: Env.BUILDED_WEBAPP_INDEX_PATH,
protocol: 'file:',
slashes: true,
hash: `#${urlSplitted[1]}`,
});
return urlToLoad;
}
/**
* #description Resolve deep link url for windows from process argv
*/
private static _getDeepLinkUrlForWin32(argv?: string[]): string {
let url: string;
const newArgv: string[] = !isNil(argv) ? argv : process.argv;
// Protocol handler for win32
// argv: An array of the second instance’s (command line / deep linked) arguments
if (process.platform === 'win32') {
// Get url form precess.argv
newArgv.forEach((arg) => {
if (/myapp:\/\//.test(arg)) {
url = arg;
}
});
if (!isNil(url)) {
return this._getUrlToLoad(url); // Load URL in WebApp
} else if (!isNil(argv) && isNil(url)) {
throw new Error('URL is undefined');
}
}
}
}
I have no worries for macOS and windows, but on linux the protocol does not exist even with the line :
ProtocolUtils.setDefaultProtocolClient(); who is responsible for creating the myapp: // protocol...
When I run this command : xdg-open myapp://deep-link/test?toto=titi An error tells me that this protocol does not exist
If anyone has an example for me to configure on Linux or can just help me ?
Thanks
Ok i have found the solution !
First, we removed electron-forge and replaced it with electron-builder (cf doc).
Then after reading a lot of documentation for deep links on Linux, Examples of documentation :
Desktop file
Specification of desktop entry
Electron builder desktop file
And my solution is :
# electron-builder.yml
appId: com.myapp.myapp
productName: myapp
directories:
output: out
linux:
icon: src/assets/icons/app/icon#256x256.png
category: Utility
mimeTypes: [x-scheme-handler/myapp] # Define MimeType
desktop: # Define desktop elem
exec: myapp %u # Define Exec
target:
- target: deb
arch:
- x64
So i defined the MimeType with the name of my protocol here myapp which could give:
myapp://toto?foo=bar
And in my desktop file define Exec with myapp %u because %u => A single URL. Local files may either be passed as file: URLs or as file path. (cf doc)
And for finish in my main.ts and protocol.utils.ts:
// main.ts
// –– B ––– PROTOCOL HANDLER –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
ProtocolUtils.setDefaultProtocolClient();
switch (process.platform) {
case 'darwin':
ProtocolUtils.setProtocolHandlerOSX();
break;
case 'linux':
case 'win32':
ProtocolUtils.setProtocolHandlerWindowsLinux();
break;
default:
throw new Error('Process platform is undefined');
}
// –– E ––– PROTOCOL HANDLER –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
// protocol.utils.ts
export abstract class ProtocolUtils {
public static setDefaultProtocolClient(): void {
if (!app.isDefaultProtocolClient('myapp')) {
// Define custom protocol handler.
// Deep linking works on packaged versions of the application!
app.setAsDefaultProtocolClient('myapp');
}
}
/**
* #description Create logic (WIN32 and Linux) for open url from protocol
*/
public static setProtocolHandlerWindowsLinux(): void {
// Force Single Instance Application
const gotTheLock = app.requestSingleInstanceLock();
app.on('second-instance', (e: Electron.Event, argv: string[]) => {
// Someone tried to run a second instance, we should focus our window.
if (MainWindow.mainWindow) {
if (MainWindow.mainWindow.isMinimized()) MainWindow.mainWindow.restore();
MainWindow.mainWindow.focus();
} else {
// Open main windows
MainWindow.openMainWindow();
}
app.whenReady().then(() => {
MainWindow.mainWindow.loadURL(this._getDeepLinkUrl(argv));
});
});
if (gotTheLock) {
app.whenReady().then(() => {
// Open main windows
MainWindow.openMainWindow();
MainWindow.mainWindow.loadURL(this._getDeepLinkUrl());
});
} else {
app.quit();
}
}
/**
* #description Create logic (OSX) for open url from protocol
*/
public static setProtocolHandlerOSX(): void {
app.on('open-url', (event: Electron.Event, url: string) => {
event.preventDefault();
app.whenReady().then(() => {
if (!isNil(url)) {
// Open main windows
MainWindow.openMainWindow();
MainWindow.mainWindow.loadURL(this._getUrlToLoad(url));
} else {
this._logInMainWindow({ s: 'URL is undefined', isError: true });
throw new Error('URL is undefined');
}
});
});
}
/**
* #description Format url to load in mainWindow
*/
private static _getUrlToLoad(url: string): string {
// Ex: url = myapp://deep-link/test?params1=paramValue
// Ex: Split for remove myapp:// and get deep-link/test?params1=paramValue
const splittedUrl = url.split('//');
// Generate URL to load in WebApp.
// Ex: file://path/index.html#deep-link/test?params1=paramValue
const urlToLoad = format({
pathname: Env.BUILDED_APP_INDEX_PATH,
protocol: 'file:',
slashes: true,
hash: `#${splittedUrl[1]}`,
});
return urlToLoad;
}
/**
* #description Resolve deep link url for Win32 or Linux from process argv
* #param argv: An array of the second instance’s (command line / deep linked) arguments
*/
private static _getDeepLinkUrl(argv?: string[]): string {
let url: string;
const newArgv: string[] = !isNil(argv) ? argv : process.argv;
// Protocol handler
if (process.platform === 'win32' || process.platform === 'linux') {
// Get url form precess.argv
newArgv.forEach((arg) => {
if (/myapp:\/\//.test(arg)) {
url = arg;
}
});
if (!isNil(url)) {
return this._getUrlToLoad(url);
} else if (!isNil(argv) && isNil(url)) {
this._logInMainWindow({ s: 'URL is undefined', isError: true });
throw new Error('URL is undefined');
}
}
}
And it's WORK :D

How to create text file(log file) having all rights(Read,Write) to all windows users (Everybody) using sprintf in VC++

I am creating Smart.log file using following code :
void S_SetLogFileName()
{
char HomeDir[MAX_PATH];
if (strlen(LogFileName) == 0)
{
TCHAR AppDataFolderPath[MAX_PATH];
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, AppDataFolderPath)))
{
sprintf(AppDataFolderPath, "%s\\Netcom\\Logs", AppDataFolderPath);
if (CreateDirectory(AppDataFolderPath, NULL) || ERROR_ALREADY_EXISTS == GetLastError())
sprintf(LogFileName,"%s\\Smart.log",AppDataFolderPath);
else
goto DEFAULTVALUE;
}
else
{
DEFAULTVALUE:
if (S_GetHomeDir(HomeDir,sizeof(HomeDir)))
sprintf(LogFileName,"%s\\Bin\\Smart.log",HomeDir);
else
strcpy(LogFileName,"Smart.log");
}
}
}
and opening and modifying it as follows:
void LogMe(char *FileName,char *s, BOOL PrintTimeStamp)
{
FILE *stream;
char buff[2048] = "";
char date[256];
char time[256];
SYSTEMTIME SystemTime;
if(PrintTimeStamp)
{
GetLocalTime(&SystemTime);
GetDateFormat(LOCALE_USER_DEFAULT,0,&SystemTime,"MM':'dd':'yyyy",date,sizeof(date));
GetTimeFormat(LOCALE_USER_DEFAULT,0,&SystemTime,"HH':'mm':'ss",time,sizeof(time));
sprintf(buff,"[%d - %s %s]", GetCurrentThreadId(),date,time);
}
stream = fopen( FileName, "a" );
fprintf( stream, "%s %s\n", buff, s );
fclose( stream );
}
Here's the problem:
UserA runs the program first, it creates \ProgramData\Netcom\Smart.log using S_SetLogFileName()
UserB runs the program next, it tries to append/ modify to Smart.log and gets access denied.
What should i need to change in my code to allow all users to access Smart.log file ?
This is solution, I am looking for, Hope useful for some one.
refer from :
void SetFilePermission(LPCTSTR FileName)
{
PSID pEveryoneSID = NULL;
PACL pACL = NULL;
EXPLICIT_ACCESS ea[1];
SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY;
// Create a well-known SID for the Everyone group.
AllocateAndInitializeSid(&SIDAuthWorld, 1,
SECURITY_WORLD_RID,
0, 0, 0, 0, 0, 0, 0,
&pEveryoneSID);
// Initialize an EXPLICIT_ACCESS structure for an ACE.
ZeroMemory(&ea, 1 * sizeof(EXPLICIT_ACCESS));
ea[0].grfAccessPermissions = 0xFFFFFFFF;
ea[0].grfAccessMode = GRANT_ACCESS;
ea[0].grfInheritance = NO_INHERITANCE;
ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID;
ea[0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
ea[0].Trustee.ptstrName = (LPTSTR)pEveryoneSID;
// Create a new ACL that contains the new ACEs.
SetEntriesInAcl(1, ea, NULL, &pACL);
// Initialize a security descriptor.
PSECURITY_DESCRIPTOR pSD = (PSECURITY_DESCRIPTOR)LocalAlloc(LPTR,
SECURITY_DESCRIPTOR_MIN_LENGTH);
InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION);
// Add the ACL to the security descriptor.
SetSecurityDescriptorDacl(pSD,
TRUE, // bDaclPresent flag
pACL,
FALSE); // not a default DACL
//Change the security attributes
SetFileSecurity(FileName, DACL_SECURITY_INFORMATION, pSD);
if (pEveryoneSID)
FreeSid(pEveryoneSID);
if (pACL)
LocalFree(pACL);
if (pSD)
LocalFree(pSD);
}

Universal app: Cannot bind `StreamSocketListener` after `EnableTransferOwnership`

I am following this sample to implement a background server universal app. Here is the experimental code:
void MainPage::OnConnectionReceived(StreamSocketListener^ sender, StreamSocketListenerConnectionReceivedEventArgs^ args)
{
OutputDebugString(L"Connection received\n");
// No idea how to transfer request handling from foreground to background task!
}
void MainPage::OnNavigatedTo(NavigationEventArgs^ e)
{
// Code to register background task is omitted
auto listener = ref new StreamSocketListener();
listener->Control->QualityOfService = SocketQualityOfService::Normal;
try
{
listener->EnableTransferOwnership(Task->TaskId, SocketActivityConnectedStandbyAction::Wake);
}
catch (...)
{
OutputDebugString(L"Error: cannot transfer ownership\n");
}
listener->ConnectionReceived += ref new TypedEventHandler<StreamSocketListener^, StreamSocketListenerConnectionReceivedEventArgs^>(this, &MainPage::OnConnectionReceived);
create_task(listener->BindServiceNameAsync("56789", SocketProtectionLevel::PlainSocket))
.then([this]()
{
OutputDebugString(L"Server started on port 56789\n");
auto m_httpClient = ref new HttpClient();
auto request = ref new HttpRequestMessage(HttpMethod::Get, ref new Uri("http://" + ip + ":56789/"));
auto request_operation = m_httpClient->SendRequestAsync(request, HttpCompletionOption::ResponseContentRead);
return create_task(request_operation);
}).then([this](task<HttpResponseMessage^> previousTask)
{
try {
auto response = previousTask.get();
// Code to process the response is omitted as it is irrelevant to the question
}
catch (Exception^ ex)
{
OutputDebugString(("Error: " + ex->Message + "\n")->Data());
}
});
}
At run time, I get the error: The attempted operation is not supported for the type of object referenced. which suggests that BindServiceNameAsync fails and I have no idea why as I have followed the documentation to do EnableTransferOwnership before doing the binding. What did I do wrong here?
You are getting The attempted operation is not supported for the type of object referenced. because you are using SocketActivityConnectedStandbyAction::Wake. Change it to SocketActivityConnectedStandbyAction::DoNotWake.
The following pseudo-code should give you an idea what else you need to do to make StreamSocketListener working with SocketActivityTrigger:
// TODO: task = socketTaskBuilder.Register();
socketListener = new StreamSocketListener();
socketListener.ConnectionReceived += OnConnected;
await socketListener.BindServiceNameAsync(port);
socketListener.EnableTransferOwnership(
task.TaskId,
SocketActivityConnectedStandbyAction.DoNotWake);
// This is required, otherwise you may get error:
// A device attached to the system is not functioning.
// (Exception from HRESULT: 0x8007001F)
await socketListener.CancelIOAsync();
socketListener.TransferOwnership(socketId);
Then, in the background task do:
public async void Run(IBackgroundTaskInstance taskInstance)
{
var deferral = taskInstance.GetDeferral();
var details = taskInstance.TriggerDetails as
SocketActivityTriggerDetails;
var socketInformation = details.SocketInformation;
var streamSocket = socketInformation.StreamSocket;
var socketListener = socketInformation.StreamSocketListener;
switch (details.Reason)
{
case SocketActivityTriggerReason.ConnectionAccepted:
// TODO: read, write, etc.
break;
default:
// ...
break;
}
// ...
deferral.Complete();
}

RFCommConnectionTrigger in Windows Universal Apps To detect Incoming Bluetooth Connection

I am working on a Windows Universal App. I Want to get the Data from a Bluetooth Device to the Windows Phone. I am Using the Concept of RFCommCommunicationTrigger for this Purpose.
Here's the code Snippet I am Using
var rfTrigger = new RfcommConnectionTrigger();
// Specify what the service ID is
rfTrigger.InboundConnection.LocalServiceId = RfcommServiceId.FromUuid(new Guid("<some_base_guid>"));
//Register RFComm trigger
var rfReg = RegisterTaskOnce(
"HWRFCommTrigger",
"BackgroundLibrary.RFBackgroundTask",
rfTrigger, null
);
SetCompletedOnce(rfReg, OnTaskCompleted);
Here the Function of RegisterTaskOnce
static private IBackgroundTaskRegistration RegisterTaskOnce(string taskName, string entryPoint, IBackgroundTrigger trigger, params IBackgroundCondition[] conditions)
{
// Validate
if (string.IsNullOrEmpty(taskName)) throw new ArgumentException("taskName");
if (string.IsNullOrEmpty(entryPoint)) throw new ArgumentException("entryPoint");
if (trigger == null) throw new ArgumentNullException("trigger");
// Look to see if the name is already registered
var existingReg = (from reg in BackgroundTaskRegistration.AllTasks
where reg.Value.Name == taskName
select reg.Value).FirstOrDefault();
Debug.WriteLine("Background task "+ taskName+" is already running in the Background");
// If already registered, just return the existing registration
if (existingReg != null)
{
return existingReg;
}
// Create the builder
var builder = new BackgroundTaskBuilder();
builder.TaskEntryPoint = entryPoint;
builder.Name = taskName;
builder.SetTrigger(trigger);
// Conditions?
if (conditions != null)
{
foreach (var condition in conditions)
{
builder.AddCondition(condition);
}
}
// Register
return builder.Register();
}
Here's the code for SetCompletedOnce this will add a Handler only once
static private void SetCompletedOnce(IBackgroundTaskRegistration reg, BackgroundTaskCompletedEventHandler handler)
{
// Validate
if (reg == null) throw new ArgumentNullException("reg");
if (handler == null) throw new ArgumentNullException("handler");
// Unsubscribe in case already subscribed
reg.Completed -= handler;
// Subscribe
reg.Completed += handler;
}
I have also Written the BackgroundLibrary.RFBackgroundTask.cs
public sealed class RFBackgroundTask : IBackgroundTask
{
public async void Run(IBackgroundTaskInstance taskInstance)
{
BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
try
{
Debug.WriteLine(taskInstance.TriggerDetails.GetType());
taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
Debug.WriteLine("RFComm Task Running");
Debug.WriteLine(taskInstance.TriggerDetails.GetType().ToString());
}
catch (System.Exception e)
{
Debug.WriteLine("RFComm Task Error: {0}", e.Message);
}
deferral.Complete();
}
}
The Run Method is Invoked Every Time The Device tries to Open the Connection.
The type of the Trigger that is obtained (the type I am debugging in the run method of the RFBackgroundTask.cs) is printed as
Windows.Devices.Bluetooth.Background.RfcommConnectionTriggerDetails
But I am Unable use that because I dont have this Class in the BackgroundLibrary project.
The Documentation says that this Provides information about the Bluetooth device that caused this trigger to fire.
It has Variables like Socket,RemoteDevice etc.
I think I am Missing something very simple
Can you please help me out .
Once your background task is launched, simply cast the TriggerDetails object to an RfcommConnectionTriggerDetails object:
public sealed class RFBackgroundTask : IBackgroundTask
{
public async void Run(IBackgroundTaskInstance taskInstance)
{
BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
try
{
taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
RfcommConnectionTriggerDetails details = (RfcommConnectionTriggerDetails)taskInstance.TriggerDetails;
StreamSocket = details.Socket; // Rfcomm Socket
// Access other properties...
}
catch (System.Exception e)
{
Debug.WriteLine("RFComm Task Error: {0}", e.Message);
}
deferral.Complete();
}
}

Resources