ContentSharingModality ContentAdded event is not getting triggered (Lync silverlight application) - silverlight-4.0

My ultimate aim is to transfer a file from one Lync client to another. I have following code.
First of all I have following 2 events registered
1.
((Modality)_conversation.Modalities[ModalityTypes.ContentSharing]).ModalityStateChanged += Modality_ModalityStateChanged;
2.
((ContentSharingModality)_conversation.Modalities[ModalityTypes.ContentSharing]).ContentAdded += _sharingModality_ContentAdded;
code for those event is
void _sharingModality_ContentAdded(object sender, ContentCollectionChangedEventArgs e)
{
MessageBox.Show("content added\n"+e.Item);
}
void Modality_ModalityStateChanged(object sender, ModalityStateChangedEventArgs e)
{
if (e.NewState == ModalityState.Connected)
{
textBox1.Text += "\nconnected";
send_file();
}
if (e.NewState == ModalityState.Connecting)
{
textBox1.Text += "\nconnecting";
}
}
Then I have a method which creates a file in isolated storage named "abc.txt".
Next there is a code which connects the content sharing modality.
private void button4_Click(object sender, RoutedEventArgs e)
{
if (_conversation.State == ConversationState.Active)
{
((Modality)_conversation.Modalities[ModalityTypes.ContentSharing])
.BeginConnect((ar) =>{((Modality)_conversation.Modalities[ModalityTypes.ContentSharing]).EndConnect(ar); }
, null);
else { MessageBox.Show("conversation not active"); }
}
After this there is 'send_file' method which actually upload the file. (this method id previously called when modality state changes to 'connected' but there (I think) conversation changes to multiparty and method returns false at 'canInvoke' statement. So Im calling it again and this time it succeeds. It is as below
void send_file()
{
if (((ContentSharingModality)_conversation.Modalities[ModalityTypes.ContentSharing]).State == ModalityState.Connected)
{
try
{
if (((ContentSharingModality)_conversation.Modalities[ModalityTypes.ContentSharing]).CanInvoke(ModalityAction.CreateShareableNativeFileOnlyContent))
{
ContentSharingModality contentSharingModality = (ContentSharingModality)_conversation.Modalities[ModalityTypes.ContentSharing];
contentSharingModality.BeginCreateContentFromFile(ShareableContentType.NativeFile, "samplefile.txt", fileNameFromIsolatedStorage, true,
(ar) =>
{
ShareableContent sContent = contentSharingModality.EndCreateContentFromFile(ar);
//_NativeFileNameAndPath = string.Empty;
sContent.Upload();
}
, null);
MessageBox.Show("upload done");
}
else { MessageBox.Show("u cannot invoke"); }
}
catch (Exception e1) { MessageBox.Show(e1.Message); }
}
else { MessageBox.Show("modality inactive"); }
}
Finally this is all I'm trying to do. The same code will lie on both sender & receiver machines. I'm new to lync development and very confused about what is going wrong. Please help. Thanks!

Related

(React Native) Huawei Location Kit - is there any way to know if network location services setting switch off?

to make our apps working indoor to fetch location we need Network Location Services switch to be on
And we're using this function to detect any setting that still off
We noticed the response which is LocationSettingsStates, when the switch on or off is always true
Am I using wrong function to detect it??
The class and methods mentioned in the original post are the right ones to be used for checking network location service availability.
Please refer to a partial code extracted from Huawei sample code obtained from Github
public void checkSettings(View view) {
new Thread() {
#Override
public void run() {
try {
CheckSettingsRequest checkSettingsRequest = new CheckSettingsRequest();
LocationRequest locationRequest = new LocationRequest();
checkSettingsRequest.setLocationRequest(locationRequest);
checkSettingsRequest.setAlwaysShow(false);
checkSettingsRequest.setNeedBle(false);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(checkSettingsRequest.getLocationRequest())
.setAlwaysShow(checkSettingsRequest.isAlwaysShow())
.setNeedBle(checkSettingsRequest.isNeedBle());
settingsClient.checkLocationSettings(builder.build())
.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
#Override
public void onComplete(Task<LocationSettingsResponse> task) {
if (task != null && task.isSuccessful()) {
LocationSettingsResponse response = task.getResult();
if (response == null) {
return;
}
LocationSettingsStates locationSettingsStates =
response.getLocationSettingsStates();
stringBuilder.append(",\nisLocationPresent=")
.append(locationSettingsStates.isLocationPresent());
stringBuilder.append(",\nisLocationUsable=")
.append(locationSettingsStates.isLocationUsable());
stringBuilder.append(",\nisNetworkLocationUsable=")
.append(locationSettingsStates.isNetworkLocationUsable());
stringBuilder.append(",\nisNetworkLocationPresent=")
.append(locationSettingsStates.isNetworkLocationPresent());
stringBuilder.append(",\nisHMSLocationUsable=")
.append(locationSettingsStates.isHMSLocationUsable());
stringBuilder.append(",\nisHMSLocationPresent=")
.append(locationSettingsStates.isHMSLocationPresent());
LocationLog.i(TAG, "checkLocationSetting onComplete:" + stringBuilder.toString());
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(Exception e) {
LocationLog.i(TAG, "checkLocationSetting onFailure:" + e.getMessage());
int statusCode = 0;
if (e instanceof ApiException) {
statusCode = ((ApiException) e).getStatusCode();
}
switch (statusCode) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
android.util.Log.i(TAG,
"Location settings are not satisfied. Attempting to upgrade "
+ "location settings ");
try {
// Show the dialog by calling startResolutionForResult(), and check the
// result in onActivityResult().
if (e instanceof ResolvableApiException) {
ResolvableApiException rae = (ResolvableApiException) e;
rae.startResolutionForResult(CheckSettingActivity.this, 0);
}
} catch (IntentSender.SendIntentException sie) {
android.util.Log.i(TAG, "PendingIntent unable to execute request.");
}
break;
default:
break;
}
}
});
} catch (Exception e) {
LocationLog.i(TAG, "checkLocationSetting exception:" + e.getMessage());
}
}
}.start();
}
The execution results when “network location service” is turned on and off are shown below. It shows the state with true and false respectively.
In some phone, LocationSettings interface may not be able to get the exact state.
You can set the Priority to be PRIORITY_BALANCED_POWER_ACCURACY and use requestLocationUpdatesWithCallback interface to get location update.
If the network location is not enabled, you will get the error code NETWORK_LOCATION_SERVICES_DISABLED 10105.
Then it means the switch is not enabled.

Accessing activity 2 while foreground is activity 1 (either using OOP or Service in XAMARIN)

i code this from a tutorial for locating your location (but I already made some changes)
using Android.App;
using Android.Widget;
using Android.OS;
using Android.Locations;
using System.Collections.Generic;
using Android.Util;
using System.Linq;
using Java.Lang;
using System.Threading.Tasks;
using System;
using Android.Views;
using Android.Content;
namespace LocatorApp
{
[Activity(Label = "Locator", MainLauncher = true, Icon = "#drawable/locator_ico")]
public class LocatorApp : Activity, ILocationListener
{
static readonly string TAG = "X:" + typeof(LocatorApp).Name;
TextView _addressText;
Location _currentLocation;
LocationManager _locationManager;
Address address;
string _locationProvider;
TextView _locationText;
private double latitude = 0;
private double longitude = 0;
public Location getCurrentLocation() { return _currentLocation; }
public double getLatitude() { return latitude; }
public double getLongitude() { return longitude; }
public Address getAddress() { return address; }
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
_addressText = FindViewById<TextView>(Resource.Id.address_text);
_locationText = FindViewById<TextView>(Resource.Id.location_text);
FindViewById<TextView>(Resource.Id.get_address_button).Click += AddressButton_OnClick;
InitializeLocationManager();
}
public void InitializeLocationManager()
{
_locationManager = (LocationManager)GetSystemService(LocationService);
Criteria criteriaForLocationService = new Criteria
{
Accuracy = Accuracy.Coarse,
PowerRequirement = Power.Medium
};
IList<string> acceptableLocationProviders = _locationManager.GetProviders(criteriaForLocationService, true);
if (acceptableLocationProviders.Any())
{
_locationProvider = acceptableLocationProviders.First();
}
else
{
_locationProvider = string.Empty;
}
Log.Debug(TAG, "Using " + _locationProvider + ".");
}
async void AddressButton_OnClick(object sender, EventArgs eventArgs)
{
if (_currentLocation == null)
{
Toast.MakeText(this, "Still waiting for location.", ToastLength.Short).Show();
}
else
{
try
{
var geoUri = Android.Net.Uri.Parse("geo:" + _currentLocation.Latitude + "," + _currentLocation.Longitude);
var mapIntent = new Intent(Intent.ActionView, geoUri);
StartActivity(mapIntent);
}
catch (System.Exception e)
{
Toast.MakeText(this, "Sorry, there is a problem with geomapping.", ToastLength.Short).Show();
}
}
}
async Task<Address> ReverseGeocodeCurrentLocation()
{
try
{
Geocoder geocoder = new Geocoder(this);
IList<Address> addressList =
await geocoder.GetFromLocationAsync(_currentLocation.Latitude, _currentLocation.Longitude, 10);
Address address = addressList.FirstOrDefault();
return address;
}
catch (System.Exception e)
{
throw;
}
return null;
}
void DisplayAddress(Address address)
{
if (address != null)
{
StringBuilder deviceAddress = new StringBuilder();
for (int i = 0; i < address.MaxAddressLineIndex; i++)
{
deviceAddress.Append(address.GetAddressLine(i));
}
// Remove the last comma from the end of the address.
_addressText.Text = "Address: "+deviceAddress.ToString();
}
else
{
_addressText.Text = "Unable to determine the address. Try again in a few minutes.";
}
}
public async void OnLocationChanged(Location location)
{
Toast.MakeText(this, "Location changed.", ToastLength.Short).Show();
_currentLocation = location;
if (_currentLocation == null)
{
_locationText.Text = "Unable to determine your location. Try again in a short while.";
}
else
{
try
{
_locationText.Text = "Location: " + string.Format("{0:f6},{1:f6}", _currentLocation.Latitude, _currentLocation.Longitude);
Address address = await ReverseGeocodeCurrentLocation();
DisplayAddress(address);
var nMgr = (NotificationManager)GetSystemService(NotificationService);
var notification = new Notification(Resource.Drawable.Icon, "Message from LocatorApp");
var pendingIntent = PendingIntent.GetActivity(this, 0, new Intent(this, typeof(LocatorApp)), 0);
notification.SetLatestEventInfo(this, "LocatorApp", "Location changed!", pendingIntent);
nMgr.Notify(0, notification);
}
catch (Java.Lang.Exception e)
{
_addressText.Text = "Unable to determine the address. Try again in a few minutes.";
Toast.MakeText(this, "Error Occured On Geocoder!", ToastLength.Short).Show();
Log.Error(TAG, e.Message);
}
}
}
public void OnProviderDisabled(string provider) { }
public void OnProviderEnabled(string provider) { }
public void OnStatusChanged(string provider, Availability status, Bundle extras) { }
protected override void OnResume()
{
base.OnResume();
if (_locationManager.IsProviderEnabled(_locationProvider))
{
_locationManager.RequestLocationUpdates(_locationProvider, 100, 0, this);
Toast.MakeText(this, _locationProvider.ToString(), ToastLength.Short).Show();
}
else
{
Toast.MakeText(this, "There is a problem with "+_locationProvider.ToString()+" provider.", ToastLength.Short).Show();
}
}
protected override void OnPause()
{
base.OnPause();
_locationManager.RemoveUpdates(this);
}
}
}
(i'm just having my experiment)
what I want is to run activity B while foreground is in activity A, just like a basic OOP . but my problem is, I don't know how to make it run. I can't also jump to activity B since it has an oncreate method. I instantiated it and can get the variables values but they are null (seems there is no process happened) . What can be a best solution for this.
note: I am currently looking how to use service for background processing but also i don't know how to run this code after I typed it from a tutorial :( there is only a tutorial for creating a service part but no tutorial for buttons to access it :(
using System;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Util;
using System.Threading;
namespace LocatorApp
{
[Service]
class SimpleService : Service
{
static readonly string TAG = "X:" + typeof(SimpleService).Name;
static readonly int TimerWait = 4000;
Timer _timer;
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
Log.Debug(TAG, "OnStartCommand called at {2}, flags={0}, startid={1}", flags, startId, DateTime.UtcNow);
_timer = new Timer(o => { Log.Debug(TAG, "Hello from SimpleService. {0}", DateTime.UtcNow); },
null,
0,
TimerWait);
return StartCommandResult.NotSticky;
}
public override void OnDestroy()
{
base.OnDestroy();
_timer.Dispose();
_timer = null;
Log.Debug(TAG, "SimpleService destroyed at {0}.", DateTime.UtcNow);
}
public override IBinder OnBind(Intent intent)
{
// This example isn't of a bound service, so we just return NULL.
return null;
}
}
}
I want to know both (OOP way and service way) since not at all time we are required to use the service.
what I want is to run activity B while foreground is in activity A, just like a basic OOP . but my problem is, I don't know how to make it run. I can't also jump to activity B since it has an oncreate method.
You can call Context.StartActivity inside your Activity with following codes:
StartActivity(new Android.Content.Intent(this, typeof(ActivityB)));
And StartActivity will call OnCreate method in ActivityB to create a new instance of ActivityB.
For details about Starting Activities, please refer to Starting Activities and Getting Results.
I am currently looking how to use service for background processing but also i don't know how to run this code after I typed it from a tutorial :( there is only a tutorial for creating a service part but no tutorial for buttons to access it :(
Similar like Activity Context.StartService offers a way to start a Service:
StartService (new Intent (this, typeof(DemoService)));
This will call the OnStartCommand method inside your Service class.
For details about usage of Service, please refer to Implementing a Service.

Error: file doesn't exist

Now am working on a project where I need to create a folder in sdcard which am able to do. Also I need to hide/unhide it according to need. The code is working fine on emulator but not in device this is my code what went wrong ?
public class FolderCreate extends MIDlet {
private Form form;
private Display display;
FileConnection fc;
String path;
public void startApp() {
form = new Form("Hello World");
String msg = "Hello World!!!!!!!";
form.append(msg);
display = Display.getDisplay(this);
display.setCurrent(form);
System.out.println("WWWW");
try {
path = System.getProperty("fileconn.dir.memorycard");
System.out.println("Path : "+path+"/sample");
fc = (FileConnection)Connector.open(path+"/ABCD/");
if(!fc.exists())
{
fc.mkdir();
System.out.println("directory created");
}
} catch (IOException e) {
// TODO Auto-generated catch block
//System.out.println("ERROR "+e.getMessage());
Alert alert = new Alert("Alert");
alert.setString(e.getMessage());
display.setCurrent(alert);
}
try
{
//fc = (FileConnection)Connector.open(path+"/sample/");
if(fc.isHidden())
{
fc.setHidden(false);
}
else{
fc.setHidden(true);
}
fc.close();
}
catch (Exception e)
{
Alert alert = new Alert("Alert2");
alert.setString(e.toString());
display.setCurrent(alert);
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
System.out.println("Destroyed");
notifyDestroyed();
}
}
The error am getting is: java.io.IOException: file does not exist
Check if path starts with "file://". If not, add the suffix.
path = System.getProperty("fileconn.dir.memorycard");
if (path != null && !path.startsWith("file://")) {
path = "file://" + path;
}
I think you are doing mistake at following line,
path = System.getProperty("fileconn.dir.memorycard");
When you are working with phone and SD-Card you should use e: drive for referring to SD Card as follows,
path = file:///e:/<folder-name>/

Improve software responsiveness when slider is manipulated in windows phone

I have a slider in my windows phone 7.1 project. When manipulated, this slider fires an event which starts a background worker to performs several trigonometric operations.
If I move the cursor on the slider, I have a certain delay in the response although I have implement background worker cancelAsync method in manipulationstarted event, I would like more responsiveness, how can I achieve this?
Code:
private void sliderCosinus_ManipulationStarted(object sender,ManipulationStartedEventArgs e)
{
if (bw.WorkerSupportsCancellation == true)
{
bw.CancelAsync(); // Cancel the asynchronous operation.
}
}
private void sldCosinus_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
{
try
{
Value = Convert.ToInt32(sldCosinus.Value) * 10;
}
catch
{
// errore message here
}
finally
{
}
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
if ((worker.CancellationPending == true))
{
e.Cancel = true;
}
else
{
Dispatcher.BeginInvoke(() => app.IsEffectApplied=TrigonometricTrans()
// TrigonomtriecTrans calculate sin and cosinus for every pixel in image
}
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// progress bar here
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if ((e.Cancelled == true))
{
//this.tbProgress.Text = "Canceled!";
}
else if (!(e.Error == null))
{
//this.tbProgress.Text = ("Error: " + e.Error.Message);
}
else
{
DoubleBufferToScreen();
}
}

CommunicationException in WCF Service

My problem is that AddExcursionAsync doesn't work, it shows CommunicationException.
In Console application this code works well. But in Silverlight it makes error. Functions
AddListOgTourNumbersAsync and GetListOfTourNumberAsync work correctly. Where I did the error?
Code:
private AdminServiceClient client;
public AddExcursionDialog()
{
InitializeComponent();
DurationElement.Value = new DateTime();
client = new AdminServiceClient();
client.GetListOfTourNumberCompleted += new EventHandler<GetListOfTourNumberCompletedEventArgs>(GetListOfTourNumber);
client.AddListOgTourNumbersCompleted += new EventHandler<AsyncCompletedEventArgs>(AddListOfTourNumbers);
client.AddExcursionCompleted += new EventHandler<AsyncCompletedEventArgs>(AddExcursion);
}
private void OKButton_Click(object sender, RoutedEventArgs e)
{
excursion = new Excursion();
excursion.Name = NameText.Text;
excursion.Cost = Convert.ToDouble(CostText.Text);
excursion.Place = PlaceText.Text;
excursion.Duration= (DateTime)DurationElement.Value;
excursion.Agency_id = tour_names[AgencyCB.SelectedValue.ToString()];
excursion.MaxPpl = Convert.ToInt32(MaxPplText.Text);
client.GetListOfTourNumberAsync();
client.AddExcursionAsync(excursion);
client.AddListOgTourNumbersAsync(tour_id, excursion.NumberOfList);
this.DialogResult = true;
}
I have also battled with CommunicationException(s). At that point, I believe the network were experiencing regular problems.
In my scenario I had to stabilise this call with a retry algorithm.
I'm not saying you should do this all the time, but use it to test.
In this code, the exception is allowed to be thrown if the 3rd attempt fails.
string[] Images64;
try { /* 1st try */
Images64 = _VideoClient.GetImagesStr(ImagePaths[0], ImagePaths[1], LFrame, RFrame);
}
catch (CommunicationException) {
try { /* 2nd try */
Images64 = _VideoClient.GetImagesStr(ImagePaths[0], ImagePaths[1], LFrame, RFrame);
}
catch (CommunicationException) {
try { /* 3rd try */
Images64 = _VideoClient.GetImagesStr(ImagePaths[0], ImagePaths[1], LFrame, RFrame);
}
catch (CommunicationException) {
throw;
}
}
}