Select an option of a html page - c#

Im trying to get my application to select an option out of a page
If looked on site for some help but could not find anything so some help would be nice
My code:
private void sellCars()
{
HtmlElementCollection elements = this.get_mainframe_tags("img");
IEnumerator enumerator2;
elements = this.get_mainframe_tags("option");
try
{
enumerator2 = elements.GetEnumerator();
while (enumerator2.MoveNext())
{
HtmlElement element2 = (HtmlElement)enumerator2.Current;
Console.WriteLine("Test = " + element2.GetAttribute("value").ToString() + "");
if (element2.GetAttribute("value").ToString() == "sell")
{
Console.WriteLine("Called");
element2.SetAttribute("value", "sell");
}
}
}
finally
{
enumerator2 = elements.GetEnumerator();
if (enumerator2 is IDisposable)
{
(enumerator2 as IDisposable).Dispose();
}
}
}

Related

How can I make an auto injection detector in c#?

I want to make an auto injection scanner in any given website and I have to use c#.
I tried some things that I found online and none of them worked for me, until i find selenium but i keep getting this error message: "OpenQA.Selenium.ElementNotInteractableException: 'element not interactable", and I have no idea why.
I didn't find anything helpful online and I think the problem may be with selenium.
I tried to find SQL, JS and BASH injections, but the script fails when i try to interact with an input. I am using OWASP juice shop to test my code.
This is my code:
static int _crntTypeOfInjection;
const int ESQL = 0, EJS = 1, EBASH = 2;
static public bool IsImportantInput(string type)
{
bool valid = false;
string[] importantTypes = new string[] { "text", "email", "password", "search", "url" };
foreach (string check in importantTypes)
{
if (type == check)
{
return true;
}
}
return false;
}
public static string getCrntInjection()
{
switch (_crntTypeOfInjection)
{
case ESQL:
return "\' OR 1=1;--";
break;
case EBASH:
return "; echo Test";
break;
case EJS:
return "<img src=\"http:\\\\url.to.file.which\\not.exist\" onerror=alert(\"JS injection success\");>";
break;
}
return "defult";
}
static public bool AttackSuccessful(string normalPage, string InjectedPage, string MainUrl, string afterClickUrl)
{
if (afterClickUrl != MainUrl || InjectedPage.Contains("Internal Server Error") || InjectedPage.Contains("JS injection success") || InjectedPage.Contains("Test"))
{
return true;
}
return false;
}
static public void Injection(string url)
{
string InjectedPage = "", NormalPage = "", AfterClickUrl = "";
var driver = new ChromeDriver("C:\\Users\\nirya\\");
driver.Url = url;
Console.WriteLine(driver.PageSource);
Actions a = new Actions(driver);
foreach (var button in driver.FindElements(By.CssSelector("button")))
{
// INJECTED PAGE
a.MoveByOffset(0, 0).Click().Perform();
foreach (IWebElement input in driver.FindElements(By.TagName("input")))
{
Console.WriteLine(input.Text);
Console.WriteLine(input.TagName);
try
{
if (IsImportantInput(input.GetAttribute("type")))
{
input.Click(); // *** HERE IS THE PROBLEM ***
input.Clear();
input.SendKeys(getCrntInjection());
}
}
catch (NoSuchElementException)
{
continue;
}
}
button.Click();
InjectedPage = driver.PageSource;
AfterClickUrl = driver.Url;
driver.Navigate().Back();
// NORMAL PAGE
a.MoveByOffset(0, 0).Click().Perform();
foreach (IWebElement input in driver.FindElements(By.CssSelector("input")))
{
try
{
if (IsImportantInput(input.GetAttribute("type")))
{
input.Clear();
input.SendKeys("normal");
}
}
catch (NoSuchElementException)
{
continue;
}
}
button.Click();
NormalPage = driver.PageSource;
driver.Navigate().Back();
if (AttackSuccessful(NormalPage, InjectedPage, url, AfterClickUrl))
{
// add to database
}
}
}
static void Main(string[] args)
{
Injection("http://localhost:3000/#/login");
}
Is there a problem with my code? Or is there another library that i can use instead?

Display sequence messages

I'm trying to display the messages from a sequence diagram, but so far no luck
Here's my code:
The function browse recursively calls itself to discover the diagrams, but i'm having no luck with DiagramLinks or DiagramObjects, any hint ?
private void browse(EA.Repository Repository, int ID, EA.ObjectType otype)
{
if (otype == EA.ObjectType.otPackage)
{
EA.Package pack = Repository.GetPackageByID(ID);
foreach(EA.Element el in pack.Elements)
{
ID = el.ElementID;
otype = el.ObjectType;
this.browse(Repository, ID, otype);
}
}
if (otype == EA.ObjectType.otElement)
{
EA.Element el = Repository.GetElementByID(ID);
foreach (EA.Diagram diag in el.Diagrams)
{
ID = diag.DiagramID;
otype = diag.ObjectType;
this.browse(Repository, ID, otype);
}
}
if (otype == EA.ObjectType.otDiagram)
{
EA.Diagram diag = Repository.GetDiagramByID(ID);
//foreach (EA.DiagramLink dobj in diag.DiagramLinks)
//{
MessageBox.Show(diag.Name+diag.Type);
//}
}
}
Here's the function that recognizes if the addin is launched from mainmenu, treeview or diagram.
It calls the above function Browse
private string simplify(EA.Repository Repository, string Location)
{
String s = "";
if (Location == "MainMenu") {
s = "ROOT";
MessageBox.Show("test");
}
else if (Location == "TreeView")
{
//Get the element in the tree view which was clicked
Object obj = null;
EA.ObjectType otype = Repository.GetTreeSelectedItem(out obj);
//Si le type n'arrive pas a etre determiné
if (!Enum.IsDefined(typeof(EA.ObjectType), otype))
{
//Should not occur
String error = "Type indeterminé.";
MessageBox.Show(error, "Erreur");
}
//The user clicked on a package - try to determine the stereotype
else if (otype == EA.ObjectType.otPackage)
{
EA.Package p = (EA.Package)obj;
//If the package has no superpackage, it must be the very top package
//-> if the very top package is clicked, ALL will be validated
int ID = p.PackageID;
bool hasParent = false;
try
{
int dummy = p.ParentID;
if (dummy != 0)
hasParent = true;
}
catch (Exception e) { }
if (!hasParent)
{
s = "ROOT";
}
else
{
this.browse(Repository, ID, otype);
}
}
else
{
int ID = 0;
if (otype == EA.ObjectType.otDiagram)
{
ID = ((EA.Diagram)obj).DiagramID;
EA.Diagram d = Repository.GetDiagramByID(ID);
this.browse(Repository, ID, otype);
}
else if (otype == EA.ObjectType.otElement)
{
ID = ((EA.Element)obj).ElementID;
EA.Element e = Repository.GetElementByID(ID);
this.browse(Repository, ID, otype);
}
}
if (obj == null)
s = "From Main Menu";
}
//If the users clicks into a diagram we must determine to which package
//the diagram belongs
else if (Location == "Diagram")
{
int ID = 0;
try
{
Object obj = null;
EA.ObjectType otype = Repository.GetContextItem(out obj);
if (otype == EA.ObjectType.otDiagram)
{
ID = ((EA.Diagram)obj).DiagramID;
EA.Diagram d = Repository.GetDiagramByID(ID);
this.browse(Repository, ID, otype);
}
else if (otype == EA.ObjectType.otElement)
{
ID = ((EA.Element)obj).ElementID;
EA.Element e = Repository.GetElementByID(ID);
this.browse(Repository, ID, otype);
}
else
{
Repository.Models.GetAt(0);
s = "From Main Menu";
}
}
catch (Exception ex)
{ }
}
return s;
this.encours = true;
}
The following Perl script snippet (hopefully it's readable) demonstrates what to do to get the connectors:
my $dia = $rep->GetDiagramByGUID("{7EA250AD-F37A-4e9a-9C52-BF8FCA3D87F7}"); # access the diagram
for (my $i = 0 ; $i < $dia->DiagramObjects->Count; $i++) { # every object inside the diagram
my $do = $dia->DiagramObjects->GetAt($i);
my $e = $rep->GetElementByID($do->ElementID); # the according element
next unless $e->Type eq "Sequence"; # look only at life lines
for (my $j = 0 ; $j < $e->Connectors->Count; $j++) { # now go through its connectors
my $con = $e->Connectors->GetAt($j);
print $con->Type . "\n"; # will print Sequence
}
}
Thanks a lot for your help Thomas
Here's the code i translated in C#
if (otype == EA.ObjectType.otDiagram)
{
EA.Diagram diag = Repository.GetDiagramByID(ID);
foreach (EA.DiagramObject dobj in diag.DiagramObjects)
{
EA.Element el = Repository.GetElementByID(dobj.ElementID);
foreach (EA.Connector con in el.Connectors)
{
if (con.Type == "Sequence")
{
MessageBox.Show(con.Name);
}
}
}
}

How to check if Html element has a background-image css property in WebBrowser control C#

here is my code :
var allEles = webBrowser1.Document.All;
foreach (HtmlElement item in allEles)
{
if (item.TagName.ToLower() == "div")
{
if(//Here i want to check if div has a background-image css property)
{
//do anything
}
}
}
i searched a lot to no avail :(
I wrote my own extension method :
public static class Extensions
{
public static bool hasBackgroundImage(this HtmlElement ele, string cssFolderPath)
{
string styleAttr = ele.Style.ToLower();
if (styleAttr.IndexOf("background-image") != -1 || styleAttr.IndexOf("background") != -1)
{
if (styleAttr.IndexOf("url") != -1)
{
return true;
}
}
string[] classes = ele.GetAttribute("className").Split(' ');
foreach (string className in classes)
{
if (className.Trim() == "")
{
continue;
}
System.IO.DirectoryInfo d = new System.IO.DirectoryInfo(cssFolderPath);
foreach (System.IO.FileInfo item in d.GetFiles().Where(p => p.Extension == ".css"))
{
string cssFile = System.IO.File.ReadAllText(item.FullName);
int start = cssFile.IndexOf(className);
if (start != -1)
{
string sub = cssFile.Substring(start + className.Length);
int end = sub.IndexOf('}');
string cssProps = sub.Substring(1, end).Replace("{", "").Replace("}", "").ToLower();
if (cssProps.IndexOf("background-image") != -1 || cssProps.IndexOf("background") != -1)
{
if (cssProps.IndexOf("url") != -1)
{
return true;
}
}
}
}
}
return false;
}
}
and now i can call my method :
var allEles = webBrowser1.Document.All;
foreach (HtmlElement item in allEles)
{
if (item.TagName.ToLower() == "div")
{
if(item.hasBackgroundImage("myCssFolderPathHere"))
{
//do anything
}
}
}
but this working only if am running a local html file .... because you must throw the css folder path as a parameter in my extension method , and thats what i was looking for :)

Does WebBrowser.DocumentText as well contains all frame documents text?

I am not sure if WebBrowser.DocumentText contains only top document source or frames document text also included. Could not find that from MSDN page.
No it does not. I have tried next:
DocumentText:
File.WriteAllText(#"C:\doc.txt", webBrowser1.DocumentText, Encoding.UTF8);
GetElementsByTagName("HTML")
HtmlElement elem;
if (webBrowser1.Document != null)
{
HtmlElementCollection elems = webBrowser1.Document.GetElementsByTagName("HTML");
if (elems.Count == 1)
{
elem = elems[0];
string pageSource = elem.OuterHtml;
File.WriteAllText(#"C:\doc.txt", pageSource, Encoding.UTF8);
}
}
IOleCommandTarget
public void ShowSource()
{
IOleCommandTarget cmdt = null;
object o = null;
object oIE = null;
try {
cmdt = (IOleCommandTarget)this.Document.DomDocument;
cmdt.Exec(cmdGUID, oCommands.ViewSource, 1, o, o);
} catch (Exception ex) {
throw new Exception(ex.Message.ToString(), ex.InnerException);
} finally {
cmdt = null;
}
}
The only way is to go through all frame documents.
Updated If iframe has different url you will get UnauthorizedAccessException when trying to retrieve iframe document

Sitecore add programmatically mobile site

I am facing the following problem: I want to add dynamically a mobile site for specific templates, I specified the mobile layout in the standard values of the specific item. This all works fine but when I changed a field of the Item the layout and renderings of the default site is gone! Does anyone has a solution/suggestion for this problem?
I am working with Sitecore 6.4.
Thanx in advance!
The code that I am currently using (this is to add hardcoded a layout to an item, the next step is (when I fixed this problem) to get the layout from the standard_values item)
public class CheckMobileLayout
{
public void Process([NotNull] SaveArgs args)
{
try
{
foreach (Sitecore.Pipelines.Save.SaveArgs.SaveItem saveItem in args.Items)
{
Item orgItem = Context.ContentDatabase.Items[saveItem.ID, saveItem.Language, saveItem.Version];
if(orgItem.Name != "Content Editor")
{
TemplateItem testTemplate = orgItem.Template;
foreach (Field orgField in orgItem.Fields)
{
if (orgField != null)
{
if (orgField.GetTemplateField().Type == "Mobile Checkbox")
{
foreach (Sitecore.Pipelines.Save.SaveArgs.SaveField saveField in saveItem.Fields)
{
if (saveField.ID == orgField.ID)
{
if (saveField.Value != orgField.Value)
{
if (saveField.Value == "1") AddMobileLayout(orgItem);
else RemoveMobileLayout(orgItem);
}
}
}
}
}
}
}
}
}
catch (NullReferenceException)
{
}
}
private void RemoveMobileLayout(Item orgItem)
{
using (new SecurityDisabler())
{
Database masterDatabase = Database.GetDatabase("master");
orgItem = masterDatabase.GetItem(orgItem.Paths.Path);
string renderingXml = orgItem[Strings.Renderings];
LayoutDefinition layoutDefinition = new LayoutDefinition();
layoutDefinition.LoadXml(renderingXml);
string mobileDeviceId = Strings.mobileDeviceID;
DeviceDefinition deviceDefinition = layoutDefinition.GetDevice(mobileDeviceId);
deviceDefinition.Layout = String.Empty;
string outputXml = layoutDefinition.ToXml();
Log.Info(outputXml, this);
orgItem.Editing.BeginEdit();
orgItem[Strings.Renderings] = outputXml;
orgItem.Editing.EndEdit();
}
}
private void AddMobileLayout(Item orgItem)
{
using (new SecurityDisabler())
{
Database masterDatabase = Database.GetDatabase("master");
Item testItem = masterDatabase.GetItem(orgItem.Paths.Path);
string renderingXml = testItem[Strings.Renderings];
LayoutDefinition layoutDefinition = new LayoutDefinition();
layoutDefinition.LoadXml(renderingXml);
string mobileDeviceId = Strings.mobileDeviceID;
DeviceDefinition deviceDefinition = layoutDefinition.GetDevice(mobileDeviceId);
deviceDefinition.Layout = Strings.mobileLayoutID;
string outputXml = layoutDefinition.ToXml();
testItem.Editing.BeginEdit();
testItem[Strings.Renderings] = layoutDefinition.ToXml();
testItem.Editing.EndEdit();
}
}
}
I've fixed this with the following to methods:
protected void RemoveMobileLayout(Item item)
{
using (new SecurityDisabler())
{
LayoutDefinition layoutDefinition = Sitecore.Layouts.LayoutDefinition.Parse(item[Sitecore.FieldIDs.LayoutField]);
DeviceDefinition mobileDevice = layoutDefinition.GetDevice(Resources.mobileDeviceID);
if (mobileDevice.Layout != null) mobileDevice.Layout = null;
if (mobileDevice.Renderings != null) mobileDevice.Renderings = null;
item.Editing.BeginEdit();
item[Sitecore.FieldIDs.LayoutField] = layoutDefinition.ToXml();
item.Editing.EndEdit();
}
}
protected void AddMobileLayout(Item item)
{
using (new SecurityDisabler())
{
LayoutDefinition layoutDefinition = Sitecore.Layouts.LayoutDefinition.Parse(item[Sitecore.FieldIDs.LayoutField]);
DeviceDefinition mobileDevice = layoutDefinition.GetDevice(Resources.mobileDeviceID);
TemplateItem itemTemplate = item.Template;
if (itemTemplate != null)
{
if (itemTemplate.StandardValues != null)
{
Item standardValues = itemTemplate.StandardValues;
foreach (DeviceItem deviceItem in Sitecore.Configuration.Factory.GetDatabase("master").Resources.Devices.GetAll())
{
if (deviceItem.ID.ToString() == Resources.mobileDeviceID)
{
mobileDevice.Layout = standardValues.Visualization.GetLayout(deviceItem).ID.ToString();
RenderingReference[] sublayouts = standardValues.Visualization.GetRenderings(deviceItem, true);
foreach (RenderingReference sublayout in sublayouts) mobileDevice.AddRendering(new RenderingDefinition() { ItemID = sublayout.RenderingItem.ID.ToString(), Placeholder = sublayout.RenderingItem.Placeholder });
}
}
}
}
item.Editing.BeginEdit();
item[Sitecore.FieldIDs.LayoutField] = layoutDefinition.ToXml();
item.Editing.EndEdit();
}
}

Categories

Resources