In my app I'm using "HandleError" whereby if an error happens, my "Error.vbhtml" view renders. This is working great, except now I want to also log the error. I've built a custom HandleError Class, Inherited the HandleErrorAttribute, and Overridden the OnException method.
Now my error gets logged, but the Error.vbhtml view doesn't get rendered... what praytell am I messing?
Imports System.Web.Mvc
Namespace Mvc.Attributes
Public Class HandleError : Inherits System.Web.Mvc.HandleErrorAttribute
Private ExceptionService As Domain.IExceptionService
Public Sub New()
ExceptionService = New Domain.ExceptionService(New Domain.ExceptionRepository)
End Sub
Public Overrides Sub OnException(ByVal exceptionContext As ExceptionContext)
''# Log the exception if it has not been handled elsewhere
If Not exceptionContext.ExceptionHandled Then
ExceptionService.AddException(exceptionContext.Exception)
ExceptionService.SubmitChanges()
''# Signal to the system that we've handled the exception
exceptionContext.ExceptionHandled = True
End If
End Sub
End Class
End Namespace
I just took a look at the source code of the HandleError method at Codeplex. I scooped some of the code from there
Dim controllerName As String = DirectCast(filterContext.RouteData.Values("controller"), String)
Dim actionName As String = DirectCast(filterContext.RouteData.Values("action"), String)
Dim model As New HandleErrorInfo(filterContext.Exception, controllerName, actionName)
filterContext.Result = New ViewResult() With { _
.ViewName = View, _
.MasterName = Master, _
.ViewData = New ViewDataDictionary(Of HandleErrorInfo)(model), _
.TempData = filterContext.Controller.TempData _
}
filterContext.ExceptionHandled = True
filterContext.HttpContext.Response.Clear()
filterContext.HttpContext.Response.StatusCode = 500
''# Certain versions of IIS will sometimes use their own error page when
''# they detect a server error. Setting this property indicates that we
''# want it to try to render ASP.NET MVC's error page instead.
filterContext.HttpContext.Response.TrySkipIisCustomErrors = True
This appears to work
Related
I'm trying to create a copy of a mailItem in my sent folder. Once I create it, I save the msg in the folder. It works for all mailItems , except when I try to save a mailItem with an attachment where I disallow the save attachment permission in outlook. Why does the mailItem.Save() not saving the mailItem only for this scenario?
In the code below, I'm using redemptions to create a copy in sent folder. msg.save() saves all mails but the one I mentioned above. Also I tried saving the mailItem before the creation, but it does not generate entryId.
static void CreateSentFolderMail(Redemption.SafeMailItem newSentMail, string nvdID, Outlook.MailItem mailItem, Redemption.SafeMailItem safeMailItem)
{
RDOFolder folder = Globals.ThisAddIn.session.GetDefaultFolder(rdoDefaultFolders.olFolderSentMail);
RDOMail msg = (RDOMail)folder.Items.Add(newSentMail);
RDOMail originalmsg = Globals.ThisAddIn.session.GetMessageFromID(mailItem.EntryID);
msg.Sent = true;
msg.SentOn = DateTime.Now;
msg.ReceivedTime =msg.CreationTime;
msg.Subject = safeMailItem.Item.Subject;
msg.To = safeMailItem.Item.To;
msg.BCC = safeMailItem.Item.BCC;
msg.Body = safeMailItem.Item.Body;
msg.Recipients = originalmsg.Recipients;
msg.Sender = Globals.ThisAddIn.session.CurrentUser;
msg.SentOnBehalfOf = Globals.ThisAddIn.session.CurrentUser;
msg.SetProps(NVDMailHeaderUtils.PS_INTERNET_HEADERS + NVDMailHeaderUtils.NVD_HEADER_ID, nvdID);
msg.Save();
}
I had used session.GetRDOObjectFromOutlookObject before calling this method to get a RDOAttachment object. But after using this: session.GetRDOObjectFromOutlookObject I was not able to the save the mailitem. Save was not getting executed and hence the EntryId was not getting generated. Due to this issue I was getting an error here : RDOMail originalmsg = Globals.ThisAddIn.session.GetMessageFromID(mailItem.EntryID); saying "invalid entry Id". I installed the new version of redemptions that solved this problem.
I just got my SendGrid account installed on my AWS EC2 Windows server 2019 my VS 2019 Pro for my VB.NET windows app.
But all the examples I can find are in C#.
I got same problem same as you.
I already developed and tested for both C#.NET and VB.NET.
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using SendGrid;
using SendGrid.Helpers.Mail;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
TestSendGrid().Wait();
}
static async Task TestSendGrid()
{
try
{
var apiKey = ConfigurationManager.AppSettings["SENDGRID_APIKEY"];
var client = new SendGridClient(apiKey);
var msg = new SendGridMessage()
{
From = new EmailAddress("test#example.com", "Test User"),
Subject = "Hello World from the SendGrid C#.NET SDK!",
PlainTextContent = "Hello, Email!",
HtmlContent = "<strong>Hello, Email!</strong>"
};
msg.AddTo(new EmailAddress("test#example.com", "Test User"));
var response = await client.SendEmailAsync(msg);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
VB.NET
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.Configuration
Imports SendGrid
Imports SendGrid.Helpers.Mail
Module Module1
Sub Main()
TestSendGrid().Wait()
End Sub
Private Async Function TestSendGrid() As Task
Try
Dim apiKey = ConfigurationManager.AppSettings("SENDGRID_APIKEY")
Dim client = New SendGridClient(apiKey)
Dim msg = New SendGridMessage() With {
.From = New EmailAddress("test#example.com", "Test User"),
.Subject = "Hello World from the SendGrid VB.NET SDK!",
.PlainTextContent = "Hello, Email!",
.HtmlContent = "<strong>Hello, Email!</strong>"
}
msg.AddTo(New EmailAddress("test#example.com", "Test User"))
Dim response = Await client.SendEmailAsync(msg)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Function
End Module
Reference: https://learn.microsoft.com/en-us/azure/sendgrid-dotnet-how-to-send-email
I couldn't find any either. Especially in v3. I finally got it working in VB.NET. Hopefully this will save someone some time. That being said, I eventually switched to mailgun because the functionality was way more robust than sendgrid...
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
SendEmail()
End Sub
Private Async Sub SendEmail()
Dim apiKey = "put your api key here ... should start with sg.something"
Dim sg = New SendGridAPIClient(apiKey)
Dim from = New Email("billgates#microsoft.com")
Dim subject = "Hello World from the SendGrid CSharp Library!"
Dim sto = New Email("barakobama#whitehouse.gov")
Dim content = New Content("text/plain", "Hello, Email!")
Dim mail = New Mail(from, subject, sto, content)
Dim response = Await sg.client.mail.send.post(requestBody:=mail.[Get]())
End Sub
End Class
This code is working for SendGrid
Imports SendGrid.Helpers.Mail
Imports SendGrid
Public Sub SchedularCallback(ByRef data As EmailDataBulk)
Try
SchedularCallbackGrid(data)
Catch ex As Exception
End Try
End Sub
Public Async sub SchedularCallbackGrid()
Dim response As Response
Try
Dim client = New SendGridClient("Send grid api Key")
Dim from = New EmailAddress("from sample mailID", "From mail name") '' Login Email and Display Its name in mail,on Inbox
Dim subject = "Hello Email!"
Dim sto = New EmailAddress("Recepient EmailID", "")
Dim plainTextContent = "Content"
Dim htmlContent = "Content"
Dim msg = MailHelper.CreateSingleEmail(from, sto, subject, plainTextContent, htmlContent)
response = Await client.SendEmailAsync(msg)
Catch ex As Exception
Throw ex
End Try
End sub
End Class
With this one, while there is no error, I'm not getting a message into sendgrid. My stats should show a mail being received and there is nothing. I converted C# code into vb.net and it made a Module. I had problems with it as a module so I changed it to a class and I'm creating an instance of it and calling it in the button_click event. Any ideas why I'm not getting an email?
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.Configuration
Imports SendGrid
Imports SendGrid.Helpers.Mail
Class sendgrid1
Sub Main(ByVal test As String)
TestSendGrid(test).Wait()
End Sub
Private Async Function TestSendGrid(ByVal test As String) As Task
Try
Dim apiKey = ConfigurationManager.AppSettings("ApiKey")
Dim client = New SendGridClient(apiKey)
Dim msg = New Helpers.Mail.SendGridMessage() With {
.From = New EmailAddress("admin#pacificwestcapital.net", test),
.Subject = "Hello World from the SendGrid VB.NET SDK!",
.PlainTextContent = "Hello, Email!",
.HtmlContent = "<strong>Hello, Email!</strong>"
}
msg.AddTo(New EmailAddress("test#test.com", "Test"))
Dim response = Await client.SendEmailAsync(msg)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Function
End Class
Partial Class admin_sendgrid
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sg As New sendgrid1
Call sg.Main("Test")
End Sub
End Class
Imports System.Net.Sockets
Imports System.Text
Imports System.Net.Mail
Imports System.Threading
Imports System
Imports System.IO
Imports SendGrid
Imports System.Net
' Create the email object first, then add the properties.
Dim myMessage As SendGridMessage
myMessage = New SendGridMessage()
' Add the message properties.
myMessage.From = New MailAddress("<my email addr>")
' Add multiple addresses to the To field.
myMessage.AddTo("<destination email addr 1>")
myMessage.AddTo("<destination email addr 2>")
myMessage.AddTo("<destination email addr 3>")
myMessage.Subject = "Testing the SendGrid Library 2"
'Add the HTML and Text bodies
myMessage.Html = "<p>Hello World!</p>"
myMessage.Text = "Hello World plain text!"
Dim credentials As NetworkCredential
credentials = New NetworkCredential("apikey", "<my api pw>")
transportWeb = New Web(credentials)
transportWeb.DeliverAsync(myMessage)
So I've created a page called "Settings". Obviously in this page is where the settings are for the app. In the Settings page I've added 2 ToggleSwitches and 1 Listpicker. Using the Nokia Developer website on basics of Saving and reading Settings i managed to pull it off so it saves the states of the toggleswitches and listpicker.
The problem i'm having right now is that i need a way to read these saved setting values on the first page when the app starts so it can prepare the app accordingly. Soo far this is what i have in the Settings page:
Imports System.IO.IsolatedStorage
Partial Public Class Settings
Inherits PhoneApplicationPage
Private AppSettings As IsolatedStorageSettings
Public Sub New()
InitializeComponent()
AppSettings = IsolatedStorageSettings.ApplicationSettings
ListPicker1.Items.Add("Saved Notes")
ListPicker1.Items.Add("Important")
End Sub
Protected Overrides Sub OnNavigatedTo(e As NavigationEventArgs)
Try
Tg1.IsChecked = CBool(AppSettings("UseAccentColor"))
Tg2.IsChecked = CBool(AppSettings("GoBack"))
ListPicker1.SelectedIndex = CByte(AppSettings("StartListFalse"))
Catch ex As KeyNotFoundException
AppSettings.Add("UseAccentColor", False)
AppSettings.Add("GoBack", False)
AppSettings.Add("StartListFalse", False)
AppSettings.Save()
End Try
End Sub
Protected Overrides Sub OnNavigatedFrom(e As NavigationEventArgs)
System.Diagnostics.Debug.WriteLine("Exiting, so save now")
AppSettings("UseAccentColor") = Tg1.IsChecked
AppSettings("GoBack") = Tg2.IsChecked
AppSettings("StartListFalse") = ListPicker1.SelectedIndex
AppSettings.Save()
End Sub
End Class
So soo far it saves on exit but i need a way to load these from startup i.e. my MainPage. Like a way to refer to this page and according to these settings change whatever needs to be changed.
How can i do this?
Thanks!
You managed to save Settings to IsolatedStorage, and IsolatedStorage is accesssible from any page of your application. So in MainPage, just read those setting from IsolatedStorage instead of the Settings Page.
EDIT :
You can do it just like in OnNavigatedTo method in Settings Page
Private AppSettings As IsolatedStorageSettings = IsolatedStorageSettings.ApplicationSettings
'Tg1.IsChecked is analog with useAccentColor
Dim useAccentColor As Boolean = CBool(AppSettings("UseAccentColor"))
'Tg2.IsChecked = goBack
Dim goBack As Boolean = CBool(AppSettings("GoBack"))
'ListPicker1.SelectedIndex = startListFalse
Dim startListFalse As Byte = CByte(AppSettings("StartListFalse"))
Does anyone know if there is a way outside of using a 3rd Party text box control, to enter HTML into a VB6 text box.
I havent found anything online.
Hopefully you'll be able to make use of this. We're doing it in .Net to allow a simple edit control on forms to send formatted emails. As such we have a RTF text box with a custom menu for creating the text, then we extract the RTF, convert it to HTML and add it as HTML content as the body of an email. The RTF to HTML conversion uses the code from this article: http://www.codeproject.com/Articles/27431/Writing-Your-Own-RTF-Converter
Here's the wrapper code we use to tie this together - it simply takes an RTF input and directly returns an HTML output:
Imports Itenso.Rtf
Imports Itenso.Rtf.Support
Imports Itenso.Rtf.Parser
Imports Itenso.Rtf.Interpreter
Imports Itenso.Rtf.Converter.Image
Imports Itenso.Rtf.Converter.Html
Imports Itenso.Sys.Application
Namespace Email
Public Class RtfToHtml
Public Function Convert(inText As String) As String
Dim struct = ParseRtf(inText)
Dim doc = InterpretRtf(struct)
Return ConvertHtml(doc)
End Function
Private Function ParseRtf(inText As String) As IRtfGroup
Dim structureBuilder As New RtfParserListenerStructureBuilder
Dim parser = New RtfParser(structureBuilder) With {.IgnoreContentAfterRootGroup = True}
Dim source = New RtfSource(inText)
parser.Parse(source)
Return structureBuilder.StructureRoot
End Function
Private Function InterpretRtf(rtfStructure As IRtfGroup) As IRtfDocument
Dim settings = New RtfInterpreterSettings With {.IgnoreDuplicatedFonts = True, .IgnoreUnknownFonts = True}
Return RtfInterpreterTool.BuildDoc(rtfStructure, settings)
End Function
Private Function ConvertHtml(document As IRtfDocument) As String
Dim settings As New RtfHtmlConvertSettings With {.Title = "Notification Of Shipment",
.IsShowHiddenText = False,
.UseNonBreakingSpaces = True}
Dim converter = New RtfHtmlConverter(document, settings)
'converter.StyleConverter = New RtfEmptyHtmlStyleConverter
Return converter.Convert
End Function
End Class
End Namespace
Depending on your application you could simply wrap this up in an assembly and call it from VB6. We've done this in the past and it's reasonably straightforward. Again, more info if you think it might be useful to you
I am setting a Session variable in an HttpHandler, and then getting its value in the Page_load event of an ASPX page. I'm setting it using
public void ProcessRequest(HttpContext context)
{
HttpPostedFile file = context.Request.Files["Filedata"];
context.Session["WorkingImage"] = file.FileName;
}
(And before someone suggests that I check the validity of file.FileName, this same problem occurs if I hard-code a test string in there.) It's working just fine in IE, but in Firefox the Session Variable is not found, getting the "Object reference not set to an instance of an object" error in the following code:
protected void Page_Load(object sender, EventArgs e)
{
string loc = Session["WorkingImage"].ToString();
}
Has anyone encountered this problem - and hopefully come up with a means for passing the session variable?
This is for an HTTPHandler? If this by some chance has something to do with Flash, and Flash is making the request, you will be very interested in reading about the Flash Cookie Bug. Basically, Flash only forwards IE cookies.
The easist fix is to call correctCookie at Application_BeginRequest in your Global.asax and put the SessionId in the querystring of the Flash request.
Public Shared Sub correctCookie()
Try
Dim session_cookie_name As String = "ASP.NET_SESSIONID"
Dim session_value As String = HttpContext.Current.Request.QueryString("sid")
If session_value IsNot Nothing Then
UpdateCookie(session_cookie_name, session_value)
End If
Catch ex As Exception
End Try
End Sub
Private Shared Sub UpdateCookie(ByVal cookie_name As String, ByVal cookie_value As String)
Dim cookie As HttpCookie = HttpContext.Current.Request.Cookies.[Get](cookie_name)
If cookie Is Nothing Then
Dim cookie1 As New HttpCookie(cookie_name, cookie_value)
HttpContext.Current.Response.Cookies.Add(cookie1)
Else
cookie.Value = cookie_value
HttpContext.Current.Request.Cookies.[Set](cookie)
End If
End Sub