Property Get Value Based on Condition - asp.net

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

Related

Why does FreeMarkers built-in "?is_string" return true for an Object?

If I pass an Object into the model and test it with the "?is_string" built-in, it will falsely return a true value.
Is it possible (without checking the class name) to have a proper type checks on Objects?
FreeMarker: 2.3.28
Code to reproduce:
public class Test {}
// In Test Controller
ModelAndView mv = new ModelAndView("test");
mv.addObject("test", new Test());
// In test.ftl
<#if test?is_string>
${test} - is a string!
</#if>
// Result
Test#455b31c - is a string
The problem is that that approach isn't really supported by FreeMarker. The Java objects are mapped to some template language values via Configuration.objectWrapper, and the template only sees the result of that mapping. Furthermore the template language has a different type system than Java, a simplistic one, without classes. (It was a design goal back then that the data-model is just some simple tree, and the templates will work no mater what objects are behind, as far as it still gives the same tree.) ?is_... doesn't check the Java type, but the type according the template language. As with the usual ObjectWrapper-s a "generic" object (means, nothing recognized like List, Map, Date, etc.) can be used as a strings whose value is whatever toString() returns, it's a string as far as the template language is concerned. It's kind of duck typed...
A workaround I can think of is that first check the value with ?is_hash, as that will catch the said generic objects (as they support ., they are hashes as well, not just strings). Or instead just check the property you expect to be present in a Test. Then on the "else" branch you can continue with ?is_string.

SonarQube complains about using ResponseEntity with a wildcard

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.

Extend Request.IsSecureConnection property

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.

SPDispose Ignore attribute not ignoring

In my SharePoint code, I have the following line:
SPWeb web = site.RootWeb; //site is an SPSite object
When I rebuild my project and run the SPDispose tool on the assembly, I get the following error:
Module: Blah.SharePoint.Features.Core.dll Method:
Blah.SharePoint.Features.Core.Helpers.FeatureDeploymentHelper.RemoveWebPartFiles(Microsoft.SharePoint.SPFeatureReceiverProperties,System.String)
Statement: web := site.{Microsoft.SharePoint.SPSite}get_RootWeb()
Source:
C:\xxx\xxx\Main\Source\SharePoint\Features\Core\Helpers\FeatureDeploymentHelper.cs
Line: 26
Notes: Disposable type not disposed: Microsoft.SharePoint.SPWeb
***This may be a false positive depending on how the type was created or if it is disposed outside the current scope More Information:
http://blogs.msdn.com/rogerla/archive/2008/02/12/sharepoint-2007-and-wss-3-0-dispose-patterns-by-example.aspx#SPDisposeCheckID_140
What I want to do is to have the SPDispose tool ignore this error, so I have pulled the SPDisposeCheckIgnore class and supporting enum into my project, and I've decorated my method appropriately:
[SPDisposeCheckIgnore(SPDisposeCheckID.SPDisposeCheckID_140, "RootWeb does not need disposed.")]
public static void RemoveWebPartFiles(SPFeatureReceiverProperties properties, string assemblyName)
{
...
}
After doing all of this, I still receive the error. Anyone know how I might go about getting rid of that error?
Two things need to be done here.
1) The SPDisposeCheckIgnore class must be defined in the SPDisposeCheck namespace. You CANNOT have your own namespace. See the related comment on this page: http://archive.msdn.microsoft.com/SPDisposeCheck/
2) Anything you are trying to ignore within RunWithElevatedPrivleges must be pulled into an external method or it will not be recognized. This was not being done in the example above, but was being done in other places.
These two rules must be followed for ignore to work. Hope this helps someone else down the road.
Double check how you're retrieving and assigning the RootWeb object. If it's done in an external method, the DisposeChecker might not pick up that it's a RootWeb reference.
I don't see anything wrong with what you've written. I pulled out getting the root web into a static method so I only had to ignore this error in one place, and it works in anonymous delegates. The following worked for me:
public class DisposeUtils
{
[SPDisposeCheckIgnore(SPDisposeCheckID.SPDisposeCheckID_140, "RootWeb does not need disposed. http://blogs.msdn.com/b/rogerla/archive/2009/11/30/sharepoint-2007-2010-do-not-dispose-guidance-spdisposecheck.aspx")]
public static SPWeb GetRootWeb(SPSite site)
{
return site.RootWeb;
}
}
Sorry, I'm not sure if that helps exactly - I'm saying your code should work. Have you checked SPDisposeCheck to see how it handles 'Documented' and 'Undocumented' errors? (I've never been entirely clear what those settings do)

ASP.NET: Can you use server tags to embed C# or VB.NET expressions into a Javascript function?

I have an enum called SiteTypes that contains several values that are all bound to a dropdown list. On the client side, I need to check this dropdown to see if the selected value is one of those enum values. I don't want to hardcode the value of the enum in the script in case it needs to change, so I want to use a server tag to get it directly from the enum itself. Conecptually, I would like to do this:
function SiteIdChanged() {
var x = "<%=SiteTypes.Employee %>";
}
The way I am doing it now is created a protected property in the codebehind that returns that specific enum value and am doing this:
function SiteIdChanged() {
var x = "<%=EmployeeSiteTypeValue %>";
}
I don't like that, though, because I have to create a special property on every page that I need to do such a check.
Is there a way to do what I want here?
Are you getting a "xxx is inaccessible due to its protection level" error when you compile or run the page? enums are public by default, classes are not. My guess is that you've defined your enum inside your page's class and you aren't explicitly marking it with the 'public' access modifier. Explicitly mark it as public or move it outside of the class and see what happens. If you're planning on using it on lots of pages you should stick the enum definition in in a file in the App_Code folder of your project.
If you don't like your current implementation I would consider using a PageMethod to compare the dropdown selection to the enum value. This approach will probably be cleaner, as you can do most of the logic server-side.
Here's a tutorial on PageMethods:
http://blogs.microsoft.co.il/blogs/gilf/archive/2008/10/04/asp-net-ajax-pagemethods.aspx
As long as your enum is marked public, you can just go with your first option. There's no need to put a property on every single page you want to retrieve the value from.
That approach is really the simplest solution for writing out server side values in your JavaScript.
You can use the Enum.IsDefined Method this well tell you if the selected value from the dropdown is actually part of your enum.
Enum.IsDefined(typeof(MyEnum), myValue)
http://msdn.microsoft.com/en-us/library/system.enum.isdefined.aspx

Resources