how to pass json with wwwform in unity - c#

I am a newbie in unity.
i want to send a post request having following json data in unity
**url** = "http://index.php"
**sampple json** = {"id":"100","name":"abc"}
I am using C#
can anyone provide me a solution for this?

I've done for doing this below. Let's go : ==>
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class btnGetData : MonoBehaviour {
void Start()
{
gameObject.GetComponent<Button>().onClick.AddListener(TaskOnClick);
}
IEnumerator WaitForWWW(WWW www)
{
yield return www;
string txt = "";
if (string.IsNullOrEmpty(www.error))
txt = www.text; //text of success
else
txt = www.error; //error
GameObject.Find("Txtdemo").GetComponent<Text>().text = "++++++\n\n" + txt;
}
void TaskOnClick()
{
try
{
GameObject.Find("Txtdemo").GetComponent<Text>().text = "starting..";
string ourPostData = "{\"plan\":\"TESTA02\"";
Dictionary<string,string> headers = new Dictionary<string, string>();
headers.Add("Content-Type", "application/json");
//byte[] b = System.Text.Encoding.UTF8.GetBytes();
byte[] pData = System.Text.Encoding.ASCII.GetBytes(ourPostData.ToCharArray());
///POST by IIS hosting...
WWW api = new WWW("http://192.168.1.120/si_aoi/api/total", pData, headers);
///GET by IIS hosting...
///WWW api = new WWW("http://192.168.1.120/si_aoi/api/total?dynamix={\"plan\":\"TESTA02\"");
StartCoroutine(WaitForWWW(api));
}
catch (UnityException ex) { Debug.Log(ex.Message); }
}
}

Well i've working with something like this:
public class RequestConnectionManager : Manager<RequestConnectionManager>
{
public int maxSubmissionAttempts = 3;
public Coroutine post() {
WWWForm playForm = new WWWForm();
playForm.AddField("id", myJson.id);
playForm.AddField("name", myJson.name);
Post playPost = new Post("http://index.php", playForm, maxSubmissionAttempts, this);
return StartCoroutine(PostWorker(playPost));
}
private IEnumerator PostWorker(Post playPost)
{
yield return null;
yield return playPost.Submit();
Debug.Log(playPost.Response);
if (playPost.Error != null)
{
MessageBoxManager.Instance.Show("Error: " + playPost.Error, "Error", MessageBoxManager.OKCancelOptionLabels, MessageOptions.Ok);
}
else
{
try
{
//do whatever you want in here
//Hashtable response = JsonReader.Deserialize<Hashtable>(playPost.Response);
//Debug.Log("UNITY LOG..." + response);
}
catch (JsonDeserializationException jsExc)
{
Debug.Log(jsExc.Message);
Debug.Log(playPost.Response);
}
catch (Exception exc)
{
Debug.Log(exc.Message);
Debug.Log(playPost.Response);
}
}
}
}
//As for the Manager class...
using UnityEngine;
using System.Collections;
// I wonder what the constraint where TManager : Singleton<TManager> would produce...
public class Manager<TManager> : SingletonW<TManager> where TManager : MonoBehaviour
{
override protected void Awake()
{
base.Awake();
DontDestroyOnLoad(this);
DontDestroyOnLoad(gameObject);
}
}
Hope this helps! =)

Related

Firebase google login in unity trouble - Freeze when Unity Editor plays

I'm trying to use firebase and Google linked login in a game made with Unity.
I tried the search method, but the editor freezes when I try to login in the first scene.
If I play in the editor, it doesn't progress.
When I tried in the second scene, I was logged in.
But then someone else worked. So I'm not sure about this.
What did I do wrong in the Google linked login process?
How do I debug the editor when it freeze?
I am not an English speaker. I am sorry that my English is strange.
This is the code I used. It's not much different from what I searched and found.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Design.Serialization;
using System.Linq;
using System.Threading.Tasks;
using Firebase;
using Firebase.Auth;
using Google;
using UnityEditor;
using UnityEngine;
using UnityEngine.Serialization;
using UnityEngine.UI;
public class GoogleSignInClass : MonoBehaviour
{
public Text infoText;
public string webClientId = "310848617796-nf5a9ds97humnn8nqv5gihmnnqg6j3g4.apps.googleusercontent.com";
private FirebaseAuth auth;
private GoogleSignInConfiguration configuration;
[SerializeField] private bool IsEditor = false;
[FormerlySerializedAs("Canvas")] [SerializeField] private GameStart Canvas;
private void Awake()
{
configuration = new GoogleSignInConfiguration { WebClientId = webClientId, RequestEmail = true, RequestIdToken = true };
CheckFirebaseDependencies();
if (Application.isEditor)
IsEditor = true;
}
private void CheckFirebaseDependencies()
{
FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
{
if (task.IsCompleted)
{
if (task.Result == DependencyStatus.Available)
auth = FirebaseAuth.DefaultInstance;
else
AddToInformation("Could not resolve all Firebase dependencies: " + task.Result.ToString());
}
else
{
AddToInformation("Dependency check was not completed. Error : " + task.Exception.Message);
}
});
}
public void SignInWithGoogle() { OnSignIn(); }
public void SignOutFromGoogle() { OnSignOut(); }
private void OnSignIn()
{
if (!IsEditor)
{
GoogleSignIn.Configuration = configuration;
GoogleSignIn.Configuration.UseGameSignIn = false;
GoogleSignIn.Configuration.RequestIdToken = true;
AddToInformation("Calling SignIn");
GoogleSignIn.DefaultInstance.SignIn().ContinueWith(OnAuthenticationFinished);
}
else
{
Canvas.GoMainMenu();
}
}
private void OnSignOut()
{
AddToInformation("Calling SignOut");
GoogleSignIn.DefaultInstance.SignOut();
}
public void OnDisconnect()
{
AddToInformation("Calling Disconnect");
GoogleSignIn.DefaultInstance.Disconnect();
}
internal void OnAuthenticationFinished(Task<GoogleSignInUser> task)
{
if (task.IsFaulted)
{
using (IEnumerator<Exception> enumerator = task.Exception.InnerExceptions.GetEnumerator())
{
if (enumerator.MoveNext())
{
GoogleSignIn.SignInException error = (GoogleSignIn.SignInException)enumerator.Current;
AddToInformation("Got Error: " + error.Status + " " + error.Message);
}
else
{
AddToInformation("Got Unexpected Exception?!?" + task.Exception);
}
}
}
else if (task.IsCanceled)
{
AddToInformation("Canceled");
}
else
{
AddToInformation("Welcome: " + task.Result.DisplayName + "!");
AddToInformation("Email = " + task.Result.Email);
AddToInformation("Google ID Token = " + task.Result.IdToken);
AddToInformation("Email = " + task.Result.Email);
SignInWithGoogleOnFirebase(task.Result.IdToken, task.Result.UserId);
}
}
private void SignInWithGoogleOnFirebase(string idToken, string UID) (Player.instance.setGoogleUID(UID))
{
Credential credential = GoogleAuthProvider.GetCredential(idToken, null);
auth.SignInWithCredentialAsync(credential).ContinueWith(task =>
{
AggregateException ex = task.Exception;
if (ex != null)
{
if (ex.InnerExceptions[0] is FirebaseException inner && (inner.ErrorCode != 0)) ;
AddToInformation("\nError code = " + inner.ErrorCode + " Message = " + inner.Message);
}
else
{
AddToInformation("Sign In Successful., UID: " + UID);
mainCanvas.GoInGame();
Player.instance.SetIsSignIn(true);
Player.instance.setGoogleUID(UID);
AddToInformation("Success2");
StartCoroutine(signInSetPlayer());
}
});
}
public void OnSignInSilently()
{
GoogleSignIn.Configuration = configuration;
GoogleSignIn.Configuration.UseGameSignIn = false;
GoogleSignIn.Configuration.RequestIdToken = true;
AddToInformation("Calling SignIn Silently");
GoogleSignIn.DefaultInstance.SignInSilently().ContinueWith(OnAuthenticationFinished);
}
public void OnGamesSignIn()
{
GoogleSignIn.Configuration = configuration;
GoogleSignIn.Configuration.UseGameSignIn = true;
GoogleSignIn.Configuration.RequestIdToken = false;
AddToInformation("Calling Games SignIn");
GoogleSignIn.DefaultInstance.SignIn().ContinueWith(OnAuthenticationFinished);
}
private void AddToInformation(string str) { infoText.text += "\n" + str; }

Unable to receive/post data from mysql database server

i am send data using unitywebrequest but db/server is getting empty json string.
public class Credentials : Singleton<Credentials>
{
public string email;
public string password;
public string ConvertToJason()
{
return JsonUtility.ToJson(this);
}
}
public class LogIn : MonoBehaviour
{
public InputField emailAddress;
public InputField passwordField;
public GameObject loadingCanvas;
public GameObject loginButton;
public GameObject loadingImg;
string Url = "linkName";
public void LoginButton()
{
loginButton.SetActive(false);
loadingImg.SetActive(true);
if (emailAddress.text == "" || passwordField.text == "")
{
Debug.Log("Empty");
loginButton.SetActive(true);
loadingImg.SetActive(false);
}
else
{
Credentials.Instance.email = emailAddress.text.ToString();
Credentials.Instance.password = passwordField.text.ToString();
//StartCoroutine(LogInAuthenticate());
Value = Credentials.Instance.ConvertToJason();
Debug.Log(Value);
StartCoroutine(LogInAuthenticate());
}
loginButton.SetActive(true);
loadingImg.SetActive(false);
}
string Value;
IEnumerator LogInAuthenticate()
{
using (UnityWebRequest www = UnityWebRequest.Post(Url, Value))
{
www.SetRequestHeader("Content-Type", "application/json");
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.LogError ("Web Issue : "+ www.error);
}
else
{
string responseText = www.downloadHandler.text;
Debug.Log("Log Message : " + responseText);
if (responseText.StartsWith("Authenticate Successfully"))
{
Debug.Log("Sucess :" + responseText);
}
else
{
Debug.LogError("Log Issue : " + responseText);
}
}
}
}
}
php code is working fine on postman application.
all data is being handled in json, i am using unityweb request, and data directly through string, becuase wwwform was not working out quite like what i expected, maybe i didnt understood it.
i think i am missing some headers or maybe its due to syntex, but there not much help on internet about this.
If you use the overload UnityWebRequest.Post(string url, string data) note that
The data in postData will be escaped, then interpreted into a byte stream via System.Text.Encoding.UTF8
In order to avoid this you could rather use
using (UnityWebRequest www = UnityWebRequest(Url, "POST"))
{
var bytes = Encoding.UTF8.GetBytes(Value);
request.uploadHandler = new UploadHandlerRaw(bytes);
request.uploadHandler.contentType = "application/json";
request.downloadHandler = new DownloadHandlerBuffer();
yield return www.SendWebRequest();
....
}

Unity - display Json array from server

I'm making a quiz game and I'm stuck at this problem that is probably easy to do.
I have this script, which gets JSON data from server and separates it:
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using System;
using TMPro;
[Serializable]
public class RootObject
{
public Results[] Result;
}
[Serializable]
public class Results
{
public string id;
public string question;
public string answer1;
public string answer2;
public string answer3;
public string answer4c;
}
public class DataLoader : MonoBehaviour
{
public PickPlace pickplace;
public string URLBase;
public void GetQustion()
{
URLBase = pickplace.url;
StartCoroutine(Run());
}
IEnumerator Run()
{
var req = CreateReturnPlayerDataRequest();
yield return req.SendWebRequest();
var results = HandleReturnPlayerDataRequest(req);
// Izvada konsolē saņemtos datus
Debug.Log("Quesiton: " + results.Result[0].question + " Answer1: " + results.Result[0].answer1 + " Answer2: " + results.Result[0].answer2 + " Answer3: " + results.Result[0].answer3 + " Answer4: " + results.Result[0].answer4c);
}
public UnityWebRequest CreateReturnPlayerDataRequest()
{
var req = UnityWebRequest.Get(URLBase);
return req;
}
public static RootObject HandleReturnPlayerDataRequest(UnityWebRequest req)
{
if (req.isNetworkError)
{
Debug.LogError("Failed to POST /player/register");
return new RootObject();
}
var results = JsonUtility.FromJson<RootObject>("{\"Result\":" + req.downloadHandler.text + "}");
return results;
}
}
My question is:
How can I call out array in, for example my GameManager script and call out separated data, so that I can put for example question text from JSON data into Text object and all 4 answers to buttons?
Currently you have a method to start the request but you never wait until / will know when it is done!
I would simply use an Action<RootObject> as parameter so you can add a callback listener and react to the result when it is invoked.
public class DataLoader : MonoBehaviour
{
public PickPlace pickplace;
public string URLBase;
public void GetQuestions(Action<RootObject> onSuccess)
{
URLBase = pickplace.url;
StartCoroutine(Run(onSuccess));
}
IEnumerator Run(Action<RootObject> onSuccess)
{
var req = CreateReturnPlayerDataRequest();
yield return req.SendWebRequest();
var results = HandleReturnPlayerDataRequest(req);
if(results == null)
{
yield break;
}
Debug.Log("Quesiton: " + results.Result[0].question + " Answer1: " + results.Result[0].answer1 + " Answer2: " + results.Result[0].answer2 + " Answer3: " + results.Result[0].answer3 + " Answer4: " + results.Result[0].answer4c);
// Now invoke the Callback so whoever started the post call gets the results
onSuccess?.Invoke(results);
}
public UnityWebRequest CreateReturnPlayerDataRequest()
{
var req = UnityWebRequest.Get(URLBase);
return req;
}
private RootObject HandleReturnPlayerDataRequest(UnityWebRequest req)
{
if(req.isHttpError || req.isNetworkError)
{
Debug.LogError($"Failed to POST /player/register! Failed with {req.responseCode} - Reason: {req.error}");
onDone?.Invoke(null);
return null;
}
var results = JsonUtility.FromJson<RootObject>("{\"Result\":" + req.downloadHandler.text + "}");
return results;
}
}
So now you can call it from another class like e.g.
// Drag these in via the Inspector
[SerializeField] private DataLoader dataLoader;
[Space]
[SerializeField] private Text questionText;
[Space]
[SerializeField] private Text button1Text;
[SerializeField] private Text button2Text;
[SerializeField] private Text button3Text;
[SerializeField] private Text button3Text;
public void SomeMethod()
{
// Do the post call and react once the results are there either as lambda expression
dataLoader.GetQuestions(results => {
Debug.Log("Successfully received data. Will update GUI", this);
// do something with the results now e.g.
var first = results.Result[0];
questionText.text = first.question;
button1Text.text = first.answer1;
button2Text.text = first.answer2;
button3Text.text = first.answer3;
button4Text.text = first.answer4;
});
// alternatively you can do the same also using a method
dataLoader.GetQuestions(OnPostRequestFinished);
}
private void OnPostRequestFinished(RootObject results)
{
Debug.Log("Successfully received data. Will update GUI", this);
// do something with the results now e.g.
var first = results.Result[0];
questionText.text = first.question;
button1Text.text = first.answer1;
button2Text.text = first.answer2;
button3Text.text = first.answer3;
button4Text.text = first.answer4;
}

Set GameObject From Http Request Result in Unity

I have 4 buttons in my project and all these buttons call different score results from server. At awake function I generate a table with random values and it works pretty fine. However when I call a function and get results I couldnt set the table with received values because entryContainer and entryTemplate would be null which I think should not be because they are instantiated!. Here is my code which works pretty fine at page opening but could not set items after receiving request
using Assets.Scripts.HttpPost;
using Assets.Scripts.Models;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
public class HighScoreTable : MonoBehaviour
{
public static Transform entryContainer;
public static Transform entryTemplate;
public List<HighscoreEntry> highscoreEntryList;
public static List<Transform> highscoreEntryTransformList;
public static bool isChanged = false;
public void Awake()
{
// Works pretty fine at opening
entryContainer = transform.Find("highscoreEmptyContainer");
entryTemplate = entryContainer.Find("highscoreEntryTemplate");
entryTemplate.gameObject.SetActive(false);
highscoreEntryList = new List<HighscoreEntry>() {
new HighscoreEntry{score = 33.6, username = "Osman"},
new HighscoreEntry{score = 46033.5, username = "Ahmet"},
new HighscoreEntry{score = 1833.5, username = "Veli"},
new HighscoreEntry{score = 563.5, username = "Can"},
new HighscoreEntry{score = 433.5, username = "Esma"},
new HighscoreEntry{score = 6533.5, username = "Gözde"},
new HighscoreEntry{score = 733.5, username = "Ayşe"},
new HighscoreEntry{score = 733.5, username = "Fatma"},
new HighscoreEntry{score = 383.5, username = "Hayriye"}
};
//generates table its ok
highscoreEntryTransformList = new List<Transform>();
foreach (var highscoreEntry in highscoreEntryList)
{
CreateHighscoreEntryTransform(highscoreEntry, entryContainer, highscoreEntryTransformList);
}
}
public void Update()
{
}
private void CreateHighscoreEntryTransform(HighscoreEntry highscoreEntry, Transform container, List<Transform> transformList)
{
float templateHeight = 30f;
while (container == null)
container = transform.Find("highscoreEmptyContainer");
Transform entryTransform = Instantiate(entryTemplate, entryContainer);
RectTransform entryRectTransform = entryTransform.GetComponent<RectTransform>();
entryRectTransform.anchoredPosition = new Vector2(0, -30 - templateHeight * transformList.Count);
entryTransform.gameObject.SetActive(true);
int rank = transformList.Count + 1;
string rankString;
switch (rank)
{
default:
rankString = rank + "TH"; break;
case 1: rankString = "1ST"; break;
case 2: rankString = "2ND"; break;
case 3: rankString = "3RD"; break;
}
entryTransform.Find("posText").GetComponent<Text>().text = rankString;
double score = highscoreEntry.score;
entryTransform.Find("scoreText").GetComponent<Text>().text = score.ToString();
entryTransform.Find("nameText").GetComponent<Text>().text = highscoreEntry.username;
transformList.Add(entryTransform);
}
#region AllVerbal
public WWW AllVerbalGet(string postAddress, string jsonData)
{
entryContainer = transform.Find("highscoreEmptyContainer");
entryTemplate = entryContainer.Find("highscoreEntryTemplate");
entryTemplate.gameObject.SetActive(false);
WWW www;
byte[] formData = null;
try
{
Hashtable postHeader = new Hashtable();
postHeader.Add("Content-Type", "application/json");
// convert json string to byte
if (!string.IsNullOrEmpty(jsonData))
{
formData = System.Text.Encoding.UTF8.GetBytes(jsonData);
}
www = new WWW(postAddress, formData, postHeader);
StartCoroutine(WaitForAllVerbalGetRequest(www));
}
catch (System.Exception ex)
{
www = null;
}
return www;
}
//Wait for the www Request
IEnumerator WaitForAllVerbalGetRequest(WWW www)
{
yield return www;
if (www.error == null)
{
//Print server response
try
{
LeaderboardListModel result = JsonUtility.FromJson<LeaderboardListModel>("{\"leaders\":" + www.text + "}");
highscoreEntryList = new List<HighscoreEntry>();
// Items received and converted to model successfully!
HighscoreEntry temp;
foreach (var item in result.leaders)
{
temp = new HighscoreEntry();
temp.username = item.username;
temp.score = item.totalScore;
temp.weekscore = item.weeklyTotalScore;
highscoreEntryList.Add(temp);
}
highscoreEntryTransformList = new List<Transform>();
foreach (var highscoreEntry in highscoreEntryList)
{
// HERE IS THE PROBLEM ENTRY CONTAINER IS NULL BUT ITS INSTANTIATED AT AWAKE FUNCTION!!!!!!!!!!!
// I ALSO TRY TO SET THESE ITEMS AGAIN BUT STILL RETURNS NULL
//entryContainer = transform.Find("highscoreEmptyContainer");
//entryTemplate = entryContainer.Find("highscoreEntryTemplate");
//entryTemplate.gameObject.SetActive(false);
//WHAT SHOULD I DO entry container is null!! :(
CreateHighscoreEntryTransform(highscoreEntry, entryContainer, highscoreEntryTransformList);
}
isChanged = true;
}
catch (System.Exception ex)
{
}
}
else
{
try
{
highscoreEntryList = new List<HighscoreEntry>();
highscoreEntryTransformList = new List<Transform>();
foreach (var highscoreEntry in highscoreEntryList)
{
CreateHighscoreEntryTransform(highscoreEntry, entryContainer, highscoreEntryTransformList);
}
}
catch (System.Exception)
{
}
}
}
#endregion
public void allVerbalButton_Click()
{
isChanged = true;
AllVerbalGet(HttpOperations.allVerbalURL, null);
}
public void allCompButton_Click()
{
isChanged = true;
AllVerbalGet(HttpOperations.allCompURL, null);
}
public void Top10VerbalButton_Click()
{
isChanged = true;
AllVerbalGet(HttpOperations.Top10VerbalURL, null);
}
public void Top10ComputButton_Click()
{
isChanged = true;
AllVerbalGet(HttpOperations.Top10CompURL, null);
}
[System.Serializable]
public class HighscoreEntry
{
public double score;
public string username;
public double weekscore;
}
}
I am pretty new at unity but couldnt solve it :( Any help would be great

Lync API: How to send instant message to contact by email address?

I have the email address of a Lync user and want to send him an instant message.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Lync.Model;
using Microsoft.Lync.Model.Conversation;
namespace Build_Server_Lync_Notifier
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine("Usage: bsln.exe <uri> <message>");
return;
}
LyncClient client = Microsoft.Lync.Model.LyncClient.GetClient();
Contact contact = client.ContactManager.GetContactByUri(args[0]);
Conversation conversation = client.ConversationManager.AddConversation();
conversation.AddParticipant(contact);
Dictionary<InstantMessageContentType, String> messages = new Dictionary<InstantMessageContentType, String>();
messages.Add(InstantMessageContentType.PlainText, args[1]);
InstantMessageModality m = (InstantMessageModality) conversation.Modalities[ModalityTypes.InstantMessage];
m.BeginSendMessage(messages, null, messages);
//Console.Read();
}
}
}
Screenshot
Link to large screenshot: http://i.imgur.com/LMHEF.png
As you can see in this screenshot, my program doesn't really seem to work, even though I'm able to manually search up the contact and send an instant message manually.
I also tried using ContactManager.BeginSearch() instead of ContactManager.GetContactByUri(), but got the same result (you can see in the screenshot): http://pastie.org/private/o9joyzvux4mkhzsjw1pioa
Ok, so I got it working now. Got it in a working state, although I need to do some serious refactoring.
Program.cs
using System;
namespace Build_Server_Lync_Notifier
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine("Usage: bsln.exe <uri> <message>");
return;
}
LyncManager lm = new LyncManager(args[0], args[1]);
while (!lm.Done)
{
System.Threading.Thread.Sleep(500);
}
}
}
}
LyncManager.cs
using Microsoft.Lync.Model;
using Microsoft.Lync.Model.Conversation;
using System;
using System.Collections.Generic;
namespace Build_Server_Lync_Notifier
{
class LyncManager
{
private string _uri;
private string _message;
private LyncClient _client;
private Conversation _conversation;
private bool _done = false;
public bool Done
{
get { return _done; }
}
public LyncManager(string arg0, string arg1)
{
_uri = arg0;
_message = arg1;
_client = Microsoft.Lync.Model.LyncClient.GetClient();
_client.ContactManager.BeginSearch(
_uri,
SearchProviders.GlobalAddressList,
SearchFields.EmailAddresses,
SearchOptions.ContactsOnly,
2,
BeginSearchCallback,
new object[] { _client.ContactManager, _uri }
);
}
private void BeginSearchCallback(IAsyncResult r)
{
object[] asyncState = (object[]) r.AsyncState;
ContactManager cm = (ContactManager) asyncState[0];
try
{
SearchResults results = cm.EndSearch(r);
if (results.AllResults.Count == 0)
{
Console.WriteLine("No results.");
}
else if (results.AllResults.Count == 1)
{
ContactSubscription srs = cm.CreateSubscription();
Contact contact = results.Contacts[0];
srs.AddContact(contact);
ContactInformationType[] contactInformationTypes = { ContactInformationType.Availability, ContactInformationType.ActivityId };
srs.Subscribe(ContactSubscriptionRefreshRate.High, contactInformationTypes);
_conversation = _client.ConversationManager.AddConversation();
_conversation.AddParticipant(contact);
Dictionary<InstantMessageContentType, String> messages = new Dictionary<InstantMessageContentType, String>();
messages.Add(InstantMessageContentType.PlainText, _message);
InstantMessageModality m = (InstantMessageModality)_conversation.Modalities[ModalityTypes.InstantMessage];
m.BeginSendMessage(messages, BeginSendMessageCallback, messages);
}
else
{
Console.WriteLine("More than one result.");
}
}
catch (SearchException se)
{
Console.WriteLine("Search failed: " + se.Reason.ToString());
}
_client.ContactManager.EndSearch(r);
}
private void BeginSendMessageCallback(IAsyncResult r)
{
_conversation.End();
_done = true;
}
}
}
Try Below Code its working Fine For me
protected void Page_Load(object sender, EventArgs e)
{
SendLyncMessage();
}
private static void SendLyncMessage()
{
string[] targetContactUris = {"sip:xxxx#domain.com"};
LyncClient client = LyncClient.GetClient();
Conversation conv = client.ConversationManager.AddConversation();
foreach (string target in targetContactUris)
{
conv.AddParticipant(client.ContactManager.GetContactByUri(target));
}
InstantMessageModality m = conv.Modalities[ModalityTypes.InstantMessage] as InstantMessageModality;
m.BeginSendMessage("Test Message", null, null);
}

Categories