reflection with stacktrace / stackframe to get both methods name and parameters - c#

while writing the question subject I came across
some other allmost related post ...leading to MSDN
http://msdn.microsoft.com/en-us/library/system.reflection.parameterinfo.aspx
but i couldn't manage to extract the bit of code i needed
i just learnd how to get method name with a helper method based on st and sf as following :
public void setLogView(View ViewMode)
{
AAdToAppLog();
Lview_AH_AutomationLog.Sorting = SortOrder.Ascending;
ColumnHeader ColHeadRowNo = new ColumnHeader();
ColumnHeader ColHeadFunction = new ColumnHeader();
ColumnHeader ColHeadContent = new ColumnHeader();
ColumnHeader ColHeadTime = new ColumnHeader();
Lview_AH_AutomationLog.View = ViewMode;
Lview_AH_AutomationLog.Columns.Add(ColHeadRowNo);
Lview_AH_AutomationLog.Columns.Add(ColHeadFunction);
Lview_AH_AutomationLog.Columns.Add(ColHeadContent);
Lview_AH_AutomationLog.Columns.Add(ColHeadTime);
ColHeadRowNo.Text = "#";
ColHeadFunction.Text = "Function Name";
ColHeadContent.Text = "Content";
ColHeadTime.Text = "Time";
ColHeadRowNo.Width = 45;
ColHeadFunction.Width = 150;
ColHeadContent.Width = 150;
ColHeadTime.Width = 100;
}
public void AAdToAppLog(string FunctionOutPut = "N/A")
{
string t = DateTime.Now.ToString("mm:ss.ff");
string h = DateTime.Now.ToString("HH");
ListViewItem FirstCell= new ListViewItem();
FirstCell.Text =h+":" +pre0Tosingle_9(LogCounter.ToString());//Another helper puts 0 infront <=9 digits
Lview_AH_AutomationLog.Items.Insert(0, FirstCell);
StackTrace st = new StackTrace();
StackFrame sf = st.GetFrame(1);
string FunctionName = sf.GetMethod().ToString().Replace("Void", "").Replace("System.Windows.Forms.", "");
FirstCell.SubItems.Add(FunctionName);
FirstCell.SubItems.Add(FunctionOutPut);
FirstCell.SubItems.Add(t);
LogCounter++;
}
so in every method i want i just put the
AddToAppLog()
that method contains my call to AddToAppLog() and then reports(Via ListView) the name of method and i just added the time of the call.
there's two things i would like to address in this post , about my implementation of that helper metod :
the "FunctionName" i recive from sf.GetMethod is nice that it throws the type of the Parameter of a given Method i liked the idea , only that it is containing parameter.type's Father + Grandfather + Great-Grandfather, but i would like only the bottom Type :
System.Windows.Forms.View
this is one of the shortest (: and i tried to get to View by it self via playing with .Replace()
so is there anothere way to strip it down or actually another method in same family that extract it the way i mentiond above or i could use a list containing every possible most-used types and do a foreach with stringReplace?
and more importently , how do i get the Method(parameterName) as well ?
thanks alot in advance !!
can someone Show An easy to comprehend , Simple syntax Example
of getting parameters name ?

The crux of this is the line that involves sf.GetMethod(); if you instead store that:
var method = sf.GetMethod();
string name = method.Name;
var parameters = method.GetParameters();
you have access to the full signature, and note that the .Name is just the simple name - not the full declaring type-name, etc. You can of course access method.DeclaringType.Name if you want more context. Note that you can only get the declaration of the parameters; you can't get their values via any normal mechanism.
However!!! I will also observe that all this has a performance cost associated with reflection and stack-walking. If you have the C# 5 compiler, you may prefer:
public void AAdToAppLog([CallerMemberName] string callerName = "")
{ ... }
which means that the compiler will supply the name of the caller voluntarily (as a constant geneated in the IL) - no need to either supply it, or go walking the stack to figure it out. You cannot, however, get the parameters like this.

Related

How to add encounter using Fhir R4 by c#

I've tried add new encounter but it shows "System.NullReferenceException: 'Object reference not set to an instance of an object'". Heare is my code:
private static void AddEncounter()
{
var encount = new Encounter();
encount.Identifier.Add(new Identifier
{
Use = (Identifier.IdentifierUse?)1,
System = "http://www.amc.nl/zorgportal/identifiers/visits",
Value = "tek001"
}) ;
encount.Class = new Coding("http://terminology.hl7.org/CodeSystem/v3-ActCode", "SS", "Lưu trú ngắn hạn");
encount.Status = 0;
encount.Priority = new CodeableConcept("http://terminology.hl7.org/CodeSystem/v3-ActPriority", "R", "routine");
encount.Subject = new ResourceReference("Patient/a07b880381ec44ad8f80743f396c8011/_history/1", "Lâm");
encount.Length.Value = 120;
encount.Length.Unit = "min";
encount.Length.System = "http://unitsofmeasure.org";
encount.Length.Code = "min";
encount.ReasonCode.Add(new CodeableConcept("http://snomed.info/sct", "184004", "Rối loạn nhịp tim rút"));
encount.Hospitalization.PreAdmissionIdentifier.Use = (Identifier.IdentifierUse?)1;
encount.Hospitalization.PreAdmissionIdentifier.System = "http://www.amc.nl/zorgportal/identifiers/pre-admissions";
encount.Hospitalization.PreAdmissionIdentifier.Value = "1598753";
encount.Hospitalization.AdmitSource = new CodeableConcept("http://terminology.hl7.org/CodeSystem/admit-source", "outp", "Khoa ngoại trú");
encount.Hospitalization.DischargeDisposition = new CodeableConcept("http://terminology.hl7.org/CodeSystem/discharge-disposition", "hosp", "Bệnh nhân đã được xuất viện và chăm sóc giảm nhẹ");
Console.WriteLine("Successful");
Console.ReadLine();
}
How can i add an exactly?
Just like you do with creating the Identifier for the Identifier field and the other complex objects for the Class, Priority and Subject fields, you will need to create a Duration for the Length field:
encount.Length = new Duration();
encount.Length.Value = 120;
// etc.
You will have to do this for all of the complex objects you use in your code, so also for the Hospitalization field and the PreAdmissionIdentifier:
encount.Hospitalization = new Encounter.HospitalizationComponent();
encount.Hospitalization.PreAdmissionIdentifier = new Identifier();
// etc.
Another change I would like to advice, is to make use of the values provided in the enum for the identifier use, to make your code more readable and your intention clear:
encount.Hospitalization.PreAdmissionIdentifier.Use = Identifier.IdentifierUse.Official;
It's difficult to say for certain without seeing the entire class but System.NullReferenceException is thrown when trying to access something that has not been instantiated.
encount.Hospitalization is likely a reference to another class which must first be instantiated. Try first creating and instance before accessing (example below).
encount.Length = new Length();
encount.Hospitalization = new Hospitalization();
Note: I'm guessing the class names (Length and Hospitalization) so you may need to adjust for your code. The main idea is that you must create the class (new ...()) before utilizing\accessing.

c# Replace string in a property of a class using linq not working

I am trying to find a specific string in a property of a class and replace it with another string if found. I tried various methods using Linq but I am not able to replace it. In debug mode, when I monitor the object again, the replace command hasn't worked. Please help. Including a sample example below.
class Tryreplace
{
public string ClubName { get; set; }
}
List<Tryreplace> tryreplaces = new List<Tryreplace>();
Tryreplace tryreplace = new Tryreplace { ClubName = "Manchester United FC" };
Tryreplace tryreplace2 = new Tryreplace { ClubName = "Arsenal FC" };
tryreplaces.Add(tryreplace);
tryreplaces.Add(tryreplace2);
Tried 2 ways below, both didn't work...
tryreplaces.ForEach(x => x.ClubName.Replace("Manchester", "Newcastle"));
List<Tryreplace> tryreplaces2 = tryreplaces.Select(x => { x.ClubName.Replace("Manchester", "Newcastle"); return x; }).ToList();
After both, I only see Manchester and not Newcastle.
I would like to see replaced string Newcastle in the objects and not Manchester. Please help!
Have an look at the official Documentation from the String.Replace() Method:
Returns a new string in which all occurrences of a specified string in
the current instance are replaced with another specified string.
So you will need to set the property as shown in the Example:
tryreplaces.ForEach(x => x.ClubName = x.ClubName.Replace("Manchester", "Newcastle"))
String.Replace() Docs from Microsoft
in C# (or most language) string are immutable, mean whenever you are making change to it, it will create another instance of string, but it will not change self variable itself.
Or simply if you want to replace part of the string you need to assign make to original variable.
string name = "Amyn";
name.Replace("A", "#");
Console.WriteLine(name); // it will be still Amyn
name = name.Replace("A", "#"); // its right way
Console.WriteLine(name); // it will display "#myn"
so in your code also you need to assign the variable back.
tryreplaces.ForEach(x => x.ClubName = x.ClubName.Replace("Manchester", "Newcastle"))

address an object by retrieving the ID name of the object from a variable

Good evening,
I am trying to get the following done. I have seen a similar post but it was related with Unity.
Anyway, I am on web forms in asp.net and I have a radiobuttonList with ID="id001"
so on my code behind, I would normally be able to get the selected value by just doing:
string value = id001.SelectedValue
However, in this situation, I don't know the exact ID name, so I have a function that retrieves it. So now I have the variable with the name of the ID. So I want to be able to now, convert the value of that variable in something like this:
string foundid = "id001"
string foundidvalue = id001.SelectedValue
I hope this makes sense.
Thanks in advance for the help.
I am assuming this one is related to your previous question. So, when you found the control, instead of using function to get the fullname, you can do like this:
foreach (Control c in Page.Form.Controls.OfType<RadioButtonList>())
{
if (c.ID.Contains("id"))
{
// string FullID = c.ID.ToString();
var radioButtonList = c as RadioButtonList;
var selectedValue = radioButtonList.SelectedValue;
}
}
You want to use FindControl.
string foundid = "id001";
var foundCtrl = (RadiobuttonList)FindControl(foundid);
var result = foundCtrl.SelectedValue;

how to insert a new notes document in the domino server with c# and the usage of interop.domino.dll?

This is my first question here.
I want to know the syntax to insert a new notes document in the lotus notes database if it is not existing using c#.
I have a code in vb script bit I do not know about vb script and lotus notes.
set doc = vw.GetDocumentByKey(empno)
if doc is nothing then
set doc = db.CreateDocument
doc.Form = "EmployeeRepository"
doc.Employno = empno
doc.FirstName = fname
doc.LastName = lname
doc.Group = grp
doc.Department = dept
doc.officeemailaddress = officemail
doc.officegeneralline = officegenline
doc.designation = desig
doc.officeaddress = officeadd
else
doc.FirstName = fname
doc.LastName = lname
doc.Group = grp
doc.Department = dept
doc.officeemailaddress = officemail
doc.officegeneralline = officegenline
doc.designation = desig
doc.officeaddress = officeadd
end if
call doc.save(true, true)
How can I achieve this in c#?
The C# syntax for the if statement is different. Instead of this:
if doc is nothing then
...
else
...
end if
You will need
if (doc != null)
{
...
}
else
{
...
}
Also, the C# language does not support shorthand notation doc.item = X. So the assignments in that format in the above code need to be changed to use the ReplaceItemValue method. I.e., instead of this:
doc.Form = "EmployeeRepository"
doc.Employno = empno
doc.FirstName = fname
doc.LastName = lname
you need to use this:
doc.ReplaceItemValue("Form","EmployeeRepository");
doc.ReplaceItemValue("Employno",empno);
doc.ReplaceItemValue("FirstName", fname);
doc.ReplaceItemValue("LastName", lname);
I might also suggest trying an ExpandoObject (although I haven't tried that yet, but I'm about to give it a go). It's a dynamic type so you have to be careful with how you create it, but you could keep adding additional properties to it without having to instantiate them directly:
dynamic noteDocument = new System.Dynamic.ExpandoObject();
noteDocument.ShortName = "wonkaWillie";
noteDocument.Comment = "No Comment";
noteDocument.MailSystem = "Other";
noteDocument.PowerLevel = "It's over NINE THOUSAND!!!!!";
I suppose you could just as easily (and probably be a little tighter of a solution) to have a pre-formatted class ready for the occasion of adding data into a specific document format too though.
So the ExpandoObject method works, but using a class with explicitly declared fields / properties is much cleaner....you can pass in an instance of a class to a method that performs this pretty handily:
class NotesDocumentItemClass
{
public string Form {get; set;} = "Person";
public string FullName {get; set;} = "Over 9000/Notes/Address/Or/Whatever";
}
and then pass an instance of that class into a method like.....
private bool AddEntry(NotesDatabase db, NoteDocumentItemClass d)
{
NotesDocument newDoc = db.CreateDocument();
doc.ReplaceItemValue("Form", d.Person);
doc.ReplaceItemValue("FullName", d.FullName);
return newDoc.Save();
}

literal error while working with c# asp.net/ wf

I made a drag-and-drop workflow, and got an Literal error while passing an object through the INargument. Any ideas how I can get around this error?
error: 'Literal': Literal only supports value types and the immutable type System.String. The type System.Object cannot be used as a literal.
I've seen some answers, but all the examples are in hard-coded workflows, and I don't want rewrite the whole workflow in hard-code.
WorkflowActivitycheckdb ActEmail = new WorkflowActivitycheckdb {
EmailList = AdminsToList,
EmailContent = tolist,
UserName = name,
UnApprovedS = UnApproved,
NumberOfUsers = tel,
NumberOfAdmins = tel2
};
WorkflowInvoker.Invoke(ActEmail);
please help.
WorkflowActivitycheckdb ActEmail = new WorkflowActivitycheckdb {
EmailList = new InArgument<Whateveryourobjectis>( x=> AdminsToList),
EmailContent = tolist,
UserName = name,
UnApprovedS = UnApproved,
NumberOfUsers = tel,
NumberOfAdmins = tel2
};
WorkflowInvoker.Invoke(ActEmail);
gl
You could try writing that particular line outside the object initializer.
Eg :
ActEmail.EmailList = AdminsToList;
Make the EmailList class immutable.

Categories

Resources