Hello I'm using Lync SDK 2013, to display number phones from contact in ListBox, and use the Items (phone number) to call this number by my API. So i did a WPF application, that contains just a ListBox, and 2 buttons (Call - Hang up). My apllication is added as custom command in Lync, in RightClick in the contact. and it doesn't have any Lync Controls. So what i want to do is: if i Right Click on the contact, my application launches and gives me the number phone List in the ListBox. I did it with a WPF that contains the controls: ContactSearchInputBox (to search a contact) and ContactSearchResultList and it works very Well, I don't know how to do it without controls.
Any One Can Help Me !!!! :(
You need to read and understand the Lync SDK 2013 Lync Contact documentation.
If you wish to "simulate" the Lync Contact "search" (as per the Client search) then you need to look into the search API.
The other concepts you need to understand is the results returned from all the API are NOT guaranteed to return all the Lync Contact data that asked for.
There is no way with the Lync SDK to "load" all the contact information which is what most people seem to not understand.
The results returned are what the local cache has and no more. To get the all the Lync Contact information you need to understand the ContactSubscription model.
For each Lync Contact that you wish to be notified of field updates (or loads) you "subscribe" to the Lync Contact and then you will be notified via the Contact.ContactInformationChanged event.
So your UI must to able to auto-update the information as the fields get loaded / updated from any initial value returned from any Lync Contact value.
public partial class ChoosePhoneNumber : Window
{
LyncClient lync_client;
Contact contact;
ContactSubscription contact_subscription;
List<ContactInformationType> contact_information_list;
ContactManager contact_manager;
public ChoosePhoneNumber()
{
InitializeComponent();
connect_lync();
get_subscribed_contact(this.contact);
}
}
private void connect_lync()
{
try
{
lync_client = LyncClient.GetClient();
contact_manager = lync_client.ContactManager;
}
catch (ClientNotFoundException)
{
MessageBox.Show("Client is ot running", "Error While GetClient", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void get_subscribed_contact(Contact contact)
{
List<object> contact_phone_numbers_list = new List<object>();
contact_information_list = new List<ContactInformationType>();
contact_information_list.Add(ContactInformationType.ContactEndpoints);
contact_information_list.Add(ContactInformationType.DisplayName);
contact = contact_manager.GetContactByUri("number"); // I put here the number phone of a contact in my list
contact_subscription = LyncClient.GetClient().ContactManager.CreateSubscription();
contact_subscription.AddContact(contact);
contact.ContactInformationChanged += Contact_ContactInformationChanged;
contact_subscription.Subscribe(ContactSubscriptionRefreshRate.High, contact_information_list);
List<object> endpoints = (List<object>)contact.GetContactInformation(ContactInformationType.ContactEndpoints);
var phone_numbers_list = endpoints.Where<object>(N => ((ContactEndpoint)N).Type == ContactEndpointType.HomePhone ||
((ContactEndpoint)N).Type == ContactEndpointType.MobilePhone || ((ContactEndpoint)N).Type == ContactEndpointType.OtherPhone
|| ((ContactEndpoint)N).Type == ContactEndpointType.WorkPhone).ToList<object>();
var name = contact.GetContactInformation(ContactInformationType.DisplayName);
if (phone_numbers_list != null)
{
foreach (var phone_number in phone_numbers_list)
{
contact_phone_numbers_list.Add(((ContactEndpoint)phone_number).DisplayName);
}
conboboxPhoneNumbers.ItemsSource = contact_phone_numbers_list;
}
}
private void Contact_ContactInformationChanged(object sender, ContactInformationChangedEventArgs e)
{
var contact = (Contact)sender;
if (e.ChangedContactInformation.Contains(ContactInformationType.ContactEndpoints))
{
update_endpoints(contact);
}
}
private void update_endpoints(Contact contact)
{
if ((lync_client != null) && (lync_client.State == ClientState.SignedIn))
{
ContactEndpoint endpoints = (ContactEndpoint)contact.GetContactInformation(ContactInformationType.ContactEndpoints);
}
}
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
App.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException; ;
try
{
string argsParam = "Contacts=";
if (e.Args.Length > 1)
{
if (e.Args[2].Contains(argsParam))
{
var contacts_sip_uri = e.Args[2].Split('<', '>')[1];
Params.contacts = contacts_sip_uri;
}
}
}
catch (Exception ex)
{
MessageBox.Show("Reading Startup Arguments Error - " + ex.Message);
}
}
private void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
string message = e.Exception.Message;
if (e.Exception.InnerException != null)
{
message += string.Format("{0}Inner Exception: {1}", Environment.NewLine, e.Exception.InnerException.Message);
}
MessageBox.Show(message, "Unhandled Exception", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
Params is a public static class that contains just contact as public static string contacts { get; set; }
public static class ParamContact
{
public static string contacts { get; set; }
}
Related
i'm trying to create an application where data in a list must be inserted into a database table at once. I made some research and found out that this is possible using user-defined table types where in c# a datatable is used and passed to a stored procedure that is executed. now my problem is that there are no data tables in Xamarin.Android. so I thought to use a list instead. my idea was to create a list in the application and pass it to the webservice method, and in my webservice method I receive the list and convert it to a datatable then pass it as a parameter to the stored procedure. I wrote the following codes:
in my webservice:
[WebMethod]
public bool insrt_dt(List<Class1> lst)
{
SqlParameter param;
SqlConnection conn = new SqlConnection(new DBConnection().ConnectionString);
DataTable dt = list_to_dt(lst);
SqlCommand cmd = new SqlCommand("Insert_Customers", conn);
cmd.CommandType = CommandType.StoredProcedure;
if (conn.State == System.Data.ConnectionState.Closed)
{
conn.Open();
}
param = new SqlParameter("#tblcustomers", dt);
param.Direction = ParameterDirection.Input;
param.DbType = DbType.String;
cmd.Parameters.Add(param);
cmd.CommandTimeout = 300;
int a=cmd.ExecuteNonQuery();
if (a > 0)
{
return true;
}
else return false;
}
}
Class1:
public class Class1
{
public int id { get; set; }
public string name { get; set; }
public string country { get; set; }
}
in my Xamarin.Android app
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
Button btn = FindViewById<Button>(Resource.Id.button1);
btn.Click += delegate
{
wr.WebService1 ws = new wr.WebService1();
wr.Class1 class1 = new wr.Class1();
List<wr.Class1> lst = new List<wr.Class1>(){
new wr.Class1() { id = 1, name = "hgf", country = "khg" },
new wr.Class1() { id = 2, name = "hgf", country = "khg"} };
ws.insrt_dt(lst);
ws.insrt_dtCompleted += Ws_insrt_dtCompleted;
};
}
private void Ws_insrt_dtCompleted(object sender, wr.insrt_dtCompletedEventArgs e)
{
bool l = e.Result;
if (l == true)
Toast.MakeText(this, "khh", ToastLength.Long).Show();
else
Toast.MakeText(this, "ijo'pioo", ToastLength.Long).Show();
}
}
but I keep getting this error:
Argument 1: cannot convert from 'System.Collections.Generic.List<app_dt.wr.Class1>' to 'app_dt.wr.Class1[]
so I used these lines instead
new wr.Class1() { id = 1, name = "hgf", country = "khg" },
new wr.Class1() { id = 2, name = "hgf", country = "khg"} };
wr.Class1[] class1s = lst.ToArray();
ws.insrt_dt(class1s);
now I don't get an error, but it doesn't work, I mean why does it say that the webservice method input must be an array and I've created it as a list. any suggestions for this?
As i know, Xamarin do not support System.Data.SqlClient. If you want to use the database for the Xamarin android project, you could use the SQLite.NET.
Install the package from the NuGet.
NuGet: sqlite-net-pcl https://www.nuget.org/packages/sqlite-net-pcl/
For the code sample about how to use the database in Xamarin, you could check the link below. https://learn.microsoft.com/en-us/xamarin/get-started/quickstarts/database?pivots=windows
For Xamarin.Android, you could check the sample code in the link below. https://learn.microsoft.com/en-us/xamarin/android/data-cloud/data-access/using-sqlite-orm
I want running this method UpdateStatus when he close app
It is my coding method UpdateStatus in android:
String id = "";
var id = Application.Current.Properties["Id"].ToString();
User user = new User(id);
user.Id = id;
user.Datetime = time;
var responseStatus = await api.UpdateStatus(new UpdateStatusQuery(user));
Could you help me ?
In the Android, When you close your applcation, based on my research, above code can not be run, because all of threads or services will be killed when applcation is killed.
If you want to run above code when application in the background, you can can use background service to achieve that, due to background execution limits in Android 8.0 or later, if you code need some time to execute, and you want code running stably, Foreground Services is a good choice.
In xamarin forms, you can use dependenceService in the OnSleep method of App.xaml.cs
OnSleep - called each time the application goes to the background.
You can create a interface.
IService.cs
public interface IService
{
void Start();
}
Then achieved DependentService to start a Foreground Service.
[assembly: Xamarin.Forms.Dependency(typeof(DependentService))]
namespace TabGuesture.Droid
{
[Service]
public class DependentService : Service, IService
{
public void Start()
{
var intent = new Intent(Android.App.Application.Context,
typeof(DependentService));
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
{
Android.App.Application.Context.StartForegroundService(intent);
}
else
{
Android.App.Application.Context.StartService(intent);
}
}
public override IBinder OnBind(Intent intent)
{
return null;
}
public const int SERVICE_RUNNING_NOTIFICATION_ID = 10000;
public override StartCommandResult OnStartCommand(Intent intent,
StartCommandFlags flags, int startId)
{
// From shared code or in your PCL
CreateNotificationChannel();
string messageBody = "service starting";
var notification = new Notification.Builder(this, "10111")
.SetContentTitle(Resources.GetString(Resource.String.app_name))
.SetContentText(messageBody)
.SetSmallIcon(Resource.Drawable.main)
.SetOngoing(true)
.Build();
StartForeground(SERVICE_RUNNING_NOTIFICATION_ID, notification);
//==============================do you work=====================
String id = "";
var id = Application.Current.Properties["Id"].ToString();
User user = new User(id);
user.Id = id;
user.Datetime = time;
var responseStatus = await api.UpdateStatus(new UpdateStatusQuery(user));
return StartCommandResult.Sticky;
}
void CreateNotificationChannel()
{
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
// Notification channels are new in API 26 (and not a part of the
// support library). There is no need to create a notification
// channel on older versions of Android.
return;
}
var channelName = Resources.GetString(Resource.String.channel_name);
var channelDescription = GetString(Resource.String.channel_description);
var channel = new NotificationChannel("10111", channelName, NotificationImportance.Default)
{
Description = channelDescription
};
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.CreateNotificationChannel(channel);
}
}
}
Here is similar thread:
How to create service doing work at period time in Xamarin.Forms?
I need to get sitecore information that collected from anonymous users to give him availability to export it or opt out - [GDPR]
any idea about contact ID for anonymous !
The way of doing it is dependent on the sitecore version.
Sitcore 9 you can use right to be forgotten
Sitecore 8+ you have to implement the feature from scratch.
Regarding Anonymous user - If the user is really anonymous, then you done need to worry about the GDPR (my view). But sometimes we map user email and sensitive personal info to anonymous user by using forms or WFFM. You can use email address of that user to query xDB (Contact Identifiers) to get the contact and contactID. Then reset informations.
Also: please note that based on WFFFM save action config, anonymous user will store in Core DB and Contact List.
To forget a user, you can use the following code. It will execute the ExecuteRightToBeForgotten function on the contact and scrub their data.
Forget User
public bool ForgetUser()
{
var id = _contactIdentificationRepository.GetContactId();
if (id == null)
{
return false;
}
var contactReference = new IdentifiedContactReference(id.Source, id.Identifier);
using (var client = _contactIdentificationRepository.CreateContext())
{
var contact = client.Get(contactReference, new ContactExpandOptions());
if (contact != null)
{
client.ExecuteRightToBeForgotten(contact);
client.Submit();
}
}
return false;
}
Fake up some data
public void FakeUserInfo()
{
var contactReference = _contactIdentificationRepository.GetContactReference();
using (var client = SitecoreXConnectClientConfiguration.GetClient())
{
// we can have 1 to many facets
// PersonalInformation.DefaultFacetKey
// EmailAddressList.DefaultFacetKey
// Avatar.DefaultFacetKey
// PhoneNumberList.DefaultFacetKey
// AddressList.DefaultFacetKey
// plus custom ones
var facets = new List<string> { PersonalInformation.DefaultFacetKey };
// get the contact
var contact = client.Get(contactReference, new ContactExpandOptions(facets.ToArray()));
// pull the facet from the contact (if it exists)
var facet = contact.GetFacet<PersonalInformation>(PersonalInformation.DefaultFacetKey);
// if it exists, change it, else make a new one
if (facet != null)
{
facet.FirstName = $"Myrtle-{DateTime.Now.Date.ToString(CultureInfo.InvariantCulture)}";
facet.LastName = $"McSitecore-{DateTime.Now.Date.ToString(CultureInfo.InvariantCulture)}";
// set the facet on the client connection
client.SetFacet(contact, PersonalInformation.DefaultFacetKey, facet);
}
else
{
// make a new one
var personalInfoFacet = new PersonalInformation()
{
FirstName = "Myrtle",
LastName = "McSitecore"
};
// set the facet on the client connection
client.SetFacet(contact, PersonalInformation.DefaultFacetKey, personalInfoFacet);
}
if (contact != null)
{
// submit the changes to xConnect
client.Submit();
// reset the contact
_contactIdentificationRepository.Manager.RemoveFromSession(Analytics.Tracker.Current.Contact.ContactId);
Analytics.Tracker.Current.Session.Contact = _contactIdentificationRepository.Manager.LoadContact(Analytics.Tracker.Current.Contact.ContactId);
}
}
}
ContactIdentificationRepository
using System.Linq;
using Sitecore.Analytics;
using Sitecore.Analytics.Model;
using Sitecore.Analytics.Tracking;
using Sitecore.Configuration;
using Sitecore.XConnect;
using Sitecore.XConnect.Client.Configuration;
namespace Sitecore.Foundation.Accounts.Repositories
{
public class ContactIdentificationRepository
{
private readonly ContactManager contactManager;
public ContactManager Manager => contactManager;
public ContactIdentificationRepository()
{
contactManager = Factory.CreateObject("tracking/contactManager", true) as ContactManager;
}
public IdentifiedContactReference GetContactReference()
{
// get the contact id from the current contact
var id = GetContactId();
// if the contact is new or has no identifiers
var anon = Tracker.Current.Contact.IsNew || Tracker.Current.Contact.Identifiers.Count == 0;
// if the user is anon, get the xD.Tracker identifier, else get the one we found
return anon
? new IdentifiedContactReference(Sitecore.Analytics.XConnect.DataAccess.Constants.IdentifierSource, Tracker.Current.Contact.ContactId.ToString("N"))
: new IdentifiedContactReference(id.Source, id.Identifier);
}
public Analytics.Model.Entities.ContactIdentifier GetContactId()
{
if (Tracker.Current?.Contact == null)
{
return null;
}
if (Tracker.Current.Contact.IsNew)
{
// write the contact to xConnect so we can work with it
this.SaveContact();
}
return Tracker.Current.Contact.Identifiers.FirstOrDefault();
}
public void SaveContact()
{
// we need the contract to be saved to xConnect. It is only in session now
Tracker.Current.Contact.ContactSaveMode = ContactSaveMode.AlwaysSave;
this.contactManager.SaveContactToCollectionDb(Tracker.Current.Contact);
}
public IXdbContext CreateContext()
{
return SitecoreXConnectClientConfiguration.GetClient();
}
}
}
I am using facebook SDK 4.0.1. I gave permission for user_friends but I am not able to get friend list of the user. I am getting the count of the user's friends but I want the name of the user's friends and ids
private FacebookCallback<LoginResult> mcallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
accessToken = loginResult.getAccessToken();
Log.d("Access Token", accessToken.toString());
Profile profile = Profile.getCurrentProfile();
// Log.d("PROFILE","PROFILE IMAHE"+profile.getName());
displayWelcomeMessage(profile);
GraphRequestBatch batch = new GraphRequestBatch(
GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject jsonObject, GraphResponse response) {
try {
SharedPreferences.Editor editor = prefs.edit();
editor.putString(Constant.KEY_ID,jsonObject.getString("id"));
editor.putString(Constant.KEY_USER_NAME,jsonObject.getString("name"));
editor.putString(Constant.KEY_USER_FNAME,jsonObject.getString("first_name"));
editor.putString(Constant.KEY_USER_LNAME,jsonObject.getString("last_name"));
// hometown = jsonObject.getJSONObject("hometown");
// editor.putString(Constant.KEY_USER_HOMETOWN,hometown.getString("name"));
editor.putString(Constant.KEY_USER_EMAIL,jsonObject.getString("email"));
editor.putString(Constant.KEY_USER_GENDER,jsonObject.getString("gender"));
// editor.putString(Constant.KEY_USER_DOB,jsonObject.getString("birthday"));
editor.commit();
// town = hometown.getString("name");
// personId = jsonObject.getString("id");
// gen = jsonObject.getString("gender");
// email = jsonObject.getString("email");
Log.d("RESPONCE", "RESPONCE user=" + jsonObject.toString());
Log.d("RESPONCE", "RESPONCE =" + response.toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}
}),
GraphRequest.newMyFriendsRequest(accessToken, new GraphRequest.GraphJSONArrayCallback() {
#Override
public void onCompleted(JSONArray jsonArray, GraphResponse response) {
//Lo Application code for users friends
Log.d("RESPONCE FRIEND", "RESPONCE FRIEND=" + jsonArray.toString());
Log.d("RESPONCE FRIEND", "RESPONCE =" + response.toString());
response.getJSONArray();
}
}));
batch.addCallback(new GraphRequestBatch.Callback() {
#Override
public void onBatchCompleted(GraphRequestBatch graphRequests) {
// Application code for when the batch finishes
}
});
batch.executeAsync();
Since v2.0 of the Graph API, it is only possible to get friends who authorized your App too - for privacy reasons. More information can be found in this and many other threads about that exact same question: Facebook Graph Api v2.0+ - /me/friends returns empty, or only friends who also use my app
I am developing a small blackberry project.
Here are the step that it is supposed to be:
User clicks Speak! button. The application record speech voice. [No Problem]
When user finishes speaking, click Stop! button. Once the stop button is clicked, the speech voice will be saved on BB as an AMR file. Then, the file will be sent to web service via ksoap2. Web service will return response as a string of file name. The problem is web service return nothing and there is an error occur: JVM error 104: Uncaught NullPointerException I wonder if I placed the code on the right place, or I did something wrong with ksoap2??
here is the code for web service
namespace VoiceServer
{
/// <summary>
/// Converting AMR to WAV
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class Service1 : System.Web.Services.WebService
{
public string UploadFile(String receivedByte, String location, String fileName)
{
String filepath = fileName;
/*don't worry about receivedByte and location, I will work on them after the problem is solved :) */
return "Success"+filepath;
}
private void InitializeComponent()
{
}
}
}
Below is the code running on Eclipse, I'm not sure if I placed the code for sending file to web service on the right place.
public class MyAudio extends MainScreen {
private ButtonField _startRecordingButton;
private ButtonField _stopRecordingButton;
private HorizontalFieldManager _fieldManagerButtons;
private VoiceNotesRecorderThread _voiceRecorder;
private LabelField _myAudioTextField;
private DateField hourMin;
private long _initTime;
public MyAudio() {
_startRecordingButton = new ButtonField("Speak!", ButtonField.CONSUME_CLICK);
_stopRecordingButton = new ButtonField("Stop!", ButtonField.CONSUME_CLICK);
_fieldManagerButtons = new HorizontalFieldManager();
_voiceRecorder = new VoiceNotesRecorderThread(500000,"file:///store/home/user/voicefile.amr",this);
_voiceRecorder.start();
myButtonFieldChangeListener buttonFieldChangeListener = new myButtonFieldChangeListener();
_startRecordingButton.setChangeListener(buttonFieldChangeListener);
_stopRecordingButton.setChangeListener(buttonFieldChangeListener);
_fieldManagerButtons.add(_startRecordingButton);
_fieldManagerButtons.add(_stopRecordingButton);
_myAudioTextField = new LabelField(" Welcome to VoiceSMS!!!" );
add(_fieldManagerButtons);
add(_myAudioTextField);
SimpleDateFormat sdF = new SimpleDateFormat("ss");
hourMin = new DateField("", 0, sdF);
hourMin.setEditable(false);
hourMin.select(false);
_initTime = System.currentTimeMillis();
add(hourMin);
}
public void setAudioTextField(String text) {
_myAudioTextField.setText(text);
}
public void startTime() {
_initTime = System.currentTimeMillis();
hourMin.setDate(0);
}
public void updateTime() {
hourMin.setDate((System.currentTimeMillis()-_initTime));
}
class myButtonFieldChangeListener implements FieldChangeListener{
public void fieldChanged(Field field, int context) {
if(field == _startRecordingButton) {
try {
_voiceRecorder.startRecording();
} catch (IOException e) {
e.printStackTrace();
}
}else if(field == _stopRecordingButton) {
_voiceRecorder.stopRecording();
//----------Send AMR to Web Service-------------//
Object response = null;
String URL = "http://http://localhost:portnumber/Service1.asmx";
String method = "UploadFile";
String NameSpace = "http://tempuri.org/";
FileConnection fc = null;
byte [] ary = null;
try
{
fc = (FileConnection)Connector.open("file:///store/home/user/voicefile.amr",Connector.READ_WRITE);
int size = (int) fc.fileSize();
//String a = Integer.toString(size);
//Dialog.alert(a);
ary = new byte[size];
fc.openDataInputStream().read(ary);
fc.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
SoapObject client = new SoapObject(NameSpace,method);
client.addProperty("receivedByte",new SoapPrimitive(SoapEnvelope.ENC,"base64",Base64.encode(ary)));
client.addProperty("location","Test/");
client.addProperty("fileName","file:///store/home/user/voicefile.amr");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut = client;
HttpTransport http = new HttpTransport(URL);
try
{
http.call(method,envelope);
}
catch(InterruptedIOException io)
{
io.printStackTrace();
}
catch (IOException e)
{
System.err.println(e);
}
catch (XmlPullParserException e)
{
System.err.println(e);
}
catch(OutOfMemoryError e)
{
System.out.println(e.getMessage());
}
catch(Exception e)
{
e.printStackTrace();
}
try
{
response = envelope.getResponse();
Dialog.alert(response.toString());
}
catch (SoapFault e)
{
System.err.println(e);
System.out.println("Soap Fault");
}
catch(NullPointerException ne)
{
System.err.println(ne);
}
Dialog.alert(response.toString());
//Dialog.alert("Send Success");
//----------End of Upload-to-Web-Service--------//
}
}
}
}
I don't know if the file is not sent to web service, or web service has got the file and produce no response??? I am a real newbie for BB programming. Please let me know if I did anything wrong.
Thanks in advance!!!
There is a typo in your URL variable value.
"http://" typed twice
String URL = "http://http://localhost:portnumber/Service1.asmx";
Hooray!!! Problem Solved!
just changed URL as Rafael suggested and added [WebMethod] above "public string UploadFile" in the web service code