Why C# gRPC client taking more than 2 minutes to connect with server for the first call in Linux Debian OS - grpc

I have developed C# gRPC client in Console application. I run the below code in windows, when executing var reply = client.SetImage(new ImageMessage() { Ok = img }); taking 20 seconds to receive ack from server but when i run the same code Linux Debian OS taking 2 mins to establish connection with server (here build is generated in Visual Studio with debian.11-x64), here second calls are taking 2ms.
can anyone tell me why taking much time in Linux Debian OS for the first call and how to solve this?
`public class GrpcChannelFactory
{
public static GrpcChannel GetGrpcChannel()
{
var channelOption = new GrpcChannelOptions
{
MaxReceiveMessageSize = int.MaxValue,
MaxSendMessageSize = int.MaxValue,
};
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
var address = "http://localhost:3131";
return GrpcChannel.ForAddress(address, channelOption);
}
}
public void SendImageTest(byte[] imageData, int frameRowSize, int frameColSize, int numberOfFrames, int numberOfIteration)
{
if (channel == null
channel = GrpcChannelFactory.GetGrpcChannel();
var client = new ImageReceiver.ImageReceiverClient(channel);
Image img = new Image() { Id = "1", Data = ByteString.CopyFrom(imageData), Dtype = "int16" };
img.Size.Add(frameRowSize);
img.Size.Add(frameColSize);
img.Size.Add(numberOfFrames);
Console.WriteLine("Size Value: " + img.Size);
Console.WriteLine("CalculateSize: " + img.CalculateSize());
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
for (int idx = 0; idx < numberOfIteration; idx++)
{
Stopwatch stopWatchTest = new Stopwatch();
stopWatchTest.Start();
var reply = client.SetImage(new ImageMessage() { Ok = img });
stopWatchTest.Stop();
TimeSpan tspan = stopWatchTest.Elapsed;
string elapsedTimeTest = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
tspan.Hours, tspan.Minutes, tspan.Seconds,
tspan.Milliseconds / 10);
Console.WriteLine("SetImage Time taken " + elapsedTimeTest);
Console.WriteLine("Greeting: " + reply.Ok);
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);
}`
I want to find why first call taking 2 minutes but subsequent calls are taking 2 milliSeconds in Linux Debian OS.

Related

Mosquitto client consuming is slowing down and data gap increasing

In a system with multiple devices, diagnostic data is published to separate topics for each device to Mosquitto Broker. A client application tries to consume data by subscribing to these topics separately for each device. The client receives 5 or 6 record per device per minute.
My problem is, after worker application started, the data received from Mosquitto Boroker starts to have delays on the client side. These delays start from 1 second, as time progresses, it lags behind by 1 day and 2 days during the time it is on. After stopping borker, the client continues to consume data.
Any ideas on what causes these delays?
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
string dataHost = _configuration.GetValue<string>("DataHost");
mqttClient = new MqttClient(dataHost);
mqttClient.MqttMsgPublishReceived += MqttClient_MqttMsgPublishReceived;
var list = _configuration.GetValue<string>("DeviceList").Split(',').ToList();
foreach (var deviceId in list)
{
mqttClient.Subscribe(
new string[] { $"{deviceId}/#" },
new byte[] { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE });
}
mqttClient.ConnectionClosed += MqttClient_ConnectionClosed;
mqttClient.Connect("client", "username", "pass", false, 10);
}
private void MqttClient_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
try
{
var message = Encoding.UTF8.GetString(e.Message);
var messageArray = e.Topic.Split('/');
if (IsValidJson(message))
{
ItemValue itemValue = JsonConvert.DeserializeObject<ItemValue>(message);
_diagnosticRepository.InsertAsync(new DiagnosticDTO
{
value = messageArray[4].ToString(),
message = message,
messageTime = DateTime.Now,
deviceTime = itemValue.datetime,
sequenceNo = itemValue.sequenceNo,
});
}
}
catch (Exception ex)
{
_logger.LogError(ex.Message, "Consumer Insert Error");
}

Xamarin.Android - How to continue a process while app is minimized or screen is locked

I've created a Xamarin app that checks the users current location every couple minutes. My problem is it doesn't work when I minimize the app or the screen locks. Is there a way for me to continue the process while minimized or when the phone is locked?
This function checks to see if the user is at the destination location.
public bool atLocation(decimal currentLat, decimal currentLong, decimal destLat, decimal destLong)
{
decimal GPSLatitudePadding = 0.001M;
decimal GPSLongitudePadding = 0.001M;
var totalLowerLatitude = Convert.ToDecimal((destLat - GPSLatitudePadding).ToString("#.####"));
var totalLowerLongitude = Convert.ToDecimal((destLong + GPSLongitudePadding).ToString("#.####"));
var totalUpperLatitude = Convert.ToDecimal((destLat + GPSLatitudePadding).ToString("#.####"));
var totalUpperLongitude = Convert.ToDecimal((destLong - GPSLongitudePadding).ToString("#.####"));
if ((Convert.ToDecimal(destLat) >= totalLowerLatitude) &&
(Convert.ToDecimal(destLat) <= totalUpperLatitude) &&
(Convert.ToDecimal(destLong) <= totalLowerLongitude) &&
(Convert.ToDecimal(destLong) >= totalUpperLongitude))
{
return true;
}
return false;
}
If the user is at the destination for 2 instances of 2 minutes the process is ended. This is where you could start a new process or update a database.
int intNumberOfTimesFoundAtLocation = 0;
void OnLocationResult(object sender, Android.Locations.Location location)
{
decimal currentLatitude = Convert.ToDecimal(location.Latitude);
decimal currentLongitude = Convert.ToDecimal(location.Longitude);
decimal destLatitude = Convert.ToDecimal(this.dblDestLatitude);
decimal destLongitude = Convert.ToDecimal(this.dblDestLongitude);
var atLocation = locationQ.atLocation(currentLatitude, currentLongitude, destLatitude, destLongitude);
if (ayLocation == true)
{
intNumberOfTimesFoundAtLocation = intNumberOfTimesFoundAtLocation + 1;
if(intNumberOfTimesFoundAtLocation == 2)
{
client.RemoveLocationUpdates(locationCallback);
}
}
}
I call this function to start the process
MyLocationCallback locationCallback;
FusedLocationProviderClient client;
public async void StartLocationUpdatesAsync()
{
// Create a callback that will get the location updates
if (locationCallback == null)
{
locationCallback = new MyLocationCallback();
locationCallback.LocationUpdated += OnLocationResult;
}
// Get the current client
if (client == null)
client = LocationServices.GetFusedLocationProviderClient(this);
try
{
locationRequest = new LocationRequest()
.SetInterval(120000)
.SetFastestInterval(120000)
.SetPriority(LocationRequest.PriorityHighAccuracy);
await client.RequestLocationUpdatesAsync(locationRequest, locationCallback);
}
catch (Exception ex)
{
//Handle exception here if failed to register
}
}
}
class MyLocationCallback : LocationCallback
{
public EventHandler<Android.Locations.Location> LocationUpdated;
public override void OnLocationResult(LocationResult result)
{
base.OnLocationResult(result);
LocationUpdated?.Invoke(this, result.LastLocation);
}
}
Create a foreground service.
Inside service call the following code to start the request updates.
locationLogger = new LocationLogger();
locationLogger.LogInterval = _currentInterval;
locationLogger.StopUpdates();
locationLogger.StartRequestionUpdates();
Check here for the code
Let me know if you need more help.

Amazon S3 Multipart UploadPartRequest allows only single thread to upload at the same time using asp.net

I am trying to upload video files Amazon S3 using Multipart upload method in asp.net and I traced the upload progress using logs. It uploads 106496 each time and runs only single thread at a time. I did not notice that multiple threads running. Please clarify me on this why it is running single thread and it's taking long time to upload even for 20Mb file it's taking almost 2 minutes.
Here is my code, which uses UploadPartRequest.
private void UploadFileOnAmazon(string subUrl, string filename, Stream audioStream, string extension)
{
client = new AmazonS3Client(accessKey, secretKey, Amazon.RegionEndpoint.USEast1);
// List to store upload part responses.
List<UploadPartResponse> uploadResponses = new List<UploadPartResponse>();
// 1. Initialize.
InitiateMultipartUploadRequest initiateRequest = new InitiateMultipartUploadRequest
{
BucketName = bucketName,
Key = subUrl + filename
};
InitiateMultipartUploadResponse initResponse =
client.InitiateMultipartUpload(initiateRequest);
// 2. Upload Parts.
//long contentLength = new FileInfo(filePath).Length;
long contentLength = audioStream.Length;
long partSize = 5 * (long)Math.Pow(2, 20); // 5 MB
try
{
long filePosition = 0;
for (int i = 1; filePosition < contentLength; i++)
{
UploadPartRequest uploadRequest = new UploadPartRequest
{
BucketName = bucketName,
Key = subUrl + filename,
UploadId = initResponse.UploadId,
PartNumber = i,
PartSize = partSize,
FilePosition = filePosition,
InputStream = audioStream
//FilePath = filePath
};
// Upload part and add response to our list.
uploadRequest.StreamTransferProgress += new EventHandler<StreamTransferProgressArgs>(UploadPartProgressEventCallback);
uploadResponses.Add(client.UploadPart(uploadRequest));
filePosition += partSize;
}
logger.Info("Done");
// Step 3: complete.
CompleteMultipartUploadRequest completeRequest = new CompleteMultipartUploadRequest
{
BucketName = bucketName,
Key = subUrl + filename,
UploadId = initResponse.UploadId,
//PartETags = new List<PartETag>(uploadResponses)
};
completeRequest.AddPartETags(uploadResponses);
CompleteMultipartUploadResponse completeUploadResponse =
client.CompleteMultipartUpload(completeRequest);
}
catch (Exception exception)
{
Console.WriteLine("Exception occurred: {0}", exception.Message);
AbortMultipartUploadRequest abortMPURequest = new AbortMultipartUploadRequest
{
BucketName = bucketName,
Key = subUrl + filename,
UploadId = initResponse.UploadId
};
client.AbortMultipartUpload(abortMPURequest);
}
}
public static void UploadPartProgressEventCallback(object sender, StreamTransferProgressArgs e)
{
// Process event.
logger.DebugFormat("{0}/{1}", e.TransferredBytes, e.TotalBytes);
}
Is there anything wrong with my code or how to make threads run simultaneously to speed up upload?
Rather than managing the Multipart Upload yourself, try using the TransferUtility that does all the hard work for you!
See: Using the High-Level .NET API for Multipart Upload
The AmazonS3Client internally uses an AmazonS3Config instance to know the buffer size used for transfers (ref 1). This AmazonS3Config (ref 2) has a property named BufferSize whose default value is retrieved from a constant in AWSSDKUtils (ref 3) - which in the current SDK version defaults to 8192 bytes - quite small value IMHO.
You may use a custom instance of AmazonS3Config with an arbitrary BufferSize value. To build an AmazonS3Client instance that respects your custom configs, you have to pass the custom config to the client constructor. Example:
// Create credentials.
AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
// Create custom config.
AmazonS3Config config = new AmazonS3Config
{
RegionEndpoint = Amazon.RegionEndpoint.USEast1,
BufferSize = 512 * 1024, // 512 KiB
};
// Pass credentials + custom config to the client.
AmazonS3Client client = new AmazonS3Client(credentials, config);
// They uploaded happily ever after.

waitInterval configuration on msdeploy DeploymentProviderOptions

As part of our build and deploy code, we have timeout issues related to stopping and starting a service.
Here is the code that stops the service
public DeploymentChangeSummary StopService(WebPublisherParameters parameters)
{
var sourceOptions = new DeploymentBaseOptions();
var destinationEndpointOptions = new DeploymentBaseOptions()
{
ComputerName = parameters.DestinationComputer
};
var destProviderOptions = new DeploymentProviderOptions(DeploymentWellKnownProvider.RunCommand)
{
Path = "Net Stop " + parameters.DestinationName
};
using (var sourceObj =
DeploymentManager.CreateObject(new DeploymentProviderOptions(DeploymentWellKnownProvider.RunCommand), sourceOptions))
{
return sourceObj.SyncTo(destProviderOptions, destinationEndpointOptions, new DeploymentSyncOptions());
}
}
We are having timeout issues and ulitmately a failed build because the service does not stop in time.
We tried configuring the waitInterval like this
destProviderOptions.ProviderSettings["waitInterval"] = 20000;
but realised that it was a read only configuration, so I was wondering if anyone could point us in the right direction to do this programmatically rather than using the command line option.
Thanks
Tapashya
You need to set RetryInterval of DeploymentBaseOptions object. Edited code from the question.
public DeploymentChangeSummary StopService(WebPublisherParameters parameters)
{
var sourceOptions = new DeploymentBaseOptions();
var destinationEndpointOptions = new DeploymentBaseOptions()
{
ComputerName = parameters.DestinationComputer
};
var destProviderOptions = new DeploymentProviderOptions(DeploymentWellKnownProvider.RunCommand)
{
Path = "Net Stop " + parameters.DestinationName
};
using (var sourceObj =
DeploymentManager.CreateObject(new DeploymentProviderOptions(DeploymentWellKnownProvider.RunCommand), sourceOptions))
{
destinationEndpointOptions.RetryInterval = 2 * 1000; // Set wait interval to 2 minutes
return sourceObj.SyncTo(destProviderOptions, destinationEndpointOptions, new DeploymentSyncOptions());
}
}

How use asp.net get video duration

using Microsoft.DirectX.AudioVideoPlayback;
Video vvideo = new Video(FileUpload.FileName.ToString());
StringBuilder sb = new StringBuilder();
sb.Append(duration.toString());
error message;
“Installed an access attempt was made to the application domain.”
“vvideo” instance is created error msj ://
But down found cods I found a working code in c #. but asp.net does not work
string file1 = "c://ds.mpeg"
IMediaPosition m_objMediaPosition = null;
FilgraphManager m_objFilterGraph = new FilgraphManager();
m_objFilterGraph.RenderFile(filename);
m_objMediaPosition = m_objFilterGraph as IMediaPosition;
int s = (int)m_objMediaPosition.Duration;
int h = s / 3600;
int m = (s - (h * 3600)) / 60;
s = s - (h * 3600 + m * 60);
I DON'T TAKE VIDEO DURATION BOYS :/
I make Function everywhere it uses ;)
public string f_VideoDuration((add path)parameters)
{
try
{
string sInputVideo = Page.MapPath(add path);
string sPath = " -i " + sInputVideo ;
Process ffmepg = new Process();
ffmepg.StartInfo.FileName = (Server.MapPath("ffmpeg.exe"));
ffmepg.StartInfo.UseShellExecute = false;
ffmepg.StartInfo.RedirectStandardOutput = true;
ffmepg.StartInfo.RedirectStandardError = true;
ffmepg.StartInfo.CreateNoWindow = true;
ffmepg.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
ffmepg.StartInfo.Arguments = sPath;
ffmepg.EnableRaisingEvents = true;
ffmepg.Start();
string sDuration = ffmepg.StandardError.ReadToEnd().ToString();
ffmepg.Close();
ffmepg.Dispose();
sDuration = sDuration.Remove(0, sDuration.LastIndexOf("Duration: ") + 10);
sDuration = sDuration.Substring(0, sDuration.IndexOf(","));
return sDuration;
}
catch (Exception ex)
{
throw (ex);
}
}
You can use our wrapper for ffprobe Alturos.VideoInfo.
You can use it simply by installing the nuget package. Also the ffprobe binary is required.
PM> install-package Alturos.VideoInfo
Example
var videoFilePath = "myVideo.mp4";
var videoAnalyer = new VideoAnalyzer("ffprobe.exe");
var analyzeResult = videoAnalyer.GetVideoInfo(videoFilePath);
var duration = analyzeResult.VideoInfo.Format.Duration;
First, I try FFMPEG Wrapper but it gets an error after found an easy solution.
You can use this nugget package:
Install-Package Microsoft.WindowsAPICodePack-Shell -Version 1.1.0
In your project add two namespaces
using Microsoft.WindowsAPICodePack.Shell;
using.Microsoft.WindowsAPICodePack.Shell.PropertySystem;
ShellFile so = ShellFile.FromFilePath("your file path");
double.TryParse(so.Properties.System.Media.Duration.Value.ToString(), out var nanoseconds);
if (nanoseconds > 0)
{
double seconds = Convert100NanosecondsToMilliseconds(nanoseconds) / 1000;
int ttl_seconds = Convert.ToInt32(seconds);
TimeSpan time = TimeSpan.FromSeconds(ttl_seconds);
}
public static double Convert100NanosecondsToMilliseconds(double nanoseconds)
{
return nanoseconds * 0.0001;
}
Here i store seconds in TimeSpan so its directly give hours:minutes:seconds.

Resources