Removing the class name before calling a custom function? - asp.net

I have a function for getting a string to have only the first letter to be uppercase.
public class Class1
{
public static string UppercaseFirst(string s)
{
// Check for empty string.
if (string.IsNullOrEmpty(s))
{
return string.Empty;
}
// Return char and concat substring.
return char.ToUpper(s[0]) + s.Substring(1).ToLower();
}
}
Example:
string MyName = "john";
string result = Class1.UppercaseFirst(MyName)
Result: "John"
Is it possible to remove the "Class1." before the call to the function?

Make it an extension method then you can call it like "john".UppercaseFirst();
You just need to declare your class as static and change the signature to the following
public static string UppercaseFirst(this string s)
{...

You could write an extension method:
public static class StringExtension
{
public static string UppercaseFirst(this string text)
{
// ..
}
}
Then you can use it like this:
string uppercase = "myText".UppercaseFirst();

Only if you call the static method from inside the same Class1. If you call it from outside the class you'll need the Class1 specifier.
However, if you make it an extension method in a static class, you can call it directly on all strings.

Related

Easy way to access POJO properties in groovy?

I'm new to groovy and still learning my way around. Is there an easy way to get POJO property values in groovy using dot notation? For example, I have the following POJO:
public class MyPOJO {
protected String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
In groovy, I would like to get the value of the name field as follows:
def doSomething (MyPOJO mpj) {
def name = mpj.name
// do something
}
The above does not work. I know that i could still use java getters and setters, but I would like to be able to get to a point where I can dynamically pull pojo values like so:
def doSomething (MyPOJO mpj, String propertyName) {
def propertyValue = mpj.'${propertyName}'
// do something
}
I'm trying to avoid using java reflection. Thanks for the help!
Michal - apologies... the first code snippet was working, the second wasn't.
stempler - that worked! this was gnawing on me. corrected snippet:
def doSomething (MyPOJO mpj, String propertyName) {
def propertyValue = mpj."${propertyName}"
// do something
}

What is the use of return this["key"]?

This is an simple Scenario , i totally understand the first code of set & get.
private string exampleValue;
public string Example
{
get { return this.exampleValue ; }
set { this.exampleValue = value ; }
}
How is it differ from this code :
public string Example
{
get
{
return this["Example"].ToString();
}
}
It is an Indexer property.
You can define your own indexers in a class. For example, here is a string indexer.
class myClass
{
...
public object this[string name]
{
get
{
... implement code here to retrieve the object that correspond to your string index
}
set
{
... implement code here to store the object that correspond to your string index
}
}
}
Indexers are not limited to string or integer. For example, the Dictionary object uses a generic Indexer:
public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, ...
...
public TValue this[TKey key] { get; set; }
Also, the Session and Application objects in ASP.NET uses a string indexer.

Page object Class got more methods

I have written Page object class for Login page to test UI look & feel for web, iphone & tablet. For each verification I have written a method to return cssValue or text for that element.
Writing that increases lot method defined in a single class. Is there any way to reduce no of methods declared in a page object class?
Example:
public String getBannerCssValue(String cssValue){
return getCssValue(driver.findElement(banner), cssValue);
}
public String getSmartPhoneLegendText(){
return getElementText(driver.findElement(smartPhoneLegend));
}
public String getSmartPhoneLegendCssValue(String cssValue){
return getCssValue(driver.findElement(smartPhoneLegend), cssValue);
}
public String getTabletLegendText(){
return getElementText(driver.findElement(tabletLegend));
}
public String getTabletLegendCssValue(String cssValue){
return getCssValue(driver.findElement(tabletLegend), cssValue);
}
public String getButtonTextValue(){
return getAttribute(driver.findElement(login), "value");
}
public String getSubmitButtonCssValue(String cssValue){
return getCssValue(driver.findElement(login), cssValue);
}
public String getForgotPasswordCssValue(String cssValue){
return getCssValue(driver.findElement(forgotYourPassword), cssValue);
}
public String getTabButtonTextValue(){
return getAttribute(driver.findElement(tabletSubmit), "value");
}
I think you should be guided by the way you'll actually use these getters.
In my code, I often read a number of controls into a single object: user data on the page gets read into a User object. So I have a single getter for that.
In other contexts, where I don't have (or need) an object, I have individual getters for individual controls.
Are there setters for some or all of these getters? If so, consider merging a getter/setter pair into a single function. I've written about this on my blog:
Getters and Setters

asp.net mvc custom attributes

I am trying to create a custom attribute in mvc to use it's parameters in a view as breadCrumb.
well, this is the code of the attribute
[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
public class BreadCrumbAttribute : Attribute {
public BreadCrumbAttribute(string title, string parent, string url) {
this._title = title;
this._parent = parent;
this._url = url;
}
#region named parameters properties
private string _title;
public string Title {
get { return _title; }
}
private string _url;
public string Url {
get { return _url; }
}
private string _parent;
public string Parent {
get { return _parent; }
}
#endregion
#region positional parameters properties
public string Comments { get; set; }
#endregion
}
this is the call of the attribute
[BreadCrumbAttribute("tile", "parent name", "url")]
public ActionResult Index() {
//code goes here
}
this is a way of how I'd like to get the values. (this is a partial view)
System.Reflection.MemberInfo inf = typeof(ProductsController);
object[] attributes;
attributes = inf.GetCustomAttributes(typeof(BreadCrumbAttribute), false);
foreach (Object attribute in attributes) {
var bca = (BreadCrumbAttribute)attribute;
Response.Write(string.Format("{0}><a href={1}>{2}</a>", bca.Parent, bca.Url, bca.Title));
}
Unfortunately, the attribute didn't get call with the way I implement it. Although, If I add the attribute in Class instead of an Action method it worked.
How could I make it work?
Thanks
The problem is that you are using reflection to get the attributes for the class, so naturally it does not include attributes defined on the action method.
To get those, you should define an ActionFilterAttribute, and in the OnActionExecuting or OnActionExecuted method, you can use filterContext.ActionDescriptor.GetCustomAttributes() method (MSDN description here).
Note that with this solution, you will likely have two different types of attributes: The first one is the one you wrote, to define the breadcrumbs. The second is the one that looks at the attributes on the executing action and builds up the breadcrumb (and presumably adds it to the ViewModel or sticks it in HttpContext.Items or something).

How do i get the requestmapping value in the controller?

In the controller , i have this code,
somehow, i want to get the request Mapping value "search".
How is it possible ?
#RequestMapping("/search/")
public Map searchWithSearchTerm(#RequestParam("name") String name) {
// more code here
}
If you want the pattern, you can try HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE:
#RequestMapping({"/search/{subpath}/other", "/find/other/{subpath}"})
public Map searchWithSearchTerm(#PathVariable("subpath") String subpath,
#RequestParam("name") String name) {
String pattern = (String) request.getAttribute(
HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
// pattern will be either "/search/{subpath}/other" or
// "/find/other/{subpath}", depending on the url requested
System.out.println("Pattern matched: "+pattern);
}
It seems you are looking for the path that this request has matched, then you can directly get it from servlet path
#RequestMapping("/search/")
public Map searchWithSearchTerm(#RequestParam("name") String name, HttpServletRequest request) {
String path = request.getServletPath();
// more code here
}
Having a controller like
#Controller
#RequestMapping(value = "/web/objet")
public class TestController {
#RequestMapping(value = "/save")
public String save(...) {
....
}
}
You cant get the controller base requestMapping using reflection
// Controller requestMapping
String controllerMapping = this.getClass().getAnnotation(RequestMapping.class).value()[0];
or the method requestMapping (from inside a method) with reflection too
//Method requestMapping
String methodMapping = new Object(){}.getClass().getEnclosingMethod().getAnnotation(RequestMapping.class).value()[0];
Obviously works with an in requestMapping single value.
Hope this helps.
#RequestMapping("foo/bar/blub")
public Map searchWithSearchTerm(#RequestParam("name") String name, HttpServletRequest request) {
// delivers the path without context root
// mapping = "/foo/bar/blub"
String mapping = request.getPathInfo();
// more code here
}
For Spring 3.1 and above you can use ServletUriComponentsBuilder
#RequestMapping("/search/")
public ResponseEntity<?> searchWithSearchTerm(#RequestParam("name") String name) {
UriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentRequest();
System.out.println(builder.buildAndExpand().getPath());
return new ResponseEntity<String>("OK", HttpStatus.OK);
}

Resources