RingCentral incoming call notification - c#

I am developing a winform application to get incoming call notification in real time. I am getting error on authorise method
Below is my code snippet
private async void button1_Click(object sender, EventArgs e)
{
//rc = new RestClient(txtClientID.Text, txtClientSecrete.Text, !chkIsSandBox.Checked);
rc = new RestClient(txtClientID.Text, txtClientSecrete.Text);
await rc.Authorize(txtUsrName.Text, txtExtension.Text, txtPWD.Text);
RegisterSubscription();
}
async void RegisterSubscription()
{
var subscription = rc.Restapi().Subscription().New();
//subscription.EventFilters.Add("/restapi/v1.0/account/~/extension/~/message-store");
subscription.EventFilters.Add("/restapi/v1.0/account/~/extension/~/presence");
subscription.PresenceEvent += subscription_PresenceEvent;
await subscription.Register();
}
void subscription_PresenceEvent(object sender, SubscriptionEventArgs e)
{
rtLog.Text += e.Message;
}
private async Task<TokenInfo> Authorize()
{
return await rc.Authorize(txtUsrName.Text, txtExtension.Text, txtPWD.Text);
}
I would like to receive notification for incoming call.
Thanks in advance.

Thanks for posting your answer on GitHub, Shridhar. I posted it here so people can find it if they run into the same issue:
I was able to resolve this by adding assembly to the GAC using Gacutil.exe.
https://github.com/ringcentral/ringcentral-csharp-client/issues/32

Related

Redis Cache - A blocking operation was interrupted by a call to WSACancelBlockingCall

I have an ASP.NET Web Forms Page with the following code:
public partial class MyAspNetWebFormPage : System.Web.UI.Page{
protected void Page_Load(object sender, EventArgs e){
ClearRedisCache("RedisCacheConnectionString_01");
ClearRedisCache("RedisCacheConnectionString_02");
}
private void ClearRedisCache(string redisConnectionString){
var serverName = redisConnectionString.Split(',')[0];
using (var redis = ConnectionMultiplexer.Connect(redisConnectionString)){
var server = redis.GetServer(serverName);
server.FlushAllDatabases(CommandFlags.None);
redis.Close(true); // this was added as an effort to fix the problem but doesn't work
// Another effort to make it work
// Added after receiving the error
do {
Thread.Sleep(1000);
} while (redis.IsConnected);
}
}
}
When I run this on my local box it seems to work perfectly fine. However, when I run it in our Azure Environment it throws an exception with the following message:
A blocking operation was interrupted by a call to WSACancelBlockingCall
Other examples that I've seen are caching the connection and keeping it open. Is that how I'm suppose to implement redis cache?
This code is executed from an Admin Dashboard that is completely disconnected from the Consumer Site. The Admin Dashboard doesn't use Redis Cache other than to clear it.
Any ideas are greatly appreciated. Thank you in advance.
Looking into this further and playing with the settings here's what worked for me:
public partial class MyAspNetWebFormPage : System.Web.UI.Page{
protected void Page_Load(object sender, EventArgs e){
ClearRedisCache("RedisCacheConnectionString_01");
ClearRedisCache("RedisCacheConnectionString_02");
}
private void ClearRedisCache(string redisConnectionString){
string securityProtocol = (SecurityProtocol)Enum.Parse(typeof(SecurityProtocol), securityProtocol);
var options = ConfigurationOptions.Parse(redisConnectionString);
options.SslProtocols = System.Security.authentication.SslProtocols.Tls12;
options.Ssl = true;
options.AllowAdmin = true;
options.AbortOnConnectFail = false;
var serverName = redisConnectionString.Split(',')[0];
using (var redis = ConnectionMultiplexer.Connect(options)){
var server = redis.GetServer(serverName);
server.FlushAllDatabases(CommandFlags.None);
}
}
}

Start thread returns System.InvalidOperationException: The current SynchronizationContext may not be used as a TaskScheduler

I add a dashboard devexpress that run a stored procedure and it takes a long time. So I created a simple thread in my application in form_load
public void LoadDashboard()
{
using (Stream s = new MemoryStream(Encoding.Default.GetBytes(Resource.Dashboard.MaterialDashboard1)))
{
s.Position = 0;
dashboardViewer1.LoadDashboard(s);
}
}
private void frmMaterialDashboard_Load(object sender, EventArgs e)
{
Thread newth=new Thread(LoadDashboard);
newth.Start();
int UserId = int.Parse(Configuration.AccountDetail.UserId.ToString());
lblUserName.Caption = _userRepository.Get().Where(i => i.Id == UserId).First().FullName;
alertControl1.Show(this, "Welcome","Welcome to SPMS Mr."+_userRepository.FindById(Configuration.AccountDetail.UserId).First().FullName +"\n Server time:"+DateTime.Now);
}
But when I run my application I get this error :
An unhandled exception of type 'DevExpress.DashboardCommon.DashboardInternalException' occurred in DevExpress.Dashboard.v15.2.Win.dll
Additional information: Internal error. Please contact the application vendor or your system administrator and provide the following information.
System.InvalidOperationException: The current SynchronizationContext may not be used as a TaskScheduler.
at System.Threading.Tasks.SynchronizationContextTaskScheduler..ctor()
at DevExpress.DashboardWin.Native.WinDashboardService.RequestCustomizationServices(RequestCustomizationServicesEventArgs e)
at DevExpress.DashboardCommon.Service.DashboardService.DevExpress.DashboardCommon.Service.IDashboardServiceAdminHandlers.OnRequestCustomizationServices(Object sender, RequestCustomizationServicesEventArgs e)
at DevExpress.DashboardCommon.Server.DashboardSession.CreateDataLoaderParameters(ReloadDataArgs args)
at DevExpress.DashboardCommon.Server.DashboardSession.CreateDataLoader(ReloadDataArgs args)
at DevExpress.DashboardCommon.Server.DashboardSession.LoadData(IEnumerable1 dataSourceComponentNames, ReloadDataArgs args)
at DevExpress.DashboardCommon.Server.DashboardSession.ReloadData(IEnumerable1 dataSourceComponentNames, ReloadDataArgs args)
at DevExpress.DashboardCommon.Server.DashboardSession.Initialize(DashboardSessionState state, Boolean isDesignMode)
at DevExpress.DashboardCommon.Service.DashboardServiceOperation`1.Execute(DashboardServiceResult result)
Updated
I change my code like this, it works without any error and the data is shown but without any async operation and I have to wait to load data
public async Task<Stream> LoadDashboard()
{
Stream s = new MemoryStream(Encoding.Default.GetBytes(Resource.Dashboard));
s.Position = 0;
return s;
}
private async void frmMaterialDashboard_Load(object sender, EventArgs e)
{
Stream dashboardData = await LoadDashboard();
dashboardViewer1.LoadDashboard(dashboardData);
int UserId = int.Parse(Configuration.AccountDetail.UserId.ToString());
lblUserName.Caption = _userRepository.Get().Where(i => i.Id == UserId).First().FullName;
alertControl1.Show(this, "Welcome","Welcome to SPMS Mr."+_userRepository.FindById(Configuration.AccountDetail.UserId).First().FullName +"\n Server time:"+DateTime.Now);
}
Without full context of the problem I can't give you an exact solution, but overall, you cannot access UI elements from another thread. That means you need to do all request and computation on another thread, and then update UI elements on UI thread. Consider such simplified solution that does not explicitly start a new thread:
// event on UI thread
private async void frmMaterialDashboard_Load(object sender, EventArgs e)
{
var dashboardData = await LoadDashboardDataFromDatabaseAsync();
dashboardViewer1.Load(dashboardData);
}
public async Task<DashboardData> LoadDashboardDataFromDatabaseAsync()
{
string query = "...";
var queryResult = await db.ExucuteQueryAsync(query).ConfigureAwait(false);
return ConvertQueryRequltToDashboardData(queryResult);
}

Verify successful post in Facebook .NET sdk

I am creating a Windows Phone 8.1 RT application. I have installed the facebook and facebook.client sdks for setting up login and sharing purposes. For login purpose I have followed the steps as mentioned here.
My App.xaml.cs OnActivated function looks like this:
protected override void OnActivated(IActivatedEventArgs args)
{
base.OnActivated(args);
var protocolArgs = args as ProtocolActivatedEventArgs;
if (protocolArgs != null)
{
LifecycleHelper.FacebookAuthenticationReceived(protocolArgs);
}
Session.OnFacebookAuthenticationFinished += OnFacebookAuthenticationFinished;
}
and here is OnFacebookAuthenticationFinished method
private async void OnFacebookAuthenticationFinished(AccessTokenData session)
{
await Session.CheckAndExtendTokenIfNeeded();
if (Constant.fbSignup)
{
User fbUser = new User();
Account userAccount = new Account();
try
{
FacebookClient fbClient = new FacebookClient(session.AccessToken);
dynamic result = await fbClient.GetTaskAsync("me?fields=id,first_name,last_name,email,location");
fbUser.FirstName = result.first_name;
fbUser.LastName = result.last_name;
userAccount.UserName = result.email;
fbUser.UserAccount = userAccount;
//fbUser.City = result.location.name;
Constant.User = fbUser;
RootFrame.Navigate(typeof(SignUpPage));
}
catch (Exception ex)
{
await new MessageDialog(ex.Message).ShowAsync();
}
}
The login works fine.
Now I want to share some content using the Session.ShowFeedDialog(). I have followed the steps mentioned here for creating AppRequests within the dialog.
I am calling the ShowFeedDialog method this way from a page StoreDetailsPage.xaml.cs
All the following code rests in StorePageDetails.xaml.cs
Session.ShowFeedDialog("", link, linkDescription, linkCaption);
The posting also works fine. But I need to check whether the post was successful or not. For this purpose I tried the
Session.OnFacebookFeedFinished = Success;
where success is
public delegate void FacebookDelegate(FBResult result);
void Success(FBResult result)
{
//Code to check if post was successful
}
So my problem is after ShowFeedDialog is closed the OnActivated event is called and success delegate method is never reached or not called.
I haven't used delegates before so I don't know if there is something wrong there. Also I haven't figured out what the logic for post verification should since I was not able to step into this function. So any suggestions would be much appreciated

Unable to find Table in Azure Mobile Service Win Phone 8.1

I am currently trying to implement Azure Mobile Service into my Windows Phone 8.1 application.
I followed documentation on it Azure.Microsoft.com:
Get started with Mobile Services and I created a new Windows Phone 8.1 project with the service. I tried making a new table with the exact configuration as the sample as well as a new Class to matching the table name & fields. Below is the original code, I changed all of the TodoItem into 'Test'
I keep getting the error:
Error: Table 'Test' does not exist
I tried making both a Javascript and .NET version for back-end but they still failed
Am I unable to find my table because I am missing a step?
sealed partial class MainPage : Page
{
private MobileServiceCollection<Test, Test> items;
private IMobileServiceTable<Test> todoTable = App.MobileService.GetTable<Test>();
public MainPage()
{
this.InitializeComponent();
}
private async Task InsertTodoItem(Test todoItem)
{
await todoTable.InsertAsync(todoItem);
items.Add(todoItem);
}
private async Task RefreshTodoItems()
{
MobileServiceInvalidOperationException exception = null;
try
{
items = await todoTable
.Where(todoItem => todoItem.Complete == false)
.ToCollectionAsync();
}
catch (MobileServiceInvalidOperationException e)
{
exception = e;
}
if (exception != null)
{
await new MessageDialog(exception.Message, "Error loading items").ShowAsync();
}
else
{
ListItems.ItemsSource = items;
this.ButtonSave.IsEnabled = true;
}
}
private async Task UpdateCheckedTodoItem(Test item)
{
await todoTable.UpdateAsync(item);
items.Remove(item);
ListItems.Focus(Windows.UI.Xaml.FocusState.Unfocused);
}
private async void ButtonRefresh_Click(object sender, RoutedEventArgs e)
{
ButtonRefresh.IsEnabled = false;
await RefreshTodoItems();
ButtonRefresh.IsEnabled = true;
}
private async void ButtonSave_Click(object sender, RoutedEventArgs e)
{
var todoItem = new Test { Text = TextInput.Text };
await InsertTodoItem(todoItem);
}
private async void CheckBoxComplete_Checked(object sender, RoutedEventArgs e)
{
CheckBox cb = (CheckBox)sender;
Test item = cb.DataContext as Test;
await UpdateCheckedTodoItem(item);
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
await RefreshTodoItems();
}
}
For Javascript backend:
Go into the azure portal and select your mobile service. Go to the tab that says data. Click add a table name the table Test.
For .Net:
Open the project in Visual Studio. Add your Test class to the DataObjects folder. Right click the Controllers folder -> add -> controller. Select Microsoft Azure Mobile Services Table Controller. Chose your Test class for the model class and there should only be one option for the data context class.
You follow this article
Get started with Mobile Services
and you saw this
and with this you got the source code. This way you got two projects:
The .Net BackEnd project
The client app project
and when you did the changes, you only changed the client app project (because the MainPage belongs to the client app).
If you changed the TodoItem class to Test class in client app project, you need to do the same for the .NET Project, which requires the changes:
change the TodoItemController to TestController
change the TodoItem to Test
do a clean, then build and if do not have any error you can publish to Azure.
To help understand a bit it, I recommend to see the following samples
Connecting a Menu App to Azure Mobile Service
this article contains a step by step to create a simple backend like you are doing and provides tips that will help you.
How to create the Azure Mobile Service in Azure Portal
AzureMobileServices: Samples to help developers to use Azure Mobile Services

get html content of a page with Silverlight

I'm trying to get the html content of a page using silverlight. Webresponse and request classes don't work in silverlight.
I did some googling and I found something. This is what i tried:
public partial class MainPage : UserControl
{
string result;
WebClient client;
public MainPage()
{
InitializeComponent();
this.result = string.Empty;
this.client = new WebClient();
this.client.DownloadStringCompleted += ClientDownloadStringCompleted;
}
private void btn1_Click(object sender, RoutedEventArgs e)
{
string url = "http://www.nu.nl/feeds/rss/algemeen.rss";
this.client.DownloadStringAsync(new Uri(url, UriKind.Absolute));
if (this.result != string.Empty && this.result != null)
{
this.txbSummery.Text = this.result;
}
}
private void ClientDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
this.result = e.Result;
//handle the response.
}
}
It gives me a runtime error after pressing the button:
Microsoft JScript runtime error: Unhandled Error in Silverlight Application An exception occurred during the operation, making the result invalid. Check InnerException for exception details. at System.ComponentModel.AsyncCompletedEventArgs.RaiseExceptionIfNecessary()
at System.Net.DownloadStringCompletedEventArgs.get_Result()
at JWTG.MainPage.ClientDownloadStringCompleted(Object sender, DownloadStringCompletedEventArgs e)
at System.Net.WebClient.OnDownloadStringCompleted(DownloadStringCompletedEventArgs e)
at System.Net.WebClient.DownloadStringOperationCompleted(Object arg)
I've tried numerous things but all failed.
What am i missing? Or does anyone know how i could achieve this in a different way?
Thanks in advance!
This is related to clientaccesspolicy.xml. Read more here:
http://msdn.microsoft.com/en-us/library/cc645032(VS.95).aspx
"If the connection request was from a WebClient or an HTTP class to a cross-domain site, the Silverlight runtime tries to download the security policy file using the HTTP protocol. The Silverlight runtime first tries to download a Silverlight policy file with a name of "clientaccesspolicy.xml" at the root of the requested target domain using the HTTP protocol.
If the "clientaccesspolicy.xml" is either not found (the web request returns a 404 status code), returned with an unexpected mime-type, is not valid XML, or has an invalid root node, then the Silverlight runtime will issue a request for a for the Flash policy file with a name of "crossdomain.xml" at the root of the requested target domain, using the HTTP protocol.
HTTP redirects for the policy file are not allowed. A redirect for a policy file will result in a SecurityException of access denied."
Try this one, instead of your btn1_Click and ClientDownloadStringCompleted methods. It invokes the GUI thread after the feed is downloaded to update the textbox. If it fails because of an error on the network, it will unpack the exception (contained as an inner exception in a TargetInvocationException) and rethrow the inner exception.
private void btn1_Click(object sender, RoutedEventArgs e)
{
string url = "http://www.nu.nl/feeds/rss/algemeen.rss";
this.client.DownloadStringAsync(new Uri(url));
}
private void ClientDownloadStringCompleted(object sender,
DownloadStringCompletedEventArgs e)
{
try
{
Dispatcher.BeginInvoke(() => this.txbSummery.Text = e.Result ?? "");
}
catch (TargetInvocationException tiex)
{
throw tiex.InnerException;
}
}
If the error occures again (I guess that will happen), please post a stacktrace and error message here.
You try it
private void btn1_Click(object sender, RoutedEventArgs e)
{
string url = "http://www.nu.nl/feeds/rss/algemeen.rss";
this.client.DownloadStringAsync(new Uri(url, UriKind.Absolute));
}
private void ClientDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
Stream s = e.Result;
StreamReader strReader = new StreamReader(s);
string webContent = strReader.ReadToEnd();
s.Close();
this.txbSummery.Text =webContent;
}
In this line
this.client.DownloadStringAsync(new Uri(url, UriKind.Absolute));
you are stating an asynchroneous download in a background thread. And in the next line you somehow expect that it is aready completed?
If you have no knowledge about Threading just try with DownloadString first. Then your code will work.

Categories

Resources