ASP Syntax Not Working - asp.net

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>

Related

Need Replacement for MS Index Service on Server 2012 with Classic ASP (VB)

I have just migrated a website from Server 2003 to Server 2012, and MS Indexing service is not available.
In doing some research, I found that MS Search Service is the 'replacement,' and, as such, I installed it on Server 2012. Beyond this, I haven't found what ASP-Classic (VB) code would be necessary to enable the new Search Service to catalog my documents, as Indexing Service did.
Does MS Search Service have the capability and flexibility to catalog and search documents, and return results in the same way that MS Indexing Service did?
Below is an example of the code that currently calls the MS Indexing Service (on the Windows 2003 server):
<%
Dim strQuery ' The text of our query
Dim objQuery ' The index server query object
Dim rstResults ' A recordset of results returned from I.S.
Dim objField ' Field object for loop
Dim objUtility
' Retreive the query from the querystring
strQuery = Request.QueryString("CiRestriction")
if strQuery <> "" then
if Request.QueryString("ExactPhrase") = "Yes" then
strQuery = """" & strQuery & """"
end if
end if
' If the query isn't blank them proceed
If strQuery <> "" Then
' Create our index server object
Set objQuery = Server.CreateObject("IXSSO.Query")
' Set its properties
objQuery.Catalog = "Test_Docs" ' Catalog to query
objQuery.MaxRecords = 75 ' Max # of records to return
objQuery.SortBy = "Rank[d], size"
objQuery.Columns = "Characterization, DocTitle, Directory, Filename, Path, Rank, Size, Vpath, Write"
' Build our Query: Hide admin page and FPSE pages
'strQuery = "(" & strQuery & ")" _
' & " AND NOT #filename = *admin*" _
' & " AND NOT #path *\_vti_*"
' Uncomment to only look for files modified last 5 days
'strQuery = strQuery & " AND #write > -5d"
' To set more complex scopes we use the utility object.
' You can call AddScopeToQuery as many times as you need to.
' Shallow includes just files in that folder. Deep includes
' subfolders as well.
'
Set objUtility = Server.CreateObject("IXSSO.Util")
objUtility.AddScopeToQuery objQuery, "d:\test_shares\test_docs", "deep"
objQuery.Query = strQuery ' Query text
Set rstResults = objQuery.CreateRecordset("nonsequential") ' Get a recordset of our results back from Index Server
' Check for no records
If rstResults.EOF Then
Response.Write "Sorry. No results found."
Else
' Print out # of results
Response.Write "<p><strong>"
Response.Write rstResults.RecordCount
Response.Write "</strong> results found:</p>"
' Loop through results
Do While Not rstResults.EOF
' Loop through Fields
' Pretty is as pretty does... good enough:
%>
<%KSize=formatnumber(rstResults.Fields("size"))
KSize= round(KSize/1024,0)%>
<p>
<%'test below using PoorMansIsNull function%>
<% If PoorMansIsNull(rstResults.Fields("DocTitle")) Or rstResults.Fields("DocTitle")="" Then %>
<%= PathToVpath(rstResults.Fields("filename")) %>
<% Else %>
<font size="3"><%= rstResults.Fields("DocTitle") %></font>
<% End If %>
<br><%= rstResults.Fields("Characterization") %><br>
<font color="#009900"><%= PathToVpath(rstResults.Fields("path")) %> - <%= KSize %>k<br /></font>
</p>
<%
' Move to next result
rstResults.MoveNext
Loop
rstResults.MoveFirst
Response.Write "<pre>"
'Response.Write rstResults.GetString()
Response.Write "</pre>"
End If
' Kill our recordset object
Set rstResults = Nothing
Set objUtility = Nothing
Set objQuery = Nothing
End If
%>
</body>
</html>
<%
Function PathToVpath(strPath)
Const strWebRoot = "d:\test_shares\test_docs\"
Dim strTemp
strTemp = strPath
strTemp = Replace(strTemp, strWebRoot, "\")
strTemp = Replace(strTemp, "\", "/")
PathToVpath = strTemp
End Function
%>
And, the results would be listed, per document (the name of the document, with excerpt from document text, along with title, size), as illustrated below:
Thanks for any leads and/or alternatives.
This example is in fact incorrect. It does not work. The following code:
objRecordSet.Open "SELECT Top 20 " & _
"System.ItemPathDisplay " & _
",System.ItemName " & _
",System.Size " & _
"FROM SYSTEMINDEX", objConnection & _
"WHERE SCOPE='file:E:\MANIF\DAAP\AC'"
Should really use the connection object at the end of the query. Spent a few hours wondering why the WHERE clause was not working.
objRecordSet.Open "SELECT Top 20 " & _
"System.ItemPathDisplay " & _
",System.ItemName " & _
",System.Size " & _
"FROM SYSTEMINDEX " & _
"WHERE SCOPE='file:E:\MANIF\DAAP\AC'", objConnection
This should help all who are having the same difficulty.
I'm facing the same problem. I've found a MS guide about this issue: Querying the Index with Windows Search SQL Syntax.
I've tested this ASP (Classic) code and ran ok:
<html>
<body>
Results<br>
<ol>
<%
Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")
objConnection.Open "Provider=Search.CollatorDSO;Extended Properties='Application=Windows';"
'change directory on scope clause
objRecordSet.Open "SELECT Top 20 " & _
"System.ItemPathDisplay " & _
",System.ItemName " & _
",System.Size " & _
"FROM SYSTEMINDEX" & _
" WHERE SCOPE='file:E:\MANIF\DAAP\AC'", objConnection
objRecordSet.MoveFirst
Do Until (objRecordSet.EOF)
%>
<li>
<strong>Path Display:</strong><%=objRecordSet("System.ItemPathDisplay")%><br>
<strong>Name:</strong><%=objRecordSet("System.ItemName")%><br>
<strong>Size:</strong><%=objRecordSet("System.Size")%><br>
<hr>
</li>
<%
objRecordSet.MoveNext
Loop
objRecordSet.Close
Set objRecordSet = Nothing
objConnection.Close
Set objConnection = Nothing
%>
</ol>
</body>
</html>
Other alternatives:
Try to register asp dll in windows server. For I could see, nobody related success on this approch. See this post;
Create a VM a previous windows version to support your asp. See this MS article.
Hope it could help you.

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.

Copyright text in asp.net view pages

Folks,
Looking for help from the community.
I have to add copyright text in all aspx/ascx/master pages on the top.
The sample copyright text is as follows -
<!-- © 2014 xyz company .. .. . .. ........ ........
.............................
-->
This copyright text needs to be added as comment on the file.
When I try to add this copyright text using powershell/macro, my page encoding gets changed to ANSI. Which intern will trouble or say troubles while merging/checking-in the file. The issue is '©' character.
Option Strict Off
Option Explicit Off
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics
Public Module RecordingModule
Sub IterateFiles()
Dim solution As Solution =
DTE.Solution
For Each prj As Project In solution.Projects
IterateProjectFiles(prj.ProjectItems)
Next
End Sub
Private Sub IterateProjectFiles(ByVal prjItms As ProjectItems)
For Each file As ProjectItem In prjItms
If file.SubProject IsNot Nothing Then
AddHeaderToItem(file)
IterateProjectFiles(file.ProjectItems)
ElseIf file.ProjectItems IsNot Nothing AndAlso file.ProjectItems.Count > 0 Then
AddHeaderToItem(file)
IterateProjectFiles(file.ProjectItems)
Else
AddHeaderToItem(file)
End If
Next
End Sub
Private Sub AddHeaderToItem(ByVal file As ProjectItem)
DTE.ExecuteCommand("view.SolutionExplorer")
If file.Name.EndsWith(".aspx") OrElse file.Name.EndsWith(".ascx") OrElse file.Name.EndsWith(".Master") Then
file.Open()
file.Document.Activate()
AddHeader()
file.Document.Save()
file.Document.Close()
End If
End Sub
Private Sub AddHeader()
Dim cmtHeader As String = "<!-- "
Dim cmtCopyright As String = "Copyright © 2014 xyz company"
Dim cmtFooter As String = " -->"
Dim cmt = "//"
DTE.UndoContext.Open("Header Comment")
Dim ts As TextSelection = CType(DTE.ActiveDocument.Selection, TextSelection)
ts.StartOfDocument()
ts.Text = String.Format(cmtHeader, cmt)
ts.NewLine()
ts.Text = String.Format(cmtCopyright)
ts.NewLine()
ts.Text = String.Format(cmtFooter)
ts.NewLine()
DTE.UndoContext.Close()
End Sub
End Module
Above please file macro code above.
Adding to this, these files have different character encoding - utf-8 and utf-8 with BOM. So I should be able to retain the encoding too.
Please let me know you need more information.
Looks like issue is ©. So I will have to replace this with (c). This is tested OK.

ASP.Net AutoCompleteExtender VB WebMethod not firing - why?

Definitely at my wits end here. This should be simple. In a page to create new user accounts, we have a database with a little of allowable users. To streamline getting the Email address of the new user correct, we want to use an AutoComplete extended textbox.
Now I know that WebMethods are working because I have a cascading-drop-down tied to web methods in another page.
As I'm just starting on this page, the code is simple.
The page itself:
<cc1:ToolkitScriptManager ID="ScriptManager2" runat="server"/>
<p></p> Please enter new user's Email:
<asp:TextBox ID="txtUser" runat="server" />
<cc1:AutoCompleteExtender runat="server" ID="autUser" TargetControlID="txtUser"
ServiceMethod="ScanGALUsers" ServicePath="~/AutoScan.asmx"
MinimumPrefixLength="3" CompletionSetCount="150" /> <p></p>
The .asmx file is simple:
<%# WebService Language="VB" CodeBehind="~/App_Code/VB_Code/AutoScan.vb" Class="AutoScan" %>
The WebMethod:
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class AutoScan
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Shared Function ScanGALUsers(ByVal strPrefix As String, ByVal intMaxCount As Integer) As String()
Dim arlResults As New ArrayList
Dim intCount As Integer
Dim dt As DataTable
Dim colParameters As New SortedList
SysDA.LogDebug("ScanGALUsers called with parameters: " & strPrefix & " and count of " & intMaxCount.ToString)
... Deleted for brevity ...
If intCount > 0 Then
Dim arrResults(intCount - 1) As String
arrResults = arlResults.ToArray(GetType(System.String))
Return arrResults
Else
Return Nothing
End If
End Function
End Class
I'm not even getting to the LogDebug statement. I've used all the same boilerplate code (Inherits, the 'WebService' tags, etc) that worked in the other WebMethod with the appropriate changes to the Class name but this really has me stumped.
What am I missing that I'm not even making it to the method?
Did you ever resolve this issue? Have you tried removing Shared from your WebService declaration? This has worked for me before (and I don't know why!).

Auto Suggested Text Box with concatenated string with LINQ to SQL

I'm creating a text box with auto-suggested. So, it works well. It suggests only first name, but I want it to suggest the full name (first and last name which two different columns). Take a look at the following code behind that worked as expected :
<System.Web.Services.WebMethod()> _
Public Shared Function GetNames(ByVal prefixText As String, ByVal count As Integer) As String()
Dim db As New DemoDataContext()
Return db.Students.Where(Function(n) n.FirstName.StartsWith(prefixText)).OrderBy(Function(n) n.FirstName).Select(Function(n) n.FirstName).Take(count).ToArray
End Function
Here's the mark-up :
<asp:TextBox ID="TextBox1" runat="server" Width="191px"></asp:TextBox>
<cc1:AutoCompleteExtender ID="TextBox1_AutoCompleteExtender" runat="server"
Enabled="True" minimumprefixlength="1" ServiceMethod ="GetNames" TargetControlID="TextBox1">
</cc1:AutoCompleteExtender>
I wrote the following code to try to get the text box to suggest the full name but it didn't work :
Dim query = (From s In db.Students _
Where s.FirstName.StartsWith(prefixText) _
Order By s.FirstName _
Select New With {.Name = s.FirstName & " " & s.LastName}).Take(count).ToArray
Return query
When I build the project it says "Value of type '1-dimensional array of (line 50)' cannot be converted to '1-dimensional array of String' because ' (line 50)' is not derived from 'String'"
Anyboy has a suggestion, please comment. Thank you.
Don't create a new anonymous object with a name attribute that is a string, just return the string itself:
Dim query = (From s In db.Students _
Where s.firstname.StartsWith(prefixText) _
Order By s.firstname _
Select s.firstname & " " & s.lastname).Take(count).ToArray

Resources