Microsoft GraphAPI working in one project, but not another - c#

I have a console app using the Graph API to process pdfs sent to an email address. I am trying to set up my api to serve the pdfs, which is in another project. I have my authentication and client creation for graph in a dll, so that is all done the same, and uses the same Azure AD application info. In the console app, everything works great, but in the API it is not working.Do I have to provision the API as a separate app in Azure? That's all I can think of. Te code is literally the same right now, and not working. No errors or anything, just hangs forever trying to get anything from Office 365.
Thanks.
The below is the working code:
try
{
client = AuthenticationHelper.GetAuthenticatedClientForApp();
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Acquiring a token failed with the following
error: {0}", ex.Message);
if (ex.InnerException != null)
{
//You should implement retry and back-off logic per the
guidance given here:http://msdn.microsoft.com/en-us/library/dn168916.aspx
//InnerException Message will contain the HTTP error status
codes mentioned in the link above
Console.WriteLine("Error detail: {0}",
ex.InnerException.Message);
}
Console.ResetColor();
Console.ReadKey();
return;
}
try
{
String email = "mail#example.com";
Console.WriteLine("\nRetreiving email from: " + email);
var folders = client.Users[email].MailFolders.Inbox.ChildFolders.Request().GetAsync().Result;
This is the code that fails:
try
{
client = AuthenticationHelper.GetAuthenticatedClientForApp();
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Acquiring a token failed with the following error: {0}", ex.Message);
if (ex.InnerException != null)
{
//You should implement retry and back-off logic per the guidance given here:http://msdn.microsoft.com/en-us/library/dn168916.aspx
//InnerException Message will contain the HTTP error status codes mentioned in the link above
Console.WriteLine("Error detail: {0}", ex.InnerException.Message);
}
Console.ResetColor();
Console.ReadKey();
return null;
}
Attachment attachment = null;
try
{
String email = "email#example.com";
var folders = client.Users[email].MailFolders.Inbox.ChildFolders.Request().GetAsync().Result;

Related

ServiceBus reciever is not throwing exception after ServiceBus Connection string Refresh and is able to process messages

I have a service-bus receiver instance running as a continuous running webjob, and there is requirement to Refresh the primary connection string 6 months once
what I learnt was if i am refreshing the connection string using azure portal then the existing receiver instance should throw unauthorized exception, but to my surprise its not throwing any exception it runs for 20 min or so and stops receiving message without any exception.
My Question here is that without getting the exception I cannot hit the key vault and create new instance of the receiver, is there any other alternative way for doing this ?
I have create a prototype of my application and the service bus package I am using is
WindowsAzure.ServiceBus 4.1.8 and running it using a console application.
static void Main(string[] args)
{
try
{
var factory = MessagingFactory.CreateFromConnectionString("connectionstring");
factory.PrefetchCount = 1;
var queue = factory.CreateMessageReceiver("test");
var options = new OnMessageOptions()
{
MaxConcurrentCalls = 1,
AutoComplete = false
};
Console.WriteLine(DateTime.Now);
queue.OnMessageAsync(HandleMessageReceived, options);
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("exception caught" + ex.Message);
throw;
}
}
and this is my message handler
async static Task HandleMessageReceived(BrokeredMessage brokeredMessage)
{
try
{
await brokeredMessage.CompleteAsync();
Console.WriteLine("Message Processing completed");
}
catch (Exception ex)
{
Console.WriteLine("Message Handlet exception" + ex.Message);
Console.WriteLine("has hit the catch of message handler ");
throw;
}
}
After Starting the application and it completes few messages from test queue i go to portal and regenerate my primary keys.

Unstable bluetooth connection on Windows IoT Core - even using an external dongle

I am using my RaspberryPis (v3) running the latest stable Windows IoT Core version (v.10.0.17763.737) to retrieve data and control my bluetooth thermostats. I am struggling quite a long time with the stability of the bluetooth connection. Some months ago I switched all my nodes to external dongles (one from the microsoft compatibility list: ORICO BTA-403), which improved the situation, but it is still far away from being stable.
After a certain time (varies from minutes to days) the bluetooth connection stops working. I already implemented a powershell script to check for such situations and fire a "devcon restart USB" command. This helps, but only in about 50% of all failures. If it does not solve the situation, I have to reboot the node. However, this is not satisfying, because from time to time the nodes freeze while booting and I made the experience that doing too many reboots will reduce the lifetime of the micro sd card.
After some hours of analysis I found out that the bluetooth support service could be the problem. Before the connection crashes I can easily restart the bluetooth support service using powershell. After the problem occured, this is not possible anymore. The service restart hangs up and the status of the service says it is pending for restart or something like this.
Do you guys made the same experience? Or is my bluetooth connection implementation too bad? I attached the function for you to have a look:
private async Task Connect()
{
try
{
int count = 0;
do
{
count++;
if (count > 10)
{
m_IsInitialized = false;
//throw new Exception("More than 10 tries have not been successfull for connecting with thermostat module. Stopping.");
}
m_IsInitialized = false;
m_Device = await BluetoothLEDevice.FromIdAsync(m_DeviceID);
if (m_Device == null)
{
throw new Exception("Device was not found.");
}
m_Characteristics = new Dictionary<ushort, GattCharacteristic>();
GattDeviceServicesResult gattServices = await m_Device.GetGattServicesAsync();
foreach (GattDeviceService service in gattServices.Services)
{
try
{
GattCharacteristicsResult characteristicsResult = await service.GetCharacteristicsAsync();
IReadOnlyList<GattCharacteristic> characteristics = characteristicsResult.Characteristics;
foreach (GattCharacteristic characteristic in characteristics)
{
try
{
m_Characteristics.Add(characteristic.AttributeHandle, characteristic);
GattCharacteristicProperties properties = characteristic.CharacteristicProperties;
if (properties.HasFlag(GattCharacteristicProperties.Notify))
{
try
{
GattCommunicationStatus status = await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
if (status == GattCommunicationStatus.Success)
{
characteristic.ValueChanged += Characteristic_ValueChanged;
m_IsInitialized = true;
//Logger.ServiceLog(string.Format("Thermostat has been initialized successfully ({0} tries).", count));
return;
}
}
catch (Exception ex4)
{
throw new Exception("4: GattCommunicationStatus: " + ex4.Message + "\nStackTrace: " + ex4.StackTrace);
}
}
}
catch (Exception ex3)
{
throw new Exception("3: GattCharacteristic: " + ex3.Message + "\nStackTrace: " + ex3.StackTrace);
}
}
}
catch (Exception ex2)
{
throw new Exception("2: GattDeviceService: " + ex2.Message + "\nStackTrace: " + ex2.StackTrace);
}
}
//Logger.ServiceLog(string.Format("Thermostat:Connect: Unsuccessful try: {0}", count));
await Task.Delay(1 * 60 * 1000);
}
while (!m_IsInitialized);
}
catch (Exception ex)
{
Logger.ServiceLog("1: Thermostat.cs Connect", ex);
}
}
As you see, the code is full of debugging helps, but no exception is raised at all when the connectivity collapses. I am really looking forward to any help, because after months of struggling I would really prefer getting to a stable solution without any hacks or workarounds.
Thanks for all your help :-)

MQTTNet Listen for Topic Messages

I am integrating MQTT in our existing application, I have used this https://github.com/chkr1011/MQTTnet library for running an embedded MQTT broker.
Currently the following method is used to start the broker:
public async Task StarBrokerAsync()
{
var optionsBuilder = new MqttServerOptionsBuilder()
.WithConnectionBacklog(ConnectionBacklog)
.WithDefaultEndpointPort(Port);
MqttServer = new MqttFactory().CreateMqttServer();
await MqttServer.StartAsync(optionsBuilder.Build());
}
What I want is to listen for messages in a specific topic without creating a separate client at best. I've not found documentation for the library or any similar questions.
Is there any solutions for the problem?
mqttServer.UseApplicationMessageReceivedHandler(e =>
{
try
{
string topic = e.ApplicationMessage.Topic;
if (string.IsNullOrWhiteSpace(topic) == false)
{
string payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
Console.WriteLine($"Topic: {topic}. Message Received: {payload}");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message, ex);
}
});

Handshake failed due to an unexpected packet format

I am trying to have a stable connection to a MySQL database hosted on Amazon Web Services. Periodically when starting the application, I will get the exception:
Handshake failed due to an unexpected packet format
This is a WinForm C# application using MySQL.Data.dll V6.9.9
Here is my code for connecting:
using (var conn = new MySqlConnection(m_connectionString))
{
try
{
conn.Open();
Console.WriteLine("Connected to database");
}
catch (MySqlException ex)
{
validConnectionFound = false;
Console.WriteLine(ex);
MessageBox.Show("Unable to connect to Database. Check your network connection and try again", "Database connection Not Found");
}
catch (CryptographicException ex)
{
validConnectionFound = false;
MessageBox.Show("Cryptographic Exception: " + ex.Message);
Environment.Exit(0);
}
catch(IOException ex)
{
validConnectionFound = false;
DebugTrace.TraceWrite(m_defaultTraceSource, TraceEventType.Error, "Incorrect certificate. Please update security certificate. Exception: " + ex.Message);
MessageBox.Show("IO Exception: " + ex.Message);
Environment.Exit(0);
}
}
My connection string is in the following format:
"user id=user;password=1234;server=amazonserver.com;database=myDatabase;convertzerodatetime=True;port=3306;sslmode=VerifyCA"
I have tried both wireless and wired connections, changing the SSL mode required (VerifyCA, Required, VerifyFull, None), and adding Amazons CA to my computers trusted root certificates.
Any insight on why I am getting this exception is appreciated.
Turns out the issue was not code related. After sniffing packets with Wireshark, I found the problem was with a faulty network switch losing packets.

Delay when send string via socket

I make an application in android can send character code to server C# when user input on android keyboard.
This is send method in android side:
public Boolean writeMessage(String message) {
try {
printWriter = new PrintWriter(socket.getOutputStream(), true);
printWriter.println(message);
return true;
} catch (Exception ex) {
Log.e(TAG,"write error: " +ex.getMessage());
return false;
}
}
And server listen the messages (C#):
Thread myThread = new Thread(new ThreadStart(ServeClient));
myThread.Start();
void ServeClient(){
StreamReader reader = new StreamReader(tcpClient.GetStream());
while (true)
{
try
{
String message = reader.ReadLine();
if (message != null)
{
Console.WriteLine(message);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
My code works, but when user input faster, the server delay read message in 1,2 or 3 seconds (I have test the method get character when user input, it works fine, not delay). Where is my problem? Thanks in advance!
Your problem may be caused by Nagle's algorithm reducing TCP traffic. Consider setting TCP_NODELAY on your client (and server - TcpClient.Client.NoDelay - if communication is two-way).
Edit: For java it is Socket.setTcpNoDelay method.

Categories

Resources