How do I create a class method to get the argument from a string input?
string value GetArugmentValueByName (string input, string name)
Example
myInput="code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp6&
client_id=21302922996.apps.googleusercontent.com&
client_secret=XTHhXh1SlUNgvyWGwDk1EjXB&
redirect_uri=https://www.example.com/back&
grant_type=authorization_code";
If I do this
string myGrantType = GetArugmentValueByName(myInput, "grant_type");
the value of myGrantType should equal "authorization_code"
You can use ParseQueryString to parse out the params into a name value collection, then index into that for the param you are looking for.
public string GetArgumentValueByName(string queryString, string paramName)
{
var paramCol = HttpUtility.ParseQueryString(queryString);
return paramCol[paramName] ?? string.Empty;
}
Related
This question already has answers here:
Get property value from string using reflection
(24 answers)
Closed 9 years ago.
I have a method that looks like this:
public string Bid(AdapterRequest adapterRequest)
{
string property = "adapterRequest.Lead.Contact.ZipCode";
string zipCode = ???
}
How can I get the value of adapterRequest.Lead.Contact.ZipCode from the string value?
You can use reflection with recursion:
public string Bid(AdapterRequest adapterRequest)
{
string propertyChain = "Lead.Contact.ZipCode";
string zipCode = ResolvePropertyChain(propertyChain.Split('.').ToList(), adapterRequest) as string;
// ... assuming other logic exists here ...
}
public object ResolvePropertyChain(List<string> propertyChain, object source)
{
object propertyValue = null;
if (source != null)
{
propertyValue = source.GetType().GetProperty(propertyChain[0]).GetValue(source, null);
if (propertyValue != null && propertyChain.Count > 1)
{
List<string> childPropertyChain = new List<string>(propertyChain);
childPropertyChain.RemoveAt(0);
propertyValue = ResolvePropertyChain(childPropertyChain, propertyValue);
}
}
return propertyValue;
}
string zipCode = (string)adapterRequest.GetType().GetProperty(property).GetValue(adapterRequest, null);
Note that this will not work in your case since you have an object herarchy, but you can split the property into parts and get objects one by one and repeat the query for next part on the latest retrieved object - GetType will work on a non null value.
I am returning string Subject from this class now if i want to return two more strings from this class how do i do it??
string Subject;
public string getdata(string EmailFrom,string EmailTo, string EmailComment )
{
{
scom.CommandType = CommandType.StoredProcedure;
try
{
SqlDataReader rdr = scom.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
Subject = rdr["EmailSubject"].ToString();
}
}
return Subject;
You can use 'out' parameters.
var string1 = String.Empty;
var string2 = String.Empty;
public string MyMethod(out string string1, out string string2)
{
string1 = "string1";
string2 = "string2";
}
For more information on this : out (C# Reference)
You could return your own DTO (Data Transfer Object) class.
class MyResult {
string Property1 { get; set;}
string Property2 { get; set;}
}
public MyResult MyMethod(){
var result = new MyResult();
result.Property1 = "string1";
result.Property2 = "string2";
return result;
}
For more information on DTOs : http://en.wikipedia.org/wiki/Data_transfer_object
Use out type parameters in class...
for Example
static void FooClass(out int foo, out int bar)
{
foo= (int)Math.Pow(2, 2);
bar= (int)Math.Pow(3, 2);
}
Also you can use List<String> to get Datareader's value into it and return List collection.
These are the available options for you.
Use ref or out keywords.- Difference between ref and out parameters in .NET
Create a class or struct and return the class or struct from the method
If you are using .Net 4.0+ you can use Tuple class. - http://msdn.microsoft.com/en-us/library/system.tuple.aspx
You can use Tuples to retun multiple parameters back as long as you dont mind the retuned params as tuple.Item1, tuple.Item2, tuple.Item3
public Tuple<string, string, string> GetData()
{
Tuple<string, string, string> tuple = new Tuple<string, string, string>("1",
"cat", "dog");
return tuple;
}
You could create a class/struct with the properties you want to return or you could return an enumaration of strings (e.g. a List<string>)
Create an object such as
public class MailType
{
string _subject=string.empty;
string _string1=string.empty1;
string _string2=string.empty2;
public string Subject
{
get{
return _subject;
}
set{
_subject=value;
}
}
public string String1
{
get{
return _string1;
}
set{
_string1=value;
}
}
public string String2
{
get{
return _string2;
}
set{
_string2=value;
}
}
}
Create an object of this class in your loop, store values in Subject, String1 and String2 properties of the object and return the List from your function: getdata..
You need to define a type that contains 3 fields, representing the information you want to return from the method. Than you change the signature of the method to return the type you defined. From within, you initialize an instance of this type with whatever data you fetched and return it.
Unfortunately, modern OO languages do not support returning two (or more things) from a method in the language level.
I need a filter on the string which takes another string as a parameter, scans first string and removes all appearances of it.
You can use string.Replace which has an overload specifically for this.
var newString = oldString.Replace("foo", string.Empty);
This takes your oldString, finds all occurrences of "foo" and removes them.
This would work
var s = "string";
s = s.Replace("st", string.Empty);
// s == "ring";
Is that not correct?
Use extension methods:
public static class StringExtensions
{
public static string RemoveOccurences(this string s, string occurence)
{
return s.Replace(occurence, "");
}
}
usage:
string s = "Remove all appearances of this and that and those";
s.RemoveOccurences("th");
Using MethodBase, is it possible to get the parameters and their values of the method that's being called?
To be specific, I'm trying to use reflection to create Cache keys. As each method and its parameter list is unique, I thought it'd be ideal to use this as the key. This is what I'm doing:
public List<Company> GetCompanies(string city)
{
string key = GetCacheKey();
var companies = _cachingService.GetCacheItem(key);
if (null == company)
{
companies = _companyRepository.GetCompaniesByCity(city);
AddCacheItem(key, companies);
}
return (List<Company>)companies;
}
public List<Company> GetCompanies(string city, int size)
{
string key = GetCacheKey();
var companies = _cachingService.GetCacheItem(key);
if (null == company)
{
companies = _companyRepository.GetCompaniesByCityAndSize(city, size);
AddCacheItem(key, companies);
}
return (List<Company>)companies;
}
Where GetCacheKey() is defined (roughly) as:
public string GetCacheKey()
{
StackTrace stackTrace = new StackTrace();
MethodBase methodBase = stackTrace.GetFrame(1).GetMethod();
string name = methodBase.DeclaringType.FullName;
// get values of each parameter and append to a string
string parameterVals = // How can I get the param values?
return name + parameterVals;
}
Why do you want to use reflection? In the place where you use your GetCacheKey method you know the values of the parameters. You can just specify them:
public string GetCacheKey(params object[] parameters)
And use like this:
public List<Company> GetCompanies(string city)
{
string key = GetCacheKey(city);
...
this is a great sample for getting parameters from a method:
public static string GetParamName(System.Reflection.MethodInfo method, int index)
{
string retVal = string.Empty;
if (method != null && method.GetParameters().Length > index)
retVal = method.GetParameters()[index].Name;
return retVal;
}
Looking for the same answer right. Besides reflection you can write an Aspect in PostSharp. This will cut any performance impact of using reflection and won't violate any substitution principles.
I have a string value that needs to be converted into my user defined custom type. how to do this, please help me.
public class ItemMaster
{
public static ItemMaster loadFromReader(string oReader)
{
return oReader;//here i am unable to convert into ItemMaster type
}
}
Depending on your type there are two ways that you could do it.
The first is adding a constructor to your type that takes a String parameter.
public YourCustomType(string data) {
// use data to populate the fields of your object
}
The second is adding a static Parse method.
public static YourCustomType Parse(string input) {
// parse the string into the parameters you need
return new YourCustomType(some, parameters);
}
Convert.ChangeType() method may help you.
string sAge = "23";
int iAge = (int)Convert.ChangeType(sAge, typeof(int));
string sDate = "01.01.2010";
DateTime dDate = (DateTime)Convert.ChangeType(sDate, typeof(DateTime));
Create a Parse method on your User Defined Custom type:
public class MyCustomType
{
public int A { get; private set; }
public int B { get; private set; }
public static MyCustomType Parse(string s)
{
// Manipulate s and construct a new instance of MyCustomType
var vals = s.Split(new char[] { '|' })
.Select(i => int.Parse(i))
.ToArray();
if(vals.Length != 2)
throw new FormatException("Invalid format.");
return new MyCustomType { A = vals[0], B = vals[1] };
}
}
Granted, the example provided is extremely simple but it at least will get you started.
First you need to define a format that your type will follow when being converted to a string.
A simple example is a social security number. You can easily describe it as a regular expression.
\d{3}-\d{2}-\d{4}
After that you simple need to reverse the process. The convention is to define a Parse method and a TryParse method for your type. The difference being that TryParse will not throw an exception.
public static SSN Parse(string input)
public static bool TryParse(string input, out SSN result)
Now the process you follow to actually parse the input string can be as complex or as simple as you wish. Typically you would tokenize the input string and perform syntactic validation. (EX: Can a dash go here?)
number
dash
number
dash
number
It really depends on how much work you want to put into it. Here is a basic example of how you might tokenize a string.
private static IEnumerable<Token> Tokenize(string input)
{
var startIndex = 0;
var endIndex = 0;
while (endIndex < input.Length)
{
if (char.IsDigit(input[endIndex]))
{
while (char.IsDigit(input[++endIndex]));
var value = input.SubString(startIndex, endIndex - startIndex);
yield return new Token(value, TokenType.Number);
}
else if (input[endIndex] == '-')
{
yield return new Token("-", TokenType.Dash);
}
else
{
yield return new Token(input[endIndex].ToString(), TokenType.Error);
}
startIndex = ++endIndex;
}
}
For the actual conversion, we would need to see the class structure for. The skeleton for this would look as follows however:
class MyType
{
// Implementation ...
public MyType ConvertFromString(string value)
{
// Convert this from the string into your type
}
}