XML axis properties do not support late binding - asp.net

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?

Related

Crystal Report over ASP.Net runtime data source change

Got a script to run crystal report over ASP.Net, export and send to email.
If I use the current database without applying logon everything works but if I change datasource (same database structure but different server) at runtime then the issue below.
Crystal 2008 runtime
ERROR:System.Runtime.InteropServices.COMException (0x80042018): The
table %1 does not exist in the document. at
CrystalDecisions.ReportAppServer.Controllers.DatabaseControllerClass.VerifyTableConnectivity(Object
Table) at
CrystalDecisions.CrystalReports.Engine.Table.TestConnectivity() at
ScriptCodeClass.ApplyLogon(ReportDocument cr, ConnectionInfo ci) at
ScriptCodeClass.Logon(ReportDocument cr, String server, String db,
String id, String pass) at ScriptCodeClass.FunCreatePDFView(String
lsHeader, String lsReportType, String msDatabaseUserId, String
msDatabasePassword)
this code can change authentication but not data source/server, wondering if need a reference or to import.
Imports System.Collections
Imports System.Data
Imports T1.Tb.Data
Imports System.IO
Imports System.Net
Imports System.Net.Mail
Imports T1.Tb
Imports T1.TB.Public
Imports CrystalDecisions.CrystalReports.Engine.ReportDocument
Imports CrystalDecisions.ReportSource
Imports System.Configuration
Imports System.Data.SqlClient
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
References CrystalDecisions.CrystalReports.Engine
References CrystalDecisions.Shared
References System.Web.Services
References System.Data
References T1.Tb.dll
References T1.TB.Public
References T1.P1.dll
References T1.P1.Public
References T1.Tb.Fun
public shared function Logon(cr as ReportDocument, server as string, db as string, id as string, pass as string) as Boolean
'Use this to change the database logon info for a crystal report
dim ci as ConnectionInfo = new ConnectionInfo()
dim subObj as SubreportObject
ci.ServerName = server
ci.DatabaseName = db
ci.UserID = id
ci.Password = pass
if ApplyLogon(cr, ci) then
for each obj as ReportObject in cr.ReportDefinition.ReportObjects
If (obj.Kind = ReportObjectKind.SubreportObject) Then
// if typeof obj.Kind.GetType() is CrystalDecisions.Shared.ReportObjectKind then
subObj = ctype(obj, SubreportObject)
if not ApplyLogon(cr.OpenSubreport(subObj.SubreportName), ci) then
return(false)
end if
end if
next
Logon = True
end if
end function
private shared function ApplyLogon(cr as ReportDocument, ci as ConnectionInfo ) as Boolean
dim li as TableLogOnInfo
dim success as Boolean
for each tbl as Table in cr.Database.Tables
li = tbl.LogOnInfo
li.ConnectionInfo = ci
tbl.ApplyLogOnInfo(li)
'check if logon was successful
'if TestConnectivity returns false, check logon credentials
if tbl.TestConnectivity() then
'drop fully qualified table location
if tbl.Location.IndexOf(".") > 0 then
tbl.Location = tbl.Location.Substring(tbl.Location.LastIndexOf(".") + 1)
else
tbl.Location = tbl.Location 'THIS IS LINE LEFT OUT IN ALL SAMPLES I SAW
end if
else
success = false
exit for
end if
success = True
next
end function
try to build the query as string in code first then pass its results to crystal reports to have the report and send it by email.
steps:
1) build a query string.
2) execute that string and fill a datatable inside a dataset with the results
3) use that dataset / datatable to generate the report in crystal reports
You have several choices:
Add Key(s) in web.config as follow :
<add key="ServerName" value=""/> Name Or IP Address
<add key="DataBaseName" value=""/> Database Name
<add key="DatabaseUser" value=""/>User Name
<add key="DatabasePassword" value=""/>Password
and call these keys in your reportviewer on load or on your event as :
Dim SERVER_NAME As String = ConfigurationManager.AppSettings("ServerName").ToString()
Dim DATABASE_NAME As String = ConfigurationManager.AppSettings("DataBaseName").ToString()
Dim DatabaseUser As String = ConfigurationManager.AppSettings("DatabaseUser").ToString()
Dim DatabasePassword As String = ConfigurationManager.AppSettings("DatabasePassword").ToString()
add your code and login to DB
CrystalReportViewer.SetDatabaseLogon(DatabaseUser, DatabasePassword, SERVER_NAME, DATABASE_NAME)
then add your datasource:
CrystalReportViewer.SetDataSource
Or you can pass it directly through your viewer as follow:
CrystalReportViewer.SetDatabaseLogon("sa", "123", "Your_Server", "YourDB")

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...

Server Control Error: Unknown server tag with ASP.NET

I am trying to get a custom control working in VB ASP.Net
I've read a few threads but it doesn't seem to help me much.
I have a solution including:
Website project called "SiteCI"
Class Library project called "SiteCI-classes"
The website project has a reference to the library project, and the library DLL are correctly generated inside the bin folder of the website project.
When I create a random class within the website project, I can access to my test control class called MailLink by typing:
SiteCI_classes.Controls.MailLink
It works perfectly, Visual Studio suggests it to me, so the link between the two projects are correctly set.
Please note that I clean/rebuild the project every time to see if it really works or not, so that's not a problem of incorrect DLL build.
In the Web Config file inside system.web -> pages -> controls I have added:
<add assembly="SiteCI-classes" namespace="Controls" tagPrefix="custom" />
But on a ASP.Net page when I add:
<custom:MailLink runat="server" id="test1"></custom:MailLink>
I am getting the Unknown server tag 'custom:MailLink' error.
To check if I did not make a mistake while typing in the web config file I tried to change the SiteCI-classes to SiteCI_classes and I got an error saying that it wasn't able to load the assembly, so I guess that part is OK, and then I tried to change namespace="Controls" in *namespace="SiteCI_classes.Controls"* or namespace="SiteCI-classes.Controls" and it didn't fix the unknown server tag issue.
I don't know what to do... it's supposed to work, isn't it?
Here is the MailLink.vb that is located in a folder called Controls of the Library project. It's a class I picked on a Microsoft page just for testing purpose.
I would be very grateful if anyone could give me a tip on what to check.
Namespace Controls
< _
AspNetHostingPermission(SecurityAction.Demand, _
Level:=AspNetHostingPermissionLevel.Minimal), _
AspNetHostingPermission(SecurityAction.InheritanceDemand, _
Level:=AspNetHostingPermissionLevel.Minimal), _
DefaultProperty("Email"), _
ParseChildren(True, "Text"), _
ToolboxData("<{0}:MailLink runat=""server""> </{0}:MailLink>") _
> _
Public Class MailLink
Inherits WebControl
< _
Bindable(True), _
Category("Appearance"), _
DefaultValue(""), _
Description("The e-mail address.") _
> _
Public Overridable Property Email() As String
Get
Dim s As String = CStr(ViewState("Email"))
If s Is Nothing Then s = String.Empty
Return s
End Get
Set(ByVal value As String)
ViewState("Email") = value
End Set
End Property
< _
Bindable(True), _
Category("Appearance"), _
DefaultValue(""), _
Description("The text to display on the link."), _
Localizable(True), _
PersistenceMode(PersistenceMode.InnerDefaultProperty) _
> _
Public Overridable Property Text() As String
Get
Dim s As String = CStr(ViewState("Text"))
If s Is Nothing Then s = String.Empty
Return s
End Get
Set(ByVal value As String)
ViewState("Text") = value
End Set
End Property
Protected Overrides ReadOnly Property TagKey() _
As HtmlTextWriterTag
Get
Return HtmlTextWriterTag.A
End Get
End Property
Protected Overrides Sub AddAttributesToRender( _
ByVal writer As HtmlTextWriter)
MyBase.AddAttributesToRender(writer)
writer.AddAttribute(HtmlTextWriterAttribute.Href, _
"mailto:" & Email)
End Sub
Protected Overrides Sub RenderContents( _
ByVal writer As HtmlTextWriter)
If (Text = String.Empty) Then
Text = Email
End If
writer.WriteEncodedText(Text)
End Sub
End Class
End Namespace
I found the problem which seem to have ONLY been caused by the dash ("-") in the name of the Project.
The name of the project is still "SiteCI-Classes" BUT the final code of the WebConfig is different:
<add assembly="SiteCIClasses" namespace="SiteCI2KClasses.Controls" tagPrefix="cc1" />
Note the difference between the two. ASP.Net 3.5 will not recognize a dash in the name of a project and seem to remove it: if you try to set it to SiteCI-Classes it will end up with an error like assembly not found.

Sending CSV created on the fly back to client for download

I'm converting a bunch of FOXPRO / FOXWEB apps to ASP.NET.
The underlying DB is still foxpro (for the moment).
I am passing a table to some VB.NET code that I want to have converted to a CSV file and sent back to the client for download. And it works! Sort of ... It works sometimes, but at other times, instead of asking me if I want to download the CSV file, it just spews the file to the browser window.
On the asp side, I am passing the response object, the table and the csv file name.
<%
Dim xls_fn As String = "test01.csv"
'OLEDB call to fill up 'tbl' ... this works.
sendTableAsCSVtoClient(response, tbl, xls_fn)
%>
In the file clsCommon.vb, I have the following code:
Option Explicit On
'Option Strict On
Imports System
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.Page
Imports System.IO
Imports Microsoft.VisualBasic
Imports System.Diagnostics
Imports System.Data
Imports System.Data.OleDb
Public Class clsCommon
Inherits Page
Public Shared Function enq(ByVal str As String) As String
Dim dq As String
dq = """"
Return dq & str & dq
End Function
' some other functions and subs defined in here ... blah blah blah
' ...
Public Shared Function sendTableAsCSVtoClient(ByVal resp As HttpResponse, ByVal sqlTable As DataTable, ByVal xls_fn As String) As Boolean
Dim r As DataRow
Dim c As DataColumn
Dim sep As String = ","
Dim FileExtension As String
Dim lcFileNameONLY As String
Dim i As Integer
Dim dq As String = """"
FileExtension = UCase(Path.GetExtension(xls_fn))
lcFileNameONLY = UCase(Path.GetFileNameWithoutExtension(xls_fn))
resp.Clear()
resp.ClearContent()
resp.ClearHeaders()
resp.ContentType = "application/vnd.ms-excel"
resp.AddHeader("Content-Disposition", "inline; filename=" & lcFileNameONLY & ".csv")
For Each c In sqlTable.Columns
resp.Write(UCase(c.ColumnName) & sep)
Next
resp.Write(vbCrLf)
For Each r In sqlTable.Rows
For i = 0 To sqlTable.Columns.Count - 1
resp.Write(enq(r(i)) & sep)
Next
resp.Write(vbCrLf)
Next
resp.End()
Return True
End Function
End Class
What's causing this?
How do I get around it?
I'm guessing it doesn't really matter that the source of the data is a table.
Note that the file is created on the fly and never exists on the file system of the server.
tx,
tff
Instead of using a Content-Disposition header that is Inline, use Attachment - this will always prompt for a download.
Change the following line from:
resp.AddHeader("Content-Disposition", "inline; filename=" & lcFileNameONLY & ".csv")
To
resp.AddHeader("Content-Disposition", "attachment; filename=" & lcFileNameONLY & ".csv")
See this and this for examples.
The inline type means that the browser is free to render it inline (within the browser), if in knows how to.
And see this SO question, asking why inline sometimes prompts for downloads (the exact opposite of your question...).
The issue is your Content-disposition header. It should be "attachment" instead of "inline".
You may also want to set the content type to be "text/csv"instead of "application/vnd.ms-excel". This way you're more accurate, and if they prefer to use something else for CSV it should work better. However for an in-house app perhaps vnd.ms-excel might work better?
I agree with the Oded and chmullig that you should change the Content-Disposition, but I also recommend using the buffer and finishing the response with a flush:
resp.Clear()
resp.Buffer = true
'build csv
resp.Flush()
resp.Close()
I believe a call to .End() throws a ThreadAbortException to stop execution which can cause issues depending on how you handle your exceptions. See here for more info

How to open varbinary word doc as HTML

I have a problem which I have not been able to find an answer to in months. I store word doc resumes as varbinary(max). I can retrieve the resumes based on a full-text search – no problem. But the resumes are retrieved as word documents in a .ashx file with the following code. I really need to implement hit highlighting on the site so that users can see if the returned resume is a good fit or not. I don’t think this can be done from an .ashx file, so I think I need to be able to open the resume as html in an aspx page and maybe use javascript to do the hit highlighting or perhaps return the text only content of the word document somehow and manipulate the text before display with html tags. I cant find anything anywhere which addresses the problem. I am really hoping that someone can point me in the right direction.
Thanks in advance for any advice.
Imports System.io
Imports System.Web
Imports System.Data
Imports System.Data.SqlClient
 
Public Class ReadResume : Implements IHttpHandler
Const conString As String = "Data Source=tcp:sql2k804.discountasp.net;Initial Catalog=SQL2008R2_284060_resumedata;User ID=SQL2008R2_284060_resumedata_user;Password=mypwd2314;"
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim con As SqlConnection = New SqlConnection(conString)
Dim cmd As SqlCommand = New SqlCommand("Select ResumeDoc, DocTypeExtension From ResumeTable WHERE CandidateId=#CandidateId", con)
Dim CId As String = System.Web.HttpContext.Current.Request.QueryString("Para")
cmd.Parameters.AddWithValue("#CandidateId", CId)
Using con
con.Open()
Dim myReader As SqlDataReader = cmd.ExecuteReader
If myReader.Read() Then
context.Response.Clear()
context.Response.ClearContent()
context.Response.ClearHeaders()
Dim file() As Byte = CType(myReader("ResumeDoc"), Byte())
Dim doc_type As String = CType(myReader("DocTypeExtension"), String)
context.Response.ContentEncoding = System.Text.Encoding.UTF8
context.Response.ContentType = "Application/msword"
context.Response.AddHeader("content-disposition", "Candidate Resume")
context.Response.BinaryWrite(file)
End If
End Using
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
You can use Microsoft Office COM components to deal with Word documents. For example, that is the way to convert Word to HTML: http://rongchaua.net/blog/c-convert-word-to-html/
UPDATE:
There are other solutions.
If you have only .docx (not .doc) documents then you can use this simple code to extract plain text from docx documents: http://www.codeproject.com/KB/office/ExtractTextFromDOCXs.aspx This is the same code: http://conceptdev.blogspot.com/2007/03/open-docx-using-c-to-extract-text-for.html
There are some commercial libraries for reading/writing Word documents:
http://www.aspose.com/categories/.net-components/aspose.words-for-.net/default.aspx
http://www.cellbi.com/Products.aspx

Resources