How to call MessageBox within photochooser task - windows-phone-7

I have a code where I am calling photochooser in WP7 and I want to show a messagebox to user when the pic is more than 2Mb. When I try to do this, since the photochooser task is running in background, we start getting unhandled exceptions.
void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.ChosenPhoto != null)
{
ProgressBar.Visibility = Visibility.Visible;
image = _UploadImgeViewModel.ReadToEnd(e.ChosenPhoto);
if (image.Length < 16384)
{
BitmapImage bi = new BitmapImage();
bi.SetSource(e.ChosenPhoto);
UserSession.ProfileImage = bi;
Session.PreviousImage = bi;
UserSession.isImageChanged = true;
UserSession.image = image;
UserSession.Uploadimage = image;
NavigationService.Navigated += new NavigatedEventHandler(navigateCompleted);
}
else
{
ProgressBar.Visibility = Visibility.Collapsed;
UserSession.isImageChanged = false;
UserSession.ProfileImage = null;
Dispatcher.BeginInvoke(() => MessageBox.Show("The message"));
}
}
}
#endregion
This only shows the background job as resuming... and the msg box in foreground. and after a few seconds, the app crashes.
Can you please help me with this?

Cool. I got some idea to resolve this. Might not be a fix, but this way we can avoid this issue. Just add a button and do the validating process in the button click event. Since we can't display the message box when the navigation is in progress.
Below is the code:
void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.ChosenPhoto != null)
{
ProcessSelectedImage(e.ChosenPhoto);
}
}
private void ProcessSelectedImage(Stream stream)
{
if (stream != null)
{
bi.SetSource(stream);
UserSession.ProfileImage = bi;
UserSession.PreviousImage = bi;
image = ConvertToImage.ReadToEnd(stream);
UserSession.image = image;
UserSession.Uploadimage = image;
}
}
private void UploadImage_Click(object sender, RoutedEventArgs e)
{
if (image.Length < 16384)
{
UserSession.isImageChanged = true;
UserSession.image = image;
UserSession.Uploadimage = image;
NavigationService.Navigate(new Uri("/Views/EditMyProfile.xaml", UriKind.Relative));
}
else
{
UserSession.isImageChanged = false;
UserSession.ProfileImage = null;
UserSession.IsChangingProfilePicture = true;
MessageBox.Show(MessageContent.ImageUploadLengh);
}
}
Thanks
Kamal

You have 10 seconds to return to the foreground completely or your app will be killed. If you have a messagebox that can display here, you will fail certification (because user could not click anything for 10 seconds) -- you need to wait for the page to load.
A workaround for this if you need to show a MessageBox is to set a bool, and check it in the Page's Loaded event.
void photoChooserTask_Completed(object sender, PhotoResult e) { if (e.ChosenPhoto != null) { ProgressBar.Visibility = Visibility.Visible;
image = _UploadImgeViewModel.ReadToEnd(e.ChosenPhoto);
if (image.Length < 16384)
{
BitmapImage bi = new BitmapImage();
bi.SetSource(e.ChosenPhoto);
UserSession.ProfileImage = bi;
Session.PreviousImage = bi;
UserSession.isImageChanged = true;
UserSession.image = image;
UserSession.Uploadimage = image;
NavigationService.Navigated += new NavigatedEventHandler(navigateCompleted);
}
else
{
ProgressBar.Visibility = Visibility.Collapsed;
UserSession.isImageChanged = false;
UserSession.ProfileImage = null;
//set flag
UserSession.ImageTooBig = true;
}
}
}
#endregion
MyPage()
{
//make sure you attach Loaded Event if not already
Loaded += (s,e) =>
{
if (UserSession.ImageTooBig)
{
UserSession.ImageTooBig = false;
MessageBox.Show("Sorry, the image exceeds 2 MB");
}
};
}

Related

Xmarin.forms iOS check whether captured photo contains face or not

In my xamarin.forms app, I created a custom camera by using Camera view and custom renders. Everything works fine. In android after the photo capture I can check whether the taken photo contains a face or not.It is done by using Camera.IFaceDetectionListener. My question is how can I achieve this in iOS? I know there is vision API. But I don't want the live face tracking. I just simply want to check whether the taken photo contains face. Any help is appreciated.
My iOS CameraPreview
public class UICameraPreview : UIView, IAVCaptureMetadataOutputObjectsDelegate
{
AVCaptureVideoPreviewLayer previewLayer;
public AVCaptureDevice[] videoDevices;
CameraOptions cameraOptions;
public AVCaptureStillImageOutput stillImageOutput;
public AVCaptureDeviceInput captureDeviceInput;
public AVCaptureDevice device;
public event EventHandler<EventArgs> Tapped;
public AVCaptureSession CaptureSession { get; set; }
public bool IsPreviewing { get; set; }
public AVCaptureStillImageOutput CaptureOutput { get; set; }
public UICameraPreview(CameraOptions options)
{
cameraOptions = options;
IsPreviewing = false;
Initialize();
}
public override void LayoutSubviews()
{
base.LayoutSubviews();
if (previewLayer != null)
previewLayer.Frame = Bounds;
}
public override void TouchesBegan(NSSet touches, UIEvent evt)
{
base.TouchesBegan(touches, evt);
OnTapped();
}
protected virtual void OnTapped()
{
var eventHandler = Tapped;
if (eventHandler != null)
{
eventHandler(this, new EventArgs());
}
}
void Initialize()
{
CaptureSession = new AVCaptureSession();
previewLayer = new AVCaptureVideoPreviewLayer(CaptureSession)
{
Frame = Bounds,
VideoGravity = AVLayerVideoGravity.ResizeAspectFill
};
videoDevices = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video);
var cameraPosition = (cameraOptions == CameraOptions.Front) ? AVCaptureDevicePosition.Front : AVCaptureDevicePosition.Back;
device = videoDevices.FirstOrDefault(d => d.Position == cameraPosition);
if (device == null)
{
return;
}
NSError error;
captureDeviceInput = new AVCaptureDeviceInput(device, out error);
CaptureSession.AddInput(captureDeviceInput);
var dictionary = new NSMutableDictionary();
dictionary[AVVideo.CodecKey] = new NSNumber((int)AVVideoCodec.JPEG);
stillImageOutput = new AVCaptureStillImageOutput()
{
OutputSettings = new NSDictionary()
};
CaptureSession.AddOutput(stillImageOutput);
Layer.AddSublayer(previewLayer);
CaptureSession.StartRunning();
IsPreviewing = true;
}
// Photo Capturing
public async Task CapturePhoto()
{
try
{
var videoConnection = stillImageOutput.ConnectionFromMediaType(AVMediaType.Video);
var sampleBuffer = await stillImageOutput.CaptureStillImageTaskAsync(videoConnection);
var jpegData = AVCaptureStillImageOutput.JpegStillToNSData(sampleBuffer);
var photo = new UIImage(jpegData);
var rotatedPhoto = RotateImage(photo, 180f);
var img = rotatedPhoto;
CALayer layer = new CALayer
{
ContentsScale = 1.0f,
Frame = Bounds,
Contents = rotatedPhoto.CGImage //Contents = photo.CGImage,
};
CaptureSession.StopRunning();
photo.SaveToPhotosAlbum((image, error) =>
{
if (!string.IsNullOrEmpty(error?.LocalizedDescription))
{
Console.Error.WriteLine($"\t\t\tError: {error.LocalizedDescription}");
}
});
}
catch (Exception ex)
{
}
//MainPage.UpdateSource(UIImageFromLayer(layer).AsJPEG().AsStream());
//MainPage.UpdateImage(UIImageFromLayer(layer).AsJPEG().AsStream());
}
}
My CameraPreviewRenderer
public class CameraPreviewRenderer : ViewRenderer<CameraPreview, UICameraPreview>, IAVCaptureMetadataOutputObjectsDelegate
{
UICameraPreview uiCameraPreview;
AVCaptureSession captureSession;
AVCaptureDeviceInput captureDeviceInput;
AVCaptureStillImageOutput stillImageOutput;
protected override void OnElementChanged(ElementChangedEventArgs<CameraPreview> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
// Unsubscribe
uiCameraPreview.Tapped -= OnCameraPreviewTapped;
}
if (e.NewElement != null)
{
if (Control == null)
{
uiCameraPreview = new UICameraPreview(e.NewElement.Camera);
SetNativeControl(uiCameraPreview);
MessagingCenter.Subscribe<Camera_Popup>(this, "CaptureClick", async (sender) =>
{
try
{
// Using messeging center to take photo when clicking button from shared code
var data = new AVCaptureMetadataOutputObjectsDelegate();
await uiCameraPreview.CapturePhoto();
}
catch (Exception ex)
{
return;
}
});
}
MessagingCenter.Subscribe<Camera_Popup>(this, "RetryClick", (sender) =>
{
Device.BeginInvokeOnMainThread(() =>
{
uiCameraPreview.CaptureSession.StartRunning();
uiCameraPreview.IsPreviewing = true;
});
});
MessagingCenter.Subscribe<Camera_Popup>(this, "FlipClick", (sender) =>
{
try
{
var devicePosition = uiCameraPreview.captureDeviceInput.Device.Position;
if (devicePosition == AVCaptureDevicePosition.Front)
{
devicePosition = AVCaptureDevicePosition.Back;
}
else
{
devicePosition = AVCaptureDevicePosition.Front;
}
uiCameraPreview.device = uiCameraPreview.videoDevices.FirstOrDefault(d => d.Position == devicePosition);
uiCameraPreview.CaptureSession.BeginConfiguration();
uiCameraPreview.CaptureSession.RemoveInput(uiCameraPreview.captureDeviceInput);
uiCameraPreview.captureDeviceInput = AVCaptureDeviceInput.FromDevice(uiCameraPreview.device);
uiCameraPreview.CaptureSession.AddInput(uiCameraPreview.captureDeviceInput);
uiCameraPreview.CaptureSession.CommitConfiguration();
}
catch (Exception ex)
{
var abc = ex.InnerException.Message;
}
});
uiCameraPreview.Tapped += OnCameraPreviewTapped;
}
}
void OnCameraPreviewTapped(object sender, EventArgs e)
{
if (uiCameraPreview.IsPreviewing)
{
uiCameraPreview.CaptureSession.StopRunning();
uiCameraPreview.IsPreviewing = false;
}
else
{
uiCameraPreview.CaptureSession.StartRunning();
uiCameraPreview.IsPreviewing = true;
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Control.CaptureSession.Dispose();
Control.Dispose();
}
base.Dispose(disposing);
}
}
The CoreImage framework has CIDetector that provides image detectors for faces, QR codes, text, .... in which you pass in an image and you get a specific "feature set" back.
Example from Xamarin docs:
var imageFile = "photoFace2.jpg";
var image = new UIImage(imageFile);
var context = new CIContext ();
var detector = CIDetector.CreateFaceDetector (context, true);
var ciImage = CIImage.FromCGImage (image.CGImage);
var features = detector.GetFeatures (ciImage);
Console.WriteLine ("Found " + features.Length + " faces");
re: https://learn.microsoft.com/en-us/dotnet/api/CoreImage.CIDetector?view=xamarin-ios-sdk-12

Xamarin, What is the difference between tab page click vs button page click?

When i click on the tab page () a new settings page comes on but it's not populated with the info i already entered but it i click on a button (Navigation.PushModalAsync(new SettingsPage());) the page comes on and its populated with info I entered. is there a difference between the two?
//for tab page
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:Bldg"
x:Class="Bldg.HomePage" >
<local:HistoryLogPage Title="Log"/>
<local:AddDrainsPage Title="Add"/>
<local:SettingsPage Title="Edit Settings"/>
<Label x:Name="drain1Label" />
</TabbedPage>
//for click button
void NextpageButton_Clicked(object sender, System.EventArgs e)
{
Navigation.PushModalAsync(new SettingsPage());
}
//SettingsPage
namespace Bldg
{
public partial class SettingsPage : ContentPage
{
public static string item, username;
public static string location1, location2;
bool is1Empty = string.IsNullOrEmpty(Settings.n1LocationSettings);
bool is2Empty = string.IsNullOrEmpty(Settings.n2LocationSettings);
List<string> list;
public SettingsPage()
{
InitializeComponent();
drainquantity();
list = new List<string>();
list.Add("1");
list.Add("2");
locationPicker1.SelectedIndexChanged += drain1Handle_SelectedIndexChanged;
locationPicker2.SelectedIndexChanged += drain2Handle_SelectedIndexChanged;
//nameofpickerinxamlfile.On<iOS().SetUpdateMode(UpdateMode.WhenFinished);
locationPicker1.On<iOS>().SetUpdateMode(UpdateMode.WhenFinished);
locationPicker2.On<iOS>().SetUpdateMode(UpdateMode.WhenFinished);
drainxPicker.SelectedItem = Settings.DrainquantitySettings;
locationPicker1.SelectedItem = Settings.n1LocationSettings;
locationPicker2.SelectedItem = Settings.n2LocationSettings;
nameEntry.Text = Settings.NameSettings;
clearButton.IsVisible = false;
drainlocationPicker2.IsEnabled = false;
drainxPicker.SelectedItem = Settings.DrainquantitySettings;
}
//this is fired when user changes or selects new selection
void drainxHandle_SelectedIndexChanged(object sender, System.EventArgs e)
{
//to get the value of user selected going to be use in switch; then save in a
variable
var drainx = drainxPicker.Items[drainxPicker.SelectedIndex];
item = (string)drainxPicker.SelectedItem;
bool isdrainxEmpty = string.IsNullOrEmpty(Settings.DrainquantitySettings);
if (isdrainxEmpty == true)
{
//switch for user selected in drainpicker
switch (drainx)
{
case "1":
n1Gridrow.IsVisible = true;
locationPicker1.IsVisible = true;
n2Gridrow.IsVisible = false;
if (is1Empty == true)
{
drainxPicker.IsEnabled = true;
}
else
drainxPicker.IsEnabled = false;
break;
case "2":
n1Gridrow.IsVisible = true;
n2Gridrow.IsVisible = true;
locationPicker2.IsEnabled = false;
break;
} //switch end
}
else
{
drainxPicker.IsEnabled = false;
nameEntry.IsEnabled = false;
n1Gridrow.IsVisible = true;
n2Gridrow.IsVisible = true;
locationPicker1.IsEnabled = false;
locationPicker2.IsEnabled = false;
settingsaveButton.IsVisible = false;
}
}
void n1Handle_SelectedIndexChanged(object sender, System.EventArgs e)
{
location1 = (string)locationPicker1.SelectedItem;
if (is1Empty == true)
{
locationPicker2.IsEnabled = true;
n2Label.IsVisible = true;
locationPicker2.Items.Remove((string)locationPicker1.SelectedItem);
}
drainxPicker.IsEnabled = false;
locationPicker1.IsEnabled = false;
}
void n2Handle_SelectedIndexChanged(object sender, System.EventArgs e)
{
location2 = (string)locationPicker2.SelectedItem;
if (is2Empty == true)
{
locationPicker2.IsEnabled = true;
}
drainxPicker.IsEnabled = false;
locationPicker2.IsEnabled = false;
}
void nxy1()
{
foreach (var location in list)
{
locationPicker1.Items.Add(location);
}
}
void nxy2()
{
foreach (var location in list)
{
locationPicker2.Items.Add(location);
}
}
void settingsaveButton_Clicked(object sender, System.EventArgs e)
{
bool isNameEmpty = string.IsNullOrEmpty(nameEntry.Text);
if (isNameEmpty == true)
{
DisplayAlert("Enter Name", "PLEASE", "OK");
}
else
{
Navigation.PushModalAsync(new HomePage());
//saving to Settings
Settings.n1LocationSettings = location1;
Settings.n2LocationSettings = location2;
Settings.NameSettings = username;
Settings.DrainquantitySettings = item;
drainxPicker.IsEnabled = false;
}
}
void entryNameHandle_Unfocused(object sender, Xamarin.Forms.FocusEventArgs e)
{
username = nameEntry.Text;
}
void clearHandle_Clicked(object sender, System.EventArgs e)
{
Settings.ClearAllData();
}
}
}
I expect that when i click on tabbed settings page, i go to the settings page with info entered populated. just like the button click it goes to settings page already populated with user entered.
Generally, tabbed settings page and pushed settings page is the same. They are all new fresh settings page.
From your code, we can see that you are setting the value of Picker by Settings plugin:
drainxPicker.SelectedItem = Settings.DrainquantitySettings;
locationPicker1.SelectedItem = Settings.n1LocationSettings;
locationPicker2.SelectedItem = Settings.n2LocationSettings;
So, whether the info entered will be populated or not when you go to the setting page is depending on the values in Settings.
For example:
If Settings.DrainquantitySettings; has value, then drainxPicker's info will be populated.
Check the Values in your Setting when you go to tabbed settings page and pushed settings page to find any difference.

How to show image on imageview using webservices and json

I am using web service for showing image in imageview. But web service image show in SYSTEM.BYTE[] Format. So how to Convert or display the image in imageview in xamarin android application??
Webservice.asmx:
[WebMethod(MessageName = "BindHospName", Description = "Bind Hospital Name Control")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
[System.Xml.Serialization.XmlInclude(typeof(GetHospName))]
public string BindHosp(decimal SpecID)
{
JavaScriptSerializer objJss = new JavaScriptSerializer();
List<GetHospName> HospName = new List<GetHospName>();
try
{
ConnectionString();
cmd = new SqlCommand("select b.HID,b.HospName,b.Logo from HospitalRegBasic b inner join HospitalRegClinical c on b.HID=c.HID " +
"where b.EmailActivationCode <> '' and b.EmailActivationStatus = 1 and b.Status = 1 and c.SPEC_ID = #SpecID ", conn);
cmd.Parameters.AddWithValue("#SpecID", SpecID);
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
var getHosp = new GetHospName
{
HospID = dr["HID"].ToString(),
HospName = dr["HospName"].ToString(),
HospLogo = dr["Logo"].ToString()
};
HospName.Add(getHosp);
}
}
dr.Close();
cmd.Dispose();
conn.Close();
}
catch (Exception)
{
throw;
}
return objJss.Serialize(HospName);
}
Class.cs:
namespace HSAPP
{
class ContListViewHospNameClass : BaseAdapter<GetHospNames>
{
List<GetHospNames> objList;
Activity objActivity;
public ContListViewHospNameClass (Activity objMyAct, List<GetHospNames> objMyList) : base()
{
this.objActivity = objMyAct;
this.objList = objMyList;
}
public override GetHospNames this[int position]
{
get
{
return objList[position];
}
}
public override int Count
{
get
{
return objList.Count;
}
}
public override long GetItemId(int position)
{
return position;
}
public static Bitmap bytesToBitmap(byte[] imageBytes)
{
Bitmap bitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
return bitmap;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
var item = objList[position];
if (convertView == null)
{
convertView = objActivity.LayoutInflater.Inflate(Resource.Layout.ContListViewHospName, null);
}
convertView.FindViewById<TextView>(Resource.Id.tvHospID).Text = item.HospID;
convertView.FindViewById<TextView>(Resource.Id.tvHospName).Text = item.HospName;
byte[] img =item.HospLogo;
Bitmap bitmap = BitmapFactory.DecodeByteArray(img, 0, img.Length);
convertView.FindViewById<ImageView>(Resource.Id.imgLogo).SetImageBitmap(bitmap);
return convertView;
}
}
}
This is JSON Code:
private void BindControl_BindHospCompleted(object sender, BindControl.BindHospCompletedEventArgs e)
{
jsonValue = e.Result.ToString();
if (jsonValue == null)
{
Toast.MakeText(this, "No Data For Bind", ToastLength.Long).Show();
return;
}
try
{
JArrayValue = JArray.Parse(jsonValue);
list = new List<GetHospNames>();
int count = 0;
while (count < JArrayValue.Count)
{
GetHospNames getHospName = new GetHospNames(JArrayValue[count]["HospID"].ToString(), JArrayValue[count]["HospName"].ToString(),JArrayValue[count]["Logo"]);
list.Add(getHospName);
count++;
}
listView.Adapter = new ContListViewHospNameClass(this, list);
}
catch (Exception ex)
{
Toast.MakeText(this, ex.ToString(), ToastLength.Long).Show();
}
}
public static void SetImageFromByteArray (byte[] iArray, UIImageView imageView)
{
if (iArray != null && iArray.Length > 0) {
Bitmap bitmap = BitmapFactory.DecodeByteArray (iArray, 0, iArray.Length);
imageView.SetImageBitmap (bitmap);
}
}
That's it. If this is not working, your byte array may not be a valid image.
public static bool IsValidImage(byte[] bytes)
{
try {
using(MemoryStream ms = new MemoryStream(bytes))
Image.FromStream(ms);
}
catch (ArgumentException) {
return false;
}
return true;
}

Issue while Playing, the recorded audio in WP7

Hi Developers,
If we save the recorded voice as a mp3 file. we get the error while opening the file as Windows Media Player cannot play the file. The Player might not support the file type or might not support the codec that was used to compress the file.
Please Give a Solution to overcome this Issue ....
Here is My Source code
namespace Windows_Phone_Audio_Recorder
{
public partial class MainPage : PhoneApplicationPage
{
MemoryStream m_msAudio = new MemoryStream();
Microphone m_micDevice = Microphone.Default;
byte[] m_baBuffer;
SoundEffect m_sePlayBack;
ViewModel vm = new ViewModel();
long m_lDuration = 0;
bool m_bStart = false;
bool m_bPlay = false;
private DispatcherTimer m_dispatcherTimer;
public MainPage()
{
InitializeComponent();
SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;
DataContext = vm;
m_dispatcherTimer = new DispatcherTimer();
m_dispatcherTimer.Interval = TimeSpan.FromTicks(10000);
m_dispatcherTimer.Tick += frameworkDispatcherTimer_Tick;
m_dispatcherTimer.Start();
FrameworkDispatcher.Update();
//icBar.ItemsSource = vm.AudioData;
}
void frameworkDispatcherTimer_Tick(object sender, EventArgs e)
{
FrameworkDispatcher.Update();
}
private void btnStart_Click(object sender, RoutedEventArgs e)
{
m_bStart = true;
tbData.Text = "00:00:00";
m_lDuration = 0;
m_micDevice.BufferDuration = TimeSpan.FromMilliseconds(1000);
m_baBuffer = new byte[m_micDevice.GetSampleSizeInBytes(m_micDevice.BufferDuration)];
//m_micDevice.BufferReady += new EventHandler(m_Microphone_BufferReady);
m_micDevice.BufferReady += new EventHandler<EventArgs>(m_Microphone_BufferReady);
m_micDevice.Start();
}
void m_Microphone_BufferReady(object sender, EventArgs e)
{
m_micDevice.GetData(m_baBuffer);
Dispatcher.BeginInvoke(()=>
{
vm.LoadAudioData(m_baBuffer);
m_lDuration++;
TimeSpan tsTemp = new TimeSpan(m_lDuration * 10000000);
tbData.Text = tsTemp.Hours.ToString().PadLeft(2, '0') + ":" + tsTemp.Minutes.ToString().PadLeft(2, '0') + ":" + tsTemp.Seconds.ToString().PadLeft(2, '0');
}
);
//this.Dispatcher.BeginInvoke(new Action(() => vm.LoadAudioData(m_baBuffer)));
//this.Dispatcher.BeginInvoke(new Action(() => tbData.Text = m_baBuffer[0].ToString() + m_baBuffer[1].ToString() + m_baBuffer[2].ToString() + m_baBuffer[3].ToString()));
m_msAudio.Write(m_baBuffer,0, m_baBuffer.Length);
}
private void btnStop_Click(object sender, RoutedEventArgs e)
{
if (m_bStart)
{
m_bStart = false;
m_micDevice.Stop();
ProgressPopup.IsOpen = true;
}
if (m_bPlay)
{
m_bPlay = false;
m_sePlayBack.Dispose();
}
}
private void btnPlay_Click(object sender, RoutedEventArgs e)
{
m_bPlay = true;
m_sePlayBack = new SoundEffect(m_msAudio.ToArray(), m_micDevice.SampleRate, AudioChannels.Mono);
m_sePlayBack.Play();
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
if (txtAudio.Text != "")
{
IsolatedStorageFile isfData = IsolatedStorageFile.GetUserStoreForApplication();
string strSource = txtAudio.Text + ".wav";
int nIndex = 0;
while (isfData.FileExists(txtAudio.Text))
{
strSource = txtAudio.Text + nIndex.ToString().PadLeft(2, '0') + ".wav";
}
IsolatedStorageFileStream isfStream = new IsolatedStorageFileStream(strSource, FileMode.Create, IsolatedStorageFile.GetUserStoreForApplication());
isfStream.Write(m_msAudio.ToArray(), 0, m_msAudio.ToArray().Length);
isfStream.Close();
}
this.Dispatcher.BeginInvoke(new Action(() => ProgressPopup.IsOpen = false));
}
}
}
DotNet Weblineindia
my Source Code For UPLOADING A AUDIO TO PHP SERVER:
public void UploadAudio()
{
try
{
if (m_msAudio != null)
{
var fileUploadUrl = "uploadurl";
var client = new HttpClient();
m_msAudio.Position = 0;
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new StreamContent(m_msAudio), "uploaded_file", strFileName);
// upload the file sending the form info and ensure a result.it will throw an exception if the service doesn't return a valid successful status code
client.PostAsync(fileUploadUrl, content)
.ContinueWith((postTask) =>
{
try
{
postTask.Result.EnsureSuccessStatusCode();
var respo = postTask.Result.Content.ReadAsStringAsync();
string[] splitChar = respo.Result.Split('"');
FilePath = splitChar[3].ToString();
Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/VoiceSlider.xaml?FName=" + strFileName, UriKind.Relative)));
}
catch (Exception ex)
{
// Logger.Log.WriteToLogger(ex.Message);
MessageBox.Show("voice not uploaded" + ex.Message);
}
});
}
}
catch (Exception ex)
{
//Logger.Log.WriteToLogger(ex.Message + "Error occured while uploading image to server");
}
}
First of all Windows Phone does not allow to record .mp3 files. So, the .mp3 file that you are saving will not be played by Windows Phone player.
Have a look at this. This demo is working fine for recording .wav file.
If you wish to save other formats like .aac,.amr then user AudioVideoCaptureDevice class.

Data grid view in win form does not re size with its content

I am trying to re size the data grid view in windows form. There are two data grid view on my form and both are fed from the database. Is there any was I can resize the data grid view on the left so that it grows with the content length and width and the data grid view shrinks with the content.
Given below is my code
private void show_Click(object sender, EventArgs e)
{
int rowIndex = Convert.ToInt32(productGridView.SelectedRows[0].Cells[2].Value);
//IEnumerable<Supplier> supplierQuery = from supplier in newNorthWindContext.Suppliers
// where supplier.SupplierID == rowIndex
// select new {} supplier;
IEnumerable<Supplier> supplierQuery = newNorthWindContext.Suppliers.Where(supliers => supliers.SupplierID == rowIndex);
supplierDataGridView.DataSource = ((ObjectQuery)supplierQuery).Execute(MergeOption.AppendOnly);
supplierDataGridView.Columns["SupplierID"].Visible = false;
supplierDataGridView.Columns["ContactTitle"].Visible = false;
supplierDataGridView.Columns["Address"].Visible = false;
supplierDataGridView.Columns["City"].Visible = false;
supplierDataGridView.Columns["Region"].Visible = false;
supplierDataGridView.Columns["PostalCode"].Visible = false;
supplierDataGridView.Columns["ContactTitle"].Visible = false;
supplierDataGridView.Columns["Address"].Visible = false;
//supplierDataGridView.AutoResizeColumns();
supplierDataGridView.AutoSizeColumnsMode =
DataGridViewAutoSizeColumnsMode.AllCells;
}
private void categoryDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
Category category = (Category)this.categoryDropDown.SelectedItem;
try
{
productGridView.DataSource = category.Products;
productGridView.Columns["SupplierID"].Visible = false;
productGridView.Columns["CategoryID"].Visible = false;
productGridView.Columns["Category"].Visible = false;
productGridView.Columns["Order_Details"].Visible = false;
productGridView.Columns["Supplier"].Visible = false;
productGridView.AllowUserToDeleteRows = true;
productGridView.AutoResizeColumns();
productGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ProductDetail_Load(object sender, EventArgs e)
{
newNorthWindContext = new NorthwindEntities();
productGridView.AutoSizeColumnsMode =
DataGridViewAutoSizeColumnsMode.AllCells;
IEnumerable<Category> categoryQuery = from category in newNorthWindContext.Categories.Include("Products")
orderby category.CategoryName
select category;
try
{
this.categoryDropDown.DataSource = ((ObjectQuery)categoryQuery).Execute(MergeOption.AppendOnly);
this.categoryDropDown.DisplayMember = "categoryName";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This solves the issue.
supplierDataGridView.Width = supplierDataGridView.Columns.GetColumnsWidth(DataGridViewElementStates.Visible)+4;
at the end of show_Click you should have something like
supplierDataGridView.Width = supplierDataGridView.Columns.Sum(x => x.Width) + supplierDataGridView.RowHeadersWidth + 2;
supplierDataGridView.Height = supplierDataGridView.GetRowDisplayRectangle(supplierDataGridView.NewRowIndex, true).Bottom + supplierDataGridView.GetRowDisplayRectangle(supplierDataGridView.NewRowIndex, false).Height;
I hope this helps!

Resources