I want to stop my application asp.net Mvc in Session_Start after a test and show to user that he isn't authorized for this application
protected void Session_Start(object sender, EventArgs e)
{
if (test)
{
//stop application
// say to user : not authorized
}
}
Finally i send a response and close the session and it works
protected void Session_Start(object sender, EventArgs e){
if (test){
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "<h2 style=\"color:RED;\"Not authorized!!</h2>. ";
byte[] data = encoding.GetBytes(postData);
char[] buf = postData.ToCharArray();
HttpContext.Current.Response.Write(buf, 0, buf.Count());
HttpContext.Current.Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
Session.Abandon();
}
}
Related
Is there any possible way to record an audio and upload to a server using xamarin forms.
The best result I got after searching was this
https://github.com/HoussemDellai/UploadFileToServer
The library used in the solution supports only Image and Video.
Thanks in advance
Is there any possible way to record an audio and upload to a server using xamarin forms.
There are many ways realizing this feature. For recording an audio within Xamarin.Forms, you could use Plugin.AudioRecorder to realize. Fore more you could refer the following code.
private AudioRecorderService _recoder;
protected override void OnAppearing()
{
_recoder = new AudioRecorderService
{
StopRecordingOnSilence = true,
StopRecordingAfterTimeout = true,
AudioSilenceTimeout = TimeSpan.FromSeconds(60)
};
_recoder.AudioInputReceived += _recoder_AudioInputReceived;
}
private void _recoder_AudioInputReceived(object sender, string e)
{
// do some stuff
}
private async void Button_Clicked(object sender, EventArgs e)
{
await RecodAudio();
}
private async Task RecodAudio()
{
try
{
if (!_recoder.IsRecording)
{
await _recoder.StartRecording();
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
private async void StopButton_Clicked(object sender, EventArgs e)
{
if (_recoder.IsRecording)
{
await _recoder.StopRecording();
}
}
For uploading file, you could use the UploadFileToServer that mentioned in your case. And you will get the audio file path in the AudioInputReceived event args.
private void _recoder_AudioInputReceived(object sender, string e)
{
var path = e;
}
I'm working on a WP7 application and I need it to play the song in the first link if the current event on the calendar is "Meeting". However, with the current code, it plays the second song instead if the first one even though the event is set correctly.
Here is my code:
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
// Set the data context of the listbox control to the sample data
DataContext = App.ViewModel;
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
// Load data for the ViewModel Items
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
if (!App.ViewModel.IsDataLoaded)
{
App.ViewModel.LoadData();
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
Appointments appts = new Appointments();
//Identify the method that runs after the asynchronous search completes.
appts.SearchCompleted += new EventHandler<AppointmentsSearchEventArgs>(Appointments_SearchCompleted);
DateTime start = DateTime.Now;
DateTime end = DateTime.Now;
int max = 1;
//Start the asynchronous search.
appts.SearchAsync(start, end, max, "Appointments Test #1");
textBlock3.Text = DateTime.Now.ToString("hh:mm:ss tt");
}
void Appointments_SearchCompleted(object sender, AppointmentsSearchEventArgs e)
{
try
{
AppointmentResultsDataLINQ.DataContext =
from Appointment appt in e.Results
where appt.IsAllDayEvent == false
select appt;
}
catch (System.Exception)
{
}
}
private void button2_Click(object sender, RoutedEventArgs e)
{
if ((AppointmentResultsDataLINQ.DataContext).Equals("Meeting"))
{
mediaElement1.Source = new Uri("http://www.opendrive.com/files/NV8zNTMwNDYwX2hxRXZR/Crystallize.mp3", UriKind.Absolute);
}
else
{
mediaElement1.Source = new Uri("https://www.opendrive.com/files/NV8zMjAxODY0X0VBNDJY/Hetken%20tie%20on%20kevyt%20(piano%20cover)%20-%20YouTube.mp3", UriKind.Absolute);
}
mediaElement1.Play();
}
}
The problem appears to be this line:
if ((AppointmentResultsDataLINQ.DataContext).Equals("Meeting"))
You're comparing the result of calling the ToString() method on the Appointment instance with the string "Meeting".
You probably want:
if ((AppointmentResultsDataLINQ.DataContext as Appointment).Subject.Equals("Meeting"))
Update
You're actually checking an Enumerable of Appointments.
Here's how to check if any of them are "Meeting":
if ((AppointmentResultsDataLINQ.DataContext as IEnumerable<Appointment>).Any(app => app.Subject.Equals("Meeting")))
i am developing a c# user-control # work. the control just loads some infos & data and displays it.
now i want to provide the user of the control with an option to load the data asynchron .. smth like this:
Cntrl.LoadSmthAsync(..)
Cntrl.LoadSmthComplete //EventHandler to give feedback if the Load was successfull.
i decided to make the Download function Async and provide return values throu EventHandlers. but that code got rather complicated .. after all.
here some code to understand what the control should do:
public byte[] LoadByPos(int pos)
{
string url = Pos2Url(pos);
// update gui
this.textBox1.Text = url;
byte[] res = LoadByUrl(url);
// update gui
this.textBox2.Text = BytesToString(res);
return res;
}
public byte[] LoadByUrl(string url)
{
return Download(url);
}
//primary problem: download function
private byte[] Download(string url)
{
System.Threading.Thread.Sleep(1000 * 30);
return StringToBytes(url);
}
//secondary problem: an other function
private string Pos2Url(int pos)
{
System.Threading.Thread.Sleep(1000 * 5);
return pos.ToString();
}
// LoadByPosAsync
public delegate void LoadByPosDoneHandler(Object sender, byte[] e);
public event LoadByPosDoneHandler LoadByPosDone;
public void LoadByPosAsync(int pos)
{
string url = Pos2Url(pos);
// update gui
this.textBox1.Text = url;
LoadByUrlDone += new LoadByUrlDoneHandler(LoadByPosAsync_LoadByUrlDone);
LoadByUrlAsync(url);
}
public void LoadByPosAsync_LoadByUrlDone(object sender, byte[] e)
{
// update gui
this.textBox2.Text = BytesToString(e);
LoadByUrlDone = null;
LoadByPosDone(sender, e);
}
//LoadByUrlAsync
public delegate void LoadByUrlDoneHandler(Object sender, byte[] e);
public event LoadByUrlDoneHandler LoadByUrlDone;
public void LoadByUrlAsync(string url)
{
DownloadDone += new DownloadDoneHandler(LoadByUrlAsync_DownloadDone);
DownloadAsync(url);
}
private void LoadByUrlAsync_DownloadDone(object sender, byte[] e)
{
LoadByUrlDone(sender, e);
}
//DownloadAsync
private delegate void DownloadDoneHandler(Object sender, byte[] e);
private event DownloadDoneHandler DownloadDone;
private void DownloadAsync(string url)
{
BackgroundWorker bw_DownloadAsync = new BackgroundWorker();
bw_DownloadAsync.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_DownloadAsync_RunWorkerCompleted);
bw_DownloadAsync.DoWork += new DoWorkEventHandler(bw_DownloadAsync_DoWork);
bw_DownloadAsync.RunWorkerAsync(url);
}
void bw_DownloadAsync_DoWork(object sender, DoWorkEventArgs e)
{
byte[] res = Download((string)e.Argument);
e.Result = res;
}
void bw_DownloadAsync_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
DownloadDone(sender, (byte[])e.Result);
}
is there an easier way to accomplish what i am intending to do ?
thx in advance
Is there an easier way to accomplish what I am intending to do?
There's the implementation side separately, but if you're using .NET 4 I would strongly advise you not to use this model for asynchrony. Rather than using event handlers, I'd encourage you to use Task<T>. You can use TaskCompletionSource to create the task if you don't have any inherent support for it, and it means your API will be much easier to use in C# 5, due to the async/await support. At that point, your UI-thread method would look like this:
public async Task<byte[]> LoadByPos(int pos)
{
string url = await Pos2UrlAsync(pos);
// update gui
this.textBox1.Text = url;
byte[] res = await LoadByUrlAsync(url);
// update gui
this.textBox2.Text = BytesToString(res);
return res;
}
The asynchrony will simply flow through your code naturally.
I have a code that adds email id and name in Isolated space. But it is not able to add multiple data. Also, how can I update in case any data was entered incorrectly?
namespace IsoStore
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
IsolatedStorageSettings.ApplicationSettings.Add("email", "someone#somewhere.com");
IsolatedStorageSettings.ApplicationSettings.Add("name", "myname");
}
private void button2_Click(object sender, RoutedEventArgs e)
{
textBlock1.Text = (string)IsolatedStorageSettings.ApplicationSettings["email"];
textBlock2.Text = (string)IsolatedStorageSettings.ApplicationSettings["name"];
}
}
}
Cleaned up your code a little for you, using a helper method to do the store:
namespace IsoStore
{
public partial class MainPage : PhoneApplicationPage
{
private IsolatedStorageSettings _appSettings;
// Constructor
public MainPage()
{
InitializeComponent();
_appSettings = IsolatedStorageSettings.ApplicationSettings;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
SaveSetting("email", "someone#somewhere.com");
SaveSetting("name", "myname");
}
private void button2_Click(object sender, RoutedEventArgs e)
{
textBlock1.Text = (string)_appSettings["email"];
textBlock2.Text = (string)_appSettings["name"];
}
private void SaveSetting( string setting, string value )
{
if (_appSettings.Contains(setting))
{
_appSettings[setting] = value;
}
else
{
_appSettings.Add(setting, value);
}
}
}
}
Try a few other examples to get your head around using IsolatedStorageSettings.
How to: Store and Retrieve Application Settings Using Isolated Storage
All about WP7 Isolated Storage - Store data in IsolatedStorageSettings
I have in mind 2 options, you either save your data to isolatedStorageFile MSDN Library OR ,this is what i might do in such case, You save under the key email all your emails as one string separate the emails with a char that is not allowed to be in an email, Coma "," lets say, when needed split your string and retrieve it to whatever makes you comfortable.
private void SaveSetting( string setting, string value )
{
if (_appSettings.Contains(setting))
{
_appSettings[settings] = _appSettings[settings] + "," + value;
}
else
{
_appSettings.Add(setting, value);
}
}
please note that this code segment is copied from HiTech Magic' answer.
I'm new in WP7, and I am trying to play sounds with a MediaElement when I press a button.
Its works, but unfortunately I get "Operation not permitted on IsolatedStorageFileStream" Exception when I press the button repeatedly, before the sound begins. How can I avoid that?
The Play method:
public void Play(string filename)
{
try
{
mediaElement.Stop();
mediaElement.ClearValue(MediaElement.SourceProperty);
using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = isf.OpenFile(#"shared\transfers\" + filename, FileMode.Open))
{
mediaElement.SetSource(fileStream);
mediaElement.IsMuted = false;
mediaElement.Volume = 1.0;
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
Event handlers:
void me_MediaOpened(object sender, RoutedEventArgs e)
{
mediaElement.Play();
}
void me_MediaEnded(object sender, RoutedEventArgs e)
{
mediaElement.ClearValue(MediaElement.SourceProperty);
}
If you'd like for the user to be allowed to click the play button only once. One way would be.
public bool IsPlaying = false;
void me_MediaOpened(object sender, RoutedEventArgs e)
{
if(!IsPlaying){
mediaElement.Play();
IsPlaying = true;
}
}
void me_MediaEnded(object sender, RoutedEventArgs e)
{
if(IsPlaying){
mediaElement.ClearValue(MediaElement.SourceProperty);
IsPlaying = false;
}
}
Loading the filestream to a memorystream, before playing should make it more flexible, if you're dealing with low size streams.