Click here to Skip to main content
15,895,011 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all ,

I am using a shared web method and it is necessary to be shared.In this webmethod iam reading an html document into a string and replacing some values.But the visual studio is telling me : Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.

And here is my code :Note(input and output are strings).

VB
<system.web.services.webmethod()> Public Shared Function GetItems() As String
        If System.IO.File.Exists(filePath) Then

            input = File.ReadAllText(filePath)
        End If
        Dim da As New DSGardlecTableAdapters.PartnersTableAdapter
        Dim dt As New DSGardlec.PartnersDataTable
        Dim dr As DSGardlec.PartnersRow
        dt = da.GetActivePartnersListSorted
        dr = dt.Rows(3)
        output = input.Replace("<%a%>", "/DynamicImages/Partners/thumbnails/" & dr.Partner_Image)
        output = output.Replace("<%Partener_Name%>", dr.Partener_Name)
        output = output.Replace("<%Partener_Link%>", dr.Partener_Link)
        Return output.ToString
    End Function


So how can i call the strings and the filepath through there classes. ?

Thanks in advance.
Posted
Updated 4-Jun-21 12:38pm

0) Why are you defining a web method as "shared". That's kinda pointless.

1) There's no reason for input and output vars to be defined outside of the method.

2) Create a static class (module in VB?) that contains the static GetItems() method.
 
Share this answer
 
Comments
mhamad zarif 21-Sep-11 14:14pm    
I defined the input and output inside the function and they are working well.But still the filepath is not working,since it is using server.mappath:

Dim filePath As String = Server.MapPath("~/HtmlTemplates/PartnersTemplate.htm")
use this

Public Shared myFilepath As String = HttpContext.Current.Server.MapPath("~/folder/filename")
 
Share this answer
 
Comments
Dave Kreskowiak 4-Jun-21 19:37pm    
I seriously doubt the OP is still looking for an answer 10 years later.
Richard Deeming 7-Jun-21 12:46pm    
Aside from the age of this question, your solution is both wrong and dangerous. You cannot control when a shared field will be initialized. It could be outside of any request to your application, in which case, HttpContext.Current will return Nothing, and your type initializer will throw a NullReferenceException.

Once that's happened, any attempt to use your class will fail with the same exception. You will have to restart your application to clear the error, and hope that it doesn't happen a second time.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900