Thursday, November 12, 2009

Top 10 worst Microsoft products of all time

Just found this top, simple curiosity: http://www.v3.co.uk/v3/news/2252318/top-worst-microsoft-products

Wednesday, November 11, 2009

Execute CMD command on ASP.NET App

Hello guys, this time I spent one full day digging my way into this one..
The main question here is: How can I execute a command or a list of commands as if I where on the command prompt, and get the response?

I can give you right now the answer! (after banging my head over and over on the keyboard for one day...)

public static string ExecuteCmdCommands(List< string > commands)
        {
            Process p = new Process();
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.FileName = @"cmd";
            p.StartInfo.UseShellExecute = false;
            p.Start();

            StreamWriter sIn = p.StandardInput;
            sIn.AutoFlush = true;

            StreamReader sOut = p.StandardOutput;

            for (int i = 0; i <= commands.Count - 1; i++)
            {
                sIn.Write(commands[i] + System.Environment.NewLine);
            }
            
            sIn.Close();
            string result = sOut.ReadToEnd().Trim();
            p.Close();

            return result;
        }

How simple is it? You just create a Process, set the RedirectStandardOutput and RedirectStandardInput to true, so you can create a Stream for reading and writing to/from that process, the FileName is the prompt itself and the UseShellExecute is a pre requisite.
Then start writing out your instructions to the command prompt, always followed by a Environment.NewLine (simulate a Return) and afterwards, you get the output on the reader Stream, that simple!

And, you don't need to change any permissions on the user executing your worker process or app pool for your application, which is great so you don't create any security holes on your web server.

Hopefully this will save you hours, like it would if I had this before!

See you soon

Thursday, November 5, 2009

Colorize C# code with RegEx and HTML

Hi guys.
This time I needed to colorize some basic sample c# code and haven't found any simple and usable componente to do that, so I decided to code one, but very simple and basic.
I know it lacks some functionality, like coloring a class on a static method call, because this is not so simple as that, but it's a start, here is the code:
private string words = "abstract|as|base|bool|break|byte|case|catch|char|checked|class|const|continue|decimal|default|delegate|do|double|else|enum|event|explicit|extern|false|finally|fixed|float|for|foreach|goto|if|implicit|in|int|interface|internal|is|lock|long|namespace|new|null|object|operator|out|override|params|private|protected|public|readonly|ref|return|sbyte|sealed|short|sizeof|stackalloc|static|string|struct|switch|this|throw|true|try|typeof|uint|ulong|unchecked|unsafe|ushort|using|virtual|volatile|void|while";
//this is a list of reserved words

private string ColorizeCode(string code)
{
  Regex regExInst = new Regex(@"(?\w+)\s\w+\s=\snew\s(?\w+)\(");//regex to colorize the object creations

  MatchCollection mcInst = regExInst.Matches(code);

  foreach (Match match in mcInst)
  {
    code = code.Remove(match.Groups["TYPE"].Index, match.Groups["TYPE"].Length);
    code = code.Insert(match.Groups["TYPE"].Index, "" + match.Groups["TYPE"].Value + "");

    Regex regExInstAux = new Regex(@"\s=\snew\s(?\w+)\(");
    MatchCollection mcInstAux = regExInstAux.Matches(code);
    foreach (Match matchAux in oMatchCollectionAux)
    {
      code = code.Remove(matchAux.Groups["TYPE"].Index,    matchAux.Groups["TYPE"].Length);
      code = code.Insert(matchAux.Groups["TYPE"].Index, "" + matchAux.Groups["TYPE"].Value + "");
    }
  }

  Regex regExCall = new Regex(@"(?\w+)\s\w+\s=\s\w+");
  //regex to colorize an object received from a method call

  MatchCollection mcCall = regExCall.Matches(code);

  foreach (Match match in mcCall)
  {
    code = code.Remove(match.Groups["TYPE"].Index, match.Groups["TYPE"].Length);
    code = code.Insert(match.Groups["TYPE"].Index, "" + match.Groups["TYPE"].Value + "");
  }

  string[] reservedWordArr = words.Split('|');

  for (int i = 0; i <= reservedWordArr.Length - 1; i++)
  {
    Regex regexRW = new Regex(@"\s(?" + reservedWordArr[i] + @")\s");
    //regex to colorize reserved words
    MatchCollection matchColRW = regexRW.Matches(code);
    foreach (Match match in matchColRW)
    {
      code = code.Remove(match.Groups["RW"].Index, match.Groups["RW"].Length);
      code = code.Insert(match.Groups["RW"].Index, "" + match.Groups["RW"].Value + "");
    }
  }

  return code;
}
and that's it! of course for your case, you change the markup I added..

See you soon :)

Monday, November 2, 2009

JQuery - ajax call with dynamic parameters

This one was discovered because a colleague of mine asked me, and I started to wonder and realized I never used it before, never really needed it..But indeed, it can be quite handy!
Before you make the $.ajax call or $.post call or whatever, you do this:

var parameters = {}; //declare the object
parameters["prop1"] = "value1"; //set some value
parameters["prop2"] = "value2"; //and again

Then, when you're making the actual request, you pass your object on the data field

$.ajax({
type: "POST",
url: "some.php",
data: parameters,
success: function(msg){
alert("nothing");
}
});

and voilá! you can build your parameters in a nice way, instead of "prop1=value1&prop2=value2"

Be back soon :)

Thursday, October 29, 2009

JQuery pass parameter to event handler

How can you pass values into a event handler, plain and simple?

here it is!

var somevar = 'value'; //declare some var

And here comes the magic, on the bind function, in the second parameter, you define the data structure to pass on to your anonymous event handler (which can be multiple parameters, comma separated).
(notice that you have to receive the event parameter on the handler function, so you can access the data you sent)

$("something").bind("click", { data: somevar }, function(event) {
event.data.data //this is the way you can access it on the handler function
}

So, what's the use of this? you can send data that is accessible in your current context, where you are defining the handler, but inside the handler it's unreachable.

Hope this is as useful for you as it was for me!

See you soon :)

Wednesday, October 28, 2009

Deserialize JSON with C#

You're using JQuery, making some fancy ajax requests, but tired of Request["setting"] to get data from client-side, starving for a strong-typed approach? STOP! I've got just what you need, and supports single object, and even lists of objects (arrays)!

Example:

Single: { "field1":"value1","field2":"value2" }
Array: [ { "field1":"value1","field2":"value2" }, { "field1":"value1","field2":"value2" } ]

For the single, the .NET Framework has the key, you need to create a class that has public fields or properties matching the field names on your JSON string, example:

public class Test
{
public string field1 { get; set; }
public string field2 { get; set; }
}

And the code to serialize your Single JSON is this:

Test myDeserializedObj = (Test)JavaScriptConvert.DeserializeObject(Request["jsonString"], typeof(Test));       

and voilá! you got yourself a strong-typed object with client-side data, sweet!


But and if I want a list of data of the same type, say an Array, how is it done? The .NET Framework hasn't got the answer for this one..
You have to download and reference the following DLL

Once it's done:

List< test > myDeserializedObjList = (List< test >)Newtonsoft.Json.JsonConvert.DeserializeObject(Request["jsonString"], typeof(List< test >));

and yes! you're done :)

How easy is this? It's perfect for your lightweight ajax applications with .NET backend.

Please post comments!

See you soon

Tuesday, October 27, 2009

JQuery and XML

Today I've started to use JQuery for XML navigation for the first time. For what I've seen it seems that it is pretty easy, just like using it for HTML, like:

$(xml).find('element').each(function() {
//do something
$('some html element').append($(this).find('nested element').attr('test'));
});

nice hã?