How to create a JSON string in Visual Basic using json.net? - json.net

I'm using json.net to parse a JSON text. I got a JObject now:
Dim json_text As String
json_text = "{" & Chr(34) & "Venue" & Chr(34) & ": {" & Chr(34) & "ID" & Chr(34) & ":" & Chr(34) & "JSON" & Chr(34) & "}}"
Console.WriteLine(json_text)
Dim json As JObject
json = JObject.Parse(json_text)
Console.WriteLine(json.SelectToken("Venue").SelectToken("ID"))
Now I want to do the opposite and create a JSON text from the JSON variable.
Unfortunately, I cannot find any solution out there.

Imports Newtonsoft.Json.Linq
Imports Newtonsoft.Json
Dim json_text As String
json_text = "{" & Chr(34) & "Venue" & Chr(34) & ": {" & Chr(34) & "ID" & Chr(34) & ":" & Chr(34) & "JSON" & Chr(34) & "}}"
Console.WriteLine(json_text)
Dim json As JObject
json = JObject.Parse(json_text)
Console.WriteLine(json.SelectToken("Venue").SelectToken("ID"))
Dim json_string As String = JsonConvert.SerializeObject(json,
Formatting.Indented, New JsonSerializerSettings())
Console.WriteLine(json_string)
This results in:
{"Venue": {"ID":"JSON"}}
JSON
{
"Venue": {
"ID": "JSON"
}
}

Related

Sending email to Hotmail or Outlook in ASP.NET

I'm trying to send email in asp.net, it works find and send email to GMAIL and YAHOO mails but not working on HOTMAIL or OUTLOOK account.
Here is code...
Dim pass As String = RandomPassword.Generate(8, 10)
ta.insertuser(txtuser.Text, pass, txtfname.Text, txtlname.Text, txtemail.Text, droprole.SelectedValue, radiostatus.SelectedValue, DateTime.Now())
Dim senderma As New MailAddress("client#karacode.ir", "karacode")
Dim recipientma As New MailAddress(txtemail.Text)
Dim mm As New MailMessage(senderma, recipientma) With {
.Subject = "Account Details",
.SubjectEncoding = System.Text.Encoding.UTF8,
.Body = "<div style='font-family: tahoma; font-size: 10pt; padding: 1em; direction:rtl; text-align: justify; line-height: 2;'>" & "Dear User" & " " & txtfname.Text & " " & txtlname.Text & "<br />" & "You're most welcom to KARACODE" & "<br /><br />" & "Your account information<br /><br />" & "Username : <br />" & txtuser.Text & "<br /><br />" & "Password : <br />" & pass & "</div>",
.BodyEncoding = System.Text.Encoding.UTF8,
.IsBodyHtml = True
}
Dim cred As New System.Net.NetworkCredential With {
.UserName = "client#karacode.ir",
.Password = "Client164418054545"
}
Dim smtp As New SmtpClient With {
.Host = "webmail.karacode.ir",
.EnableSsl = False,
.UseDefaultCredentials = True,
.Credentials = cred,
.Port = 25
}
smtp.Send(mm)
Please gives the tips to solve the problem.
MANY THANKS

User Control code keep calling repetedly

I have created a user control and registered inside asp.net page and
used that user control also. Everything works fine but user control
code executing repeatedly and thsi cycle goes on. I am not able to
find why this user control code keep on executing, Any help would be
highly appreciated.
Header.ascx code
<%# Control Language="C#" AutoEventWireup="true" Inherits="SSBilling.UserControl.header" %>
<script language="C#" runat="Server">
public void buffer()
{
try
{
Response.Buffer = true;
}
catch
{
}
}
public string cleanupCookie(string cookie)
{
string tmpcookie = cookie.Replace("%28", "(");
tmpcookie = tmpcookie.Replace("%29", ")");
tmpcookie = tmpcookie.Replace("%27", "'");
tmpcookie = tmpcookie.Replace("%2E", ".");
tmpcookie = tmpcookie.Replace("%3F", "?");
tmpcookie = tmpcookie.Replace("%2C", ",");
tmpcookie = tmpcookie.Replace("%5F", " ");
tmpcookie = tmpcookie.Replace("%2D", "-");
tmpcookie = tmpcookie.Replace('_', ' ');
tmpcookie = tmpcookie.Replace("ITEMCLICK2", "itemClick2");
return tmpcookie;
}
</script>
<%
//************************************************************************************************
//* 2012-06-05 HRHC
//* * migration updated
//************************************************************************************************
buffer();
%>
<script language=vbscript>
sub printthis()
window.focus()
window.print()
end sub
sub backbutton()
on error resume next
<%
Response.Write("' " + ((Request.Cookies["mID"] == null) ? String.Empty : Request.Cookies["mID"].Value) + "\r\n");
//response.write "self.parent.document.all.tmp.tmpMenu.value = """ & cleanupCookie(request.cookies("mID")) & """" & vbcrlf
Response.Write("top.document.all.tmp.tmpMenu.value = \"" + cleanupCookie((Request.Cookies["mID"] == null) ? String.Empty : Request.Cookies["mID"].Value) + "\"" + "\r\n");
//response.write " if instr(1, """ & request.cookies("deptlist") & """, "","" & self.parent.document.all.tmp.currDept.value & "","") > 0 then " & vbcrlf
Response.Write(" if instr(1, \"" + ((Request.Cookies["deptlist"] == null) ? String.Empty : Request.Cookies["deptlist"].Value) + "\", \",\" & top.document.all.tmp.currDept.value & \",\") > 0 then " + "\r\n");
Response.Write(" if err.number <> 0 then exit sub " + "\r\n");
Response.Write("top.go \"visible\"" + "\r\n");
//response.write "self.parent.document.all.menuadmin.style.visibility = ""visible""" & vbcrlf
Response.Write("else" + "\r\n");
Response.Write("top.go \"hidden\"" + "\r\n");
//response.write "self.parent.document.all.menuadmin.style.visibility = ""hidden""" & vbcrlf
Response.Write(" end if " + "\r\n");
//what?
//Session("CurrentUserAdmin") = "Y"
%>
end sub
' 2012-04-04 HRHC
' - modified to avoid scripting error after migrated
' the following if statement only works when the
' child and parent frames are under the same domain
'----------------------------------------------------
'If IsObject(self.parent.document.frames) Then
' If self.parent.document.frames.length = 0 Then
' loc = InStr(8, self.location.href, "/")
' loc = Mid(self.location.href, loc)
'
' location.href = "/default.asp?loc=" & loc
' Else
' Call backbutton
' End If
'End If
</script>
<script type="text/javascript">
if (top === self) {
/*
2012-08-18 HRHC
- no in the trinity frameset (both zone and new app), call the default page.
this will no longer be used after app migrated
*/
var loc = "";
top.location = "/default.aspx?loc=" + loc;
}
else {
/*
- in the frameset, do nothing
*/
}
</script>
<link REL="stylesheet" TYPE="text/css" HREF="/include/content.css">
<%
//response.write "hello from header.inc<br />"
%>
Registerd in asp.net page like this:
<%# Register TagPrefix="uc" TagName="header"
Src="~/UserControl/header.ascx" %>
And called the header.ascx like this:
<uc:header id="ucHeader" runat="server"></uc:header>
Thank You!

How to Send email with High Importance in asp.net VB

How do I set the code below to generate email with high priority in the subject line? Thank you for any guidance.
Private Sub SendEmail(ByVal pharmEmail As String, ByVal backupEmail As String)
Dim smtpClient As New System.Net.Mail.SmtpClient()
Dim message As New System.Net.Mail.MailMessage()
Try
Dim fromAddress As New System.Net.Mail.MailAddress(WebConfigurationManager.AppSettings("EmailFromAddr"), WebConfigurationManager.AppSettings("EmailFromName"))
message.From = fromAddress
message.To.Add(pharmEmail)
message.Subject = WebConfigurationManager.AppSettings("EmailSubject")
If (WebConfigurationManager.AppSettings("backupEnabled") = True) Then
message.CC.Add(backupEmail)
End If
message.IsBodyHtml = True
Dim orderURL As New HyperLink
orderURL.Text = "here"
orderURL.NavigateUrl = "http://" & WebConfigurationManager.AppSettings("ServerName") & "/User/ReviewOrder.aspx?orderID=" & webOrderID
message.Body = "An order was created using the account of " + Profile.FirstName.ToString() + " " + Profile.LastName.ToString() + ". " + WebConfigurationManager.AppSettings("EmailBody") + "<a href='" + orderURL.NavigateUrl + "'>here.</a>"
'message.Body = WebConfigurationManager.AppSettings("EmailBody") & " " & orderURL.
smtpClient.Send(message)
Catch ex As Exception
ErrorHandler.WriteError(ex.ToString)
Throw ex
End Try
I believe you can set the Priority property on the MailMessage. See MSDN for more details.

The parameter 'from' cannot be an empty string. Parameter name: from

Ok, so basically I have a comments form on my website. People but comments in the comment box and it emails the comments to my email. The email part works fine and goes through. However, the error comes when I try to clear the form fields. It gives me an error saying:
Error: The parameter 'from' cannot be an empty string.
Parameter name: from
So anyone have any thoughts? like I said the email part works fine its just clearing the fields is giving me trouble
here is the code:
Imports System.Web.Mail
Imports System.Text
Partial Class Pages_ContactUs : Inherits System.Web.UI.Page
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim body As String = "From: " + YourName.Text + " " + Environment.NewLine + "Email: " + YourEmail.Text + Environment.NewLine + Environment.NewLine + "Message: " + Environment.NewLine + Comments.Text
Dim MM As New System.Net.Mail.SmtpClient
MM.EnableSsl = True
MM.Host = "smtp.gmail.com"
Dim cred As New System.Net.NetworkCredential("myEmail#gmail.com", "myPassword")
MM.Credentials = cred
MM.Send(YourEmail.Text, "myEmail#gmail.com", Subject.Text, body)
ClearFields()
lblEmail.ForeColor = Drawing.Color.Green
lblEmail.Text = "Your message has been sent successfuly"
lblEmail.Visible = True
End Sub
Protected Sub ClearFields()
YourName.Text = ""
YourEmail.Text = ""
Comments.Text = ""
Subject.Text = ""
End Sub
End Class
You must supply it, just make it yours. Basic pattern:
Using SmtpServer As New SmtpClient()
Using mail As New System.Web.Mail.MailMessage()
Try
SmtpServer.UseDefaultCredentials = True
SmtpServer.EnableSsl = True
SmtpServer.Credentials = New Net.NetworkCredential(un, pw)
SmtpServer.Port = 25
SmtpServer.Host = "smtp.address"
mail.From = New MailAddress(sender)
mail.To.Add(some address)
mail.Subject = subject
mail.Body = body
mail.Sender = New MailAddress(sender)
SmtpServer.Send(mail)
Catch
End Try
End Using
End Using

sugestions on global error handler to get dump of diagnostic data

there are loads of resources that show how to use global.ascx global error event handler to capture un-managed errors in the web application but i am yet to find a good sample of code to include in this method that will report on major topics like error message, an output of stack trace, page that generated the error, the user-name/ role that generated the error... and the such.
has anyone used, have, or come across a nice code spinet for this purpose?
thanks in advance.
Your best best it to do nothing. ASP.NET Health Monitoring will write an event to the event log containing most of the data you could need.
If that's not enough information for you, then you should look into wrapping certain of your exceptions in an outer exception which includes the additional data. For instance:
string fileSpec = " ... ";
try
{
using (var stream = new FileStream(fileSpec))
{
// Something
}
}
catch (IOException ex)
{
throw new Exception(String.Format("Error processing {0}", fileSpec), ex);
}
Here's what we're using though we may now want to switch to Health Monitoring seeing the other answers to this question.
public static void LogErrorWithStackTrace(String message, Exception exception,
EventLogEntryType entryType)
{
var context = HttpContext.Current;
var session = context.Session;
var request = context.Request;
var errorMessage =
String.Format(
#"Message: {0}
Error in: {1}
Referer: {2}
Agent: {3}
IP: {4}
Request type: {5}",
message, request.Url, request.UrlReferrer,
request.UserAgent, request.UserHostAddress, request.RequestType);
errorMessage += "\rQuery string variables:";
errorMessage = request.QueryString.Keys.Cast<string>().Aggregate(errorMessage,
(current, key) =>
current +
"\r " + key + " = " +
request.QueryString[
key]);
errorMessage += "\rForm variables:";
errorMessage = request.Form.Keys.Cast<string>().Aggregate(errorMessage,
(current, key) =>
current + "\r " + key +
" = " +
request.Form[key]);
errorMessage += "\rCookies:";
errorMessage = request.Cookies.Keys.Cast<string>().Aggregate(errorMessage,
(current, key) =>
current + "\r " + key +
" = " +
request.Cookies[key]);
if (session != null)
{
errorMessage += "\rISession:";
var sess = (ISession) session["session"];
errorMessage += sess.ToString();
errorMessage += "\rSession:";
errorMessage = session.Keys.Cast<string>().Aggregate(errorMessage,
(current, sessionKey) =>
current +
"\r " + sessionKey + ": " +
session[sessionKey]);
}
errorMessage += "\rStack Trace:";
errorMessage += exception.StackTrace;
WriteEntry(errorMessage, entryType);
if (!QuietTypes.Contains(exception.GetType()))
SendExceptionEmail(errorMessage);
}
This is some VB code we use, it provides enougth info for us to diagnose most problems. Only downside with emailing errors like this is when there is a major failure you can end up with thousands of messages in your mailbox :(
Dim e As Exception
If System.Web.HttpContext.Current.Request.IsLocal Then Exit Sub
e = System.Web.HttpContext.Current.Server.GetLastError
If e IsNot Nothing Then
If TypeOf e Is HttpException Then
Dim he As HttpException = DirectCast(e, HttpException)
If he.GetHttpCode=404 Then
System.Web.HttpContext.Current.Server.ClearError()
Response.Redirect("/")
Exit Sub
End If
End If
MsgBody += "Exception: " & e.Message & vbCrLf & vbCrLf
MsgBody += e.ToString & vbCrLf & vbCrLf & vbCrLf
Else
MsgBody += "Unknown Error" & vbCrLf & vbCrLf & vbCrLf
End If
If System.Web.HttpContext.Current.Request.Url Is Nothing Then
MsgBody += "URL: ?" & vbCrLf & vbCrLf
Else
MsgBody += "URL: " & System.Web.HttpContext.Current.Request.Url.ToString & vbCrLf
If System.Web.HttpContext.Current.Request.RawUrl IsNot Nothing Then MsgBody += System.Web.HttpContext.Current.Request.RawUrl & vbCrLf
MsgBody += vbCrLf
End If
If System.Web.HttpContext.Current.Request.UrlReferrer Is Nothing Then
MsgBody += "Referer: <direct>" & vbCrLf & vbCrLf
Else
MsgBody += "Referer: " & System.Web.HttpContext.Current.Request.UrlReferrer.ToString() & vbCrLf & vbCrLf
End If
If User IsNot Nothing Then MsgBody += "User: " & User.Identity.Name & vbCrLf
MsgBody += "User-Agent: " & System.Web.HttpContext.Current.Request.UserAgent & vbCrLf
MsgBody += "User-IP: " & System.Web.HttpContext.Current.Request.UserHostAddress & vbCrLf
MsgBody += "Server: " & System.Environment.MachineName & vbCrLf
MsgBody += vbCrLf & "RequestType: " & System.Web.HttpContext.Current.Request.RequestType() & vbCrLf & vbCrLf
' dump request items
' QueryString, Form, Cookies, ServerVariables
MsgBody += "Querystring Variables ================" & vbCrLf
If Request.QueryString.Count > 0 Then
For Each key As String In Request.QueryString.Keys
MsgBody += key & " = " & Request.QueryString(key) & vbCrLf
Next
Else
MsgBody += "(none)" & vbCrLf
End If
MsgBody += vbCrLf
MsgBody += "Form Variables =======================" & vbCrLf
If Request.Form.Count > 0 Then
For Each key As String In Request.Form.Keys
MsgBody += key & " = " & Request.Form(key) & vbCrLf
Next
Else
MsgBody += "(none)" & vbCrLf
End If
MsgBody += vbCrLf
MsgBody += "Cookies ==============================" & vbCrLf
If Request.Cookies.Count > 0 Then
For Each key As String In Request.Cookies.Keys
MsgBody += key & " = " & Request.Cookies(key).Value & vbCrLf
Next
Else
MsgBody += "(none)" & vbCrLf
End If
MsgBody += vbCrLf
MsgBody += "ServerVariables ======================" & vbCrLf
If Request.ServerVariables.Count > 0 Then
For Each key As String In Request.ServerVariables.Keys
MsgBody += key & " = " & Request.ServerVariables(key) & vbCrLf
Next
Else
MsgBody += "(none)" & vbCrLf
End If
MsgBody += vbCrLf
' we send MsgBody via email using the System.Net.Mail.MailMessage & System.Net.Mail.SmtpClient classes
' we've handled the error
System.Web.HttpContext.Current.Server.ClearError()
' depending on the error we redirect to our homepage /default.aspx unless that is the faulting page then redirect to static /error.html

Resources