I'm actually not sure if this is possible in VB.NET, but I am trying to extend the built in property Request.IsSecureConnection.
I am using SSL offloading on a reverse proxy so all connections hitting the node would always return false for Request.IsSecureConnection. My own extension would check the HTTP_X_FORWARDED_PROTO first then fallback to the standard method if the header is not present.
Here's what I have so far, but when I set a breakpoint in here this block never gets hit. I'm sure for a very good reason.. just not sure what that reason is?
Module Extensions
<Extension()>
Public Function IsSecureConnection(Request As HttpRequestBase) As Boolean
If HttpContext.Current.Request("HTTP_X_FORWARDED_PROTO") <> "" Then
Dim https As String = HttpContext.Current.Request("HTTP_X_FORWARDED_PROTO")
If https.ToLower = "on" Then
Return True
Else
Return False
End If
Else
Return Request.IsSecureConnection '<< Not sure here how I would reference the .net framework class without looping back into this function?
End If
End Function
End Module
EDIT:
The reason I want to intercept this property rather than write my own custom method is because a library I am dependent on is referencing this property and I cannot override this.
MSDN says that:
An extension method will never be called if it has the same signature
as a method defined in the type.
https://msdn.microsoft.com/en-GB/library/bb383977.aspx
So I suspect you cannot achieve what you want using extension methods.
Related
I use SpringBoot for REST web services development and SonarQube for static analysis.
I have a few endpoints in my application that look the following way:
#PostMapping
ResponseEntity<?> addSomething(#RequestBody Some object) {
// some code there
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
SonarQube complains about using ResponseEntity with a wildcard, reporting me a Critical issue "Generic wildcard types should not be used in return parameters".
I wonder if I should disable this verification in SonarQube or come up with something different for return type for these cases.
What do you think about it?
#PostMapping
ResponseEntity<Object> addSomething(#RequestBody Some object) {
// some code there
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
This will also remove the error. It is still very generic, but it is one of the solutions if you want to return different types based on the outcome. For instance:
#PostMapping
ResponseEntity<Object> addSomething(#RequestBody Some object) {
//Will return ResponseEntity<> with errors
ResponseEntity<Object> errors = mapValidationService(bindingResult);
if (!ObjectUtils.isEmpty(errors)) return errors;
// some code there
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
So actually i find the rule pretty self describing:
Using a wildcard as a return type implicitly means that the return value should be considered read-only, but without any way to enforce this contract.
Let's take the example of method returning a "List". Is it possible on this list to add a Dog, a Cat, ... we simply don't know. The consumer of a method should not have to deal with such disruptive questions.
https://sonarcloud.io/organizations/default/rules#rule_key=squid%3AS1452
So Actually in your case, you do not want any kind of Class in there, you specifically want an Serializable-object - for obvious reasons: it should be serialized later on
So instead of using ? it would be more suitable in your case to use Serializable. This is always case dependent, but normally you definitly expect some kind of common interface or base class as a return value. Hence that, the follow up developer, definitly knows what he can expect, and what kind of functionality he definitly can use.
Finally I've removed <?> from return value, so the code looks like the following now:
#PostMapping
ResponseEntity addSomething(#RequestBody Some object) {
// some code there
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
SonarQube doesn't complain anymore and code seems a little bit simpler now.
I want to create a class that returns a path in a string based on a Boolean. For instance, I have a property called ErrorLog. If the current environment is development, the string returned for the property is "C:\LogFiles\AppLogs\ErrorLogs" and in production, the string returned would be "D:\LogFiles\AppLogs\ErrorLogs"
I can determine the environment in a method and return a boolean - I just don't know how to return the correct path. I have been looking at conditional properties, but am not sure this is the best method.
You should look at Web.config transformations since you are using VS 2010. With this you can set up the path to the log file in the appSettings section and have it automatically changed to the appropriate value when you deploy your app to Production.
There's a very complete example here.
You can use this
protected String ErrorLog
{
get {return YourMethodThatReturnTrueIfDevelopment() ? "C:\LogFiles\AppLogs\ErrorLogs" : "D:\LogFiles\AppLogs\ErrorLogs";}
set {ErrorLog = value;}
}
Define the Get method, returning a Bool that eval which enviroment is, and then use the ternary operator to return one or another string.
Anyway, this is how to do what you ask; I recommend (after seeing) the Icarus' answer
I have some web pages that include other pages, and I need to check if a variable (a string) has been declared in the page or not.
I was exploring try catch and finally, but im always getting a compiler error saying the variable doesnt exits.
syntax in my head is:
if variable(exists) then
do something
else
do nothing
end if
From what im finding is this wont even compile if the variable wasnt defined anywhere. I kinda knew that, I was just hoping to find some kind of work around. :/
The only way I know of is to use reflection...
This will not work for variables defined within subs/functions...
Friend Function VariableExists(ByVal variableName As String) As Boolean
For Each tField As FieldInfo In Me.GetType.GetFields
If tField.Name.ToLower() = variableName.ToLower() Then
Return True
End If
Next
Return False
End Function
Cose here is untested and may contain minor errors. Think of it more like pseudocode.
Instead of declaring a variable, how about adding a simple Interface that you can use in the pages that need to be processed a specific way, then you can test whether or not the page implements the Interface?
For example:
Public Interface IMySpecialInterface
End Interface
In the pages that you want special behavior for:
Public Page MySpecialPage
Implements IMySpecialInterface
End Page
In the code that processes the pages:
If TypeOf Me.Page Is IMySpecialInterface Then
What about using an interface:
Public Interface ISpecialProp
Property SpecialProp() As String
End Interface
Then you can test, if a class implements the interface or not using this code:
Dim spec = TryCast(obj, ISpecialProp)
If spec IsNot Nothing Then
Console.WriteLine(spec.SpecialProp)
End If
Working on an ecommerce site which will be integrated with a 3rd party vendor--that vendor uses different identifiers for stores than we use internally (i.e. their store ABC123 is our 001-321).
I'm researching the best approach to inspect incoming requests for reserved query-string parameters that indicate the request is using their identifiers and map the identifiers back to our identifiers (so if the request is example.com/&theirId=ABC123 I want to transform the request to example.com/&ourId=001-321).
To do this mapping I need to inspect the provided ID, execute a lookup against the database or cache, and forward the request to the specified page--limiting the modifications to just the query-string parameters (other parameters will need to be maintained, as with the details of the HTTPHeader, etc).
So far I'm researching a few different approaches:
Implementing it in a base Page (which already does too much, but has the benefit of our Logging infrastructure and some other injected dependencies)
Implementing it in an IHttpModule
Using URL Rewriting
Using URL Routing (looks like routing isn't what I want, feel free to offer insight if you think it still fits)
Performance cost is a consideration: the actual number of times this translation will occur will be very small compared to the number of requests not requiring it--perhaps 1%.
However for another integrated site we will perform this mapping on nearly every request--would a different approach be better suited to this scenario from the previous?
This is a classic case where a HTTP module makes the most sense--you wish to dive into the URL handling on all requests. Perf-overhead-wise you shouldn't have that much of an issue presuming you can short-circuit things correctly and avoid doing DB/cache lookups where you don't need.
Configuration-wise, you should already have to solve the problem of deploying and managing your configuration, so I doubt if another custom module adds much overhead.
Code-wise, its generally better to favor composition over inheritance--you can add or remove the module as required--but having code statically included into a bloated base page class can create more challenges.
I have implemented something similar to this as a base page class for my aspx pages, but as you mentioned a module would work as well. In my opinion, if this functionality is needed across all pages I would just crate a base class only because maintaining another http-module is more of a pain because it needs to be mapped in your web config / iis. Url rewriting is cpu intensive and may not provide you the flexibility you need - again it just adds another configuration / iss dependency. I don't think either of these are going to incur much overhead as long as you implement some sort of caching.
Hope this helps...
Enjoy!
I usually create a Singleton class to hold the site's request context, and store it in the HttpContext.Current.Items(). I initialize this class in the Application_BeginRequest routine.
Imports System.Web
Public Class SiteContext
Private _viewId As Int32
Private _tab As String
Private _action As String
Private Sub New()
_viewId = -1
_tab = String.Empty
_action = String.Empty
FillContext()
End Sub
Public Shared Function Instance() As SiteContext
' gets the site specific context for the current request
If HttpContext.Current.Items("RequestContext") Is Nothing Then
HttpContext.Current.Items("RequestContext") = New SiteContext
End If
Return HttpContext.Current.Items("RequestContext")
End Function
' fill the request context with site specific items
Private Sub FillContext()
' iterate through all items passes via the querystring and save values to matching key property names
For i As Int16 = 0 To _context.Request.QueryString.Count - 1
Dim qryItem As String = _context.Request.QueryString.Keys.Item(i)
Select Case qryItem
Case "v", "view", "viewid", "vid" ' VIEW ID
If IsNumeric(_context.Request.QueryString(qryItem)) AndAlso CType(_context.Request.QueryString(qryItem), Double) < 10000 Then
_viewId = CType(_context.Request.QueryString(qryItem), Int32)
End If
Case "tab" ' TAB ID; secondary parameter to choose sub view
_tab = _context.Request.QueryString(qryItem)
Case "action" ' ACTION ID; tertiary parameter to choose sub-sub view
_action = _context.Request.QueryString(qryItem)
Case Else
End Select
Next
End Sub
Public Property ViewId() As Int32
Get
Return _viewId
End Get
Set(ByVal Value As Int32)
If Value < 1 Then
Value = 1
End If
_viewId = Value
End Set
End Property
Public Property Tab() As String
Get
Return _tab
End Get
Set(ByVal Value As String)
_tab = Value.Trim
End Set
End Property
Public Property Action() As String
Get
Return _action
End Get
Set(ByVal Value As String)
_action = Value.Trim
End Set
End Property
End Class
I need to find a way to detect if a request is a callback when the Application_BeginRequest method is called.
Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)<br />
Dim _isCallBack As Boolean = False
' Code to set _isCallBack is True or False Here
If Not _isCallBack Then
'... Some Code
End If
End Sub
I need to know what to replace "[Code to set _isCallBack is True or False Here]" with.
This may help you:
http://msdn.microsoft.com/en-us/magazine/cc163941.aspx
Search for the word __CALLBACKID:
To determine the callback mode, the ASP.NET runtime looks for a __CALLBACKID entry in the Request collection. If such an entry is found, the runtime concludes that a callback invocation is being made.
We needed to do this from within an app_code file where access to the Page.xxxx objects was not available. This is the code I ended up using:
If Not IsNothing(HttpContext.Current.Request("__CALLBACKID")) Then
'The request is a callback
Else
'The request is not a callback
End If
Maybe not the prettiest solution, but it does the job. We were using Array.IndexOf for a while, but it seems that sometimes that form parameter arrives back as lowercase parameter (not sure why or how), and Array.IndexOf is a case sensitive search.
Be careful looking for these kinds of __XXXX request keys. I remember reading somewhere that it's not a good idea to "shortcut" to these elements since their names could change in some future version of .net. Just keep that in mind!
I needed something similar and, following on Dean L's answer, figured .NET itself must know what to do. Looking in the HttpResponse.Redirect method with Reflector, you see code like this:
Page handler = Context.Handler as Page;
if (handler != null && handler.IsCallback)
{
//Code...
}
Seems to work fine in Global.asax.
Depends on the context of your question. I see you are talking about ASP.NET in the tags, using VB.NET. You can probably use:
If Not Request.IsPostback Then
' Your code here
End If