Start:
if(fileName.Contains("$track"))
if(musicInfo.Tag.Track.ToString() != "") {
fileName.Replace("$track", musicInfo.Tag.Track.ToString());
}
else {
switch(System.Windows.Forms.MessageBox.Show("Error: Track # missing from tag info", "Error", System.Windows.Forms.MessageBoxButtons.AbortRetryIgnore, System.Windows.Forms.MessageBoxIcon.Error)) {
case System.Windows.Forms.DialogResult.Abort:
fileName = "ABORTED";
return fileName;
case System.Windows.Forms.DialogResult.Retry:
goto Start;
case System.Windows.Forms.DialogResult.Ignore:
fileName.Replace("$track", "");
}
}
I can't think of any better way to write this, there would be 7 more blocks of this code.
How about this?
public string GetFileName(string fileName)
{
if(fileName.Contains("$track") &&
!String.IsNullOrEmpty(musicInfo.Tag.Track.ToString())
{
return fileName.Replace("$track", musicInfo.Tag.Track.ToString());
}
var userOption = System.Windows.Forms.MessageBox.Show(
"Error: Track # missing from tag info", "Error",
System.Windows.Forms.MessageBoxButtons.AbortRetryIgnore,
System.Windows.Forms.MessageBoxIcon.Error)
switch(userOption)
{
case System.Windows.Forms.DialogResult.Abort:
return "ABORTED";
case System.Windows.Forms.DialogResult.Retry:
return GetFileName(fileName);
case System.Windows.Forms.DialogResult.Ignore:
return fileName.Replace("$track", "");
}
}
Related
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?
Hi I have a "dumb" question. Here is my problem:
string ct=ctx.Request.ContentType;
if (!string.IsNullOrEmpty(ct))
{
ct=new ContentType(ct).MediaType;
if (!ct.Equals(KnownMimeType.Json, StringComparison.InvariantCultureIgnoreCase) || !ct.Equals(KnownMimeType.Xml, StringComparison.InvariantCultureIgnoreCase))
{
RespondWith(Status.BadRequest, "!json or xml");
return;
}
}
With the conditional Operator when an XML is sent the if body is executed which shouldn't be the case.
This is my current solution but the code with the empty method bodies is horrible. :/
string ct=ctx.Request.ContentType;
if (!string.IsNullOrEmpty(ct))
{
ct=new ContentType(ct).MediaType;
if (ct.Equals(KnownMimeType.Json, StringComparison.InvariantCultureIgnoreCase)) { }
else if (ct.Equals(KnownMimeType.Xml, StringComparison.InvariantCultureIgnoreCase)) { }
else
{
RespondWith(Status.BadRequest, "!json or xml");
return;
}
}
The goal is that every Content Type except JSON and XML should be responded with Status.BadReqeust
What can I do to refactor this?
Thanks from a newbie.
Use this.
if (!(ct.Equals(KnownMimeType.Json, StringComparison.InvariantCultureIgnoreCase) || ct.Equals(KnownMimeType.Xml, StringComparison.InvariantCultureIgnoreCase))) { RespondWith(Status.BadRequest, "!json or xml");
//For the sake of brevity and readable code.This may be your solution
string ct=ctx.Request.ContentType;
if (!string.IsNullOrEmpty(ct))
{
ct=new ContentType(ct).MediaType;
var isJson = ct.Equals(KnownMimeType.Json, StringComparison.InvariantCultureIgnoreCase);
var isXml =ct.Equals(KnownMimeType.Xml, StringComparison.InvariantCultureIgnoreCase);
if(isJson || isXml)
continue;
else
return RespondWith(Status.BadRequest, "!json or xml");
}
else
return RespondWith(Status.BadRequest, "Invalid content type");
//Maybe you can change status code instead of BadRequest for invalid content type
private Result RespondWith(Status status,string message)
{
}
//I assume that you return a dto like this
public class Result
{
public Status Status;
public string Message;
}
I'm doing an C# app where I use
if ((message.Contains("test")))
{
Console.WriteLine("yes");
} else if ((message.Contains("test2"))) {
Console.WriteLine("yes for test2");
}
There would be any way to change to switch() the if() statements?
Correct final syntax for [Mr. C]s answer.
With the release of VS2017RC and its C#7 support it works this way:
switch(message)
{
case string a when a.Contains("test2"): return "no";
case string b when b.Contains("test"): return "yes";
}
You should take care of the case ordering as the first match will be picked. That's why "test2" is placed prior to test.
Nope, switch statement requires compile time constants. The statement message.Contains("test") can evaluate true or false depending on the message so it is not a constant thus cannot be used as a 'case' for switch statement.
If you just want to use switch/case, you can do something like this, pseudo-code:
string message = "test of mine";
string[] keys = new string[] {"test2", "test" };
string sKeyResult = keys.FirstOrDefault<string>(s=>message.Contains(s));
switch (sKeyResult)
{
case "test":
Console.WriteLine("yes for test");
break;
case "test2":
Console.WriteLine("yes for test2");
break;
}
But if the quantity of keys is a big, you can just replace it with dictionary, like this:
static Dictionary<string, string> dict = new Dictionary<string, string>();
static void Main(string[] args)
{
string message = "test of mine";
// this happens only once, during initialization, this is just sample code
dict.Add("test", "yes");
dict.Add("test2", "yes2");
string sKeyResult = dict.Keys.FirstOrDefault<string>(s=>message.Contains(s));
Console.WriteLine(dict[sKeyResult]); //or `TryGetValue`...
}
This will work in C# 8 using a switch expresion
var message = "Some test message";
message = message switch
{
string a when a.Contains("test") => "yes",
string b when b.Contains("test2") => "yes for test2",
_ => "nothing to say"
};
For further references
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/switch-expression
Simple yet efficient with c#
string sri = "Naveen";
switch (sri)
{
case var s when sri.Contains("ee"):
Console.WriteLine("oops! worked...");
break;
case var s when sri.Contains("same"):
Console.WriteLine("oops! Not found...");
break;
}
string message = "This is test1";
string[] switchStrings = { "TEST1", "TEST2" };
switch (switchStrings.FirstOrDefault<string>(s => message.ToUpper().Contains(s)))
{
case "TEST1":
//Do work
break;
case "TEST2":
//Do work
break;
default:
//Do work
break;
}
You can do the check at first and then use the switch as you like.
For example:
string str = "parameter"; // test1..test2..test3....
if (!message.Contains(str)) return ;
Then
switch(str)
{
case "test1" : {} break;
case "test2" : {} break;
default : {} break;
}
Faced with this issue when determining an environment, I came up with the following one-liner:
string ActiveEnvironment = localEnv.Contains("LIVE") ? "LIVE" : (localEnv.Contains("TEST") ? "TEST" : (localEnv.Contains("LOCAL") ? "LOCAL" : null));
That way, if it can't find anything in the provided string that matches the "switch" conditions, it gives up and returns null. This could easily be amended to return a different value.
It's not strictly a switch, more a cascading if statement but it's neat and it worked.
Some custom swtich can be created like this. Allows multiple case execution as well
public class ContainsSwitch
{
List<ContainsSwitch> actionList = new List<ContainsSwitch>();
public string Value { get; set; }
public Action Action { get; set; }
public bool SingleCaseExecution { get; set; }
public void Perform( string target)
{
foreach (ContainsSwitch act in actionList)
{
if (target.Contains(act.Value))
{
act.Action();
if(SingleCaseExecution)
break;
}
}
}
public void AddCase(string value, Action act)
{
actionList.Add(new ContainsSwitch() { Action = act, Value = value });
}
}
Call like this
string m = "abc";
ContainsSwitch switchAction = new ContainsSwitch();
switchAction.SingleCaseExecution = true;
switchAction.AddCase("a", delegate() { Console.WriteLine("matched a"); });
switchAction.AddCase("d", delegate() { Console.WriteLine("matched d"); });
switchAction.AddCase("a", delegate() { Console.WriteLine("matched a"); });
switchAction.Perform(m);
Stegmenn nalied it for me, but I had one change for when you have an IEnumerable instead of a string = message like in his example.
private static string GetRoles(IEnumerable<External.Role> roles)
{
string[] switchStrings = { "Staff", "Board Member" };
switch (switchStrings.FirstOrDefault<string>(s => roles.Select(t => t.RoleName).Contains(s)))
{
case "Staff":
roleNameValues += "Staff,";
break;
case "Board Member":
roleNameValues += "Director,";
break;
default:
break;
}
}
This will work in C# 7. As of this writing, it has yet to be released. But if I understand this correctly, this code will work.
switch(message)
{
case Contains("test"):
Console.WriteLine("yes");
break;
case Contains("test2"):
Console.WriteLine("yes for test2");
break;
default:
Console.WriteLine("No matches found!");
}
Source: https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/
switch(message)
{
case "test":
Console.WriteLine("yes");
break;
default:
if (Contains("test2")) {
Console.WriteLine("yes for test2");
}
break;
}
I am checking the uploaded image in a registration form , where i need to use try catch blocks. here is my code:
public bool CheckFileType(string FileName)
{
string Ext = Path.GetExtension(FileName);
switch (Ext.ToLower())
{
case ".gif":
return true;
break;
case ".JPEG":
return true;
break;
case ".jpg":
return true;
break;
case ".png":
return true;
break;
case ".bmp":
return true;
break;
default:
return false;
break;
}
}
please suggest me how to use the try catch blocks here.
thanks in advance.
It would be better to do it this way,
public bool CheckFileType(string FileName)
{
bool result = false ;
try
{
string Ext = Path.GetExtension(FileName);
switch (Ext.ToLower())
{
case ".gif":
case ".JPEG":
case ".jpg":
case ".png":
case ".bmp":
result = true;
break;
}
}catch(Exception e)
{
// Log exception
}
return result;
}
There are plenty of ways that you can use exceptions in methods that return values:
Place your return statement outside the try-catch For example:
T returnValue = default(T);
try
{
// My code
}
catch
{
// Exception handling code
}
return returnValue;
Put a return statement inside your catch
try
{
// My code
}
catch
{
// Handle exception
return default(T);
}
Throw an exception
You don't have to return a value, the method simply has to end (e.g. reach a return statement or a throw statement). Depending on the exception its not always valid to return a value.
You should think carefully about when and how to catch and handle exceptions:
What might fail?
Why / how can they fail?
What should I do when they fail?
In your case:
The only statement that can fail is string Ext = Path.GetExtension(FileName);, which according to the documentation can fail if FileName contains. (Note that GetExtension doesn't return null, even if FileName is null).
This might happen if the user supplied a string that contains these invalid characters.
If this happens, I guess that we should return false, to indicate that the path is not valid (however this depends on the application).
So I'd probably handle exceptions like this:
public bool CheckFileType(string FileName)
{
string Ext;
try
{
Ext = Path.GetExtension(FileName);
}
catch (ArgumentException ex)
{
return false;
}
// Switch statement
}
Note that we only catch the exception that we are expected (ArgumentException), and we only place the try statement around the statement that we expect the exception to be thrown from.
In fact its a good idea to avoid throwing and catching exceptions wherever possible - not only do they incur a performance penalty (which can cause serious problems if this method is called inside a loop), but you might inadvertently catch and handle an exception that you didn't anticipate, masking a more serious problem.
In this case we can avoid throwing the exception entirely by checking ourselves to see if FileName contains any invalid characters:
public bool CheckFileType(string FileName)
{
if (FileName == null)
{
return false;
}
if (FileName.IndexOfAny(System.IO.Path.GetInvalidPathChars()) >= 0)
{
return false;
}
// Your original method goes here
}
As you're not actually testing the file type (only the extension of the filename), I'd first start by renaming the method. You can make an extension method to handle it:
public static bool HasImageExtension(this string fileName)
{
try
{
if (fileName == null) return false;
string[] validExtensions = new string[] { ".gif", ".jpg", ".jpeg", ".png", ".bmp" };
string extension = Path.GetExtension(fileName);
return validExtensions.Contains(extension);
}
// catch the specific exception thrown if there are
// invalid characters in the path
catch (ArgumentException ex)
{
// do whatever you need to do to handle
// the fact there are invalid chars
throw;
}
}
Which you can then call, like so:
string fileName = "testFileName.jpg";
bool hasImageExtension = fileName.HasImageExtension();
This should work:
public bool CheckFileType(string FileName)
{
try
{
string Ext = Path.GetExtension(FileName).ToLower();
string[] okExt = ".gif|.jpg|.jpeg|.png|.bmp".Split('|');
foreach(var item in okExt)
{
if(Ext == item)
return true;
}
return false;
}
catch(Exception ex)
{
throw;
}
}
And remember: never catch exceptions you're not going to handle. (or atleast re-throw them)
In the method below there are numerous case statements (many have been removed) that make calls to Manager classes. For example, the first one calls ApplicationManager.GetByGUID. Any time a "manager" class is used, security checks occur.
Problem: I have entities that may be permitted to some of these but not all. So when this method gets run, if one of them craps out it'll throw a security exception and crash the whole report.
Someone has suggested to me that I could just throw try-catch blocks around each case but the more I read the more I feel like that might be sloppy. I admittedly am not very knowledged about exceptions...I was hoping someone could suggest a way to do this with more finesse...I need to be able to get back good data and ignore the ones that throw security exceptions....or maybe try-catches are ok in this case?
Hope that makes sense...thanks
private string GetLookup(string value, string type)
{
MySqlConnection mconn = new MySqlConnection(ConfigurationSettings.AppSettings["UnicornConnectionString_SELECT"]);
try
{
mconn.Open();
lock (reportLookups)
{
if (reportLookups.ContainsKey(type+value))
return reportLookups[type+value].ToString();
else if (reportLookups.ContainsKey(value))
return reportLookups[value].ToString();
else
{
switch (type)
{
case "ATTR_APPLICATIONNAME":
if (value != Guid.Empty.ToString())
{
reportLookups.Add(type + value, applicationManager.GetByGUID(value).Name);
}
else
{
reportLookups.Add(type + value, "Unknown");
}
mconn.Close();
return reportLookups[type + value].ToString();
break;
case "ATTR_CITYNAME":
reportLookups.Add(type + value, UMConstantProvider.UMConstantProvider.GetConstant<UMString64>(int.Parse(value), UMMetricsResourceLibrary.Enumerations.ConstantType.CITY_NAME, ref mconn));
mconn.Close();
return reportLookups[type + value].ToString();
break;
case "ATTR_COUNTRYNAME":
reportLookups.Add(type + value, UMConstantProvider.UMConstantProvider.GetConstant<UMString2>(int.Parse(value), UMMetricsResourceLibrary.Enumerations.ConstantType.COUNTRY_NAME, ref mconn));
mconn.Close();
return reportLookups[type + value].ToString();
break;
case "ATTR_ITEMDURATION":
MediaItem mi = mediaItemManager.GetMediaItemByGUID(value);
if (mi.MediaItemTypeID == (int)MediaItemType.ExternalVideo || mi.MediaItemTypeID == (int)MediaItemType.ExternalAudio)
{
reportLookups.Add(type + value, mediaItemManager.GetMediaItemByGUID(value).ExternalDuration);
mconn.Close();
return reportLookups[type + value].ToString();
}
else
{
List<BinaryAsset> bins = fileSystemManager.GetBinaryAssetsByMediaItemGuid(value, mi.DraftVersion);
var durationasset = from d in bins
where d.Duration != 0
select d.Duration;
if (durationasset.Count() > 0)
{
reportLookups.Add(type + value, durationasset.ToList()[0]);
}
else
{
reportLookups.Add(type + value, 0);
mconn.Close();
return reportLookups[type + value].ToString();
}
}
break;
}
}
return string.Empty;
}
}
finally
{
mconn.Close();
}
}
As a rule, Exceptions should indicate that something went wrong. If you're expecting exceptions during the course of a typical run through this method, you should change your APIs to allow you to avoid that exception:
if (mediaItemManager.CanAccessMediaItem(value))
{
MediaItem mi = mediaItemManager.GetMediaItemByGUID(value);
....
}
Here's a quick attempt on my part to refactor this code into something more reasonable:
private string GetLookup(string value, string type)
{
var lookupKey = type + value;
using (MySqlConnection mconn = new MySqlConnection(ConfigurationSettings.AppSettings["UnicornConnectionString_SELECT"]))
{
mconn.Open();
lock (reportLookups)
{
if (reportLookups.ContainsKey(lookupKey))
{
return reportLookups[lookupKey].ToString();
}
var value = GetLookupValue(type, value);
reportLookups[lookupKey] = value;
return value;
}
}
}
private string GetLookupValue(string type, string value)
{
switch (type)
{
case "ATTR_APPLICATIONNAME":
return value == Guid.Empty.ToString()
? "Unknown"
: applicationManager.CanGetByGUID(value)
? applicationManager.GetByGUID(value).Name
: string.Empty;
case "ATTR_CITYNAME":
return UMConstantProvider.UMConstantProvider.GetConstant<UMString64>(int.Parse(value), UMMetricsResourceLibrary.Enumerations.ConstantType.CITY_NAME, ref mconn);
case "ATTR_COUNTRYNAME":
return UMConstantProvider.UMConstantProvider.GetConstant<UMString2>(int.Parse(value), UMMetricsResourceLibrary.Enumerations.ConstantType.COUNTRY_NAME, ref mconn);
case "ATTR_ITEMDURATION":
if(mediaItemManager.CanGetMediaItemByGUID(value)) {
MediaItem mi = mediaItemManager.GetMediaItemByGUID(value);
if (mi.MediaItemTypeID == (int)MediaItemType.ExternalVideo || mi.MediaItemTypeID == (int)MediaItemType.ExternalAudio)
{
return mediaItemManager.GetMediaItemByGUID(value).ExternalDuration;
}
else
{
List<BinaryAsset> bins = fileSystemManager.GetBinaryAssetsByMediaItemGuid(value, mi.DraftVersion);
var durationasset = from d in bins
where d.Duration != 0
select d.Duration;
return durationasset.FirstOrDefault() ?? "0";
}
}
else
{
return string.Empty;
}
default:
return string.Empty;
}
}
Since I don't understand the full scope of this code, I probably oversimplified some aspects of it, but you can see that there is a lot of refactoring to be done here. In the future, you might want to run some code by http://refactormycode.com/, until you get accustomed to using best practices.
Somewhere you will have some code like:
foreach(Request req in allRequests)
{
Reply result = MakeReply(req);
WriteReply(result);
}
Turn this into:
foreach(Request req in allRequests)
{
Reply result;
try
{
result = CreateReply(req);
}
catch(SecurityException ex)
{
result = CreateReplyUnauthorized();
}
catch(Exception ex) // always the last
{
LogException(ex); // for bug hunting
// Don't show the exception to the user - that's a security risk
result = CreateReplySystemError();
}
WriteReply(result);
}
You might want to put the try-catch into a separate function as the body of your foreach loop is getting large once you catch several types of exceptions.
StriplingWarrior is also right in his reply: "Exceptions should indicate that something went wrong." Let them propagate to the main loop and show them there.