Get Parent Class from external .cs file - c#

I have a small Console app where I search for keywords in a large group of .cs files. I now want to follow the inheritance of a subfile to its parent root file. So far I have completed this by using a very noobish method that I don't like.
I think Reflection will be perfect but then I struggle to figure out how to use Reflection on an external file.
Can someone advise me on how I can achieve this?
EDIT:
static string GetParent(string location, string word)
{
string[] file = location.Split(new[] { "\\" }, StringSplitOptions.None);
try
{
using (StreamReader test = new StreamReader(location))
{
while ((line = test.ReadLine()) != null)
{
if (word == "ControlEventStates" && line.Contains(file.Last().ToString().Replace(".cs", "")))
{
string[] a = line.Split(new[] { " ", "(", ")", ";", ".", ",", "<", ">" }, StringSplitOptions.None);
for (int p = 0; p < a.Length; p++)
{
if (a[p] == ":" && a[p + 1] != "FunctionBase")
{
recValue = a[p + 1] + ".cs";
foreach (var item in Frontendfiles)
{
//newlocation = item;
string loc = Path.GetFileName(item);
if (loc == recValue)
{
GetParent(item, word);
}
else if (loc != recValue)
{
FindLine(item, a[p + 1] + " : ");
}
}
}
}
if (location != "" && location != null)
{
//LinesList = FindLine(newlocation, word);
return line;
}
}
}
}
return "";
}
catch (Exception ex)
{
throw ex;
}
}
So as I said this is terrible coding for what I want to accomplish. Basically I search for the line containing the current class name then filtering out the strings to find where the parent file is. Then I use the parent file name to search for its directory and then start the process over again.

Related

How can tell the difference between the link and the footnote using C# ITextSharp?

I have a simple PDF file that has the Link and the Footnote on a page. When I run the annotation check using iTextSharp, both of the links return the sub type as Link. Is there a way to tell the difference between those two items?
I did examine through an intellisence the structure of an annotation dictionary and notice the annotation object dictionary for the Footnote has once extra item, which is named "F", and that item has a value of 4. That item is NOT present at all in the annotation dictionary for the Link. Can I use the 'F' item/parameter as a way to tell the difference between the Link and the Footnote?
Thank you very much in advance
Here is the PDF file
Here is our code
public string AnyPDFCheckComments(string inFileName, string strUsername, string strFilename)
{
string strCommentType = string.Empty;
string strWidgetFound = string.Empty;
string strPageNumber = string.Empty;
string message = string.Empty;
string strComments = string.Empty;
string strCommentsFound = string.Empty;
int intCommentCount = 0;
PdfReader reader = new PdfReader(inFileName);
for (int i = 1; i <= reader.NumberOfPages; ++i)
{
strPageNumber = i.ToString();
PdfDictionary pagedic = reader.GetPageN(i);
PdfArray annotarray = (PdfArray)PdfReader.GetPdfObject(pagedic.Get(PdfName.ANNOTS));
if (annotarray == null || annotarray.Size == 0)
{
continue;
}
// Finding out the links
foreach (object annot in annotarray.ArrayList)
{
PdfDictionary annotationDic = null;
if (annot is PdfIndirectReference)
{
annotationDic = (PdfDictionary)PdfReader.GetPdfObject((PdfIndirectReference)annot);
}
else
{
annotationDic = (PdfDictionary) annot;
}
PdfName subType = (PdfName)annotationDic.Get(PdfName.SUBTYPE);
if ((subType.Equals(PdfName.TEXT)) && (strCommentsVariables.IndexOf("text") != -1))
{
strCommentType = "text";
//break;
}
else if ((subType.Equals(PdfName.LINK)) && (strCommentsVariables.IndexOf("Link") != -1))
{
strCommentType = "Link";
//break;
}
if ((strCommentType != ""))
{
strCommentsFound = "Yes";
intCommentCount = ++intCommentCount;
strComments = strComments + "<BR>" + "A comment type of '" + "<b>" + strCommentType + "</b>" + "' has been found on page no: " + "<b>" + strPageNumber + "</b>";
if (intCommentCount == 5)
{
break;
}
else
{
strCommentType = string.Empty;
}
}
}
}
return strComments;
}
This code worked for us
var footnoteIdentifier = annotationDic.Get(PdfName.F);
if (footnoteIdentifier != null)
{
continue;
}

Get nunit (2.5.10) TestCases with parameters from dll

I got a compiled dll and I need to run every TestCase from this dll seperately with the nunit console tool, one test after the other. To run a TestCase I need to read the name and the parameters of the TestCase from the dll.
I tried reflection, but so far I ran into several problems. Is there a simple way to get the whole TestCase to run it with the nunit console? I heard of the --explore option of nunit3 to get all information of a dll, but unfortunately I have to use the version 2.5.10.
First of all I do not get the amount of methods defined when I try this:
List<MethodInfo> testMethods = new List<MethodInfo>(from type in
assembly.GetTypes()
from method in type.GetMethods()
where method.IsDefined(typeof(TestAttribute)) ||
method.IsDefined(typeof(TestCaseAttribute))
select method);
Afterwards I iterate over the items of the list and try to get the corresponding parameters with "CustomAttributeData.GetCustomAttributes(method)". But every TestCase has a different signature, so its difficult building the form nunit-console wants, like so: methodname(param1,...,paramN)
foreach (CustomAttributeData cad in attributes)
{
String test = method.Name + "(";
String attr = String.Empty;
foreach (CustomAttributeTypedArgument cata in cad.ConstructorArguments)
{
if (cata.Value.GetType() == typeof(ReadOnlyCollection<CustomAttributeTypedArgument>))
{
foreach (CustomAttributeTypedArgument cataElement in
(ReadOnlyCollection<CustomAttributeTypedArgument>)cata.Value)
{
if (cataElement.ArgumentType.Name == "String")
{
String elem = String.Empty;
if (cataElement.Value == null)
{
attr += "null" + ",";
}
else
{
elem = cataElement.Value.ToString().Replace(#"\", #"\\");
//escape quotation marks
attr += #"\" + "\"" + elem + #"\" + "\"" + ",";
}
}
else if (cataElement.ArgumentType.IsEnum)
{
var enumName = cataElement.ArgumentType.Name;
foreach (var fieldInfo in cataElement.ArgumentType.GetFields())
{
if (fieldInfo.FieldType.IsEnum)
{
var fName = fieldInfo.Name;
var fValue = fieldInfo.GetRawConstantValue();
if (cataElement.Value.ToString().Equals(fValue.ToString()))
{
attr += fName + ",";
}
}
}
}
else
{
attr += cataElement.Value + ",";
}
}
}
else if (cata.ArgumentType.IsEnum)
{
var enumName = cata.ArgumentType.Name;
foreach (var fieldInfo in cata.ArgumentType.GetFields())
{
if (fieldInfo.FieldType.IsEnum)
{
var fName = fieldInfo.Name;
var fValue = fieldInfo.GetRawConstantValue();
if (cata.Value.ToString().Equals(fValue.ToString()))
{
attr = fName;
}
}
}
}
else if (cata.Value.GetType() == typeof(String))
{
String elem = String.Empty;
if (cata.Value == null)
{
attr = "null";
}
else
{
elem = cata.Value.ToString().Replace(#"\", #"\\");
attr = #"\" + "\"" + elem + #"\" + "\"";
}
}
else
{
attr = cata.ToString();
}
//do stuff to get form of TestCase
Indeed it needs to be refactored, but I wonder if there is an easier way to get all TestCases and its Parameters.

C# Read a row in a file

Given text file which contains the registration data like a database:
[ID] [Uname] [PW] [Email]
0 Aron asd asd#mail.com
1 Aron2 asdd asd#mail.com
I have the username and the password input.
How would i read only that line in this text file where my uname.Text and password.Text are given?
I agree with all the comments above. With the hypothesis that the file is not huge, you can simply load it all in memory and work on it:
//Load your files in a list of strings
IList<string> lines = File.ReadLines("\path\to\your\file.txt");
//Filter the list with only the pattern you want
var pattern = username + "[ ]{1,}" + password;
Regex regex = new Regex(pattern);
IList<string> results = lines.Where(x => regex.IsMatch(x)).ToList();
Here's a .NET fiddler that shows this.
If anyone have this problem too, this is my solve:
int check=0;
if (txt_uname.Text != "")
{
check = 0;
System.IO.StreamReader file = new System.IO.StreamReader(path);
string[] columnnames = file.ReadLine().Split('\t');
string newline;
while ((newline=file.ReadLine()) != null)
{
string[] values = newline.Split('\t');
if (check== 0){
for (int i = 0; i < values.Length; i++)
{
if (txt_uname.Text == values[i] && txt_pw.Text == values[i + 1])
{
Console.WriteLine("User found");
check= 1;
break;
}
else
{
Console.WriteLine("User isn't exists");
}
}
}
}
Try this:
var username = "Aron2";
var password = "asdd";
List<string> matchedValues; // Contains field values of matched line.
var lines = File.ReadLines("input.txt");
foreach (string l in lines)
{
var values = l.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
if (values.Contains(username) && values.Contains(password))
{
matchedValues = values;
break; // Matching line found. No need to loop further.
}
}

How to check the existence of the file in this file upload function?

I am trying to develop upload file function with security as my programming instructor asked me to do. I implemented it in such a way that it will check the size, file format and the existence of the file. The logic was working well except for checking the existence of the file. For example, when I tried to upload a file which is already existed, I will not get a message telling me that the file is already existed and I don't know why it is not working.
protected void UploadFile(object sender, EventArgs e)
{
if(FileUpload1.HasFile)
try
{
string[] validTypes = { "bmp", "gif"};
string ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
if (size < limit)
{
for (int i = 0; i < validTypes.Length; i++)
{
if (ext == "." + validTypes[i])
{
string path = #"~\Images\";
string comPath = Server.MapPath(path + "\\" + FileUpload1.FileName);
if (!File.Exists(comPath))
{
FileUpload1.PostedFile.SaveAs(comPath);
Label1.Text = "File uploaded";
}
else
{
Label1.Text = "Existed";
}
}
else
{
Label1.Text = "Invalid File." + string.Join(",", validTypes);
}
}
}
else
{
Label2.ForeColor = System.Drawing.Color.Red;
Label2.Text = "file is heavy";
}
}
catch (Exception ex)
{
Label2.Text = "The file could not be uploaded. The following error occured: " + ex.Message;
}
}
When I debugged the code, I found that it will execute the else statement, but instead of displaying it to the user, it will display the message in the outer else statement which is "Invalid File.". Why?
if (ext == "." + validTypes[i])
{
string path = #"~\Images\";
string comPath = Server.MapPath(path + "\\" + FileUpload1.FileName);
if (!File.Exists(comPath))
{
FileUpload1.PostedFile.SaveAs(comPath);
Label1.Text = "File uploaded";
}
else
{
Label1.Text = "Existed";
}
}
else
{
Label1.Text = "Invalid File." + string.Join(",", validTypes);
}
Also, my instructor told me that the following line causes a vulnerability called path traversal.
string path = #"~\Images\";
So how to prevent this security hole? ?Any ideas?
There is logical problem in you code.In the block
for (int i = 0; i < validTypes.Length; i++)
It will always run two time for each file.
What you can do you take a Boolean variable at set it to false.
Go inside the loop and if file found set boolean to true and use break statement.
At the end of loop check for the Boolean value and code accordingly.
Edit-1
Rather than looping through the array you can use like this
string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
int pos = Array.IndexOf(stringArray, value);
if (pos >- 1)
{
// the array contains the string and the pos variable
// will have its position in the array
}
In your case
string[] validTypes = { "bmp", "gif"};
string ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
int pos = Array.IndexOf(validTypes , ext );
if(pos>=0)
{
string path = #"~\Images\";
string comPath = Server.MapPath(path + "\\" + FileUpload1.FileName);
if (!File.Exists(comPath))
{
FileUpload1.PostedFile.SaveAs(comPath);
Label1.Text = "File uploaded";
}
else
{
Label1.Text = "Existed";
}
}
else
{
Label1.Text = "Invalid File." + string.Join(",", validTypes);
}

webbrowser not refreshing stylesheet

I post the complete code below, so you can see what I'm doing.
Situation:
I create a IHTMLDocument2 currentDoc pointing to the DomDocument
I write the proper string
I close the currentDoc
program shows me the html code including the CSS stuff 100% correct. Works
Now I want to change the CSS, instead of 2 columns I set it to 3 columns
(Simply change the width:48% to width:33%)
and rerun the code with the new 33%
now it suddenly doesn't apply any CSS style anymore.
When I close the program, and then change the CSS to 33% again, it works flawless
So, somehow, without disposing the complete webbrowser, I can't load the CSS a 2nd time..
or, the first CSS is somewhere in some cache, and conflicts with the 2nd CSS.. Just riddling here.. really need help on how to solve this
I searched the internet and stackoverflow long enough that I need to post this, even if someone else on this planet already posted it somewhere, I didn't find it.
private void doWebBrowserPreview()
{
if (lMediaFiles.Count == 0)
{
return;
}
Int32 iIndex = 0;
for (iIndex = 0; iIndex < lMediaFiles.Count; iIndex++)
{
if (!lMediaFiles[iIndex].isCorrupt())
{
break;
}
}
String strPreview = String.Empty;
String strLine = String.Empty;
// Set example Media
String strLinkHTM = lMediaFiles[iIndex].getFilePath();
FileInfo movFile = new FileInfo(strLinkHTM + lMediaFiles[iIndex].getFileMOV());
String str_sizeMB = (movFile.Length / 1048576).ToString();
if (str_sizeMB.Length > 3)
{
str_sizeMB.Insert(str_sizeMB.Length - 3, ".");
}
//Get info about our media files
MediaInfo MI = new MediaInfo();
MI.Open(strLinkHTM + lMediaFiles[iIndex].getFileM4V());
String str_m4vDuration = // MI.Get(0, 0, 80);
MI.Get(StreamKind.Video, 0, 74);
str_m4vDuration = "Duration: " + str_m4vDuration.Substring(0, 8) + " - Hours:Minutes:Seconds";
String str_m4vHeightPixel = MI.Get(StreamKind.Video, 0, "Height"); // "Height (Pixel): " +
Int32 i_32m4vHeightPixel;
Int32.TryParse(str_m4vHeightPixel, out i_32m4vHeightPixel);
i_32m4vHeightPixel += 16; // for the quicktime embed menu
str_m4vHeightPixel = i_32m4vHeightPixel.ToString();
String str_m4vWidthPixel = MI.Get(StreamKind.Video, 0, "Width"); //"Width (Pixel): " +
foreach (XElement xmlLine in s.getTemplates().getMovieHTM().Element("files").Elements("file"))
{
var query = xmlLine.Attributes("type");
foreach (XAttribute result in query)
{
if (result.Value == "htm_header")
{
foreach (XElement xmlLineDes in xmlLine.Descendants())
{
if (xmlLineDes.Name == "dataline")
{
strLine = xmlLineDes.Value;
strLine = strLine.Replace(#"%date%", lMediaFiles[iIndex].getDay().ToString() + " " + lMediaFiles[iIndex].getMonth(lMediaFiles[iIndex].getMonth()) + " " + lMediaFiles[iIndex].getYear().ToString());
strPreview += strLine + "\n";
}
}
}
}
}
strLine = "<style type=\"text/css\">" + "\n";
foreach (XElement xmlLine in s.getTemplates().getLayoutCSS().Element("layoutCSS").Elements("layout"))
{
var query = xmlLine.Attributes("type");
foreach (XAttribute result in query)
{
if (result.Value == "layoutMedia")
{
foreach (XElement xmlLineDes in xmlLine.Elements("layout"))
{
var queryL = xmlLineDes.Attributes("type");
foreach (XAttribute resultL in queryL)
{
if (resultL.Value == "layoutVideoBox")
{
foreach (XElement xmlLineDesL in xmlLineDes.Descendants())
{
if (xmlLineDesL.Name == "dataline")
{
strLine += xmlLineDesL.Value + "\n";
}
}
}
}
}
}
}
}
strLine += "</style>" + "\n";
strPreview = strPreview.Insert(strPreview.LastIndexOf("</head>", StringComparison.Ordinal), strLine);
for (Int16 i16Loop = 0; i16Loop < 3; i16Loop++)
{
foreach (XElement xmlLine in s.getTemplates().getMovieHTM().Element("files").Elements("file"))
{
var query = xmlLine.Attributes("type");
foreach (XAttribute result in query)
{
if (result.Value == "htm_videolist")
{
foreach (XElement xmlLineDes in xmlLine.Descendants())
{
if (xmlLineDes.Name == "dataline")
{
strLine = xmlLineDes.Value;
strLine = strLine.Replace(#"%m4vfile%", strLinkHTM + lMediaFiles[iIndex].getFileM4V());
strLine = strLine.Replace(#"%moviefile%", strLinkHTM + lMediaFiles[iIndex].getFileMOV());
strLine = strLine.Replace(#"%height%", str_m4vHeightPixel);
strLine = strLine.Replace(#"%width%", str_m4vWidthPixel);
strLine = strLine.Replace(#"%duration%", str_m4vDuration);
strLine = strLine.Replace(#"%sizeMB%", str_sizeMB);
strLine = strLine.Replace(#"%date%", lMediaFiles[iIndex].getDay().ToString() + " " + lMediaFiles[iIndex].getMonth(lMediaFiles[iIndex].getMonth()) + " " + lMediaFiles[iIndex].getYear().ToString());
strPreview += strLine + "\n";
}
}
}
}
}
}
foreach (XElement xmlLine in s.getTemplates().getMovieHTM().Element("files").Elements("file"))
{
var query = xmlLine.Attributes("type");
foreach (XAttribute result in query)
{
if (result.Value == "htm_footer")
{
foreach (XElement xmlLineDes in xmlLine.Descendants())
{
if (xmlLineDes.Name == "dataline")
{
strPreview += xmlLineDes.Value + "\n";
}
}
}
}
}
webBrowserPreview.Navigate("about:blank");
webBrowserPreview.Document.OpenNew(false);
mshtml.IHTMLDocument2 currentDoc = (mshtml.IHTMLDocument2)webBrowserPreview.Document.DomDocument;
currentDoc.clear();
currentDoc.write(strPreview);
currentDoc.close();
/*
try
{
if (webBrowserPreview.Document != null)
{
IHTMLDocument2 currentDocument = (IHTMLDocument2)webBrowserPreview.Document.DomDocument;
int length = currentDocument.styleSheets.length;
IHTMLStyleSheet styleSheet = currentDocument.createStyleSheet(#"", 0);
//length = currentDocument.styleSheets.length;
//styleSheet.addRule("body", "background-color:blue");
strLine = String.Empty;
foreach (XElement xmlLine in s.getTemplates().getLayoutCSS().Element("layoutCSS").Elements("layout"))
{
var query = xmlLine.Attributes("type");
foreach (XAttribute result in query)
{
if (result.Value == "layoutMedia")
{
foreach (XElement xmlLineDes in xmlLine.Elements("layout"))
{
var queryL = xmlLineDes.Attributes("type");
foreach (XAttribute resultL in queryL)
{
if (resultL.Value == "layoutVideoBox")
{
foreach (XElement xmlLineDesL in xmlLineDes.Descendants())
{
if (xmlLineDesL.Name == "dataline")
{
strLine += xmlLineDesL.Value;
}
}
}
}
}
}
}
}
//TextReader reader = new StreamReader(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "basic.css"));
//string style = reader.ReadToEnd();
styleSheet.cssText = strLine;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}*/
webBrowserPreview.Refresh();
}
I now successfully implemented the berkelium-sharp method to my project
Has the same bug!
Found a solution!
First attempt which didn't work:
I had a persistent form (main form) and inside it a nested WebBrowser.
After changing the html with it's css, i told it to navigate to this new html!
This didn't work either:
Then I tried putting webbrowser on an own form. Which I simply open/close each
time I need a refresh. TO be sure the garbage collector cleans everything
Then I tried the Berkelium and rewrote it to my needs:
same logic as attempt 2 with the webbrowser. No luck either.
So I tried to open firefox itself and see if I can emulate this behaviour with a real browser. Indeed! When I open firefox, and force open the file (if you simply open a new file, firefox doesn't actually navigate to it, but detects this was already opened and simply refreshes it)
I noticed this due to the fast opening of the page!
A little scripting to force opening the same file twice (navigating) in 1 firefox session had the same effect: all CSS corrupt!
so, for some reason, you shouldn't navigate the same file twice, but instead of closing anything, simply force a refresh! Not a "Navigate"
Hope this info can help others, since I lost a lot of time finding out that it is the "navigate" to the same file more then once causing the corruption of stylesheets

Categories