G.Mich G.Mich - 2 months ago 17
Vb.net Question

Cache return value on web service method (vb)

I want to add cache in all my web methods for a web service. But i don't know the right way to do it ...

Any ideas what can i do for this ? Thanks !

Here is my code ..

Dim _cache As Cache = New Cache()
<WebMethod>
Public Function GetAllSpeakers(SubSite As String, MyUsername As String, MyPassword As String) As String
If ValidateUser(MyUsername, MyPassword) Then

Dim cachedSpeakers As String
cachedSpeakers = CStr(_cache("CacheSpeakers"))

If (cachedSpeakers Is Nothing) Then
Try
Dim passWordEnc As SecureString = New SecureString()
For Each c As Char In Password.ToCharArray()
passWordEnc.AppendChar(c)
Next

Dim subContext As ClientContext = New ClientContext("url")
subContext.Credentials = New SharePointOnlineCredentials(Username, passWordEnc)

Dim json As String = JsonConvert.SerializeObject(LibraryMethods.Methods.GetSpeakers(subContext))

_cache.Insert("CacheSpeakers", json,
Nothing, System.Web.Caching.Cache.NoAbsoluteExpiration,
New TimeSpan(0, 30, 0))

Return json

Catch ex As Exception
Return "ERROR: " & ex.InnerException.ToString
End Try
Else
Return _cache("CacheSpeakers").ToString()
End If
Else
Return "AUTHENTICATION FAILED"
End If
End Function

Answer

I make some changes om my method and now cache working !! I use HttpRuntime.Cache .

<WebMethod>
Public Function GetAllSpeakers(SubSite As String, MyUsername As String, MyPassword As String) As String
    If ValidateUser(MyUsername, MyPassword) Then

        If (HttpRuntime.Cache("CacheSpeakers") Is Nothing) Then
            Try
                Dim passWordEnc As SecureString = New SecureString()
                For Each c As Char In Password.ToCharArray()
                    passWordEnc.AppendChar(c)
                Next

                Dim subContext As ClientContext = New ClientContext("url")
                subContext.Credentials = New SharePointOnlineCredentials(Username, passWordEnc)

                Dim json As String = JsonConvert.SerializeObject(LibraryMethods.Methods.GetSpeakers(subContext))


                HttpRuntime.Cache.Insert("CacheSpeakers", json, Nothing,
                Cache.NoAbsoluteExpiration, New TimeSpan(0, 30, 0),
                CacheItemPriority.NotRemovable, Nothing)

                Return json

            Catch ex As Exception
                Return "ERROR: " & ex.InnerException.ToString
            End Try
        Else
            Return HttpRuntime.Cache("CacheSpeakers").ToString()
        End If
    Else
        Return "AUTHENTICATION FAILED"
    End If
End Function