I'm new in telegram bot and write this code for check message coming to bot :
var updates = await Bot.GetUpdatesAsync(offset);
foreach (var update in updates)
{
if (update.Message.Text.Contains("hi") || update.Message.Text.Contains("Hi"))
{
//for first time that code work correct but after 4 hourse in this line
var updates = await Bot.GetUpdatesAsync(offset);
}
}
get error but i can not read error because after 1 minute reset visual studio that error solve,what happen?how can i solve that problem?thanks.
If you use the desktop application, it's best to use a timer that invokes your code every 1 second
private void timer1_Tick(object sender, EventArgs e)
{
yourGetUpdateFunc();
}
void yourGetUpdateFunc(){
var updates = await Bot.GetUpdatesAsync(offset);
foreach (var update in updates)
{
if (update.Message.Text.Contains("hi") || update.Message.Text.Contains("Hi"))
{
// do work
}
}
}
Related
I am getting following error when accessing HttpContext.Session from static method placed in separate task:
Session has not been configured for this application or request.
I used this article to implement access to HttpContext outside the controller
From controller I invoke this static method that used to retrieve image data:
public static void CreateDummyGallery(Gallery gallery)
{
Logger.LogDebug(LogModule.Dummy, $"Starting gallery creation.");
Task.Factory.StartNew(() =>
{
try
{
List<DummyPicture> pictures;
using (var context = new MyzeumContext())
{
int top = 10;
pictures = context.DummyPictures.FromSql($"SELECT * FROM dummypictures ORDER BY RAND() LIMIT {top}").ToList();
}
Logger.LogDebug(LogModule.Dummy, $"Starting retrieving images.");
Parallel.ForEach(pictures, picture => {
using (WebClient client = new WebClient())
{
}
});
Logger.LogDebug(LogModule.Dummy, $"Done retrieving images.");
}
catch(Exception e)
{
Logger.LogError(LogModule.Server, e.Message, e);
}
});
}
The problem occurs in Logger.LogDebug() because this is where I access HttpContext:
public void LogDebug(LogModule module, string message, Exception stackTrace = null)
{
Log record = new Log();
record.Module = module;
record.ThreadId = Environment.CurrentManagedThreadId;
record.SessionId = HttpContextHelper.Current?.Session?.Id;
record.Message = message;
record.Logged = DateTime.UtcNow;
if(stackTrace != null)
{
record.Message += $" :{stackTrace.StackTrace}";
}
queue.Enqueue(record);
}
The problem 99% occurs in the first call inside task:
Logger.LogDebug(LogModule.Dummy, $"Starting retrieving images.");
BUT, right after application starts this whole task block works fine and does not throw any exception. Problem starts after following requests.
NOTE: Using the Sign-in button is NOT an option
A year ago I was having a problem creating a moment. Back then I was using version 1.2 of the Google+ API .Net client. As I described in this post, I had it working although the code failed to insert a moment from time to time. I was hoping that the process is more stable and easier to implement now, and it seems like it as can be seen in the example that you can download here - the current version as of this writing is v1.8. So I created a simple project following the SimpleOAuth2 sample in the download, but implementing Google+. This is the code I came up:
public partial class _Default : System.Web.UI.Page
{
private PlusService service;
// Application logic should manage users authentication.
// This sample works with only one user. You can change
// it by retrieving data from the session.
private const string UserId = "user-id";
protected void Page_Load(object sender, EventArgs e)
{
GoogleAuthorizationCodeFlow flow;
var assembly = Assembly.GetExecutingAssembly();
using (var stream = assembly.GetManifestResourceStream(
"GPlusSample.client_secrets.json"))
{
flow = new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer
{
DataStore = new FileDataStore("GPlusSample.Store"),
ClientSecretsStream = stream,
//
// Tried only this scope but it did not work
//Scopes = new[] { PlusService.Scope.PlusMe }
//
// I tried the following: but did not work either
//Scopes = new[] { PlusService.Scope.PlusMe,
// "https://www.googleapis.com/auth/plus.moments.write" }
//
// I tried this as well and it failed
//Scopes = new[] { PlusService.Scope.PlusLogin }
//
// Maybe this... but still no joy
Scopes = new[] { PlusService.Scope.PlusLogin,
PlusService.Scope.PlusMe }
});
}
var uri = Request.Url.ToString();
var code = Request["code"];
if (code != null)
{
var token = flow.ExchangeCodeForTokenAsync(UserId, code,
uri.Substring(0, uri.IndexOf("?")), CancellationToken.None).Result;
// Extract the right state.
var oauthState = AuthWebUtility.ExtracRedirectFromState(
flow.DataStore, UserId, Request["state"]).Result;
Response.Redirect(oauthState);
}
else
{
var result = new AuthorizationCodeWebApp(flow, uri, uri)
.AuthorizeAsync(UserId, CancellationToken.None).Result;
if (result.RedirectUri != null)
{
// Redirect the user to the authorization server.
Response.Redirect(result.RedirectUri);
}
else
{
// The data store contains the user credential,
// so the user has been already authenticated.
service = new PlusService(new BaseClientService.Initializer
{
ApplicationName = "Plus API Sample",
HttpClientInitializer = result.Credential
});
}
}
}
/// <summary>Gets the TasksLists of the user.</summary>
public async System.Threading.Tasks.Task InsertMoment()
{
try
{
var me = service.People.Get("me").Execute();
var request = service.Moments.Insert(new Moment()
{
Target = new ItemScope {
Id=Guid.NewGuid().ToString(),
Image="http://www.google.com/s2/static/images/GoogleyEyes.png",
Type="",
Name = "test message",
Description="test",
Text="test message",
},
Type = "http://schemas.google.com/AddActivity",
}, me.Id, MomentsResource.InsertRequest.CollectionEnum.Vault);
var response =await request.ExecuteAsync();
output.Text = "<h1>" + response.Id + "</h1>";
}
catch (Exception ex)
{
var str = ex.ToString();
str = str.Replace(Environment.NewLine, Environment.NewLine + "<br/>");
str = str.Replace(" ", " ");
output.Text = string.Format("<font color=\"red\">{0}</font>", str);
}
}
protected async void createMomentButton_Click(object sender, EventArgs e)
{
await InsertMoment();
}
}
That code always give me a 401 Unauthorized error, even if I have the Google+ API turned on for my project. Here's the actual error I got:
The service plus has thrown an exception: Google.GoogleApiException:
Google.Apis.Requests.RequestError Unauthorized [401] Errors [
Message[Unauthorized] Location[ - ] Reason[unauthorized]
Domain[global] ]
It's interesting to see that the insert moment is failing even though the call to People.Get("me") works - get("me") works with all of the scope combinations I listed above. It's important to note that each time I try a new scope, I first log out of my Google account and delete the access token that is stored in GPlusSample.Store.
EDIT
I tried setting just the Url instead of individual items as suggested by Ian and I got the exact same error.
var request = service.Moments.Insert(new Moment()
{
Target = new ItemScope {
Url = "https://developers.google.com/+/web/snippet/examples/thing"
},
Type = "http://schemas.google.com/AddActivity",
}, me.Id, MomentsResource.InsertRequest.CollectionEnum.Vault);
var response =await request.ExecuteAsync();
https://www.googleapis.com/auth/plus.login is the right scope for writing moments, but you need to have requested the specific app activity types you want to write as well. The parameter for this is request_visible_actions, and it takes a space separated list of arguments of the types (Listed on https://developers.google.com/+/api/moment-types/ - e.g. http://schemas.google.com/AddActivity).
The client library may not have a method for adding request_visible_actions, so you may have to add it on to the auth URL you redirect the user to manually (remember to URLencode the app activity type URLs!)
I´m developing a windows 8 store app in c# and xaml for a website(the website is in .net mvc 4) .In the web site i can create, edit, and delete products (i´m using sql server 2008 r2).
In my w8 app i call a wcf service to get the data and populate the items.
I wanted to know if there is a way to notify or update the data in the w8 app after someone create or edit a product through the website.
One of the posible solution that i thought, was call the wcf service every time that the user click to see the list of products but i dont think is a good practice.
Here is my code:
//App.xaml.cs
protected override async void OnLaunched(LaunchActivatedEventArgs args)
{
ServiceProduct serviceData = (ServiceProduct)App.Current.Resources["serviceProducts"];
if (serviceData != null)
{
if (serviceData.ListaIos.Count == 0)
{
try
{
await serviceData.GetListProductsAsync();
}
catch(ServiceException)
{
var messageDialog = new Windows.UI.Popups.MessageDialog("Error");
var result = messageDialog.ShowAsync();
}
}
}
*** code ***
}
//Items page
protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
// TODO: Assign a bindable collection of items to this.DefaultViewModel["Items"]
ServiceProduct serviceData = (ServiceProduct)App.Current.Resources["serviceProducts"];
if (serviceData != null)
{
this.DefaultViewModel["Items"] = serviceData.GetProducts;
}
}
public async Task GetListProductsAsync()
{
ProductServiceClient service = new ProductServiceClient();
Product product;
try
{
var wcfCall = await service.GetListaAsync();
foreach (var item in wcfCall.List)
{
map product
this.ListaIos.Add(product);
}
}
catch(Exception)
{
throw new NotImplementedException();
}
}
I'm wondering if anyone has encountered this before:
I handle a command, and in the handler, I save an event to the eventstore (joliver).
Right after dispatching, the handler for the same command is handled again.
I know its the same command because the guid on the command is the same.
After five tries, nservicebus says the command failed due to the maximum retries.
So obviously the command failed, but I don't get any indication of what failed.
I've put the contents of the dispatcher in a try catch, but there is no error caught. After the code exits the dispatcher, the event handler will always fire as if something errored out.
Tracing through the code, the events are saved to the database (I see the row), the dispatcher runs, and the Dispatched column is set to true, and then the handler handles the command again, the process repeats, and another row gets inserted into the commits table.
Just what could be failing? Am I not setting a success flag somewhere in the event store?
If I decouple the eventstore from nServicebus, both will run as expected with no retries and failures.
The dispatcher:
public void Dispatch(Commit commit)
{
for (var i = 0; i < commit.Events.Count; i++)
{
try
{
var eventMessage = commit.Events[i];
var busMessage = (T)eventMessage.Body;
//bus.Publish(busMessage);
}
catch (Exception ex)
{
throw ex;
}
}
}
The Wireup.Init()
private static IStoreEvents WireupEventStore()
{
return Wireup.Init()
.LogToOutputWindow()
.UsingSqlPersistence("EventStore")
.InitializeStorageEngine()
.UsingBinarySerialization()
//.UsingJsonSerialization()
// .Compress()
//.UsingAsynchronousDispatchScheduler()
// .DispatchTo(new NServiceBusCommitDispatcher<T>())
.UsingSynchronousDispatchScheduler()
.DispatchTo(new DelegateMessageDispatcher(DispatchCommit))
.Build();
}
I had a transaction scope opened on the save that I never closed.
public static void Save(AggregateRoot root)
{
// we can call CreateStream(StreamId) if we know there isn't going to be any data.
// or we can call OpenStream(StreamId, 0, int.MaxValue) to read all commits,
// if no commits exist then it creates a new stream for us.
using (var scope = new TransactionScope())
using (var eventStore = WireupEventStore())
using (var stream = eventStore.OpenStream(root.Id, 0, int.MaxValue))
{
var events = root.GetUncommittedChanges();
foreach (var e in events)
{
stream.Add(new EventMessage { Body = e });
}
var guid = Guid.NewGuid();
stream.CommitChanges(guid);
root.MarkChangesAsCommitted();
scope.Complete(); // <-- missing this
}
}
I'm trying to get my head around designing a UI that remains responsive while a long running task is being executed.
To that end, I created a simple app in VS2012 and added the following class to it:
using System.Threading.Tasks;
namespace TaskTest
{
class Class1
{
public async Task<int> Async()
{
//simulate a long running process
for (long x = 0; x < long.MaxValue; x++) { }
return 1;
}
}
}
I then modified the main page's LoadState() method thusly:
protected override async void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
await DoLongRunningProcess();
}
private async Task DoLongRunningProcess()
{
var id = 0;
id = await new Class1().Async();
await new MessageDialog(id + "").ShowAsync();
}
I want the page to remain responsive while that process executes. However, when I run this code, the page takes a long time to load. What am I doing wrong?
TIA
async isn't magic; it just gives you the capability to write asynchronous code. In particular, async does not execute code on a background thread. You can use Task.Run to do this.
You may find my async/await intro or the MSDN documentation helpful.
That was helpful. I made the following changes and I got the result I was looking for:
class Class1
{
public int Launch()
{
//throw new Exception("Class1 exception");
for (var i = 0; i < int.MaxValue / 2; i++) ;
return 1;
}
}
...
protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
var task = DoLongRunningProcess();
await task;
await new MessageDialog(task.Result + "").ShowAsync();
}
private Task<int> DoLongRunningProcess()
{
return Task.Run<int>(() => new Class1().Launch());
}
The page continues to load and after a short pause the message dialog is displayed. Now however, I need to know how to catch exceptions. If I uncomment the //throw new Exception ... line in method Launch(), it is reported as an unhandled exception. I want to catch this exception in the main UI thread (i.e., in the body of method LoadState) but I can't seem to manage it.