set alarm in Xamarin forms and set the next time for it from sql lite table using Broadcast receiver without using AlarmManager.SetRepeating - sqlite

I want to set the alarm on different times but want to set the next by getting the time from sqllite table by using Broadcast receiver.
I've also created dependency service
Here's what I have tried
public void LocalNotification(string title, string body, int id, DateTime notifyTime)
{
var intent = CreateIntent(id);
Random generator = new Random();
_randomNumber = generator.Next(100000, 999999).ToString("D6");
var pendingIntent = PendingIntent.GetBroadcast(Application.Context, Convert.ToInt32(_randomNumber), intent, PendingIntentFlags.Immutable);
var alarmManager = GetAlarmManager();
var todaysdate = notifyTime;
var _UpcomingSalah = new NextSalahTimeRemaining().getNextSalahTime(todaysdate);
var ms = (long)(_UpcomingSalah.SalahTime).TotalMilliseconds;
alarmManager.Set(AlarmType.ElapsedRealtimeWakeup, Android.OS.SystemClock.ElapsedRealtime() +ms, pendingIntent);
}
BroadcastReciever's 'On recieve func'
public override async void OnReceive(Context context, Intent intent)
{
var sound = Android.Net.Uri.Parse(ContentResolver.SchemeAndroidResource + "://" + context.PackageName + "/" + Resource.Raw.azan);
Ringtone r = RingtoneManager.GetRingtone(context, sound);
r.Play();
await TextToSpeech.SpeakAsync("It's Time for salah");
Xamarin.Forms.DependencyService.Get<ILocalNotificationService>().LocalNotification("Local Notification", "sdfasdf", 0, System.DateTime.Now.AddMinutes(1));
}
I'm calling the dependecy service for next time form sqllite table, the alarm works once but stops instantly after that.

Related

Notification hub device registration with installation

After reading this I've been trying to create an installation in my xamarin.android app but I keep getting an 'Unauthorized error' I feel that I'm missing something. Any help is appreciated.
Previously I was able to register with the hub using
var regID = hub.Register(token, tags.ToArray()).RegistrationId;
so I'm sure my hub has been setup correctly and that I am using the correct connectionstring.
My installation object
install.installationId = installationId; //guid
install.tags = Tags;
install.platform = "gcm";
install.pushChannel = token; //refresh token from fcm
Call to Create installation
private async Task<HttpStatusCode> CreateOrUpdateInstallationAsync(DeviceInstallation deviceInstallation,
string hubName, string listenConnectionString)
{
if (deviceInstallation.installationId == null)
return HttpStatusCode.BadRequest;
// Parse connection string (https://msdn.microsoft.com/library/azure/dn495627.aspx)
ConnectionStringUtility connectionSaSUtil = new ConnectionStringUtility(listenConnectionString);
string hubResource = "installations/" + deviceInstallation.installationId + "?";
string apiVersion = "api-version=2015-04";
// Determine the targetUri that we will sign
string uri = connectionSaSUtil.Endpoint + hubName + "/" + hubResource + apiVersion;
//=== Generate SaS Security Token for Authorization header ===
// See, https://msdn.microsoft.com/library/azure/dn495627.aspx
string SasToken = connectionSaSUtil.getSaSToken(uri, 60);
using (var httpClient = new HttpClient())
{
string json = JsonConvert.SerializeObject(deviceInstallation);
httpClient.DefaultRequestHeaders.Add("Authorization", SasToken);
var response = await httpClient.PutAsync(uri, new StringContent(json, System.Text.Encoding.UTF8, "application/json"));
return response.StatusCode;
}
}

Amazon S3 Multipart UploadPartRequest allows only single thread to upload at the same time using asp.net

I am trying to upload video files Amazon S3 using Multipart upload method in asp.net and I traced the upload progress using logs. It uploads 106496 each time and runs only single thread at a time. I did not notice that multiple threads running. Please clarify me on this why it is running single thread and it's taking long time to upload even for 20Mb file it's taking almost 2 minutes.
Here is my code, which uses UploadPartRequest.
private void UploadFileOnAmazon(string subUrl, string filename, Stream audioStream, string extension)
{
client = new AmazonS3Client(accessKey, secretKey, Amazon.RegionEndpoint.USEast1);
// List to store upload part responses.
List<UploadPartResponse> uploadResponses = new List<UploadPartResponse>();
// 1. Initialize.
InitiateMultipartUploadRequest initiateRequest = new InitiateMultipartUploadRequest
{
BucketName = bucketName,
Key = subUrl + filename
};
InitiateMultipartUploadResponse initResponse =
client.InitiateMultipartUpload(initiateRequest);
// 2. Upload Parts.
//long contentLength = new FileInfo(filePath).Length;
long contentLength = audioStream.Length;
long partSize = 5 * (long)Math.Pow(2, 20); // 5 MB
try
{
long filePosition = 0;
for (int i = 1; filePosition < contentLength; i++)
{
UploadPartRequest uploadRequest = new UploadPartRequest
{
BucketName = bucketName,
Key = subUrl + filename,
UploadId = initResponse.UploadId,
PartNumber = i,
PartSize = partSize,
FilePosition = filePosition,
InputStream = audioStream
//FilePath = filePath
};
// Upload part and add response to our list.
uploadRequest.StreamTransferProgress += new EventHandler<StreamTransferProgressArgs>(UploadPartProgressEventCallback);
uploadResponses.Add(client.UploadPart(uploadRequest));
filePosition += partSize;
}
logger.Info("Done");
// Step 3: complete.
CompleteMultipartUploadRequest completeRequest = new CompleteMultipartUploadRequest
{
BucketName = bucketName,
Key = subUrl + filename,
UploadId = initResponse.UploadId,
//PartETags = new List<PartETag>(uploadResponses)
};
completeRequest.AddPartETags(uploadResponses);
CompleteMultipartUploadResponse completeUploadResponse =
client.CompleteMultipartUpload(completeRequest);
}
catch (Exception exception)
{
Console.WriteLine("Exception occurred: {0}", exception.Message);
AbortMultipartUploadRequest abortMPURequest = new AbortMultipartUploadRequest
{
BucketName = bucketName,
Key = subUrl + filename,
UploadId = initResponse.UploadId
};
client.AbortMultipartUpload(abortMPURequest);
}
}
public static void UploadPartProgressEventCallback(object sender, StreamTransferProgressArgs e)
{
// Process event.
logger.DebugFormat("{0}/{1}", e.TransferredBytes, e.TotalBytes);
}
Is there anything wrong with my code or how to make threads run simultaneously to speed up upload?
Rather than managing the Multipart Upload yourself, try using the TransferUtility that does all the hard work for you!
See: Using the High-Level .NET API for Multipart Upload
The AmazonS3Client internally uses an AmazonS3Config instance to know the buffer size used for transfers (ref 1). This AmazonS3Config (ref 2) has a property named BufferSize whose default value is retrieved from a constant in AWSSDKUtils (ref 3) - which in the current SDK version defaults to 8192 bytes - quite small value IMHO.
You may use a custom instance of AmazonS3Config with an arbitrary BufferSize value. To build an AmazonS3Client instance that respects your custom configs, you have to pass the custom config to the client constructor. Example:
// Create credentials.
AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
// Create custom config.
AmazonS3Config config = new AmazonS3Config
{
RegionEndpoint = Amazon.RegionEndpoint.USEast1,
BufferSize = 512 * 1024, // 512 KiB
};
// Pass credentials + custom config to the client.
AmazonS3Client client = new AmazonS3Client(credentials, config);
// They uploaded happily ever after.

Application is not working when using SQlite databse in windows phone 8

I developed my first application in windows phone 8.1.It is working fine in my local emulator and device but whenever i upload the app in store it is not working.whenever I open the app it is suddenly come back.I used the SQlite database in my application.When I am not using the Sqlite database it is working fine(I uploaded in beta).Please any one help me solve from this issue.
Thank you in advance
sqlite code:
public async void createdatabase()
{
SQLiteConnectionString c = new SQLiteConnectionString(System.IO.Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, "newDB.db"), true);
var conn = new SQLiteAsyncConnection(c.DatabasePath);
await conn.CreateTableAsync<Operators>();
}
public async void Drop()
{
SQLiteConnectionString c = new SQLiteConnectionString(System.IO.Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, "newDB.db"), true);
using (var dbConn = new SQLiteConnection(c.DatabasePath))
{
SQLiteCommand cmd = new SQLiteCommand(dbConn);
cmd.CommandText = "DROP TABLE IF EXISTS Operators";
int response = cmd.ExecuteNonQuery();
}
public async void insert()
{
rechargeOperator1.Items.Clear();
rechargeCircles1.Items.Clear();
SQLiteConnectionString c = new SQLiteConnectionString(System.IO.Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, "newDB.db"), true);
var conn = new SQLiteAsyncConnection(c.DatabasePath);
var client = new pavandatabase.JsonWebClient();
var resp1 = await client.DoRequestAsync(Url.weburl + "getRechargeCircleList");
string result1 = resp1.ReadToEnd();
JArray jsonArray = JArray.Parse(result1);
for (int j = 0; j < jsonArray.Count; j++)
{
JObject jobj = (JObject)jsonArray[j];
string id = (string)jobj["CircleID"];
string statename = (string)jobj["CircleName"];
//circles combobox......
rechargeCircles1.Items.Add(statename);
Operators op = new Operators();
op.Operatorid = int.Parse(OperatorID);
op.Operatorname = Operator;
op.servicetypeid = int.Parse(ServiceTypeID);
await conn.InsertAsync(op);
}
Try to put the break points on the first line of your application and keep on pressing f10 and see at which line it com out and post that line.
Hope it will help you to get the solution.
Thanks,

Updating Red5 SharedObject closing stream

I'm trying to create a voice conference room with all users can speak and use the mic. But as an Admin, I should have the privilege to mute any user. So, I add to the user an attribute for the mic which will be check in client side and enable/disable user's mic accordingly. The server side code looks like:
String identifier;
String userID;
private int _gId = 1;
private Map<String,Object> newUser;
#Override
public boolean appConnect(IConnection conn, Object[] params) {
identifier = (String)params[1];
userID = (String)params[0];
int _globalUserId = _gId++;
conn.getClient().setAttribute("id", _globalUserId);
newUser = new HashMap<String,Object>();
newUser.put("identifier", (String)params[0]);
newUser.put("mic", 1); //mic value to be checked in client side
return true;
}
#Override
public boolean roomJoin(IClient client, IScope scope) {
ISharedObject so = getSharedObject(scope, "users_so");
so.setAttribute(userID,newUser);
return true;
}
#SuppressWarnings("unchecked")
public void muteUser(String userID){
IScope scope = Red5.getConnectionLocal().getScope();
ISharedObject so = getSharedObject(scope, "users_so");
Map<String,Object> user= new HashMap<String,Object>();
user = (Map<String, Object>) so.getAttribute(userID);
if(user != null){
user.put("mic", 0);
so.beginUpdate();
boolean removed = so.removeAttribute(userID);
boolean updated = so.setAttribute(userID,user);
so.endUpdate();
log.info("Mic: " + user.get("mic"));
log.info("Removed: " + removed);
log.info("Updated: " + updated);
}
}
The problem arises when I try to call the muteUser method. Red5 says that the stream is closed. I think this happens when I remove the attribute of the user and added it again but I couldn't find another way to update the sharedObject's mic value.
Does any one have a better idea to update a sharedObject without losing stream?
The SO that you're requesting doesn't work like a user map that it would appear you think it does in your example. I would suggest storing a map in the SO and then do a get / add to the map; the map in this case being shared, so you'd have to make it thread-safe; I'd use a ConcurrentMap there like so:
ISharedObject so = getSharedObject(scope, "users_so");
if (so == null) {
// make sure your so exists
}
so.beginUpdate();
ConcurrentMap<String, Object> users = (ConcurrentMap<String, Object>) so.getAttribute("users");
if (users == null) {
users = new ConcurrentHashMap<String, Object>();
so.setAttribute("users" users);
}
Object user = users.get(userID);
user.put("mic", 0);
so.endUpdate();

Workflow application.PersistableIdle event not firing

Hi I am new to Windows Workflow. This may be very easy, but I am stuck on this from long.
I have a state machine workflow, in which i have a workflow host class.
Persistence is not working in this code. While debugging pointer never goes to application.persistableIdle event.
I use custom input argument, for which I have set as Serializable.
below is my code of the host class:
static InstanceStore instanceStore;
static AutoResetEvent instanceUnloaded = new AutoResetEvent(false);
static Activity activity = new Activity1();
static Guid id = new Guid();
static int intContractHeaderKey;
static Contract contract = new Contract();
public ContractActivityHost(Guid wfid, Int32 contractHeaderID)
{
SetupInstanceStore();
StartAndUnloadInstance(contractHeaderID);
if (intContractHeaderKey > 0)
{
LoadAndCompleteInstance(id, intContractHeaderKey);
}
}
static void StartAndUnloadInstance(Int32 contractHeaderID)
{
contract = new Contract();
//var objContract = new object();
var input = new Dictionary<string, object>
{
{"TheContract", contract}
};
input.Add("ContractHeaderKey", contractHeaderID);
WorkflowApplication application = new WorkflowApplication(activity, input);
application.InstanceStore = instanceStore;
//returning IdleAction.Unload instructs the WorkflowApplication to persists application state and remove it from memory
application.PersistableIdle = (e) =>
{
return PersistableIdleAction.Unload;
};
application.Unloaded = (e) =>
{
instanceUnloaded.Set();
};
//application.Idle = (e) =>
// {
// //application.Unload();
// instanceUnloaded.Set();
// };
//This call is not required
//Calling persist here captures the application durably before it has been started
application.Persist();
id = application.Id;
application.Run();
instanceUnloaded.WaitOne();
//application.Unload();
//contract = (Contract)objContract;
intContractHeaderKey = contract.ContractID;
}
static void LoadAndCompleteInstance(Guid wfid, Int32 contractHeaderID)
{
//string input = Console.ReadLine();
while (!contract.ContractWFPause)
{
contract.FireContract(contract.ContractID);
WorkflowApplication application = new WorkflowApplication(activity);
application.InstanceStore = instanceStore;
application.Completed = (workflowApplicationCompletedEventArgs) =>
{
//Console.WriteLine("\nWorkflowApplication has Completed in the {0} state.", workflowApplicationCompletedEventArgs.CompletionState);
strWFStatus = "Completed";
};
application.Unloaded = (workflowApplicationEventArgs) =>
{
//Console.WriteLine("WorkflowApplication has Unloaded\n");
strWFStatus = "Unloaded";
instanceUnloaded.Set();
};
application.Load(wfid);
instanceUnloaded.WaitOne();
}
}
private static void SetupInstanceStore()
{
instanceStore =
new SqlWorkflowInstanceStore(#"Data Source=.;Initial Catalog=WorkflowInstanceStore;Integrated Security=True;");
InstanceHandle handle = instanceStore.CreateInstanceHandle();
InstanceView view = instanceStore.Execute(handle, new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(10));
handle.Free();
instanceStore.DefaultInstanceOwner = view.InstanceOwner;
}
I have been trying to resolve this from long time, but not sure where I am missing anything. I have gone through couple of sample applications and changed my code to match the flow and logic, but still it does not work.
After application.persist, record is inserted in [System.Activities.DurableInstancing].[InstancesTable] view.
But debug pointer does not move beyond instanceUnloaded.WaitOne();
it actually goes to idle state. if I uncomment application.idle event, it goes in that event code.
Any help to resolve this would be great.
Thanks.
Please check If you have added the below details
instanceStore = new SqlWorkflowInstanceStore(ConfigurationManager.ConnectionStrings["WFPersistenceDb"].ConnectionString);
StateMachineStateTracker.Promote(this.instanceStore);

Resources