What's wrong with my ASP.NET / Visual Basic code? - asp.net

I'm new to ASP.NET / Visual basic. I'm trying to create a simple get request to get the data from the database. But whenever the page loads, I get a generic 500 server error code in the console. Here is my ASP.NET code:
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<script>
var dataSource = new kendo.data.DataSource({ transport: {
read: {
url: "/webservices/alertService.asmx/GetAlert",
dataType: "json"
},
update: {
url: "/webservices/alertService.asmx/UpdateAlert",
dataType: "json"
}
}});
var alertObj = dataSource.read();
console.log("alertObj: ", alertObj);
var pageBody = document.getElementById('page-body');
pageBody.innerHTML = "<h1>Website alert page is currently being built...</h1><br/>" +
"<p>" + alertObj.alert_title + "</p><br/>" +
"<p>" + alertObj.alert_body + "</p><br/>"
</script>
<div id="page-body"></div>
</asp:content>
Here is my Visual Basic code:
<%# WebService Language="VB" Class="MapService" %>
Imports System
Imports System.IO
Imports System.Security
Imports System.Configuration
Imports System.Xml
Imports System.Web
Imports System.Web.Script.Serialization
Imports System.Web.Script.Services
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Diagnostics
Imports System.Xml.Serialization
Imports MySql.Data.MySqlClient
Imports System.Data
Imports System.Data.Odbc
Imports System.Data.SqlClient
Imports System.Data.Sql
Imports System.Collections.Generic
Imports Newtonsoft.Json
Imports System.Net.Http
<System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class MapService
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Sub GetAlert()
Dim xmlString As String = ""
Try
Dim sConnString As String = ConfigurationManager.ConnectionStrings("WebApp").ConnectionString
Dim odbcConn As OdbcConnection = New OdbcConnection(sConnString)
Dim sQueryString As String = "SELECT * FROM tblalert WHERE alert_id = 1"
Dim DBCommand As New OdbcCommand(sQueryString, odbcConn)
odbcConn.Open()
Try
Dim odbcReader As OdbcDataReader = DBCommand.ExecuteReader(CommandBehavior.CloseConnection)
While odbcReader.Read()
xmlString += "{"
xmlString += """alert_id"":""" & Convert.ToInt16(odbcReader("alert_id")) & ""","
xmlString += """alert_title"":""" & Trim(odbcReader("alert_title").ToString) & ""","
xmlString += """alert_body"":""" & Trim(odbcReader("alert_body").ToString) & ""","
xmlString += """show_alert"":""" & Convert.ToInt16(odbcReader("show_alert")) & ""","
xmlString += "}"
End While
odbcReader.Close()
Catch ex As Exception
odbcConn.Close()
End Try
odbcConn.Close()
Catch ex As Exception
End Try
'xmlString = xmlString.Trim().Substring(0, xmlString.Length - 1)
'xmlString = "[" & xmlString & "]"
HttpContext.Current.Response.BufferOutput = True
HttpContext.Current.Response.ContentType = "application/x-javascript"
HttpContext.Current.Response.Write(xmlString)
HttpContext.Current.Response.Flush()
End Sub
What is wrong with my code? Why is the "dataSource.read()" function not getting the data from the VB file?

According to this web-site http://net-informations.com/q/mis/500.html the problem is on your server side. Something isn't configured correctly. Double check the connection string you are using to make sure it is connecting to the right server and then check to make sure the server is running and accessible.

Related

Paypal SDK problems

Goodmornig,
I have some problems with the integration of SDK paypal, I have the IPN that works nice, now I was trying to do the first request, instead of the form client side, the call server side, to be more safe.
I have put in my bin folder Paypal.dll and Newtonsoft.Json.dll then I have configurated the web.config
This is what I have read when I downloaded the Paypal nuget from Visual.
ATTENTION: This package replaces the RestApiSDK package (https://www.nuget.org/packages/restapisdk). You do not need to include the RestApiSdk package in your project if you are using this, the PayPal .NET SDK, package.
The PayPal REST API uses HTTP verbs and a RESTful endpoint structure. OAuth2.0 is used as the API Authorization framework. Request and response payloads are formatted as JSON.
I usually dont use editor, I have downloaded Visual just to get out these dll.
Then I have copied them inside my Web ASP.NET application.
<configSections>
<section name="paypal" type="PayPal.SDKConfigHandler, PayPal" />
</configSections>
<!-- PayPal SDK settings -->
<paypal>
<settings>
<add name="mode" value="live" />
<add name="connectionTimeout" value="360000"/>
<add name="requestRetries" value="1"/>
<add name="clientId" value="xxx" />
<add name="clientSecret" value="yyy" />
</settings>
</paypal>
And then I have translated the c#.net script sample to vb.net, this is the code
<%# Page Language="VB" Debug="true" aspcompat=true%>
<%# Import Namespace="MySql.Data.MySqlClient" %>
<%# Import Namespace="PayPal.Api" %>
<%
' Initialize an APIContext object with a fresh access token.
' The config will be populated with values set in the Web.config file.
Dim config = ConfigManager.Instance.GetProperties()
Dim accessToken = New OAuthTokenCredential(config).GetAccessToken()
Dim apiContext = New APIContext(accessToken)
Dim abc = Payment.Get(apiContext, "6N135681R73257100")
%>
I have put the ID of the transaction and I have this kind of error
PayPal.HttpException: The remote server returned an error: (404) Not Found.
If I try to do a payment so to do like this
<%# Page Language="VB" Debug="true" aspcompat=true%>
<%# Import Namespace="MySql.Data.MySqlClient" %>
<%# Import Namespace="PayPal.Api" %>
<%
' Initialize an APIContext object with a fresh access token.
' The config will be populated with values set in the Web.config file.
Dim config = ConfigManager.Instance.GetProperties()
Dim accessToken = New OAuthTokenCredential(config).GetAccessToken()
Dim apiContext = New APIContext(accessToken)
' Initialize Payout object
Dim payout = New Payout() With { _
.sender_batch_header = New PayoutSenderBatchHeader() With { _
.sender_batch_id = "batch_" + System.Guid.NewGuid().ToString().Substring(0, 8), _
.email_subject = "You have a payment" _
}, _
.items = New List(Of PayoutItem)({ _
New PayoutItem() With { _
.recipient_type = PayoutRecipientType.EMAIL, _
.amount = New Currency() With { _
.value = "0.99", _
.currency = "USD" _
}, _
.receiver = "shirt-supplier-one#mail.com", _
.note = "Thank you.", _
.sender_item_id = "item_1" _
}, _
New PayoutItem() With { _
.recipient_type = PayoutRecipientType.EMAIL, _
.amount = New Currency() With { _
.value = "0.90", _
.currency = "USD" _
}, _
.receiver = "shirt-supplier-two#mail.com", _
.note = "Thank you.", _
.sender_item_id = "item_2" _
}, _
New PayoutItem() With { _
.recipient_type = PayoutRecipientType.EMAIL, _
.amount = New Currency() With { _
.value = "2.00", _
.currency = "USD" _
}, _
.receiver = "shirt-supplier-three#mail.com", _
.note = "Thank you.", _
.sender_item_id = "item_3" _
} _
}) _
}
' Create the payout
Dim createdPayout = payout.Create(apiContext, False)
%>
I have this kind of error, Did I forgot to copy inside my project anything? How could I fix it? Thank you very much
PayPal.HttpException: The remote server returned an error: (403) Forbidden.

Creating a webservice that accepts XML as a string

I have been trying to create a webservice that needs to allow the client to send thru 3 parameters being Username, Password and XML_In all 3 of type string. This then sends the variables to a Stored procedure which processes the data and returns an XML string which is then returned to the client.
The Stored procedure works 100% but I'm getting an error with the XML being sent thru as a string. From reading up most gave the suggestion of adding <httpRuntime requestValidationMode="2.0"/> and <pages validateRequest="false"> to my web.config which works but that would then apply to my entire site which I dont want at all.
The other suggestion was to place it in the #Page part but that does not apply to a web service as it has no user defined layout. Please see my code below and help. I'm still quite a newbie to .Net thus the reason I'm doing 90% of it in SQL.
The error That gets returned is :
System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client (XML_In="<senddata><settings ...").
at System.Web.HttpRequest.ValidateString(String value, String collectionKey, RequestValidationSource requestCollection)
at System.Web.HttpRequest.ValidateHttpValueCollection(HttpValueCollection collection, RequestValidationSource requestCollection)
at System.Web.HttpRequest.get_Form()
at System.Web.Services.Protocols.HtmlFormParameterReader.Read(HttpRequest request)
at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
here's the code:
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Xml
Imports JumpStart.Framework.Database
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
' <System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://mydomainname.co.za/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class LeadProcessor
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function Lead_Processing(ByVal UserName As String, ByVal PassWord As String, ByVal XML_In As String) As XmlDocument
Dim poDSL As New DSL
Dim Result As String
Dim XML_Out = New XmlDocument()
Result = poDSL.ExecuteProcedure_ExecuteScalar("DECLARE #Result XML " & _
"EXEC [dbo].[APP_InsertLeadFromXML] " & _
"#Username = N'" & UserName & "', " & _
"#Password = N'" & PassWord & "', " & _
"#ParmListXML = '" & XML_In.ToString & "', " & _
"#XMLResult = #Result OUTPUT " & _
"SELECT #Result")
XML_Out.LoadXml(Result)
Return XML_Out
End Function
I agree with CodeCaster comment (new projects - WCF or WebApi).
But if you can't change it now, consider use a XMLDocument as parameter, or an XElemento, or directly, do a Base64 transform of the text, in order to avoid that errors.
Code for your service' client:
your_proxy.Lead_Processing(sUserName, sPassWord, Convert.ToBase64String(Encoding.UTF8.GetBytes(sXML))
Then, in your service, do this
<WebMethod()> _
Public Function Lead_Processing(ByVal UserName As String, ByVal PassWord As String, ByVal XML_In As String) As XmlDocument
Dim oData As Byte() = Convert.FromBase64String(XML_In)
Dim sDecodedXML As String = System.Text.Encoding.UTF8.GetString(oData)
Dim poDSL As New DSL
Dim Result As String
Dim XML_Out = New XmlDocument()
Result = poDSL.ExecuteProcedure_ExecuteScalar("DECLARE #Result XML " & _
"EXEC [dbo].[APP_InsertLeadFromXML] " & _
"#Username = N'" & UserName & "', " & _
"#Password = N'" & PassWord & "', " & _
"#ParmListXML = '" & sDecodedXML & "', " & _
"#XMLResult = #Result OUTPUT " & _
"SELECT #Result")
XML_Out.LoadXml(Result)
Return XML_Out
End Function
Hope it helps
Edit:
Your service with base64.
We're telling that Asmx it's almost a legacy tech. New projects may use WCF tech (I can't teach you WCF in a few lines).
You can put that code into your asmx service. You can use that code in the way I edited my answer.

Switching databases with LINQ to SQL with proper authentication

I'm writing an ASP.NET (VS2013) web app that uses LINQ to SQL. The datacontext is created via the graphical interface and it works great. I need to switch from DEV to INT and then to PROD programmatically.
sounds simple and after reading many, many postings I'm super frustrated.
When I switch to DEV it works because the connection already exists. when I switch to INT it fails but NOT because the authentication but because the the Store Procedure doesn't exist... that makes NO sense...
can anyone please help me with tested statements??? (i already tried lots of "I think...")
----WP_LINQ2SQLDB.DESIGNER.VB----
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Data.Linq
Imports System.Data.Linq.Mapping
Imports System.Linq
Imports System.Linq.Expressions
Imports System.Reflection
<Global.System.Data.Linq.Mapping.DatabaseAttribute(Name:="WorkOrder")> _
Partial Public NotInheritable Class WP_LinQ2SQLDataContext
Inherits System.Data.Linq.DataContext
Private Shared mappingSource As System.Data.Linq.Mapping.MappingSource = New AttributeMappingSource()
#Region "Extensibility Method Definitions"
Partial Private Sub OnCreated()
End Sub
#End Region
Public Sub New()
MyBase.New("", mappingSource)
OnCreated()
End Sub
Public Sub New(ByVal connection As String)
MyBase.New(connection, mappingSource)
OnCreated()
End Sub
etc...
----WP_LINQ2SQLDB.VB----
Inherits System.Data.Linq.DataContext
Private Sub OnCreated()
Dim connectionStr As String = Nothing
Select Case My.Settings.DB_to_Use
Case "DEV"
Case "INT"
connectionStr = "Data Source=SERVER\DBINST;Initial Catalog=CAT_Order;Integrated Security=True;"
Case "PRD"
End Select
Dim DB_TUAcct = My.Settings.DB_TUAcct
Dim DB_TUPwd = My.Settings.DB_TUPwd
connectionStr = connectionStr + "User ID=Domain\blah" + DB_TUAcct.ToUpper + ";Password=" + My.Settings.DB_TUPwd + ";"
----DEFAULT.VB----
' I've tried...
Dim dc As WP_LinQ2SQLDataContext = New WP_LinQ2SQLDataContext(temp)
Dim dc As WP_LinQ2SQLDataContext = New WP_LinQ2SQLDataContext(builder.ConnectionString)
' building a connection string from sql builder
Dim builder2 As IDbConnection = New SqlClient.SqlConnection(temp)
dc.Connection.ConnectionString = builder.ConnectionString
BUT at the end of the day, I cannot make the LINQ to fail because the connection string is bad... and I dont know to fix...

ASP Syntax Not Working

I'm very new to ASP and am trying to figure out how to use some code I found on a site. The code is here:
http://msdn.microsoft.com/en-us/library/bb387090.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1
and is used to convert CSV values into an XML file. I've created an ASP file and copy and pasted the VB script into the file in between <% and %> tags but I get an error when I pull the page up (the page doesn't actually load).
I must be missing some simple syntax? Are those underscores supposed to be at the end of some of the lines? Here is the code that I am referring to:
' Create the text file.
Dim csvString As String = "GREAL,Great Lakes Food Market,Howard Snyder,Marketing Manager,(503) 555-7555,2732 Baker Blvd.,Eugene,OR,97403,USA" & vbCrLf & _
"HUNGC,Hungry Coyote Import Store,Yoshi Latimer,Sales Representative,(503) 555-6874,City Center Plaza 516 Main St.,Elgin,OR,97827,USA" & vbCrLf & _
"LAZYK,Lazy K Kountry Store,John Steel,Marketing Manager,(509) 555-7969,12 Orchestra Terrace,Walla Walla,WA,99362,USA" & vbCrLf & _
"LETSS,Let's Stop N Shop,Jaime Yorres,Owner,(415) 555-5938,87 Polk St. Suite 5,San Francisco,CA,94117,USA"
File.WriteAllText("cust.csv", csvString)
' Read into an array of strings.
Dim source As String() = File.ReadAllLines("cust.csv")
Dim cust As XElement = _
<Root>
<%= From strs In source _
Let fields = Split(strs, ",") _
Select _
<Customer CustomerID=<%= fields(0) %>>
<CompanyName><%= fields(1) %></CompanyName>
<ContactName><%= fields(2) %></ContactName>
<ContactTitle><%= fields(3) %></ContactTitle>
<Phone><%= fields(4) %></Phone>
<FullAddress>
<Address><%= fields(5) %></Address>
<City><%= fields(6) %></City>
<Region><%= fields(7) %></Region>
<PostalCode><%= fields(8) %></PostalCode>
<Country><%= fields(9) %></Country>
</FullAddress>
</Customer> _
%>
</Root>
Console.WriteLine(cust)
I wrapped that in those ASP tags but it didn't work. This is copy and pasted directly from that site because I want to get it working before customizing it for my own use. Thanks for your help!
The code you copied is for a console application. You'll need to do some more (little) work to get it to render in a web page.
The sample is written in VB and takes advantage of xml literals support. The code is written that way to distinguish "in line" code and literals (<%= ...%>). If you check the C# version it'll be apparent.
Trivial Example:
Create your aspx page (vb - so you can still do xml literals)
<%# Page Language="VB" AutoEventWireup="false" CodeFile="csvtoxml.aspx.vb" Inherits="csvtoxml" %>
...boiler plate aspx/web forms HTML stuff....
<body>
<form id="form1" runat="server">
<div>
<p>This is where we will output the XML</p>
<textarea runat="server" id="theXML" cols="70" rows="60"></textarea>
</div>
</form>
In code-behind (xml literals):
Imports System.IO
Partial Class csvtoxml
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.theXML.InnerText = Me.MyFunc()
End Sub
Protected Function MyFunc() As String
Dim csvString As String = "GREAL,Great Lakes Food Market,Howard Snyder,Marketing Manager,(503) 555-7555,2732 Baker Blvd.,Eugene,OR,97403,USA" & vbCrLf & _
"HUNGC,Hungry Coyote Import Store,Yoshi Latimer,Sales Representative,(503) 555-6874,City Center Plaza 516 Main St.,Elgin,OR,97827,USA" & vbCrLf & _
"LAZYK,Lazy K Kountry Store,John Steel,Marketing Manager,(509) 555-7969,12 Orchestra Terrace,Walla Walla,WA,99362,USA" & vbCrLf & _
"LETSS,Let's Stop N Shop,Jaime Yorres,Owner,(415) 555-5938,87 Polk St. Suite 5,San Francisco,CA,94117,USA"
Dim filePath As String = Path.Combine(MapPath("~/"), "cust.csv") 'Just adding this for debug (write permissions) in VS (local rights to file system)
File.WriteAllText(filePath, csvString) 'Note: as above you can't just write on a server filesystem - ensure proper permissions
' Read into an array of strings.
Dim source As String() = File.ReadAllLines(filePath)
Dim cust As XElement = _
<Root>
<%= From strs In source _
Let fields = Split(strs, ",") _
Select _
<Customer CustomerID=<%= fields(0) %>>
<CompanyName><%= fields(1) %></CompanyName>
<ContactName><%= fields(2) %></ContactName>
<ContactTitle><%= fields(3) %></ContactTitle>
<Phone><%= fields(4) %></Phone>
<FullAddress>
<Address><%= fields(5) %></Address>
<City><%= fields(6) %></City>
<Region><%= fields(7) %></Region>
<PostalCode><%= fields(8) %></PostalCode>
<Country><%= fields(9) %></Country>
</FullAddress>
</Customer> _
%>
</Root>
Return cust.ToString() 'Write XElement out to string
End Function
Result
<Root>
<Customer CustomerID="GREAL">
<CompanyName>Great Lakes Food Market</CompanyName>
<ContactName>Howard Snyder</ContactName>
<ContactTitle>Marketing Manager</ContactTitle>
<Phone>(503) 555-7555</Phone>
<FullAddress>
<Address>2732 Baker Blvd.</Address>
<City>Eugene</City>
<Region>OR</Region>
<PostalCode>97403</PostalCode>
<Country>USA</Country>
</FullAddress>
</Customer>
<Customer CustomerID="HUNGC">
...
</root>

XML axis properties do not support late binding

Im having a problem with the XML in this function and many functions like it.
Error
XML axis properties do not support late binding.
Namespace
Imports Microsoft.VisualBasic
Imports System.Web
Imports System.IO
Imports System.Xml.Linq
Function
Public Shared Function get_intro(ByVal root_folder As String) As String
Dim content As String = ""
Dim docXML = XDocument.Load(root_folder & print_shop_doc)
Dim intro_doc = From doc In docXML...<d:printshopdoc> _
Select New With {.intro = doc.<d:intro>.Value}
content = "<p" & no_indent & ">" & intro_doc(0).intro & "</p>" & vbCrLf
Return content
End Function
docXML...<d:printshopdoc>
seems to be where the error is occurring and I'm not quite sure how to fix it.
Does putting an XML namespace declaration Imports <xmlns:d="http://example.com/"> (where instead of http://example.com/ you put the namespace URI used in the input XML) fix the problem?

Resources