Twitter Unsupported Authentication Problem - Tweetinvi Streams V2 - Asp.net Core MVC - twitter

When I try to use Tweetinvi Streams V2, it gives an error in the StartAsync section.
public async Task streamFonk()
{
stream.TweetReceived += (sender, eventReceived) =>
{
Console.WriteLine(eventReceived.Tweet);
};
var pars = new StartFilteredStreamV2Parameters();
pars.ClearCustomQueryParameters();
pars.ClearAllFields();
pars.UserFields = new HashSet<string>(new string[] { "tolgaylmzyzlm" });
try
{
await stream.StartAsync(pars);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
error: https://api.twitter.com/2/tweets/search/stream
I get the same error when using Tweetinvi Stream V1.1.

Related

ImageCropper.Forms is not working in ios platform (System.MissingMethodException)

I am using ImageCropper.Forms package for cropping images. It is working fine on the android part but when I try it on ios, I am getting the below exception:
Exception:>System.MissingMethodException: Method not found: System.Threading.Tasks.Task`1<Plugin.Media.Abstractions.MediaFile> Plugin.Media.Abstractions.IMedia.TakePhotoAsync(Plugin.Media.Abstractions.StoreCameraMediaOptions)
at System.Runtime.CompilerServices.AsyncVoidMethodBuilder.Start[TStateMachine] (TStateMachine& stateMachine) [0x0002c] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs:84
at Stormlion.ImageCropper.ImageCropper.Show (Xamarin.Forms.Page page, System.String imageFile) [0x00033] in <548dc893a11b47fe908c9c3d7f4a39ba>:0
at ImageCropDemo.MainPage.OnClickedRectangle (System.Object sender, System.EventArgs e) [0x00002] in /Users/companyname/Downloads/ImageCropDemo/ImageCropDemo/ImageCropDemo/MainPage.xaml.cs:29
Found the same question here, but it didn't solve my problem.
My Code
try
{
new ImageCropper()
{
Success = (imageFile) =>
{
Device.BeginInvokeOnMainThread(() =>
{
image.Source = ImageSource.FromFile(imageFile);
});
}
}.Show(this);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Exception:>" + ex);
}
I tried to install ImageCropper.Forms.Fix.v3 to solve this issue. When I try to install Fix.v3 getting the below errors:
Severity Code Description Project File Line Suppression State
Error NU1101 Unable to find package Plugin.Persmissions. No packages exist with this id in source(s): Microsoft Visual Studio Offline Packages, nuget.org ImageCropDemo C:\Users\user\Downloads\ImageCropDemo\ImageCropDemo\ImageCropDemo\ImageCropDemo.csproj 1=
Error Package restore failed. Rolling back package changes for 'ImageCropDemo'.
The ImageCropper.Forms.Fix.v5 installation is success, but no change in the exception. ImageCropper.Forms.Fix.v6 and ImageCropper.Forms.Fix.v7 packages are also available, which package will solve this issue in ios?
I have uploaded a sample here for reference.
The issue seems caused by the package itself . Here is a similar issue .
If you do want to implement it you could use the plugin Xamarin.Plugin.ImageEdit to edit your image .
Install it into your forms project and each platform project.
public byte[] GetImageStreamAsBytes(Stream input)
{
var buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
async void OpenCamera(object sender, EventArgs args)
{
try
{
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
await DisplayAlert("Alert", "No camera available.", "Ok");
return;
}
_mediaFile = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
Directory = "Sample",
Name = "test.jpg",
AllowCropping = true,
PhotoSize = PhotoSize.Medium
});
if (_mediaFile == null)
return;
using (var newImage = await CrossImageEdit.Current.CreateImageAsync(GetImageStreamAsBytes(_mediaFile.GetStream())))
{
var croped = await Task.Run(() =>
newImage.Crop(0, 0, 250, 300)
.Rotate(180)
.Resize(100, 0)
.ToPng()
);
image.Source = ImageSource.FromStream(() => new MemoryStream(croped));
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("CameraException:>" + ex);
}
}
This plugin can only crop the image with a fix value . If you want to set the area in runtime , check the sample in the github project site .

Mqtt: Persist message on server side

We decided to use mqtt protocol for chat module in our mobile application. I want to save messages of topic in server side also. But i saw,mqtt client is global here,so one way is i have to subscribe single instance of mqtt client to all topics and save messages in database. but is it right approach to do it. i am just worring about it.
private void buildClient(){
log.debug("Connecting... "+CLIENT_ID);
try {
mqttClient = new MqttClient(envConfiguration.getBrokerUrl(), CLIENT_ID);
} catch (MqttException e) {
log.debug("build client stopped due to "+e.getCause());
}
chatCallback = new ChatCallback();
mqttClient.setCallback(chatCallback);
mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setCleanSession(false);
}
#Override
public void connect() {
if(mqttClient == null || !mqttClient.getClientId().equals(CLIENT_ID)){
buildClient();
}
boolean tryConnecting = true;
while(tryConnecting){
try {
mqttClient.connect(mqttConnectOptions);
} catch (Exception e) {
log.debug("connection attempt failed "+ e.getCause() + " trying...");
}
if(mqttClient.isConnected()){
tryConnecting = false;
}else{
pause();
}
}
}
#Override
public void publish() {
boolean publishCallCompletedErrorFree = false;
while (!publishCallCompletedErrorFree) {
try {
mqttClient.publish(TOPIC, "hello".getBytes(), 1, true);
publishCallCompletedErrorFree = true;
} catch (Exception e) {
log.debug("error occured while publishing "+e.getCause());
}finally{
pause();
}
}
}
#Override
public void subscribe() {
if(mqttClient != null && mqttClient.isConnected()){
try {
mqttClient.subscribe(TOPIC, 2);
} catch (MqttException e) {
log.debug("subscribing error.."+e.getCause());
}
}
}
#Override
public void disconnect() {
System.out.println(this.mqttClient.isConnected());
try {
mqttClient.disconnect();
log.debug("disconnected..");
} catch (MqttException e) {
log.debug("erro occured while disconneting.."+e.getCause());
}
}
There are two possibilities how to solve this issue:
Write a MQTT client that subscribes to all topics using a wildcard (# in MQTT)
Write a broker plugin that does the job for you, depending on the broker implementation you're using
There is a good description of how to implement both options at the HiveMQ website, also describing limitations of the first option.

In NServiceBus full duplex application Server could not send/reply/return message

I have created a ASP.Net Web API project and using this link. NServiceBus is integrated with web api. Here is my configuration at web api as a client.
Configure.Serialization.Xml();
Configure.Transactions.Enable();
Configure.With()
.DefineEndpointName(Constants.ClientName)
.DefaultBuilder()
.ForWebApi()
.Log4Net()
.UseTransport<Msmq>()
.PurgeOnStartup(false)
.UnicastBus()
.ImpersonateSender(false)
.CreateBus()
.Start();
This is how I'm sending message to Server
var response = await Bus.Send(Constants.ServerName, request)
.Register<ResponseModel>((NServiceBus.CompletionResult completionResult) =>
{
ResponseModel responseMessage = null;
if (completionResult != null && completionResult.Messages.Length > 0)
{
var status = completionResult.Messages[0] as RequestStatus?;
if (status == RequestStatus.Successful)
{
responseMessage = TransactionManager.TransactionDictionary[request.RequestId].ResponseModel;
}
}
return responseMessage;
});
This is how I'm sending response from Server. I have commented some lines to show what I have already tried.
public void Handle(RequestModel message)
{
ProcessRequest(message).RunSynchronously();
}
private async Task ProcessRequest(RequestModel message)
{
....
ResponseModel response = new ResponseModel();
response.RequestId = message.RequestId;
response.Result = await responseMessage.Content.ReadAsStringAsync();
//Bus.Send(Util.Constants.ClientName, response);
//Bus.Reply(response);
//Bus.Reply<ResponseModel>((ResponseModel response) =>
//{
// response = Bus.CreateInstance<ResponseModel>(r =>
// {
// r.RequestId = message.RequestId;
// r.Result = responseMessage.Content.ReadAsStringAsync().Result;
// });
//});
await Bus.Send(Util.Constants.ClientName, response).Register((NServiceBus.CompletionResult completionResult) =>
{
if (completionResult != null && completionResult.Messages.Length > 0)
{
var msg = completionResult.Messages[0];
if (msg != null)
{
var status = (RequestStatus)msg;
return status;
}
}
return RequestStatus.Error;
});
....
}
From any of the above response methods ultimately all messages end up in error queue.
Previously I was getting 'Could not enlist message' error. Now it is not throwing that error. But Server could not send message to Client.
I could not get what I'm doing wrong. Please also suggest if you see any scope for improvements.
I'm not sure if TransactionScope work correctly with async/await in C#. According to this question (Get TransactionScope to work with async / await) in .NET 4.5.1 there was introduced option for TransactionScope that enable mixing it with async/await. Unfortunately NServiceBus doesn't support .NET 4.5/4.5.1 so try just remove async/await.

Windows Service just stops. No messages, no alerts, errors, warning - nothing

I have a Windows service that just silently stops on its own. Here is the relevant code:
OnStart() method:
protected override void OnStart(string[] args)
{
try
{
InitializeLogging();
// we don't DO command line arguments
if (args.Length > 0)
{
eventLog.WriteEntry("All command line arguments are ignored. You must edit the app.config file manually to make changes to what watchers are run.");
throw new ArgumentException("Command line arguments are ignored.");
}
ReadAppConfig();
RecalculateStartTimes();
InitializeWatchers();
}
catch (Exception e)
{
eventLog.WriteFormattedEntry("Error on Start: {0}", e.Message);
}
finally
{
eventLog.WriteEntry("Service start completed");
}
}
OnStop() method:
protected override void OnStop()
{
eventLog.WriteEntry("Service stopped.");
}
InitializeWatchers() method:
private void InitializeWatchers()
{
try
{
var watchers = _watcherSection.Watchers.ToList<WatcherElement>();
eventLog.WriteEntry(string.Format("Initializing {0} watchers.", watchers.Count()));
var obsWatchers = watchers.ToObservable();
obsWatchers.SelectMany(
watcher =>
Observable.Timer(watcher.StartTime, TimeSpan.FromHours(watcher.Interval))
.SelectMany(
Observable.FromAsync(
async () => new
{
watcher,
response = await CheckFolder(watcher.Path)
})))
.Subscribe(
onNext: x =>
{
eventLog.WriteFormattedEntry("\nWatcher: {0}, Time:{1}", x.watcher.Name, DateTimeOffset.Now);
if (x.response.Success)
eventLog.WriteFormattedEntry("| Success!\n| Value: '{0}'\n| Message: {0}", x.response.Value, x.response.Message);
else
eventLog.WriteFormattedEntry("| FAILURE!\n| Value: '{0}'\n| Message: {0}\n| Errors: '{0}'", x.response.Value, x.response.Message, x.response.Exceptions.First());
},
onError: e =>
{
var err = e;
var sb = new StringBuilder();
sb.AppendLine("The observer threw an error:")
.AppendFormatLine("| Message: {0}", e.Message);
while (e.InnerException != null)
{
sb.AppendFormatLine("| Inner: {0}", e.InnerException.Message);
e = e.InnerException;
}
sb.AppendLine();
eventLog.WriteEntry(sb.ToString());
throw err;
});
eventLog.WriteEntry("about to wait.");
obsWatchers.Wait();
eventLog.WriteEntry("passed the wait");
}
catch (Exception e)
{
eventLog.WriteFormattedEntry("Exception thrown in InitializeWatchers(WatchersSection): {0}", e.Message);
throw;
}
}
When I run this code, the service starts normally. The event log records three events:
Service & Logging started.
Initializing 1 watchers.
Service start completed.
... and it stops. I have to manually refresh the Services window, but it quits running. I don't get any errors, or any of the other eventLog entries.
The frustrating thing is that this code works perfectly as a Console app. I've changed all the eventLog.WriteEntry() to Console.WriteLine(), but other than that, the code is identical and performs as expected.
Any wisdom would be appreciated.
I suspect that the Service Control Manager is terminating your service because it did not return from OnStart within the timeout window (30 seconds, IIRC).
I have a blog post on managed service basics, which is based on a blog entry by the BCL team. Note that the MSDN docs are insufficient; you must know the information in the BCL team blog post to correctly write a managed service.
Instead of using obsWatchers.Wait() which blocks and causes the problems Stephen has said, just asynchronously subscribe.
Add this property to your class:
private SingleAssignmentDisposable _subscription = new SingleAssignmentDisposable();
Add this to your OnStop method:
_subscription.Dispose();
In your InitializeWatchers(), eliminate the nested call to Subscribe and replace obsWatchers.Wait() with a call to subscribe, like so:
private void InitializeWatchers()
{
try
{
var watchers = _watcherSection.Watchers.ToList<WatcherElement>();
eventLog.WriteEntry(string.Format("Initializing {0} watchers.", watchers.Count()));
var obsWatchers = watchers.ToObservable();
_subscription.Disposable = obsWatchers
.SelectMany(watcher => Observable
.Timer(watcher.StartTime, TimeSpan.FromHours(watcher.Interval))
.SelectMany(_ => Observable.FromAsync(async () => new
{
watcher,
response = await CheckFolder(watcher.Path)
})))
.Subscribe(
onNext: x =>
{
eventLog.WriteFormattedEntry("\nWatcher: {0}, Time:{1}", x.watcher.Name, DateTimeOffset.Now);
if (x.response.Success)
eventLog.WriteFormattedEntry("| Success!\n| Value: '{0}'\n| Message: {0}", x.response.Value, x.response.Message);
else
eventLog.WriteFormattedEntry("| FAILURE!\n| Value: '{0}'\n| Message: {0}\n| Errors: '{0}'", x.response.Value, x.response.Message, x.response.Exceptions.First());
},
onError: e =>
{
var err = e;
var sb = new StringBuilder();
sb.AppendLine("The observer threw an error:")
.AppendFormatLine("| Message: {0}", e.Message);
while (e.InnerException != null)
{
sb.AppendFormatLine("| Inner: {0}", e.InnerException.Message);
e = e.InnerException;
}
sb.AppendLine();
eventLog.WriteEntry(sb.ToString());
throw err;
});
eventLog.WriteEntry("passed the wait");
}
catch (Exception e)
{
eventLog.WriteFormattedEntry("Exception thrown in InitializeWatchers(WatchersSection): {0}", e.Message);
throw;
}
}

problems in silverlight 4 when using Action callbacks to check for successful file upload

So the async requirement for silverlight ends up in some really convoluted code!!
Im uploading a file just exactly like this answer suggests.
The difference is Im posting the file to an MVC action method. Everything works file except, like I commented on the bottom of that answer, I don't get any callback for when the file DOES NOT successfully upload.
So I created another action method in my mvc app (Services/CheckForFile/{id}) and it returns a string depending on whether the file is found.
Now, how and when do I call this mvc action method is the problem:
void DoUpload() { //Gets call on BtnUpload.Click
//opn is an OpenFileDialog
up.UploadFile(_filename, opn.File.OpenRead(),
e =>
{
//do some ui stuff here.
BeginCheck();// calling this causes PROBLEMS!
});
}
private void BeginCheck()
{
Uploader up = new Uploader();
up.CheckForFile(_filename, success =>
{
if (!success)
{
MessageBox.Show("There was problem uploading the file. Please try again", "Error", MessageBoxButton.OK);
}
});
}
Here is the problem:
When the BeginCheck() function runs, the file, for some reason, NEVER uploads! If I comment it out it does!? It seems like The BeginCheck() runs during the upload or something? Shouldn't it run after!?
How/where would I call BeginCheck() after the upload, to ensure the file has been uploaded?
Here is how I defined the Uploader class:
public class Uploader
{
public void UploadFile(string fileName, Stream data, Action<Exception> callback)
{
UriBuilder ub = new UriBuilder(_mvcurl+"Services/UploadFile/" + fileName);
WebClient c = new WebClient();
c.OpenWriteCompleted += (sender, e) =>
{
try
{
PushData(data, e.Result);
e.Result.Close();
data.Close(); //this does not block.
callback(null);//this ALWAYS hits!
}
catch (Exception err)
{
if (callback != null)
{
callback(err);
}
}
};
c.OpenWriteAsync(ub.Uri);
}
public void CheckForFile(string filename, Action<bool> callback)
{
UriBuilder ub = new UriBuilder(_mvcurl+"Services/CheckForFile/" + fileName);
WebClient c = new WebClient();
c.OpenReadCompleted += (sender, e) =>
{
using (StreamReader sw = new StreamReader(e.Result))
{
if (sw.ReadToEnd().Equals("Found", StringComparison.InvariantCultureIgnoreCase))
{
callback(true);
}
else
{
callback(false);
}
}
};
c.OpenReadAsync(ub.Uri);
}
private void PushData(Stream input, Stream output)
{//4KB is not a limitation. We only copy 4Kb at a time from in to out stream
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
{
output.Write(buffer, 0, bytesRead);
}
}
}
I'm embarrased to say that the original answer of mine to which you refer isn't entirely accurate. It seems to work for what the OP wanted but in fact the code doesn't block at the point that I thought it did. In reality what you are actually looking for is the WriteStreamClosed event, its here that you can discover any failure of the request.
Here is an ammended version that works the way you are expecting:-
public void UploadFile(string fileName, Stream data, Action<Exception> callback)
{
UriBuilder ub = new UriBuilder(_mvcurl+"Services/UploadFile/" + fileName);
WebClient c = new WebClient();
c.OpenWriteCompleted += (sender, e) =>
{
try
{
PushData(data, e.Result);
e.Result.Close();
data.Close(); //this does not block.
}
catch (Exception err)
{
if (callback != null)
callback(err);
}
};
c.WriteStreamClosed += (sender, e) =>
{
if (callback != null)
callback(e.Error);
}
c.OpenWriteAsync(ub.Uri);
}
Now your BeginCheck will only run after the server has responded to the file upload.

Resources