Code of the week ~ Fun with Enums

//Returns the correct Target Method in Enumeration
//otherwise it just whines

public targetmethod ConvertToTarget(string _input)
{
targetmethod Result = targetmethod.YouHaveNoIdeaWhatYouareLookingFor;
try
{
Result = (targetmethod)Enum.Parse(typeof(targetmethod), _input, true);
}
catch (Exception omg)
{
Console.WriteLine(omg.Message + “what” + “everrrrrrrrrrrrrrrrrrrrrrrrrrrrr”);
}
return Result;
}

public enum targetmethod{

Method1,
Method2,
SomeOther

}

 

 

 

Cash Machine II

Just a quick revisit to Cash machine with some quick UI

<!–DOCTYPE html>

xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head runat=”server”>
<title>Cash Machine II</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
Type Amount of $ you would like, please.
<asp:TextBox ID=”txtAmount1″ runat=”server”>
<asp:Button ID=”btnGetCash” runat=”server” Text=”Withdraw” OnClick=”btnGetCash_Click” />
</div>
</form>
</body>
</html>

 

protected void btnGetCash_Click(object sender, EventArgs e)
{
string msg = string.Empty;
Response.Write(Withdraw(System.Convert.ToDecimal(txtAmount1.Text), ref msg).ToString());
if (msg != null)
{
Response.Write(msg);
}
}

private decimal Withdraw(decimal amount, ref string message)
{
decimal currentAmount = 0;
int cashAvailable = 1000;

StringBuilder CashUsed = new StringBuilder(“
“);

if (amount > cashAvailable)
{
message = “Not enough funds available”;
return (decimal)0.0;
}

for (int i = 1; i < cashAvailable; i++)
{

if (currentAmount == amount)
{
message += CashUsed.ToString();
return currentAmount;
}
if (currentAmount < amount && ((amount – currentAmount) / 100) % 100 == 0 || currentAmount + 100 < amount && ((amount – currentAmount) / 100) / 100 > 0)
{
currentAmount += 100;
CashUsed.Append(“$100″);
}
if (currentAmount < amount && ((amount – currentAmount) / 10) % 10 == 0 || currentAmount + 10 < amount && ((amount – currentAmount) / 10) / 10 > 0)
{
currentAmount += 10;
CashUsed.Append(“$10″);
}
else if (currentAmount < amount && ((amount – currentAmount) / 5) % 5 == 0 || currentAmount + 10 < amount && ((amount – currentAmount) / 5) / 5 > 0)
{
currentAmount += 5;
CashUsed.Append(“$5″);
}
else if (currentAmount < amount && ((amount – currentAmount) / 1) % 1 == 0)
{
currentAmount += 1;
CashUsed.Append(“$1″);
}
}

return currentAmount;
}

Coding Exercise Dujour ~ manually removing characters from string & log scanning for counts

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CsharpConsole
{
public static class Program
{
static void Main(string[] args)
{
Console.Write(removeCharacterFromString(“Thanks!!! for the #@somevalue eg. $100 (dollars) \n”, (char)’$’));
Console.Write(removeCharacterFromString(“Thanks!!! for the #@somevalue $100 (dollars) \n”));
Console.Write(“Here are the current counts \n”);
Console.Write(countsFromLOG(@”c:\tcounts.txt”));

int[] dasnumbers = { 20, 31, 5, 16, 22, 7 };
NumberLessThanInArray(20, dasnumbers);

Console.ReadKey();
}
private static readonly HashSet badChars =
new HashSet { ‘!’, ‘@’, ‘#’, ‘$’, ‘%’, ‘_’ };

public static string removeCharacterFromString(this string str)
{
var result = new StringBuilder(str.Length);
for (int i = 0; i < str.Length; i++)
{
if (!badChars.Contains(str[i]))
result.Append(str[i]);
}
return result.ToString();
}

public static string removeCharacterFromString(this string str, char BadChar)
{
var result = new StringBuilder(str.Length);
for (int i = 0; i < str.Length; i++)
{
if (BadChar != ((char)str[i]))
result.Append(str[i]);
}
return result.ToString();
}

public static long countsFromLOG(string fileFullname)
{
long SumTotal = 0;
try
{
StreamReader sr = new StreamReader(fileFullname);

int rowCounter = 0;

while (!sr.EndOfStream)
{
string currentLine = sr.ReadLine();

long lResult = 0;
if (long.TryParse(currentLine, out lResult))
{
SumTotal += System.Convert.ToInt64(currentLine);
}
rowCounter += 1;
}

return SumTotal;
}
catch (Exception ex)
{
dynamic msg = “Exception parsing log file ” + fileFullname + “. ” + ex.Message;
throw new Exception(msg, ex);
}
}

public static void NumberLessThanInArray(int Target, int[] numbers)
{
Console.Write(“\n Here are the numbers less than ” + Target + “\n”);
IEnumerable numbersSmallerThan = numbers.Where(r => r
{
Console.Write(i + ” “);
}
);

}

}
}

Some more on JQuery Binding

http://jsfiddle.net/mattgre/4vwuG/

The example is running on JFiddle and here is the code:

$( “img” ).bind( “click”, function( event ) {

var str = “( ” + event.pageX + “, ” + event.pageY + ” )”;

$( “span” ).text( “Click happened! ” + str );

});

$( “img” ).bind( “dblclick”, function() {

$( “span” ).text( “Double-click happened in ” + this.nodeName );    $( “img” ).animate({

opacity: 0.25,

left: “+=50″,

height: “toggle”

}, 5000, function() {

// Animation complete.

});

});

$( “img” ).bind( “mouseenter mouseleave”, function( event ) {

$( this ).toggleClass( “over” );

});

JQuery Proxy Object Test on JFiddle

I have been digging deeper on JQuery & I really like the proxy usage:

http://jsfiddle.net/mattgre/BNPQ2/

here is the JS Side of it:

var obj = {
name: "John",
test: function() {
$( "#log" ).append( this.name );
$( "#test" ).off( "click", obj.test );
$( "#test" ).off( "click", obj.test2 );
$("#test").off("click", obj.test3);

},
test2: function () {

$( “#op1″ ).append(‘The obj.name===John is’).append(obj.name===”John”);
$(“#op2″).append(‘We know 7==”7″ is ‘).append(7 == “7″);

}, test3: function() {

$( “#op3″ ).append(“Than surely 7===7 is ==”).append(7===7 );
$(“#op4″).append(‘But is 7===”7″ [').append(7 === "7").append('] NO result NO’);
}
};

$( “#test” ).on( “click”, jQuery.proxy( obj, “test” ) );
$( “#test” ).on( “click”, jQuery.proxy( obj, “test2″ ) );
$(“#test”).on(“click”, jQuery.proxy(obj, “test3″));

Async Screen Scraping

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using HtmlAgilityPack;
using Org.Mentalis.Network.ProxySocket;
using AwaitSample1.Proxy;

async Task<string> AccessTheWebAsync()
{
string uri = “http://www.some~data.somewhere.com/2014/ClinicalData&#8221;;

  HttpClient client = new HttpClient();

   Task<string> getStringTask = client.GetStringAsync(uri);

// You can do work here that doesn’t rely on the string from 
// DoIndependentWork();

string urlContents = await getStringTask;

// Normally the return statement specifies result.
//here getlinks will post to our XAML Label
  getlinks(urlContents);

return urlContents;
}

private void Button_Click(object sender, RoutedEventArgs e)
{
      StatusLabel.Content = “Loading ….”;
      AccessTheWebAsync();
}

/// <summary>
/// Using HTML Agility Pack to traverse the HTML Document
/// </summary>
/// <param name=”input”>string</param>
/// <returns>string</returns>
private string getlinks(string input)
{

     StatusLabel.Content = String.Empty;
     HtmlDocument doc = new HtmlDocument();
     doc.LoadHtml(input);

  var aTags = doc.DocumentNode.SelectNodes(“//a”);
  int counter = 1;
  if (aTags != null)
  {
          foreach (var aTag in aTags){
    StatusLabel.Content += counter + “. ” + aTag.InnerHtml + ” – ” +    aTag.Attributes["href"].Value + “\t” + Environment.NewLine;
 counter++;
 }
}
return String.Empty;
}