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);
}
}
}
Related
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
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
I'm trying to create a web app which does many things but the one that I'm currently focused in is the inbox count. I want to use EWS StreamSubscription so that I can get notification for each event and returns the total count of items in the inbox. How can I use this in terms of MVC? I did find some code from Microsoft tutorial that I was gonna test, but I just couldn't figure how I could use it in MVC world i.e. What's the model going to be, if model is the count then how does it get notified every time an event occurs in Exchange Server, etc.
Here's the code I downloaded from Microsoft, but just couldn't understand how I can convert the count to json and push it to client as soon as a new change event occurs. NOTE: This code is unchanged, so it doesn't return count, yet.
using System;
using System.Linq;
using System.Net;
using System.Threading;
using Microsoft.Exchange.WebServices.Data;
namespace StreamingNotificationsSample
{
internal class Program
{
private static AutoResetEvent _Signal;
private static ExchangeService _ExchangeService;
private static string _SynchronizationState;
private static Thread _BackroundSyncThread;
private static StreamingSubscriptionConnection CreateStreamingSubscription(ExchangeService service,
StreamingSubscription subscription)
{
var connection = new StreamingSubscriptionConnection(service, 30);
connection.AddSubscription(subscription);
connection.OnNotificationEvent += OnNotificationEvent;
connection.OnSubscriptionError += OnSubscriptionError;
connection.OnDisconnect += OnDisconnect;
connection.Open();
return connection;
}
private static void SynchronizeChangesPeriodically()
{
while (true)
{
try
{
// Get all changes from the server and process them according to the business
// rules.
SynchronizeChanges(new FolderId(WellKnownFolderName.Inbox));
}
catch (Exception ex)
{
Console.WriteLine("Failed to synchronize items. Error: {0}", ex);
}
// Since the SyncFolderItems operation is a
// rather expensive operation, only do this every 10 minutes
Thread.Sleep(TimeSpan.FromMinutes(10));
}
}
public static void SynchronizeChanges(FolderId folderId)
{
bool moreChangesAvailable;
do
{
Console.WriteLine("Synchronizing changes...");
// Get all changes since the last call. The synchronization cookie is stored in the _SynchronizationState field.
// Only the the ids are requested. Additional properties should be fetched via GetItem calls.
var changes = _ExchangeService.SyncFolderItems(folderId, PropertySet.IdOnly, null, 512,
SyncFolderItemsScope.NormalItems, _SynchronizationState);
// Update the synchronization cookie
_SynchronizationState = changes.SyncState;
// Process all changes
foreach (var itemChange in changes)
{
// This example just prints the ChangeType and ItemId to the console
// LOB application would apply business rules to each item.
Console.Out.WriteLine("ChangeType = {0}", itemChange.ChangeType);
Console.Out.WriteLine("ChangeType = {0}", itemChange.ItemId);
}
// If more changes are available, issue additional SyncFolderItems requests.
moreChangesAvailable = changes.MoreChangesAvailable;
} while (moreChangesAvailable);
}
public static void Main(string[] args)
{
// Create new exchange service binding
// Important point: Specify Exchange 2010 with SP1 as the requested version.
_ExchangeService = new ExchangeService(ExchangeVersion.Exchange2010_SP1)
{
Credentials = new NetworkCredential("user", "password"),
Url = new Uri("URL to the Exchange Web Services")
};
// Process all items in the folder on a background-thread.
// A real-world LOB application would retrieve the last synchronization state first
// and write it to the _SynchronizationState field.
_BackroundSyncThread = new Thread(SynchronizeChangesPeriodically);
_BackroundSyncThread.Start();
// Create a new subscription
var subscription = _ExchangeService.SubscribeToStreamingNotifications(new FolderId[] {WellKnownFolderName.Inbox},
EventType.NewMail);
// Create new streaming notification conection
var connection = CreateStreamingSubscription(_ExchangeService, subscription);
Console.Out.WriteLine("Subscription created.");
_Signal = new AutoResetEvent(false);
// Wait for the application to exit
_Signal.WaitOne();
// Finally, unsubscribe from the Exchange server
subscription.Unsubscribe();
// Close the connection
connection.Close();
}
private static void OnDisconnect(object sender, SubscriptionErrorEventArgs args)
{
// Cast the sender as a StreamingSubscriptionConnection object.
var connection = (StreamingSubscriptionConnection) sender;
// Ask the user if they want to reconnect or close the subscription.
Console.WriteLine("The connection has been aborted; probably because it timed out.");
Console.WriteLine("Do you want to reconnect to the subscription? Y/N");
while (true)
{
var keyInfo = Console.ReadKey(true);
{
switch (keyInfo.Key)
{
case ConsoleKey.Y:
// Reconnect the connection
connection.Open();
Console.WriteLine("Connection has been reopened.");
break;
case ConsoleKey.N:
// Signal the main thread to exit.
Console.WriteLine("Terminating.");
_Signal.Set();
break;
}
}
}
}
private static void OnNotificationEvent(object sender, NotificationEventArgs args)
{
// Extract the item ids for all NewMail Events in the list.
var newMails = from e in args.Events.OfType<ItemEvent>()
where e.EventType == EventType.NewMail
select e.ItemId;
// Note: For the sake of simplicity, error handling is ommited here.
// Just assume everything went fine
var response = _ExchangeService.BindToItems(newMails,
new PropertySet(BasePropertySet.IdOnly, ItemSchema.DateTimeReceived,
ItemSchema.Subject));
var items = response.Select(itemResponse => itemResponse.Item);
foreach (var item in items)
{
Console.Out.WriteLine("A new mail has been created. Received on {0}", item.DateTimeReceived);
Console.Out.WriteLine("Subject: {0}", item.Subject);
}
}
private static void OnSubscriptionError(object sender, SubscriptionErrorEventArgs args)
{
// Handle error conditions.
var e = args.Exception;
Console.Out.WriteLine("The following error occured:");
Console.Out.WriteLine(e.ToString());
Console.Out.WriteLine();
}
}
}
I just want to understand the basic concept as in what can be model, and where can I use other functions.
Your problem is that you are confusing a service (EWS) with your applications model. They are two different things. Your model is entirely in your control, and you can do whatever you want with it. EWS is outside of your control, and is merely a service you call to get data.
In your controller, you call the EWS service and get the count. Then you populate your model with that count, then in your view, you render that model property. It's really that simple.
A web page has no state. It doesn't get notified when things change. You just reload the page and get whatever the current state is (ie, whatever the current count is).
In more advanced applications, like Single Page Apps, with Ajax, you might periodically query the service in the background. Or, you might have a special notification service that uses something like SignalR to notify your SPA of a change, but these concepts are far more advanced than you currently are. You should probably develop your app as a simple stateless app first, then improve it to add ajax functionality or what not once you have a better grasp of things.
That's a very broad question without a clear-cut answer. Your model could certainly have a "Count" property that you could update. The sample code you found would likely be used by your controller.
I've this piece of code in my page, but it don't run when i make changes in the database, what could be the problem.
This starts well, when i load the page this executes the function twice, but if i send a message to the database this doens't execute.
$(function () {
var chat = $.connection.chatHub;
chat.client.allTalks = function () {
refresh();
};
$.connection.hub.start();
refresh();
});
SERVER SIDE (HUB):
[HubName("chatHub")]
public class ChatHub : Hub
{
public static void AllTalks()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
context.Clients.All.allTalks();
}
}
HANDLER
...
using (SqlCommand command = new
SqlCommand(#"SELECT * FROM [dbo].[chat_talks]", connection)) {
//CONTENT
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
...
}
public void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
ChatHub.AllTalks();
}
GLOBAL.ASAX
protected void Application_Start(object sender, EventArgs e)
{
SqlDependency.Start(ConfigurationManager.ConnectionStrings["ProjectSellerConnection"].ConnectionString);
}
First off, it is redundant to have your first line in your server-side code. There is no need to call for a hubContext inside the Hub. You can just do:
public static void AllTalks()
{
Clients.All.allTalks();
}
I would suggest, perhaps foolishly, to not use SQL Dependency. I would instead suggest using the following technique of calling SignalR (specifically, it will call the client functions):
var hubContext = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
hubContext.Clients.All.allTalks();
You can call this in, for example, actions in MVC and WebAPI Controllers, thus meaning if you've done any database updates in those actions, you can subsequently call clients using this methodology. I know it's not as fancy as SQL Dependency, and perhaps not the answer your looking for, but it will solve your problem - since it appears the problem seems to be with SignalR detecting the database changes.
In other words, this methodology will work, but it's probably not the precise one you are hoping for.
so I have succeeded in connecting my Windows Phone 8 Application to the Live API, I also succeeded in reading data from my hotmail account.
I have access to the needed client ID and the live access token.
But when I quit and restart my application, I lose all references to the session and the client objects and I have to start the process anew.
I don't want to annoy the user with the web mask in which he has to agree again that he provides me with the needed permissions every time he is starting the application. But I also haven't found a way to get a reference to a session object without this step.
The login mask is only shown the first time after installing the application, after that, only the screen mentioned above is shown.
But it is still quite annoying for the user to accept this every time.
I already tried serializing the session object, which is not possible, because the class does not have a standard constructor.
Maybe it is possible to create a new session by using the live access token, but I haven't found a way to do so.
Any ideas? What am I doing wrong, I know that there is a way to login again without prompting the user.
I'm thankful for every idea.
Some code I use:
/// <summary>
/// This method is responsible for authenticating an user asyncronesly to Windows Live.
/// </summary>
public void InitAuth()
{
this.authClient.LoginCompleted +=
new EventHandler<LoginCompletedEventArgs>(this.AuthClientLoginCompleted);
this.authClient.LoginAsync(someScopes);
}
/// <summary>
/// This method is called when the Login process has been completed (successfully or with error).
/// </summary>
private void AuthClientLoginCompleted(object sender, LoginCompletedEventArgs e)
{
if (e.Status == LiveConnectSessionStatus.Connected)
{
LiveConnector.ConnectSession = e.Session; // where do I save this session for reuse?
this.connectClient = new LiveConnectClient(LiveConnector.ConnectSession);
// can I use this access token to create a new session later?
LiveConnector.LiveAccessToken = LiveConnector.ConnectSession.AccessToken;
Debug.WriteLine("Logged in.");
}
else if (e.Error != null)
{
Debug.WriteLine("Error signing in: " + e.Error.ToString());
}
}
I have tried to use the LiveAuthClient.InitializeAsync - method to login in background after restarting the application, but the session object stays empty:
// this is called after application is restarted
private void ReLogin()
{
LiveAuthClient client = new LiveAuthClient(LiveConnector.ClientID);
client.InitializeCompleted += OnInitializeCompleted;
client.InitializeAsync(someScopes);
}
private void OnInitializeCompleted(object sender, LoginCompletedEventArgs e)
{
Debug.WriteLine("***************** Inititalisation completed **********");
Debug.WriteLine(e.Status); // is undefined
Debug.WriteLine(e.Session); // is empty
}
Does anyone have an idea how I could get access to a new session after restarting the application?
After two full days searching for the mistake I was making, I finally found out what I was doing wrong: I have to use the wl.offline_access scope to make this work!
Let me quote another user here:
"If your app uses wl.offline_access scope than the live:SignInButton control saves it for you and loads it automatically. Just use the SessionChanged event to capture the session object. This way the user will need to sign in only once."
(see WP7 how to store LiveConnectSession during TombStoning?)
Now everything is fun again. Can't believe that this was the problem. Tested & working. Nice!
Been struggling to get this working on a Windows Live + Azure Mobile Service app myself so thought I would post a complete working code sample here now that I've got it working.
The key parts are the wl.offline_access scope and the call to InitializeAsync.
Note: this sample also connects with Windows Azure Mobile Services. Just remove the stuff related to MobileService if you're not using that.
private static LiveConnectSession _session;
private static readonly string[] scopes = new[] {"wl.signin", "wl.offline_access", "wl.basic"};
private async System.Threading.Tasks.Task Authenticate()
{
try
{
var liveIdClient = new LiveAuthClient("YOUR_CLIENT_ID");
var initResult = await liveIdClient.InitializeAsync(scopes);
_session = initResult.Session;
if (null != _session)
{
await MobileService.LoginWithMicrosoftAccountAsync(_session.AuthenticationToken);
}
if (null == _session)
{
LiveLoginResult result = await liveIdClient.LoginAsync(scopes);
if (result.Status == LiveConnectSessionStatus.Connected)
{
_session = result.Session;
await MobileService.LoginWithMicrosoftAccountAsync(result.Session.AuthenticationToken);
}
else
{
_session = null;
MessageBox.Show("Unable to authenticate with Windows Live.", "Login failed :(", MessageBoxButton.OK);
}
}
}
finally
{
}
}