NotImplementedException when handling errors in Global.asax Application_Error - asp.net-mvc-3

I have code
protected void Application_Error(object sender, EventArgs e)
{
HttpContext ctx = HttpContext.Current;
Exception ex = ctx.Server.GetLastError();
ctx.Response.Clear();
var viewResult = new ViewResult();
if (ex.GetType() != typeof(SecurityException))
{
RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext;
IController controller = new ModuleController();
var context = new ControllerContext(rc, (ControllerBase)controller);
var httpException = ex as HttpException;
if (httpException != null)
{
switch (httpException.GetHttpCode())
{
case 404:
viewResult.ViewName = "Error404";
Response.StatusCode = 404;
break;
case 500:
viewResult.ViewName = "Error500";
Response.StatusCode = 500;
break;
default:
viewResult.ViewName = "Error";
Response.StatusCode = httpException.GetHttpCode();
break;
}
}
else
{
viewResult.ViewName = "Error";
}
viewResult.ViewData.Model = new HandleErrorInfo(ex, context.RouteData.GetRequiredString("controller"), context.RouteData.GetRequiredString("action"));
viewResult.ExecuteResult(context);
ctx.Server.ClearError();
}
else
{
var context = new ControllerContext { RouteData = new RouteData() };
context.RouteData.Values.Add("controller", "Security");
context.Controller = new SecurityController();
HttpCookie cookie = this.mebershipService.GetCookie();
cookie.Expires = DateTime.Now.AddDays(-1);
this.Context.Response.Cookies.Add(cookie);
viewResult.ViewName = "HackedDetect";
Response.StatusCode = 403;
viewResult.ExecuteResult(context);
ctx.Server.ClearError();
}
}
When processing SecurityException, and the call controller that does not relate to the system (in order not to walk in a circle) on the code viewResult.ExecuteResult (context); be a NotImplementedException
But I was not clear which method or operation is not defined.
That's what copied to the clipboard from the mistakes
System.NotImplementedException not handled by user code
HResult = -2147467263
Message = The method or operation is not implemented.
Source = System.Web
StackTrace:
in System.Web.HttpContextBase.get_Response ()
in System.Web.Mvc.ViewResultBase.ExecuteResult (ControllerContext context)
in SGN.Web.MvcApplication.Application_Error (Object sender, EventArgs e) in C: \ Project \ SGN \ SGN.Web \ Global.asax.cs: line 142
in System.EventHandler.Invoke (Object sender, EventArgs e)
in System.Web.HttpApplication.RaiseOnError ()
InnerException:
UPDATE
I'll write what I do to get this error
I created custom Identity class and when is initialized, I'm validate the cookie. If cookie not validate I create SecurityException

Related

Cannot invoke "org.apache.commons.logging.Log.isDebugEnabled()" because "this.logger" is null

Here the code that I used to save data and I use #Transactional. I want to write a test for this method, but it fails.
#Transactional(rollbackFor = BadRequestException.class, propagation = Propagation.REQUIRES_NEW)
public void saveContent(ContentAbstractEntity content) {
mongoTemplate.setSessionSynchronization(SessionSynchronization.ALWAYS);
TransactionBody txnBody =
(() -> {
ContentAbstractEntity contentAbstractEntity = contentRepository.save(content);
if (content instanceof LearningContent) {
LearningContent learningContent = (LearningContent) content;
Long tutorCountInDB = tutorRepository.countBy_idIn(learningContent.getTutorIds());
if (!countryRepository.existsBySyllabuses_grades_subjects__id(
learningContent.getSubjectId()))
throw new BadRequestException("Subject is not found");
Topic topic = topicRepository.findBy_id(learningContent.getTopicId());
if (topic == null) throw new BadRequestException("Topic is not found");
List<ObjectId> lessonIds =
topic.getLessons().stream().map(m -> m.get_id()).collect(Collectors.toList());
boolean allLessonsExists =
learningContent.getLessonIds().stream().allMatch(a -> lessonIds.contains(a));
if (!allLessonsExists) throw new BadRequestException("Lessons are not mismatched");
if (tutorCountInDB != learningContent.getTutorIds().size()) {
throw new BadRequestException("Tutors are not matched");
}
}
return "Successfully inserted";
});
MongoClient client = MongoClients.create(uri);
ClientSession clientSession = client.startSession();
try {
clientSession.withTransaction(txnBody);
} catch (BadRequestException e) {
throw new BadRequestException(e.getMessage());
} finally {
clientSession.close();
}
}
I tried to write a test for the above code, but it returns an error
#Test
void whenSaveContent() throws Exception {
ContentAbstractDto contentAbstractDto = new ContentAbstractDto();
ContentAbstractEntity content = learningVideo();
if (contentAbstractDto instanceof LearningDocsDto) {
LearningDocsDto learninfDocsDto = (LearningDocsDto) contentAbstractDto;
// ToDo when a Doc Saves and Assessment saves
}
when(contentRepository.save(content)).thenReturn(content);
if (content instanceof LearningContent) {
LearningContent learningContent = (LearningContent) content;
Long tutorCountInDB = (long) learningContent.getTutorIds().size();
when(tutorRepository.countBy_idIn(learningContent.getTutorIds())).thenReturn(tutorCountInDB);
when(subjectRepository.existsBy_id(learningContent.getSubjectId())).thenReturn(true);
Topic topic = getTopic();
when(topicRepository.findBy_id(learningContent.getTopicId())).thenReturn(topic);
if (topic == null) throw new BadRequestException("Topic is not found");
List<ObjectId> lessonIds =
topic.getLessons().stream().map(m -> m.get_id()).collect(Collectors.toList());
boolean allLessonsExists =
learningContent.getLessonIds().stream().allMatch(a -> lessonIds.contains(a));
if (!allLessonsExists) throw new BadRequestException("Lessons are not mismatched");
if (tutorCountInDB != learningContent.getTutorIds().size()) {
throw new BadRequestException("Tutors are not matched");
}
}

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.

Server cannot set status after HTTP headers have been sent in my C# .NET MVC Application while exporting datatable to spreadsheet

I am trying to Export datatable to spreadsheet.
I am getting this exception
Server cannot set status after HTTP headers have been sent.
on this line
httpContext.Response.StatusCode = ex is HttpException ? ((HttpException)ex).GetHttpCode() : 500;
Please help what can I do for solving this...
For Reference I am adding full code here::::
The code of export function is
public static void ExportToSpreadsheet(DataTable table, string name)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
foreach (DataColumn column in table.Columns)
{
context.Response.Write(column.ColumnName + ";");
}
context.Response.Write(Environment.NewLine);
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
context.Response.Write(row[i].ToString().Replace(";", string.Empty) + ";");
}
context.Response.Write(Environment.NewLine);
}
string saveAsFileName = string.Format("Results-{0:d}.xls", DateTime.Now);
context.Response.ContentType = "application/vnd.ms-excel";
context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", saveAsFileName));
context.Response.End();
}
the exception got catched in global.asax.cs in Application_Error function
protected void Application_Error(object sender, EventArgs e)
{
var httpContext = ((MvcApplication)sender).Context;
//var currentController = " ";
//var currentAction = " ";
string currentController;
string currentAction;
var currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
currentController = "";
currentAction = "";
if (currentRouteData != null)
{
if (currentRouteData.Values["controller"] != null && !String.IsNullOrEmpty(currentRouteData.Values["controller"].ToString()))
{
currentController = currentRouteData.Values["controller"].ToString();
}
if (currentRouteData.Values["action"] != null && !String.IsNullOrEmpty(currentRouteData.Values["action"].ToString()))
{
currentAction = currentRouteData.Values["action"].ToString();
}
}
else
{
currentController = "Home";
currentAction = "Index";
}
var ex = Server.GetLastError();
var controller = new ErrorController();
var routeData = new RouteData();
var action = "Error";
if (ex is HttpException)
{
var httpEx = ex as HttpException;
switch (httpEx.GetHttpCode())
{
case 400:
action = "BadRequest";
break;
case 401:
action = "Unauthorized";
break;
case 403:
action = "Forbidden";
break;
case 404:
action = "NotFound";
break;
case 408:
action = "RequestTimeout";
break;
case 500:
action = "InternalServerError";
break;
case 502:
action = "BadGateway";
break;
case 503:
action = "ServiceUnavailable";
break;
case 504:
action = "GatewayTimeout";
break;
}
}
httpContext.ClearError();
httpContext.Response.Clear();
// on this below line exception occurs
httpContext.Response.StatusCode = ex is HttpException ? ((HttpException)ex).GetHttpCode() : 500;
httpContext.Response.TrySkipIisCustomErrors = true;
routeData.Values["controller"] = "Error";
routeData.Values["action"] = action;
controller.ViewData.Model = new HandleErrorInfo(ex, currentController, currentAction);
((IController)controller).Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));
// to set error details in HandleErrorInfo model to send email notification
ErrorController.setHandleErrorInfoModel(new HandleErrorInfo(ex, currentController, currentAction));
}

WebClient.DownloadStringAsync webexception wp7

I'm trying to remove a node from an xml file, everything works, but sometimes it happens that the xml web page does not load. this is my code:
private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
XDocument xdoc = XDocument.Parse(e.Result, LoadOptions.None);
if (e.Error == null)
{
XDocument doc = XDocument.Parse(e.Result, LoadOptions.None);
var lyric = doc.Descendants(XName.Get("Lyric", "http://api.chartlyrics.com/")).FirstOrDefault();
TextBlock1.Text = lyric.Value;
}
}
}
private void btnLoad_Click(object sender, RoutedEventArgs e)
{
WebClient wc = new WebClient();
wc.DownloadStringCompleted += HttpsCompleted;
wc.DownloadStringAsync(new Uri("http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect?artist=michael%20jackson&song=bad));
}
I' ve read to use the WebException to handle this "mistake" but I am not able to use it. can someone give me some help?
Have you tried this way?
private void btnLoad_Click(object sender, RoutedEventArgs e)
{
try
{
WebClient wc = new WebClient();
wc.DownloadStringCompleted += HttpsCompleted;
wc.DownloadStringAsync(new Uri("http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect?artist=michael%20jackson&song=bad"));
}
catch (WebException ex)
{
// Check the exception here
}
}
And check for error in the handler too:
private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
XDocument xdoc = XDocument.Parse(e.Result, LoadOptions.None);
if (e.Error == null)
{
XDocument doc = XDocument.Parse(e.Result, LoadOptions.None);
var lyric = doc.Descendants(XName.Get("Lyric", "http://api.chartlyrics.com/")).FirstOrDefault();
TextBlock1.Text = lyric.Value;
}
}
else
{
// Check for error here
}
}
I realized it sometimes return Error, and I think the problem is in the server, because if I access it from the web browser, I sometimes get the result, but many times I get an error.

Code to execute if a navigation fails

Hello I have no idea where I should start looking. I add few prop (before that my code run fine), then I get
System.Diagnostics.Debugger.Break();
so then I comment that changes, but that didn't help.
Could you suggest me where I should start looking for solution?
MyCode:
namespace SkydriveContent
{
public partial class MainPage : PhoneApplicationPage
{
private LiveConnectClient client;
FilesManager fileManager = new FilesManager();
// Constructor
public MainPage()
{
InitializeComponent();
}
private void signInButton1_SessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
{
if (e.Status == LiveConnectSessionStatus.Connected)
{
client = new LiveConnectClient(e.Session);
infoTextBlock.Text = "Signed in.";
client.GetCompleted +=
new EventHandler<LiveOperationCompletedEventArgs>(OnGetCompleted);
client.GetAsync("/me/skydrive/files/");
fileManager.CurrentFolderId = "/me/skydrive/files/";
}
else
{
infoTextBlock.Text = "Not signed in.";
client = null;
}
}
void OnGetCompleted(object sender, LiveOperationCompletedEventArgs e)
{
//Gdy uda nam się podłaczyc do konta skydrive
if (e.Error == null)
{
signInButton1.Visibility = System.Windows.Visibility.Collapsed;
infoTextBlock.Text = "Hello, signed-in user!";
List<object> data = (List<object>)e.Result["data"];
fileManager.FilesNames.Clear();
filemanager.filesnames.add("..");
foreach (IDictionary<string,object> item in data)
{
File file = new File();
file.fName = item["name"].ToString();
file.Type = item["type"].ToString();
file.Url = item["link"].ToString();
file.ParentId = item["parent_id"].ToString();
file.Id = item["id"].ToString();
fileManager.Files.Add(file);
fileManager.FilesNames.Add(file.fName);
}
FileList.ItemsSource = fileManager.FilesNames;
}
else
{
infoTextBlock.Text = "Error calling API: " +
e.Error.ToString();
}
}
private void FileList_Tap(object sender, GestureEventArgs e)
{
foreach (File item in fileManager.Files)
{
if (item.fName == FileList.SelectedItem.ToString() )
{
switch (item.Type)
{
case "file":
MessageBox.Show("Still in progress");
break;
case "folder":
fileManager.CurrentFolderId = item.ParentId.ToString();
client.GetAsync(item.Id.ToString() + "/files");
break;
default:
MessageBox.Show("Coś nie działa");
break;
}
}
else if (FileList.SelectedItem.ToString() == "..")
{
client.GetAsync(fileManager.CurrentFolderId + "/files");
}
}
}
}
}
Running stop at that line.
// Code to execute if a navigation fails
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// A navigation has failed; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
You should check all of the URLs you have both in the XAML and code. When you get to the NavigationFailed function, it means that the phone tried to navigate to some page that did not existed. We would be able to help more if you could tell what were you doing when the app threw the exception.
System.Diagnostics.Debugger.Break();
usually happens because of an Uncaught Exception.
Either post the code which started giving problems, or the stack trace when you encounter this problem.
No one can tell anything without actually seeing what you are doing.

Resources