Migrate Web Services (VS2003) to WCF (VS2010) - ajax

Our site is maintained with VS2003. We converted our solution to VS2010--it is a Web Application Project. It has several Web Services files (.asmx file endings) that we hoped to convert to WCF in two stages, first preserve the function of the asmx files that write back XML documents via AJAX to the client..., and then learn to build AJAX-enabled WCF Services to do the same things.
We have researched the 'Could not create type xxx'-error and the advice varies. We're certain(!!) that having an App_Code folder is not the difference, and that we've named our namespace and class correctly, and that we've decorated the Web Service code correctly, and that we're able to use ASP.Net 2.0 to activate these services, and that we have the application level set correctly in IIS... and we're still not able to get past the error.
Here is our asmx code (we created a test page with ScriptManager control to try to hit this one Web Method, but we never got past the build for the service). You certainly don't need to bother with the actual database pulls, but I left them in anyway:
Imports System
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Web.Script.Services
Imports System.ComponentModel
Imports System.Data.SqlClient
Imports System.Text
Imports System.Uri
Imports System.Xml
Imports System.IO
<WebService([Namespace]:="nsCarousel", Description:="Carousel Web Service Methods")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<System.Web.Script.Services.ScriptService()> _
Public Class Carousel
Inherits WebService
<WebMethod(Description:="Get Dealer Info")> _
Public Function GetDealerInfo(ByVal DID%) As String
Dim s$, sql$, sRequest$, sRequestPathQuery$, sDID$, sAJAX$, sReturn$, sIP$, sWebSite$, sErr$, sDealerSearch$
Dim sXML$, sXMLDealerResults$, sXMLPath$
Dim sUserName$, sGeneralDesc$, sStatusText$
Dim bPost As Boolean
Dim bHaveData As Boolean
Dim ds As DataSet
Dim dasql As SqlDataAdapter
Dim sqldr As SqlDataReader
Dim sqlConn As SqlConnection
Dim sqlCmd As SqlCommand
Dim xdoc As New XmlDocument
Dim xnode As XmlNode
Dim xrefnode As XmlNode
Dim xnewnode As XmlElement
Try
'/ need test of sRequest for reference and use in test just below
bPost = False
sDID = Convert.ToString(DID)
sGeneralDesc = "Dealer Pull"
sqlConn = New SqlConnection(ConfigurationSettings.AppSettings("ConnectionStringLong"))
sqlConn.Open()
'/ new sp to preserve nodes, even when fields are null
'/ get results for individual dealer
sql = "insert into junk(entrydate, sql_stmts) select GetDate(), '" & sDID & "';"
sqlCmd = New SqlCommand(sql, sqlConn)
sqlCmd.ExecuteNonQuery()
sqlCmd.Dispose()
sql = "Select_DRPROByDID_xml " & sDID
sqlCmd = New SqlCommand(sql, sqlConn)
sqldr = sqlCmd.ExecuteReader()
'/ quick test if have data
bHaveData = False
Do While sqldr.Read
If Not (IsDBNull(sqldr("DNum"))) Then
bHaveData = True
End If
Exit Do
Loop
sqldr.Close()
sqldr = Nothing
sqlCmd.Dispose()
sqlCmd = Nothing
'/ s will include a node for NewDataSet -> remove and add nodes for msg based on status
'/ and DealerError
If bHaveData Then
dasql = New SqlDataAdapter(sql, sqlConn)
ds = New DataSet
dasql.Fill(ds)
s = ds.GetXml
sXMLDealerResults = s
dasql.Dispose()
ds.Clear()
dasql = Nothing
ds = Nothing
'/ query the XML doc
xdoc.LoadXml(s)
xnode = xdoc.SelectSingleNode("/NewDataSet/Table")
If (xnode.HasChildNodes) Then
If (sDID.Length > 0) Then
sStatusText = xdoc.GetElementsByTagName("DRStat").Item(0).InnerText
Select Case sStatusText
Case "A"
'/ test next when opportunity exists
'/ set current node at Table
'sXMLPath = "/NewDataSet/Table"
'/ set Table as the current node
'xrefnode = xdoc.SelectSingleNode(sXMLPath)
'xnewnode = xdoc.CreateElement("DealerMsg")
'sStatusText = "Active dealer found."
'xdoc.InsertAfter(xnewnode, xrefnode)
sXMLDealerResults = sXMLDealerResults.Replace("<Table>", "<Table><DealerMsg>Active dealer found.</DealerMsg>")
Case "C"
sXMLDealerResults = sXMLDealerResults.Replace("<Table>", "<Table><DealerMsg>Dealer has been cancelled.</DealerMsg>")
Case "H"
sXMLDealerResults = sXMLDealerResults.Replace("<Table>", "<Table><DealerMsg>Dealer is on hold.</DealerMsg>")
Case Else
sXMLDealerResults = sXMLDealerResults.Replace("<Table>", "<Table><DealerMsg>Dealer status is invalid.</DealerMsg>")
End Select
sXMLDealerResults = sXMLDealerResults.Replace("<Table>", "<Table><DealerError>1</DealerError>")
Else
'/ do nothing
End If
Else
sXMLDealerResults = sXMLDealerResults.Replace("<Table>", "<Table><DealerError>0</DealerError><DealerMsg>Dealer not found.</DealerMsg>")
End If
Else
sXMLDealerResults = "<Table><DealerError>0</DealerError><DealerMsg>Dealer not found.</DealerMsg></Table>"
End If
sXMLDealerResults = sXMLDealerResults.Replace("<NewDataSet>", "")
sXMLDealerResults = sXMLDealerResults.Replace("</NewDataSet>", "")
If (sDID.Length > 0) Then
sXMLDealerResults = sXMLDealerResults.Replace("<Table>", "")
sXMLDealerResults = sXMLDealerResults.Replace("</Table>", "")
Else
sXMLDealerResults = sXMLDealerResults.Replace("<Table>", "<Dealer>")
sXMLDealerResults = sXMLDealerResults.Replace("</Table>", "</Dealer>")
End If
sXML = "<?xml version=""1.0"" ?><DealerFetch>" + sXMLDealerResults.Trim + "</DealerFetch>"
'If sReturn.Trim.Length = 0 Then
' Response.ContentType = "text/xml"
' Response.Write(sXML)
'End If
sqlConn.Close()
sqlConn = Nothing
Return sXML
Catch exp As Exception
sErr = sErr & " " & exp.Message.ToString
End Try
End Function
End Class
Any help would be appreciated. Maybe it's something obvious that will appear to someone here quickly, but it sure is making us fret!!! If you need more info or code, please let us know.

There are tons of good samples and demos how to achieve this.......
Just a few a quick Google search turned up:
Convert existing asmx .net web service to WCF service in .net 3.0/3.5
Convert .asmx file to WCF .svc file to create simple API web service
Migrating a Versionable ASMX Web Service to WCF
I would just search Google for your keywords (ASMX, WCF, Migrate) and you should get tons of links and useful resources.....
As for resources to learn the basics of WCF: there's the MSDN WCF Developer Center which has everything from beginner's tutorials to articles and sample code.
Also, check out the screen cast library up on MSDN for some really useful, 10-15 minute chunks of information on just about any topic related to WCF you might be interested in.

Related

Errors Loading a Network File into a Stream in Classic ASP

I have a Classic ASP website that currently loads PDF files from a local directory and writes them to the Response. I create a stream and use LoadFromFile to pull the data. This has worked well for years, but we now want to delete the local files and pull from a network "\" drive, where all of our .NET sites pull the files from.
We do this in our .NET sites with no problem, but I cannot figure out how to open a network file from Classic ASP and load it into a stream. Nothing I have tried seems to recognize the "\server\directory\file" as a valid path.
So, just to be as clear as possible, this is what we do:
Pull a DocID from the QueryString.
Pass the DocID as a parameter to a SQL proc to pull the path to the file (In the current ASP page it pulls a local path, in .NET it pulls a network path. In our new ASP page it will now pull a network path).
We create a stream and load the file into it (this is the part that does not work in Classic ASP if the path is "\" instead of "D:\").
We change the Response.ContentType to "application/pdf".
We Response.BinaryWrite and Flush the Response.
The result is the page displays the PDF with no indication of the file name or location.
Adding partial code:
' sets the Cache-Control HTTP header to prevent proxy caching
Response.CacheControl = "Private"
Response.Expires = 0
Response.Buffer = True
Response.Clear
sDocID = Request.QueryString("DocID")
sSQL = "exec Get_DocData '" & sDocID & "'"
Set rsDoc = Server.CreateObject("ADODB.RecordSet")
rsDoc.Open sSQL, conn, 3, 1
'
' sPath = \\server\directory\filename.ext
' sFileName = filename.ext
'
sPath = rsDoc.Fields("DocPath").Value
sFileName = rDoc.Fields("DocDescription").Value
rsDoc.Close
Set rsDoc = Nothing
'sPath = Replace(sPath,"\\<svr>\<dir>","Z:")
If sPath <> "" Then
Set oStream = Server.CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1 ' adTypeBinary
oStream.LoadFromFile sPath
Response.ContentType = "application/pdf"
Response.AddHeader "Content-Disposition", "inline; filename=""" & sFileName & """"
Response.Charset = "UTF-8"
Do while not oStream.EOS
Response.BinaryWrite oStream.read(3670016)
Response.Flush
Loop
oStream.Close
Set oStream = Nothing
Else
Response.ContentType = "text/html"
'Response.Write("Invalid Document ID.")
End If
Response.End
Well, I knew I would feel stupid when I figured this out. As Lankymart commented, the LoadFromFile() does support UNC formatted paths, which lead me to suspect the issue was permission-based and not code-based.
Although our ApplicationPool was running under a general account which had permission to the network drives, the site was not. I simply brought up the site in IIS7, clicked on Basic Settings and used the "Connect as..." button to run the site under the same general account. That corrected my issue. Palm-slapping my head.

Google Spreadsheet to SSIS VB Code issue

Requirement:
Convert Google Spreadsheet data to SQL Server through SSIS.
Method:
With help from this website, I'm doing coding in Visual Studio 2015 Community edition. I have prepared Variables, Control Flow, Data Flow and added Script component and the required Google References.
Code pasted in VS as Visual Basic 2015:
Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper
Imports Microsoft.SqlServer.Dts.Runtime.Wrapper
Imports Google.GData.Client
Imports Google.GData.Extensions
Imports Google.GData.Spreadsheets
<Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute> 'Line 15 Error here
<CLSCompliant(False)> 'Line 17 Error here
Public Class ScriptMain
Inherits UserComponent
Dim objListFeed As ListFeed
Public Overrides Sub PreExecute()
MyBase.PreExecute()
Dim objService As SpreadsheetsService
Dim objWorkSheetQuery As WorksheetQuery
Dim objWorkSheetFeed As WorksheetFeed
Dim objWorkSheet As WorksheetEntry
Dim objListFeedLink As AtomLink
Dim objListQuery As ListQuery
Dim bt(0) As Byte
'Create a connection to the google account
objService = New SpreadsheetsService("exampleCo-exampleApp-1")
Me.Log(Variables.strPassword, 0, bt)
Me.Log(Variables.strUserName, 0, bt)
objService.setUserCredentials(Variables.strUserName, Variables.strPassword)
Me.Log("Service: " + Variables.strUserName, 0, bt)
'Connect to a specific spreadsheet
objWorkSheetQuery = New WorksheetQuery(Variables.strKey, "private", "full")
objWorkSheetFeed = objService.Query(objWorkSheetQuery)
objWorkSheet = objWorkSheetFeed.Entries(0)
Me.Log("Spreadsheet: " + objWorkSheet.Title.Text.ToString, 0, bt)
'Get a list feed of all the rows in the spreadsheet
objListFeedLink = objWorkSheet.Links.FindService(GDataSpreadsheetsNameTable.ListRel, Nothing)
objListQuery = New ListQuery(objListFeedLink.HRef.ToString())
objListFeed = objService.Query(objListQuery)
Me.Log("ListFeed: " + objListFeed.Feed.ToString, 0, bt)
End Sub
Public Overrides Sub PostExecute()
MyBase.PostExecute()
End Sub
Public Overrides Sub CreateNewOutputRows()
Dim objRow As ListEntry
For Each objRow In objListFeed.Entries
With Output0Buffer
.AddRow()
.Product = objRow.Elements.Item(0).Value
.Qty = objRow.Elements.Item(1).Value
End With
Next
Output0Buffer.EndOfRowset()
End Sub
End Class
Problem:
Upon pressing Build, I get the following error on Line 15 and 17.
BC32035 VB.NET Attribute specifier is not a complete statement. Use a
line continuation to apply the attribute to the following statement.
Here it says to add a space and underscore following the attribute, however, when I add them they are just automatically removed.
I just created a new script component in a new SSIS package dataflow, and here are the lines between the import block and the Class declaration:
' This is the class to which to add your code. Do not change the name, attributes, or parent
' of this class.
<Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute> _
<CLSCompliant(False)> _
Public Class ScriptMain
Inherits UserComponent
I have never heard of the situation you describe where the underscores just "disappear", but maybe if you paste these lines over your lines it will work.
If not, you may need to copy your code to the clipboard, and then destroy the script component and create a new one, and paste your code into it.

WMI Scripting issues displaying multiple drive info

Please note that I am a newbie in WMI, have been researching this issue for most of the day, and even though there are hundres of posts, I am struglling to find any help on this specific problem.
Experiencing an issues using Win32_DiskDrive - Caption and also name functions:
When I execute the VB.script:
Try
Dim connection As New ConnectionOptions
connection.Username = userNameBox.Text
connection.Password = passwordBox.Text
connection.Authority = "ntlmdomain:ms1"
Dim scope As New ManagementScope( _
"\\ms1\root\CIMV2", connection)
scope.Connect()
Dim query As New ObjectQuery( _
"SELECT * FROM Win32_DiskDrive")
Dim searcher As New ManagementObjectSearcher(scope, query)
For Each queryObj As ManagementObject in searcher.Get()
Console.WriteLine("-----------------------------------")
Console.WriteLine("Win32_DiskDrive instance")
Console.WriteLine("-----------------------------------")
Console.WriteLine("Caption: {0}", queryObj("Caption"))
Next
it correctly lists the 5 harddrives that I have in the server i am querying.
But when I execute it in asp.net (vb) it lists only the 1 drive.
Dim query4 As New ObjectQuery("Select * from Win32_DiskDrive")
Dim searcher4 As New ManagementObjectSearcher(scope, query4)
For Each queryObj3 As ManagementObject In searcher4.Get()
'Availability
' text15.Text = queryObj3("Name")
text16.Text = queryObj3("Caption")
Next
My resuls are bountd to a textfield, formatted to wrap and multiline.
Regards
Louis van Rooyen
It seems you overrwrite text16.Text again and again, so the result in the end would be the information of the last device only.
Try concatenating the string instead:
' TODO: Use proper string formating instead of simpy string concatenating '
text16.Text = text16.Text & queryObj3("Caption")

unable to upload the pdf document in .net 2.0 and getting exception error

I have developed a application where i am uploading the PDF files and binding it to Gridview. I can upload less size files like up to 3.5MB after that i can not upload PDF file as i get error message like "Server Error in '/STAT' Application. Runtime Error" or "Page can not be displayed (while testing in local system)"
Technologies used :
vs 2005
.net 2.0 and it is web application.
I have pasted the code below which i wrote :
Protected Sub btnUploadSTPI_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUploadSTPI.Click
Try
If txtStpiRegNo.Text <> "" Then
If txtfilepathSTPI.Value <> "" Then
Dim objDS As DataSet
Dim UploadFile, UploadPath, strFile, sUploadPath, sUploadfilename As String
Dim arr As Array
UploadFile = txtfilepathSTPI.Value
UploadPath = UploadFile.LastIndexOf("\") + 1
strFile = UploadFile.Substring(UploadPath)
sUploadPath = System.Configuration.ConfigurationSettings.AppSettings("UploadTempFile").ToString()
arr = strFile.Split(".")
strFile = CType(arr(0).ToString() + "_" + txtStpiRegNo.Text + "_" + System.DateTime.Now.Second.ToString() + "." + arr(1).ToString, String)
sUploadfilename = sUploadPath + strFile
txtfilepathSTPI.PostedFile.SaveAs(sUploadfilename)
objDS = Session("TempDS")
If objDS.Tables.Count > 1 Then
Dim objRow As DataRow
objRow = objDS.Tables(1).NewRow()
objRow.Item("UploadFileName") = arr(0).ToString()
objRow.Item("UploadFilePath") = strFile
objRow.Item("CompanyID") = ddlCompany.SelectedValue
objRow.Item("CompanyDocuments") = "STPI REG NO - " + txtStpiRegNo.Text
objDS.Tables(1).Rows.InsertAt(objRow, objDS.Tables(1).Rows.Count + 1)
dgCompanyFiles.DataSource = objDS.Tables(1)
dgCompanyFiles.DataBind()
Session("TempDS") = objDS
End If
Else
lblError.Text = "Please select a file to upload."
End If
Else
lblError.Text = "Please enter STPI REG No."
End If
Catch ex As Exception
End Try
End Sub
Even I tried tracking the application and it is not going to the particular button event after browsing the file and clicking on the Upload button for larger file size more then 3.5MB..
Error Message :
Server Error in '/STAT' Application.
Runtime Error
Description: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.
Details: To enable the details of this specific error message to be viewable on remote machines, please create a tag within a "web.config" configuration file located in the root directory of the current web application. This tag should then have its "mode" attribute set to "Off".
First, you need to edit web.config to enable viewing errors. The method for doing this is displayed in the reported error itself.
Second, you need to allow larger upload file sizes:
<configuration>
<system.web>
<httpRuntime maxRequestLength="xxx" />
</system.web>
</configuration>

Crystal Reports TestConnection Fails

I have a Crystal Reports app that I am loading through VS2010. I have the CR Runtime 13.0.2 loaded on my machine. When I run the app using debug, it works fine. (Great in fact.) But when I install the application that is built (even on the VERY same dev machine.) the TestConnection line comes back false, which indicates to me that it's not connecting properly to my database.
If I don't put this code in there, the app prompts for login credentials at THIS line:
Me.CrystalReportViewer1.ReportSource = reportDocument1
But the DB Name and Server Name are incorrect and grayed out, and anything that I put in UserName and PW doesn't work.
I've searched google and tried any number of "fixes" and NOTHING gets it to work.
I also used database expert to "update" my datasource, and ran a "verify database" from design mode and still the same thing happens.
Here is my code:
Private Function ConnectReport(sDatabaseFile As String, _serverName As String, ReportDocument1 As ReportDocument)
ReportDocument1.SetDatabaseLogon("sa", "sqlAdmin2008", _serverName, sDatabaseFile, True)
For x As Integer = 0 To ReportDocument1.DataSourceConnections.Count - 1
ReportDocument1.DataSourceConnections(x).SetConnection(_serverName, sDatabaseFile, "sa", "sqlAdmin2008")
Next
For Each cTable As Table In ReportDocument1.Database.Tables
If cTable.Name <> "Command" Then
SetTableConnectionInfo(cTable, sDatabaseFile, _serverName)
End If
Next
For Each obj As ReportObject In ReportDocument1.ReportDefinition.ReportObjects
If obj.Kind = ReportObjectKind.SubreportObject Then
Dim subReport As SubreportObject = CType(obj, SubreportObject)
Dim subReportDocument As ReportDocument = ReportDocument1.OpenSubreport(subReport.SubreportName)
ConnectReport(sDatabaseFile, _serverName, subReportDocument)
End If
Next
End Function
Private Function SetTableConnectionInfo(cTable As Table, sDatabaseFile As String, _serverName As String)
Dim logonInfo As TableLogOnInfo = cTable.LogOnInfo
Dim connInfo As ConnectionInfo = New ConnectionInfo()
connInfo.DatabaseName = sDatabaseFile
connInfo.ServerName = _serverName
connInfo.UserID = "sa"
connInfo.Password = "sqlAdmin2008"
'connInfo.Type = ConnectionInfoType.SQL
logonInfo.ConnectionInfo = connInfo
cTable.ApplyLogOnInfo(logonInfo)
If cTable.TestConnectivity = False Then
Throw New ApplicationException("Cannot connect Crystal Reports to Database.")
End If
cTable.Location = sDatabaseFile & "." & "dbo" & "." & cTable.Location
End Function
It would seem to me that you need to pass the table in as a reference like this.
Private Function SetTableConnectionInfo(ref cTable As Table, sDatabaseFile As String, _serverName As String)

Resources