I am getting errors while using this code, not able to use the switch case.
Is there any alternative method for using two or more actors
protected async override Task RunAsync(CancellationToken cancellationToken)
{
await base.RunAsync(cancellationToken);
var proxy = ActorProxy.Create<T>(new ActorId(0));
switch (proxy)
{
case IInvoiceMailActor a1:
await a1.RegisterReminder();
break;
case IActor2 a2:
await a2.RegisterReminder();
break;
default:
throw new NotImplementedException($"{GetType().FullName}.{nameof(RunAsync)}");
}
}
My Actor Class
[StatePersistence(StatePersistence.None)]
internal class Actor1 : Actor, IActor1, IRemindable {
public Actor1(ActorService actorService, ActorId actorId) :
base(actorService, actorId) { }
public async Task ReceiveReminderAsync(string reminderName, byte[] state, TimeSpan dueTime, TimeSpan period) {
var location = Directory.GetCurrentDirectory();
var current = DateTime.Now;
Thread.Sleep(2 * 60 * 1000);
using (var writer = File.AppendText("actor.txt")) {
await writer.WriteLineAsync("1 :: " + current.ToString() + " --> " + DateTime.Now.ToString());
}
}
public async Task RegisterReminder() {
try {
var previousRegistration = GetReminder("Reminder1");
await UnregisterReminderAsync(previousRegistration);
} catch (ReminderNotFoundException) { }
var reminderRegistration = await RegisterReminderAsync("Reminder1",
null, TimeSpan.FromMinutes(0), TimeSpan.FromMinutes(1));
}
}
internal class ScheduledActorService<T> : ActorService where T : IActor {
public ScheduledActorService(StatefulServiceContext context, ActorTypeInformation actorType) : base(context, actorType) { }
protected async override Task RunAsync(CancellationToken cancellationToken) {
await base.RunAsync(cancellationToken);
var proxy = ActorProxy.Create<T>(new ActorId(0));
switch (proxy) {
case IActor1 a1:
await a1.RegisterReminder();
break;
case IActor2 a2:
await a2.RegisterReminder();
break;
default:
throw new NotImplementedException($"{GetType().FullName}.{nameof(RunAsync)}");
}
}
}
Related
I have a problem when try get the json object from json array. The catched error say that JSONArray cannot be convertered to JSONObject. Effectively can get JSON response from web service, but i don't know how convert array to object
error message
org.json.JSONException: Value [{"codaspirante":"1","nombre":"Saul","apellido":"Goodman","mail":"sg#g.com","telefono":"012034948123","codusuario":"0"},{"codaspirante":"2","nombre":"Lalo","apellido":"Salamanca","mail":"ls#g.com","telefono":"12351233","codusuario":"10"},{"codaspirante":"3","nombre":"Walter","apellido":"White","mail":"ww#g.com","telefono":"54843439","codusuario":"10"},{"codaspirante":"4","nombre":"Gustavo","apellido":"Frings","mail":"gf#g.com","telefono":"845738848434","codusuario":"10"}] at 0 of type org.json.JSONArray cannot be converted to JSONObject
Method:
private void buscarCandidatos_Serivicio(String URL){
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, URL, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject candidato = response.getJSONObject(i);
Candidato c = new Candidato(
candidato.getInt("codaspirante"),
candidato.getString("nombre"),
candidato.getString("apellido"),
candidato.getString("mail"),
candidato.getString("telefono"),
candidato.getInt("codusuario")
);
listaCandidatos.add(c);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), e.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
);
RequestQueue rq= Volley.newRequestQueue(this);
rq.add(jsonArrayRequest);
}
The error is because response.getJSONObject(0) is returning a JSONArray and not a JSONObject.
I am guessing you want to fetch the data from that Array.
In your On response Method you should add response = response.getJSONArray(0).
public void onResponse(JSONArray response) {
try {
response = response.getJSONArray(0);
for (int i = 0; i < response.length(); i++) {
That should fix your problem.
val stringRequest = object : StringRequest(
Request.Method.POST, Config."your URL",
Response.Listener<String> { response ->
try {
val obj = JSONObject(response)
if (!obj.getBoolean("error")) {
val userssListArray = obj.getJSONArray("arrayname")
for (i in 0 until userssListArray.length()) {
var usersObj = userssListArray.getJSONObject(i)
}
} else {
if (obj.getString("message") == "Your login expired please re login") {
val intent = Intent(this, LoginActivity::class.java)
startActivity(intent)
finish()
}
}
} catch (e: JSONException) {
e.printStackTrace()
}
},
Response.ErrorListener {
Toast.makeText(this, "Network Error Try Again...", Toast.LENGTH_LONG).show()
}) {
#Throws(AuthFailureError::class)
override fun getParams(): Map<String, String> {
val params = HashMap<String, String>()
return params
}
}
stringRequest.retryPolicy = DefaultRetryPolicy(
15000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)
//adding request to queue
VolleySingleton.instance?.addToRequestQueue(stringRequest)
you can use volley like this
I am trying the fan-out, fan-in pattern. Here's my code
[FunctionName("af_cancellation")]
public static async Task<string> RunOrchestrator(
[OrchestrationTrigger] DurableOrchestrationContext context, ILogger log)
{
var taskList = new List<Task<string>>();
var tokenSource = new CancellationTokenSource();
taskList.Add(context.CallActivityAsync<string>("af_cancellation_Hello", new { ct = tokenSource.Token, city = "Tokyo" }));
taskList.Add(context.CallActivityAsync<string>("af_cancellation_Hello", new { ct = tokenSource.Token, city = "Seattle" }));
taskList.Add(context.CallActivityAsync<string>("af_cancellation_Hello", new { ct = tokenSource.Token, city = "London" }));
try
{
await Task.WhenAll(taskList);
}
catch (FunctionException)
{
log.LogError("trigger function failed");
tokenSource.Cancel();
}
string output = "";
foreach (var t in taskList)
{
output += t.Result;
}
return output;
}
I would like to cancel all the tasks in taskList if any of them throw an exception. What i am noticing is that await Task.WhenAll finishes all the tasks before moving forward.
Here's the sample trigger function
[FunctionName("af_cancellation_Hello")]
public static string SayHello([ActivityTrigger] DurableActivityContext context, ILogger log)
{
var data = context.GetInput<dynamic>();
var name = (string)data.city;
// unable to de-serialize cancellation token here but we'll ignore that.
var ct = JsonConvert.DeserializeObject<CancellationToken>(data.ct);
if (name != "London")
{
System.Threading.Thread.Sleep(1000 * 30);
}
else
{
System.Threading.Thread.Sleep(1000 * 10);
throw new FunctionException("don't like london");
}
log.LogInformation($"Saying hello to {name}.");
return $"Hello {name}!";
}
How can i achieve this?
According to this I think it's not possible. If you need to undo the job from the other activities that succeeded, you must take a look on the Saga Pattern and launch compensating activities.
more info:
https://microservices.io/patterns/data/saga.html
https://www.enterpriseintegrationpatterns.com/patterns/conversation/CompensatingAction.html
Below is my synchronous implementation of the IMessageSessionHandler interface. One problem I have is that when there are no messages in the queue the InitializeReceiverSync method will repeatedly run until the web job ungracefully times out in Azure, resulting in a failure. On the other hand if there are messages in the queue to be read, once they are read, the session closes and the program exits.
What is the best way to exit the method if there are no messages in the queue?
public void ReceiveMessagesFromAzure()
{
int i = 0;
while (i < 4)
{
var QueueName = ConfigurationManager.AppSettings["QueueName"];
var connectionString = ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"];
CancellationTokenSource cts = new CancellationTokenSource();
InitializeReceiverSync(connectionString, QueueName, cts.Token);
i++;
}
}
public void InitializeReceiverSync(string connectionString, string queueName, CancellationToken ct)
{
var receiverFactory = MessagingFactory.CreateFromConnectionString(connectionString);
ct.Register(() => receiverFactory.Close());
var client = receiverFactory.CreateQueueClient(queueName, ReceiveMode.PeekLock);
client.RegisterSessionHandler(
typeof(SessionHandler),
new SessionHandlerOptions
{
MessageWaitTimeout = TimeSpan.FromSeconds(5),
MaxConcurrentSessions = 1,
AutoComplete = false
});
}
class SessionHandler : IMessageSessionHandler
{
AzureRepository ar = new AzureRepository([queueName], [connectionString]);
void IMessageSessionHandler.OnMessage(MessageSession session, BrokeredMessage message)
{
ar.ProcessMessage(message);
}
void IMessageSessionHandler.OnCloseSession(MessageSession session)
{
Console.WriteLine("Session closed");
Environment.Exit(0);
}
void IMessageSessionHandler.OnSessionLost(Exception exception)
{
Console.WriteLine(exception.Message);
Console.WriteLine("Press any key to exit");
}
}
I am using xamarin forms. I want to pick photo from gallery for my iphone app and want to save it in Azure DB. Is there any solution available for xamarin forms. Or Is there any plugin available to deal with Photo, Document, or Audio. Any help is appreciated.
Using dependency service you can take or pick photos from Android / iPhone :-
Please refer to code below and try to implement the similar code:-
This is the interface in PCL:-
public interface IGalleryProvider
{
Task<List<AttachmentMediaFile>> PickPhotoAsync();
Task<List<AttachmentMediaFile>> PickAudioAsync();
Task<List<AttachmentMediaFile>> PickDocumentAsync();
Task<AttachmentMediaFile> PickProfilePhotoAsync();
Task SaveToGalleryAsync(AttachmentMediaFile file);
}
Below is the code using which you can pick or take photos from iPhone only:-
using AssetsLibrary;
using AVFoundation;
using ELCImagePicker;
using Foundation;
using MediaPlayer;
using MobileCoreServices;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using UIKit;
[assembly: Xamarin.Forms.Dependency(typeof(GalleryProvider))]
namespace SanketSample.MobileApp.Sample.iOS.Common
{
public class GalleryProvider : IGalleryProvider
{
private TaskCompletionSource<List<AttachmentMediaFile>> _audioPickedTask;
public async Task<List<AttachmentMediaFile>> PickAudioAsync()
{
_audioPickedTask = new TaskCompletionSource<List<AttachmentMediaFile>>();
var picker = new MPMediaPickerController();
ShowViewController(picker);
picker.ItemsPicked += OnAudioPicked;
picker.DidCancel += OnCancel;
var media = await _audioPickedTask.Task;
return media;
}
private void OnCancel(object sender, EventArgs e)
{
var picker = sender as MPMediaPickerController;
picker.DidCancel -= OnCancel;
picker.DismissViewController(true, null);
_audioPickedTask.TrySetResult(new List<AttachmentMediaFile>());
}
private void OnAudioPicked(object sender, ItemsPickedEventArgs e)
{
var media = new List<AttachmentMediaFile>();
var picker = sender as MPMediaPickerController;
picker.ItemsPicked -= OnAudioPicked;
picker.DismissViewController(true, null);
if (e.MediaItemCollection.Items != null)
{
foreach (var item in e.MediaItemCollection.Items)
{
//var vm1 = (new ViewModelLocator()).AttachmentsVM.SelectedAttachments.Add();
if (!item.IsCloudItem)
{
try
{
//var error = new NSError();
//var asset = new AVUrlAsset(item.AssetURL);
//var exporter = new AVAssetExportSession(asset, item.Title);
//exporter.OutputFileType = "com.apple.m4a-audio";
//AVAssetExportSession session = new AVAssetExportSession(asset, "");
//var reader = new AVAssetReader(asset, out error);
//var settings = new NSDictionary();
//Func<byte[]> bytesGetter = e.MediaItemCollection
//TODO item.Title, item.Title SSSanket,
//var _asset = AVAsset.FromUrl(NSUrl.FromFilename(item.AssetURL.ToString()));
//var _exportSession = new AVAssetExportSession(_asset, AVAssetExportSession.PresetPassthrough);
//_exportSession.OutputFileType = AVFileType.Aiff;
// media.Add(new AttachmentMediaFile(item.AssetURL.AbsoluteString, AttachmentMediaFileType.Audio, null , item.Title));
}
catch (Exception ex)
{
// throw ;
}
}
}
}
_audioPickedTask.TrySetResult(media);
}
public async Task<List<AttachmentMediaFile>> PickDocumentAsync()
{
var task = new TaskCompletionSource<List<AttachmentMediaFile>>();
var allowedUTIs = new string[]
{
UTType.UTF8PlainText,
UTType.PlainText,
UTType.RTF,
UTType.Text,
UTType.PDF,
"com.microsoft.word.doc",
"com.microsoft.excel.xls"
};
var pickerMenu = new UIDocumentMenuViewController(allowedUTIs, UIDocumentPickerMode.Open);
pickerMenu.DidPickDocumentPicker += (sender, args) =>
{
args.DocumentPicker.DidPickDocument += (sndr, pArgs) =>
{
var securityEnabled = pArgs.Url.StartAccessingSecurityScopedResource();
NSError err;
var fileCoordinator = new NSFileCoordinator();
var docs = new List<AttachmentMediaFile>();
// Read bytes.
fileCoordinator.CoordinateRead(pArgs.Url, 0, out err, (NSUrl newUrl) =>
{
NSData data = NSData.FromUrl(newUrl);
docs.Add(new AttachmentMediaFile(pArgs.Url.AbsoluteString, AttachmentMediaFileType.Doc, data.ToArray(),null));
task.TrySetResult(docs);
});
};
ShowViewController(args.DocumentPicker);
};
ShowViewController(pickerMenu);
return await task.Task;
}
public async Task<List<AttachmentMediaFile>> PickPhotoAsync()
{
var media = new List<AttachmentMediaFile>();
var picker = ELCImagePickerViewController.Instance;
picker.MaximumImagesCount = 15;
ShowViewController(picker);
await picker.Completion.ContinueWith(result =>
{
picker.BeginInvokeOnMainThread(() =>
{
picker.DismissViewController(true, null);
if (!result.IsCanceled && result.Exception == null)
{
var imageEditor = new ImageEditor();
var items = result.Result as List<AssetResult>;
foreach (var item in items)
{
var bbytes= imageEditor.ResizeImage(item.Image, 1024, 1024);
media.Add(new AttachmentMediaFile(item.Path, AttachmentMediaFileType.Photo, bbytes, item.Name));
}
}
});
});
return media;
}
public async Task<AttachmentMediaFile> PickProfilePhotoAsync()
{
AttachmentMediaFile selectMediaFile = null;
var picker = ELCImagePickerViewController.Instance;
picker.MaximumImagesCount = 1;
ShowViewController(picker);
await picker.Completion.ContinueWith(result =>
{
picker.BeginInvokeOnMainThread(() =>
{
picker.DismissViewController(true, null);
if (!result.IsCanceled && result.Exception == null)
{
var imageEditor = new ImageEditor();
var items = result.Result as List<AssetResult>;
foreach (var item in items)
{
var bbytes = imageEditor.ResizeImage(item.Image, 1024, 1024);
selectMediaFile = new AttachmentMediaFile(item.Path, AttachmentMediaFileType.Photo, bbytes, item.Name);
}
}
});
});
return selectMediaFile;
}
public async Task SaveToGalleryAsync(AttachmentMediaFile file)
{
var bytes = file.GetBytes();
var originalImage = ImageEditor.ImageFromByteArray(bytes);
var library = new ALAssetsLibrary();
var orientation = (ALAssetOrientation)originalImage.Orientation;
var nsUrl = await library.WriteImageToSavedPhotosAlbumAsync(originalImage.CGImage, orientation);
}
private void ShowViewController(UIViewController controller)
{
var topController = UIApplication.SharedApplication.KeyWindow.RootViewController;
while (topController.PresentedViewController != null)
{
topController = topController.PresentedViewController;
}
topController.PresentViewController(controller, true, null);
}
}
}
Below are useful classes :-
public class AttachmentMediaFile
{
private readonly Func<byte[]> _bytesGetter;
public string LocalPath { get; private set; }
public string Name { get; private set; }
public AttachmentMediaFileType Type { get; private set; }
public AttachmentMediaFile(string localPath, AttachmentMediaFileType type, byte[] bytesGetter, string name = null)
{
LocalPath = localPath;
Type = type;
_bytesGetter = () =>
{
return bytesGetter;
};
if (string.IsNullOrEmpty(name))
{
Name = FileNameHelper.PrepareName(localPath);
}
else
{
Name = name;
}
}
public byte[] GetBytes()
{
return _bytesGetter();
}
}
public enum AttachmentMediaFileType
{
Photo = 0,
Audio = 1,
Doc = 2,
Video = 3,
}
public static class FileNameHelper
{
private const string Prefix = "IMG";
public static string PrepareName(string localPath)
{
var name = string.Empty;
if (!string.IsNullOrEmpty(localPath))
{
name = localPath.Split('/').Last();
}
return name;
}
public static string GenerateUniqueFileName(Extension extension)
{
var format = ".jpg";
var fileName = string.Concat(Prefix, '_', DateTime.UtcNow.Ticks, format);
return fileName;
}
public enum Extension
{
JPG
}
}
Now if you want to store your data to Azure Server Table so you are already using Azure mobile service client SDK similarly you need Blob nuget from Azure using which you can save your photos by making blob objects to Azure server :-
use blob helper nuget from manage nuget package install Microsoft.WindowsAzure.Storage.Auth;
Microsoft.WindowsAzure.Storage.Blob;
this and try to implement the code similarly I given bellow:-
using Acr.UserDialogs;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using SanketSample.MobileApp.sample.Business.Azure;
using SanketSample.MobileApp.sample.Business.Interfaces;
using SanketSample.MobileApp.sample.Models;
using SanketSample.MobileApp.sample.Models.AzureTables;
using SanketSample.MobileApp.sample.Models.Media;
using SanketSample.MobileApp.sample.Utils;
using Xamarin.Forms;
namespace SanketSample.MobileApp.Sanket.Common.Media
{
public class BlobHelper
{
private const string ContainerName = "attachments";
private Dictionary<string, TaskCompletionSource<bool>> _tasks;
private IHttpService _httpservice { get; set; }
#region Singleton Implementation
private static readonly Lazy<BlobHelper> lazyInstance = new Lazy<BlobHelper>(() => new BlobHelper(), true);
private BlobHelper()
{
_tasks = new Dictionary<string, TaskCompletionSource<bool>>();
}
public static BlobHelper Instance
{
get { return lazyInstance.Value; }`enter code here`
}
#endregion Singleton Implementation
public async Task UploadAttachments(IList<AttachmentFile> attachments, long associatedRecordId, string category)
{
foreach (var attachment in attachments)
{
await UploadAttachment(attachment, associatedRecordId, category);
}
}
public async Task UploadAttachment(AttachmentFile attachment, long associatedRecordId, string category)
{
try
{
CommonHelper commonHelper = new CommonHelper();
attachment.ContainerName = ContainerName;
attachment.AssociatedRecordId = associatedRecordId;
//attachment.RecordId = commonHelper.GenerateRecordId();
if (attachment.FileExtension == null)
{
attachment.FileExtension = ConvertType(attachment.MediaFile);
}
attachment.Category = category;
var taskCompletionSource = new TaskCompletionSource<bool>();
if (!_tasks.ContainsKey(attachment.Name))
{ _tasks.Add(attachment.Name, taskCompletionSource); }
else
{
_tasks[attachment.Name] = taskCompletionSource;
}
// _tasks.Add(attachment.Name, taskCompletionSource);
var attachmentsTableOnline = AzureServiceProvider.Instance.GetRemoteTable<AttachmentFile>();
if (CheckInternetConnection.IsConnected())
{
await attachmentsTableOnline.InsertAsync(attachment);
}
var attachmentsTableOffline = AzureServiceProvider.Instance.GetLocalTable<AttachmentFile>();
await attachmentsTableOffline.InsertAsync(attachment);
if (!string.IsNullOrEmpty(attachment.SasQueryString))
{
var credentials = new StorageCredentials(attachment.SasQueryString);
var imageUri = new Uri(attachment.Uri);
var container = new CloudBlobContainer(new Uri(string.Format("https://{0}/{1}",
imageUri.Host, attachment.ContainerName)), credentials);
var blobFromSASCredential = container.GetBlockBlobReference(attachment.Name);
try
{
var bytes = attachment.MediaFile.GetBytes();
await blobFromSASCredential.UploadFromByteArrayAsync(bytes, 0, bytes.Length);
if (CheckInternetConnection.IsConnected())
{
await attachmentsTableOnline.UpdateAsync(attachment);
}
await attachmentsTableOffline.UpdateAsync(attachment);
taskCompletionSource.TrySetResult(true);
}
catch (Microsoft.WindowsAzure.Storage.StorageException ex)
{
// Throws from UploadFromByteArrayAsync, but image uploaded.
System.Diagnostics.Debug.WriteLine($"BlobHelper: {ex}");
taskCompletionSource.TrySetResult(true);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"BlobHelper: {ex}");
taskCompletionSource.TrySetResult(false);
}
}
}
catch (Exception ca)
{
//throw ca;
}
}
/// <summary>
/// Downloads Blob Data boject and returns the Byts[] data
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public async Task<byte[]> DownloadAttachment(AttachmentFile file)
{
byte[] bytes = null;
var fileContainer = file.Uri.Replace(file.Name, string.Empty);
var container = new CloudBlobContainer(new Uri(fileContainer));
var blob = container.GetBlockBlobReference(file.Name);
using (var stream = new MemoryStream())
{
var isExist = await blob.ExistsAsync();
if (isExist)
{
await blob.DownloadToStreamAsync(stream);
bytes = stream.ToArray();
}
}
return bytes;
}
/// <summary>
/// Updates the Attachments Byts in the Azure Local Tables.
/// </summary>
/// <param name="AttachmentFileRecordId">Attachments Byte[] Data.</param>
/// <returns></returns>
public async Task<byte[]> DownloadAttachmentFileDetails(long? AttachmentFileRecordId, IHttpService service)
{
_httpservice = service;
try
{
ResponseWrapper<AttachmentFileDetail> result = new ResponseWrapper<AttachmentFileDetail>();
if (AttachmentFileRecordId != null)
{
var request = Constants.API_BASE_URL + string.Format(Constants.API_ATTACHMENTS_PARAMETERS, AttachmentFileRecordId);
var response = await _httpservice.SendRequestAsync(HttpMethod.Get, request);
result.Status = response.Status;
if (response.IsSuccess)
{
result.Result = JsonConvert.DeserializeObject<AttachmentFileDetail>(response.Result);
if (result.Result == null)
{
result.Status = System.Net.HttpStatusCode.InternalServerError;
}
else
{
var output = result.Result;
var data = new List<AttachmentFileDetail>() { output };
await AzureServiceProvider.Instance.DatabaseService.InsertDataToLocalDB<AttachmentFileDetail>(data);
return result.Result.FileByteArray;
}
}
}
}
catch (Exception ex)
{
////throw ex;
}
finally
{
}
return null;
}
private string ConvertType(AttachmentMediaFile file)
{
switch (file.Type)
{
case AttachmentMediaFileType.Doc:
return "doc";
case AttachmentMediaFileType.Audio:
return "mp3";
}
return "jpeg";
}
}
}
media plugin on github
works pretty well for me.
I want to implement MDM in J2ME. Whenever I update App, I am able to upload New App in Mobile, I can upload it successfully. But My Problem is that, I want to replace existing App and then want to upload new App. As of now I can add App on Device with Different name (Same App Name is not working) but cant replace App.
Here is my code for MDM:
public void getUpdateApp() {
new Thread(new Runnable() {
public void run() {
try {
DataHelper dh = new DataHelper(parent);
dh.openRecord();
String response_rms = dh.getupdateAppinfo_str();
System.out.println("response from RMS of Update App info in appupdate---" + response_rms);
System.out.println("Sending update App Call.");
HttpConn httpConnect = new HttpConn(parent);
UserInfo userInfo = getUserInfo();
String data = "AppCode=" + AppData.appCode+ "&CurrentVersion=" + AppData.currentversion
+ "&TerminalNumber=" + userInfo.getTerminalNumber()
+ "&apifunction=" + "GetAppUpdate";
httpConnect.sendPostRequest_appupdate(AppData.AppUpdateURL, data, new ConnectionListener() {
public void onRequestFailure(Object title, Object message) {
System.out.println("==>GetUpdateApp Failure\nTitle:"
+ (String) title
+ "\n Failure Message" + (String) message);
showMessageDialog((String) title, (String) message, new SettingsForm("Settings", parent), 2000);
}
public void onRequestSuccess(Object httpResponse) {
try {
System.out.println("==>On Success--of Update App");
String response = (String) httpResponse;
System.out.println("==>Login Form--Update App \nResponse:" + response);
JSONObject jsonObject = new JSONObject(response);
int responseCode = Integer.parseInt(jsonObject.getString("ResponseCode"));
switch (responseCode) {
case 000: {
String latestbuild = jsonObject.getString("LatestBuild");
String latestversion = jsonObject.getString("LatestVersion");
String downloadURL = jsonObject.getString("DownloadURL");
if (latestversion != null) {
if (!latestversion.equals(AppData.currentversion) || !latestbuild.equals(AppData.currentBuild)) {
if (Integer.parseInt(latestbuild) > Integer.parseInt(AppData.currentBuild)) {
System.out.println("Download URL--" + downloadURL);
// parent.platformRequest(downloadURL);
System.out.println("platform request boolean variable returns---"+ parent.platformRequest(downloadURL));
parent.platformRequest(downloadURL);
parent.destroyApp(true);
} else {
System.out.println("Incomapatible types");
showMessageDialog("Alert", "No new updates available", new SettingsForm("Settings", parent),2000);
}
} else {
System.out.println("App Version Number is same,No New Build Available");
showMessageDialog("Alert", "Application is already upto date", new SettingsForm("Settings", parent),2000);
}
} else {
System.out.println("App version not available on server");
showMessageDialog("Alert", "No new updates available", new SettingsForm("Settings", parent),2000);
}
break;
}
}
} catch (JSONException ex) {
ex.printStackTrace();
showdisplayExceptionDialog(ex, new SettingsForm("Settings", parent));
} catch (ConnectionNotFoundException ex) {
showdisplayExceptionDialog(ex, new SettingsForm("Settings", parent));
}
}
});
} catch (Exception e) {
showdisplayExceptionDialog(e, new SettingsForm("Settings", parent));
}
}
}).start();
}
If any 1 has any idea regarding Replacing App in J2ME then please Help me. Thanks a lot in Advance.