how can I get external files in C# xamarin forms android? - c#

I'm trying to get images with Xamarin forms Android and I don't know how to do it.
I have a list called listNameImg (I have the name of the each image there). So, what i want is search each image and then save it in a MultipartFormDataContent
This is my code:
MultipartFormDataContent content3 = new MultipartFormDataContent();
private async void takePhotos()
{
try
{
var file2 = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
SaveToAlbum = true
});
while (file2 != null)
{
Image im = new Image();
im.ClassId = contador.ToString();
im.Source = ImageSource.FromFile(file2.Path);
im.HeightRequest = 600;
im.WidthRequest = 600;
im.MinimumHeightRequest = 600;
im.MinimumWidthRequest = 600;
im.VerticalOptions = LayoutOptions.End;
im.HorizontalOptions = LayoutOptions.End;
im.Aspect = Aspect.AspectFill;
imgs.Children.Add(im);
Button deleteButton = new Button();
deleteButton.ClassId = contador.ToString();
deleteButton.Text = "Borrar imagen";
deleteButton.VerticalOptions = LayoutOptions.CenterAndExpand;
deleteButton.HorizontalOptions = LayoutOptions.Center;
deleteButton.MinimumWidthRequest = 100;
deleteButton.ClassId = contador.ToString();
deleteButton.AutomationId = contador.ToString();
deleteButton.Clicked += async (sender, args) => {
listDelete.Add(Convert.ToInt32(deleteButton.ClassId));
imgs.Children.Remove(im);
imgs.Children.Remove(deleteButton);
};
imgs.Children.Add(deleteButton);
listImgName.Add(file2.OriginalFilename);
file2 = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
SaveToAlbum = true
});
contador++;
}
btnScannerQR.IsVisible = false;
btnSacarFotos.IsVisible = true;
btnEnviarImagenes.IsVisible = true;
}
catch(Exception ex)
{
await DisplayAlert("Error", "Sorry we had a problem. Try again.", "OK");
await Shell.Current.GoToAsync($"//{nameof(HomePage)}");
}
private async void storageNameInList() {
string testPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "listNameImg.txt");
if (File.Exists(testPath) == false)
{
File.Create(testPath);
}
TextWriter tw = new StreamWriter(testPath);
foreach (var s in listImgName)
{
tw.WriteLine(s);
}
tw.Close();
}
what I'm trying:
private async void sendImages(){
string testPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "listNameImg.txt");
var imgGroup = Directory.GetFiles(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyPictures));
TextReader tw = new StreamReader(testPath);
String line;
int cont = 0;
while ((line = tw.ReadLine()) != null)
{
byte[] byteArray = Encoding.UTF8.GetBytes(line);
content3.Add(new StreamContent(File.OpenRead(line)), "file", line);
cont++;
}
}
My problems are:
how can I write in the file .txt correctly?
how can I get the images and save it in the MultipartFormDataContent?
Thank you very much!

Related

Xamarin iOS AvPlayer doesn't play video type as "application/x-www-form-urlencoded"

I'm trying to play video with AvPlayer in Xamarin.iOS. I'm working with Firebase Storage. If I upload video from android, media type is set as mp4 but from iOS, media type is set as urlencoded. I can play mp4 files with AvPlayer but urlencoded files are not playable. On the other hand, urlencoded files are playable in android VideoView. Do you have any idea about it?
Here my codes, first pick video from gallery:
private async void PickVideoButton_TouchUpInside(object sender, EventArgs e)
{
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsPickVideoSupported)
{
return;
}
try
{
file = await CrossMedia.Current.PickVideoAsync();
if (file == null)
{
return;
}
fileStream = await ConvertMovToMp4();
mediaType = "Video";
avp = new AVPlayer(NSUrl.FromFilename(file.Path));
avpvc = new AVPlayerViewController();
avpvc.Player = avp;
AddChildViewController(avpvc);
GeneralPostingStoryViewBackground.AddSubview(avpvc.View);
avpvc.View.Frame = GeneralPostingStoryImageView.Frame;
avpvc.ShowsPlaybackControls = true;
avp.Play();
}
catch (Exception ex)
{
alert = UIAlertController.Create("Error", "Gallery doesn't support", UIAlertControllerStyle.Alert);
alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
PresentViewController(alert, true, null);
}
}
public async Task<Stream> ConvertMovToMp4()
{
string exportPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string exportFilePath = Path.Combine(exportPath, DateTime.Now.ToString() + ".mp4");
var asset = AVAsset.FromUrl(NSUrl.FromFilename(file.Path));
var length = asset.Duration.Seconds;
lengthDuration = Convert.ToInt32(length).ToString();
AVAssetExportSession export = new AVAssetExportSession(asset, AVAssetExportSession.PresetMediumQuality);
export.OutputUrl = NSUrl.FromFilename(exportFilePath);
export.OutputFileType = AVFileType.Mpeg4;
export.ShouldOptimizeForNetworkUse = true;
await export.ExportTaskAsync();
var stream = File.OpenRead(exportFilePath);
return stream;
}
Then, upload video to firebase storage:
private async void ShareButton_TouchUpInside(object sender, EventArgs e)
{
try
{
var result = await PortableSharediOS(ID, mediaType, fileStream, commentText);
if (result == "Success.")
{
CommonValues.viewControllerIndexList.RemoveAt(CommonValues.viewControllerIndexList.Count - 1);
NavigateViewController();
}
else
{
alert = UIAlertController.Create("Error", result.ToString(), UIAlertControllerStyle.Alert);
alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
PresentViewController(alert, true, null);
}
}
catch (Exception ex)
{
alert = UIAlertController.Create("Error", "Check your internet connection.", UIAlertControllerStyle.Alert);
alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
PresentViewController(alert, true, null);
}
}
Finally, I'm trying to play videos, as I said the mp4 files are playable which I've upload from android, but files which I've upload from iOS, avplayer doesn't play them..:
public async Task GetStory(int storyIndex)
{
var mediaType = stories[storyIndex].StoryType;
var story = stories[storyIndex];
user = await firebaseHelper.GetUser(story.StoryOwner);
if (mediaType == "Photo")
{
GetImage(story.MediaLink, storyViewStoryImageView);
GetImage(user.PhotoLink, storyViewImageView);
storyViewUserName.Text = user.UserName;
storyViewContentView.Text = story.Content;
time = story.MediaDuration;
storyViewDuration.Text = time.ToString();
}
else
{
storyViewUserName.Text = user.UserName;
storyViewContentView.Text = story.Content;
time = story.MediaDuration;
var asset = AVAsset.FromUrl(NSUrl.FromString(story.MediaLink));
var item = AVPlayerItem.FromAsset(asset);
avp = new AVPlayer(item);
avp.Muted = false;
avpvc = new AVPlayerViewController();
avpvc.Player = avp;
AddChildViewController(avpvc);
storyViewStoryImageView.AddSubview(avpvc.View);
avpvc.View.Hidden = false;
avpvc.View.Frame = storyViewStoryImageView.Frame;
avpvc.ShowsPlaybackControls = false;
avp.Play();
storyViewDuration.Text = time.ToString();
}
timer.Enabled = false;
timer.Close();
TimerTextVoid();
}
I can play all files on Android. Doesn't matter where they were uploaded from.
I figured out my problem. Download and save file to device from Firebase Storage. Then assign it to AVAsset. Codes:
public async Task GetStory(int storyIndex)
{
var mediaType = stories[storyIndex].StoryType;
var story = stories[storyIndex];
user = await firebaseHelper.GetUser(story.StoryOwner);
if (mediaType == "Photo")
{
GetImage(story.MediaLink, storyViewStoryImageView);
GetImage(user.PhotoLink, storyViewImageView);
storyViewUserName.Text = user.UserName;
storyViewContentView.Text = story.Content;
time = story.MediaDuration;
storyViewDuration.Text = time.ToString();
}
else
{
storyViewUserName.Text = user.UserName;
storyViewContentView.Text = story.Content;
time = story.MediaDuration;
var asset = await GetVideo(story.MediaLink);
var item = new AVPlayerItem(asset);
avp = new AVPlayer(item);
avp.Muted = false;
avpvc = new AVPlayerViewController();
avpvc.Player = avp;
AddChildViewController(avpvc);
storyViewStoryImageView.AddSubview(avpvc.View);
avpvc.View.Hidden = false;
avpvc.View.Frame = storyViewStoryImageView.Frame;
avpvc.ShowsPlaybackControls = false;
avp.Play();
storyViewDuration.Text = time.ToString();
}
timer.Enabled = false;
timer.Close();
TimerTextVoid();
}
public async Task<AVAsset> GetVideo(string url)
{
string videoFile;
using (var client = new WebClient())
{
var content = client.DownloadData(url);
var stream = new MemoryStream(content);
string folder = Path.GetTempPath();
videoFile = Path.Combine(folder, DateTime.Now.ToString() + ".mp4");
if (!System.IO.File.Exists(videoFile))
{
using (FileStream outputStream = System.IO.File.Create(videoFile))
{
await stream.CopyToAsync(outputStream);
}
}
}
var asset = AVUrlAsset.FromUrl(NSUrl.FromFilename(videoFile));
return asset;
}

ReceiveDetections Method is Calling Multiple Times

I am scanning QR CODE but the problem is ReceiveDetections method is calling multiple times even after a successful scan.How can I prevent calling the api multiple times after a successful call.
here is the code snippet
public void ReceiveDetections(Detections detections)
{
SparseArray qrcodes = detections.DetectedItems;
if (qrcodes.Size() != 0)
{
txtscankanbancloseResult.Post(async () =>
{
Vibrator vibrator = (Vibrator)GetSystemService(Context.VibratorService);
vibrator.Vibrate(1000);
txtscankanbancloseResult.Text = ((Barcode)qrcodes.ValueAt(0)).RawValue;
try
{
var client = new HttpClient();
var uri = new Uri(string.Format(AppStatics.clsStatic.url + "//Kanban/SaveKanbanStatus"));
List<string> lstskanban = new List<string>();
String myDate = DateTime.Now.ToString("dd-MMM-yyyy");
string adateddate = DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss");
JsonScankanbanclose objjscan = new JsonScankanbanclose();
lstskanban.Add(txtscankanbancloseResult.Text);
objjscan.UpdateBy = SingletonSession.Instance().getUsername();
objjscan.KANBANNOList = lstskanban;
objjscan.IsKANBANClosed = true;
string jsonData = JsonConvert.SerializeObject(objjscan);
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(uri, content);
var result = await response.Content.ReadAsStringAsync();
if (response.ReasonPhrase == "OK")
{
JArray scanresult = JArray.Parse(result);
Scanlist objscan = new Scanlist();
if (ScanSucessfull.Count == 0)
{
objscan.KanbanID = "Kanban NO";
objscan.KanbanQty = "Kanban Qty";
ScanSucessfull.Add(objscan);
objscan = new Scanlist();
}
// Scanlist item = ScanSucessfull.Find(c => c.KanbanID == scanresult[0]["KANBANID"].ToString());
//int itemPosition = ScanSucessfull.BinarySearch(scanresult[0]["KANBANID"].ToString());
//if (itemPosition.cou=="")
//{
objscan.KanbanID = scanresult[0]["KANBANNumber"].ToString();
objscan.KanbanQty = scanresult[0]["Qty"].ToString();
ScanSucessfull.Add(objscan);
//}
var adapter = new CustomAdapterScan(this, ScanSucessfull);
lstviewscankanbanclose.SetAdapter(adapter);
lstviewscankanbanclose.Clickable = false;
//lstview.Enabled = false;
lstviewscankanbanclose.ItemSelected += null;
mPlayer = Android.Media.MediaPlayer.Create(this, Resource.Raw.successful);
currentSong = Resource.Raw.successful;
mPlayer.SeekTo(1);
mPlayer.Start();
//Toast.MakeText(this, , ToastLength.Short).Show();
Helper.ShowToastMessage(this, Color.DarkGreen, "Data Save Sucessfully..", ToastLength.Short);
_kanbancount++;
txtscankanbanclosekanbancount.Text = "Kanban Count:" + " " + _kanbancount;
txtscankanbanclosekanbancount.Visibility = ViewStates.Visible;
}
else
{
string[] result1 = result.Split(':');
string[] result2 = result1[1].Split('"');
string[] result3 = result2[1].Split('"');
mPlayer = Android.Media.MediaPlayer.Create(this, Resource.Raw.fail);
// mPlayer.SeekTo(2);
currentSong = Resource.Raw.fail;
mPlayer.Start();
//Toast.MakeText(this, result3[0].ToString(), ToastLength.Short).Show();
Helper.ShowToastMessage(this, Color.DarkRed, result3[0].ToString(), ToastLength.Short);
}
// dialog.Hide();
cameraSource.Start(surfaceView.Holder);
//txtResult.Text = "";
}
catch (System.Exception ex)
{
Helper.ShowToastMessage(this, Color.DarkRed, ex.Message, ToastLength.Short);
//Toast.MakeText(this, ex.Message.ToString(), ToastLength.Short).Show();
// txtResult.Text = "";
txtscankanbancloseResult.Visibility = ViewStates.Invisible;
//cameraSource.Start(surfaceView.Holder);
}
});
using (var h = new Handler(Looper.MainLooper))
h.Post(() =>
{
cameraSource.Stop();
// Toast.MakeText(this, "This Kanban Already Scanned....", ToastLength.Short).Show();
});
}
}
Here is the code where I crate and open the camera source to scan the QR code
private void btnkanbanscan_Click(object sender, EventArgs e)
{
try
{
#region validation
if (spnSiteID.SelectedItemPosition < 0)
{
throw new Exception("Please Select Site...");
}
if (spnLocation.SelectedItemPosition < 0)
{
throw new Exception("Please Select Location..");
}
if (spnInspactionType.SelectedItemPosition < 0)
{
throw new Exception("Please Select Inspection Type..");
}
#endregion
LayoutInflater layoutInflater = LayoutInflater.From(this);
View scanview = LayoutInflater.Inflate(Resource.Layout.scan_popup, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.SetView(scanview);
surfaceView = scanview.FindViewById<SurfaceView>(Resource.Id.spvscan);
dialog = alertDialogBuilder.Create();
dialog.SetCanceledOnTouchOutside(false);
dialog.Show();
barcodeDetector = new BarcodeDetector.Builder(this)
.SetBarcodeFormats(BarcodeFormat.Code128 | BarcodeFormat.QrCode)
.Build();
cameraSource = new CameraSource.Builder(this, barcodeDetector)
.SetRequestedPreviewSize(480, 480)
.SetAutoFocusEnabled(true)
.Build();
surfaceView.Holder.AddCallback(this);
barcodeDetector.SetProcessor(this);
surfaceView.Visibility = ViewStates.Visible;
_definemethod = "KANBAN";
}
catch (Exception ex)
{
Helper.ShowToastMessage(this, Color.DarkRed, ex.Message, ToastLength.Short);
//Toast.MakeText(this, ex.Message.ToString(), ToastLength.Short).Show();
}
}
NCTB: I noticed that after opening the dialog to scan the QR CODE the ReceiveDetections method get called frequently and the scanned value comes in detections parameter .which is normal and it supposed to do so.But the problem is after a successful scan it should not call anymore.

Tesseract self fails and closes

After running for 1 hour, my picture solving application using Teserract crashes:
System.AccessViolationException: 'An attempt to read or write protected memory. This is usually an indication that the other memory is corrupt.'
try
{
IWebElement ttID = driver.FindElement(By.CssSelector("div#root div.captcha__container > img"));
pictureBox1.ImageLocation = ttID.GetAttribute("src");
Thread.Sleep(2000);
var img = new Bitmap(pictureBox1.Image);
var ocr = new TesseractEngine("./tessdata", "eng");
var sonuc = ocr.Process(img);
richTextBox1.Text = sonuc.GetText();
if (infoCheckBox.Checked == true)
{
durum.Text = "otomatik çözme deneniyor...";
Yandexİleri();
}
durum.Text = "otomatik çözme denendi.";
}
catch
{
baslat_kodlari();
}
My suspition is memoty leak, I hope this helps:
try
{
IWebElement ttID = driver.FindElement(By.CssSelector("div#rootdiv.captcha__container > img"));
pictureBox1.ImageLocation = ttID.GetAttribute("src");
Thread.Sleep(2000);
using (var img = new Bitmap(pictureBox1.Image))
{
var ocr = new TesseractEngine("./tessdata", "eng");
var sonuc = ocr.Process(img);
richTextBox1.Text = sonuc.GetText();
if (infoCheckBox.Checked == true)
{
durum.Text = "otomatik çözme deneniyor...";
Yandexİleri();
}
durum.Text = "otomatik çözme denendi.";
}
}
catch
{
baslat_kodlari();
}``

How to choose multiple image from Gallery at one time (tickbox) in Xamarin Android?

Hi have a Xamarin Android project using C#. Currently I am using await CrossMedia.Current.PickPhotoAsync() method to upload image. However, it did not provide a tickbox beside the images for me to select multiple. How can I manage to select multiple images and upload together?
You could implement it by yourself.
1.Add these methods to your MainActivity.cs file
public static int OPENGALLERYCODE = 100;
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
//If we are calling multiple image selection, enter into here and return photos and their filepaths.
if (requestCode == OPENGALLERYCODE && resultCode == Result.Ok)
{
List<string> images = new List<string>();
if (data != null)
{
//Separate all photos and get the path from them all individually.
ClipData clipData = data.ClipData;
if (clipData != null)
{
for (int i = 0; i < clipData.ItemCount; i++)
{
ClipData.Item item = clipData.GetItemAt(i);
Android.Net.Uri uri = item.Uri;
var path = GetRealPathFromURI(uri);
if (path != null)
{
images.Add(path);
}
}
}
else
{
Android.Net.Uri uri = data.Data;
var path = GetRealPathFromURI(uri);
if (path != null)
{
images.Add(path);
}
}
}
}
}
/// <summary>
/// Get the real path for the current image passed.
/// </summary>
public String GetRealPathFromURI(Android.Net.Uri contentURI)
{
try
{
ICursor imageCursor = null;
string fullPathToImage = "";
imageCursor = ContentResolver.Query(contentURI, null, null, null, null);
imageCursor.MoveToFirst();
int idx = imageCursor.GetColumnIndex(MediaStore.Images.ImageColumns.Data);
if (idx != -1)
{
fullPathToImage = imageCursor.GetString(idx);
}
else
{
ICursor cursor = null;
var docID = DocumentsContract.GetDocumentId(contentURI);
var id = docID.Split(':')[1];
var whereSelect = MediaStore.Images.ImageColumns.Id + "=?";
var projections = new string[] { MediaStore.Images.ImageColumns.Data };
cursor = ContentResolver.Query(MediaStore.Images.Media.InternalContentUri, projections, whereSelect, new string[] { id }, null);
if (cursor.Count == 0)
{
cursor = ContentResolver.Query(MediaStore.Images.Media.ExternalContentUri, projections, whereSelect, new string[] { id }, null);
}
var colData = cursor.GetColumnIndexOrThrow(MediaStore.Images.ImageColumns.Data);
cursor.MoveToFirst();
fullPathToImage = cursor.GetString(colData);
}
return fullPathToImage;
}
catch (Exception ex)
{
Toast.MakeText(Xamarin.Forms.Forms.Context, "Unable to get path", ToastLength.Long).Show();
}
return null;
}
2.invoked the following in the specific Activity which you want to open the picker
public void OpenGallery()
{
try
{
var imageIntent = new Intent(Intent.ActionPick);
imageIntent.SetType("image/*");
imageIntent.PutExtra(Intent.ExtraAllowMultiple, true);
imageIntent.SetAction(Intent.ActionGetContent);
this.StartActivityForResult(Intent.CreateChooser(imageIntent, "Select photo"), OPENGALLERYCODE);
Toast.MakeText(this, "Tap and hold to select multiple photos.", ToastLength.Short).Show();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Toast.MakeText(this, "Error. Can not continue, try again.", ToastLength.Long).Show();
}
}
void ClearFileDirectory()
{
var directory = new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures), ImageHelpers.collectionName).Path.ToString();
if (Directory.Exists(directory))
{
var list = Directory.GetFiles(directory, "*");
if (list.Length > 0)
{
for (int i = 0; i < list.Length; i++)
{
File.Delete(list[i]);
}
}
}
}
//collectionName is the name of the folder in your Android Pictures directory.
public static readonly string collectionName = "TmpPictures";
public string SaveFile(byte[] imageByte, string fileName)
{
var fileDir = new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures), collectionName);
if (!fileDir.Exists())
{
fileDir.Mkdirs();
}
var file = new Java.IO.File(fileDir, fileName);
System.IO.File.WriteAllBytes(file.Path, imageByte);
return file.Path;
}
public string CompressImage(string path)
{
byte[] imageBytes;
//Get the bitmap.
var originalImage = BitmapFactory.DecodeFile(path);
//Set imageSize and imageCompression parameters.
var imageSize = .86;
var imageCompression = 67;
//Resize it and then compress it to Jpeg.
var width = (originalImage.Width * imageSize);
var height = (originalImage.Height * imageSize);
var scaledImage = Bitmap.CreateScaledBitmap(originalImage, (int)width, (int)height, true);
using (MemoryStream ms = new MemoryStream())
{
scaledImage.Compress(Bitmap.CompressFormat.Jpeg, imageCompression, ms);
imageBytes = ms.ToArray();
}
originalImage.Recycle();
originalImage.Dispose();
GC.Collect();
return SaveFile(imageBytes, Guid.NewGuid().ToString());
}

Issue with +CDS AT COMMAND

I'm issue when I get +CDS in AT COMMAND throught c# using SerialPort, any times I get this +CDS truncated, example:
+CDS: 25
0002970C91555868047414212181414094882121814140948830
Why I've this problem, why any times work nice?
I'm starting SerialPort:
public PortCOM(string porta)
: base(porta, 115200, Parity.None, 8, StopBits.One)
{
this.StatusPort = StatusPorta.Ready;
this.DiscardNull = true;
this.ReadTimeout = 21000;
this.RtsEnable = true;
this.DtrEnable = true;
this.ReceivedBytesThreshold = 9;
this.NewLine = "\r\n";
this.ReadBufferSize = 1024;
}
public static void TestPort()
{
var p = new PortCom("COM12");
if (!p.IsOpen)
p.Open();
p.StatusPort = StatusPorta.Ready;
p.DataReceived += new SerialDataReceivedEventHandler(p_DataReceivedSample);
p.PinChanged += new SerialPinChangedEventHandler(p_PinChanged);
p.ErrorReceived += new SerialErrorReceivedEventHandler(p_ErrorReceived);
p.Disposed += new EventHandler((obj, porta) =>
{
Console.WriteLine(((PortaCOM)obj).ToString());
});
if (Console.ReadKey().Key == ConsoleKey.B)
{
p.Close();
p.Dispose();
}
}
static void p_DataReceivedSample(object sender, SerialDataReceivedEventArgs e)
{
var p = (PortaCOM)sender;
try
{
Console.WriteLine(p.ReadExisting());
var sb = new StringBuilder();
sb.Append(p.ReadExisting());
int y = sb.ToString().IndexOf("\r\n");
var stop = Stopwatch.StartNew();
stop.Start();
while (y == -1)
{
sb.Append(p.ReadExisting());
y = sb.ToString().IndexOf("\r\n");
if (stop.Elapsed.TotalSeconds > 10)
break;
}
stop.Stop();
var _retorno = sb.ToString();
var cmt = regCMT.Match(_retorno);
var succ = regSucess.Match(_retorno);
var report = regStatusReport.Match(_retorno);
var erro = regError.Match(_retorno);
#region Resposta
if (cmt.Success)
{
var smss = new SMS();
var source = cmt.Groups[3].Value;
SMS.Fetch(smss, ref source);
var resposta = new Resposta()
{
Mensagem = smss.Message,
Data = smss.ServiceCenterTimeStamp,
Sender = smss.PhoneNumber,
Operadora = p.OperadoraName.NomeOperadora.ToString()
};
GravaResposta().ToAsync(Scheduler.TaskPool).Invoke(p, cmt.Groups[3].Value);
p.IsError = false;
}
#endregion
#region StatusReport
if (report.Success)
{
RecebeReport(p, report.Groups[2].Value.Trim());
p.IsError = false;
}
#endregion
}
catch (Exception err)
{
Console.WriteLine(err.Message);
}
}
Please I really need help with it, I'm glad for any help!
+cds is alert for incoming message with message location on SIM memeory.
so here its seems in PDU mode data. and it is seems may be flash message content.
Convert the data PDU mode to Text mode to receive message.
review this ATSMS library

Categories

Resources