Blog Archives

directory info get files show directories C# .Net

There is sometimes a misunderstanding between a “file” and a “folder” in filesystems. In C# .Net the following is often used to list all “files” in a folder.

DirectoryInfo di = new DirectoryInfo("yourpath");

foreach (FileInfo fi in di.GetFiles()) {
//do work
}

However, even though you can specify to search containing subdirectories, the above function will not inherently list folders. If you are looking for the equivalent to “dir” or “ls”, instead use “GetFileSystemInfos()”.

            DirectoryInfo di = new DirectoryInfo("yourpath");
		
//note the difference here with getfilesysteminfos
		foreach (dynamic d in di.GetFileSystemInfos()) {
}

Note the usage of dynamic in the above example compared to the first example. This avoids any potential issues with inheritance and choosing the right class for your temp iterator variable for unboxing etc.

Android Launch Browser from App to handle external URLs

Upon googling for this one, I found some good relevant links on stack overflow as well as the android webview documentation, but no singular solution that tied everything together.

First, I created a custom WebViewClient class. Note that this is optional as you can do inline class declarations in this environment.

package com.example.testapp;

import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.content.Intent;

public class MyWebViewClient extends WebViewClient {
@Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url != null && url.startsWith('http://192.168.1.101')) {
            return false;
        } else {
        	view.getContext().startActivity(
                    new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            return true;
        }
    }
}

Then, in the main activity, use code within onCreate to support for multiple windows and to set the web view client to your own custom client.

package com.example.testapp;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Menu;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.KeyEvent;
import android.webkit.WebChromeClient;
import android.net.Uri;

public class MainActivity extends Activity {

	private WebView webView;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	final Context context = this;
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    	webView = (WebView) findViewById(R.id.webView1);
    	webView.getSettings().setJavaScriptEnabled(true);
    	
    	webView.getSettings().setSupportMultipleWindows(true);

    	webView.setWebViewClient(new MyWebViewClient());
    	webView.loadUrl('http://192.168.1.1/login.aspx');
    }

If you want to use an inline class declaration instead of defining a seperate mywebviewclient class, you can also use something like:

    	webView.setWebViewClient(new WebViewClient() {
    	      @Override
    	      public boolean shouldOverrideUrlLoading(WebView view, String url) {
//etc, same code as above
    	      }
});

If you have not already addressed the question of handling the android back button within your webview, the android documentation has a good quick simple code reference on how to accomplish this.

Enjoy. :)

References
StackOverflow, http://stackoverflow.com/questions/5979361/android-open-url-in-a-new-window-without-leaving-app

StackOverflow, http://stackoverflow.com/questions/7028258/launch-browser-from-within-app-how-do-you-get-back-to-the-app

Android Documentation, http://developer.android.com/reference/android/webkit/WebView.html

Cisco iOS Emulator Hardware and Software Simulations

Good article with introductory discussion:

http://www.techrepublic.com/blog/networking/practice-cisco-router-configuration-using-a-free-emulator/419

Supported Hardware

Dynagen/Dynamips:
Cisco 7200, Cisco 3600 series (3620, 3640 and 3660), 3700 series (3725, 3745) and 2600 series (2610 to 2650XM, 2691).

Emulators/Simulators

Dynagen/Dynamips (excellent choice and good for windows and *nix):
http://www.gns3.net/download
http://www.ipflow.utc.fr/index.php/Cisco_7200_Simulator
http://dynagen.org/tutorial.htm

Boson (proprietary at least 100USD$):
http://www.boson.com/AboutNetSim.html

pyios (not as much following as the other two):
http://sourceforge.net/projects/pyios/

C# MySQL On Windows Named Pipes Development Mode

While outlining the scope for a new project I’ve considered the possibility of using MySQL for budgeting purposes with respect to the potential size and growth rate of the database.

I downloaded and ran through the latest setup for MySQL on Windows (x64 although I opted for the 32 bit binaries) and popped in the MySql Connector DLL (ADO not ODBC) into my project and began whipping up some code in no time.

However, this little trick seemed to be not well known after some google searching on why MySQL Workbench (great tool btw) can connect, but my app could not.

Being a security conscious developer, when installing SQL I selected developer mode and opted for a safer named pipes connection for local development vs socket network connection looping through my localhost via TCP.

If you also selected this option, you may have had trouble getting your app to connect as well.

After searching through various (not necessarily directly related) sites, I found the answer.

See simple connection string snippet below.

Pipe=MySQL;Protocol=pipe;Host=.;Database=[yourdb];User ID=[youruser];Password=[yourpass]

To my surprise, the little note about specifying a period “.” as the host for named pipe connections was not easily found in the references below..

References
PhalangerMySQL (Java2s), https://www.java2s.com/Open-Source/CSharp/Database/PhalangerMySQL/MySql/Data/CatalogData.htm
.Net MySQL Connector Documentation (MySql), http://dev.mysql.com/doc/refman/5.1/en/connector-net.html
Network Traffic Filter Documentation (wireshark), http://wiki.wireshark.org/DisplayFilters
Connecting MySQL via CLI (MySQL), http://dev.mysql.com/doc/refman/5.1/en/connecting.html
Connection String Reference (MySQL), http://dev.mysql.com/doc/refman/5.1/en/connector-net-connection-options.html
MySQL Workbench Documentation (huihoo), http://docs.huihoo.com/mysql/refman-5.5-en/wb-intro.html
Connectionstrings.com, http://www.connectionstrings.com/mysql
codemaker.co.uk, http://www.codemaker.co.uk/it/tips/ado_conn.htm#MySQLNETNativeProvider
MySqlConnection in C# (bitdaddys)http://bitdaddys.com/MySQL-ConnectorNet.html
PHP MySQL Reference, http://php.net/manual/en/function.mysql-connect.php
MySqlCommand in C# (stackoverflow) http://stackoverflow.com/questions/2775692/c-and-mysql-net-connector-any-way-of-preventing-sql-injection-attacks-in-a-ge

Get Current Directory in Objective-C

Since Mac OS X is a unix based system, you can always use “getcwd” from the standard C library, but in general if you want to stick within the context of Objective-C/Cocoa, see the examples below.

Here’s one snippet you will probably Google quickly, but ultimately not the solution I chose.

(original code from stackoverflow see reference below)

NSFileManager *filemgr;
NSString *currentpath;

filemgr = [[NSFileManager alloc] init];

currentpath = [filemgr currentDirectoryPath];

Solution

Using the “bundle path” rather than “executable path” turned out to work much better in my instance:

NSString *currentpath = [[[[NSBundle mainBundle] bundlePath] stringByDeletingPathExtension] stringByDeletingLastPathcomponent];
NSString *fileName = [NSString stringWithFormat:@"%@/%@/",currentpath,@"filename.pdf"];

References
stackoverflow.com, http://stackoverflow.com/questions/3692489/getting-current-directory-in-objective-c
friendlydeveloper.com, “NSFileManager”, http://www.friendlydeveloper.com/tag/nsfilemanager/
techtopia.com, “Working with Directories in Objective c”, http://www.techotopia.com/index.php/Working_with_Directories_in_Objective-C
Macrumors Forums, http://forums.macrumors.com/showthread.php?t=524754
stackoverflow, “Find Parent Directory of a path”, http://stackoverflow.com/questions/1309524/cocoa-objc-find-parent-directory-of-a-path

HTTP Post in C# .Net

Why re-invent the wheel? ;)

See below for a few quick examples from the minds over at csharp-online and codeproject.


Note:
Any snippets may have been condensed from their original sources for brevity. See references for original articles.

All examples are in C# .Net.

HTTP Post:

using System.Net;
...
string HttpPost (string uri, string parameters)
{ 
   // parameters: name1=value1&name2=value2	
   WebRequest webRequest = WebRequest.Create (uri);
   //string ProxyString = 
   //   System.Configuration.ConfigurationManager.AppSettings
   //   [GetConfigKey("proxy")];
   //webRequest.Proxy = new WebProxy (ProxyString, true);
   //Commenting out above required change to App.Config
   webRequest.ContentType = "application/x-www-form-urlencoded";
   webRequest.Method = "POST";
   byte[] bytes = Encoding.ASCII.GetBytes (parameters);
   Stream os = null;
   try
   { // send the Post
      webRequest.ContentLength = bytes.Length;   //Count bytes to send
      os = webRequest.GetRequestStream();
      os.Write (bytes, 0, bytes.Length);         //Send it
   }
   catch (WebException ex)
   {
      MessageBox.Show ( ex.Message, "HttpPost: Request error", 
         MessageBoxButtons.OK, MessageBoxIcon.Error );
   }
   finally
   {
      if (os != null)
      {
         os.Close();
      }
   }
 
   try
   { // get the response
      WebResponse webResponse = webRequest.GetResponse();
      if (webResponse == null) 
         { return null; }
      StreamReader sr = new StreamReader (webResponse.GetResponseStream());
      return sr.ReadToEnd ().Trim ();
   }
   catch (WebException ex)
   {
      MessageBox.Show ( ex.Message, "HttpPost: Response error", 
         MessageBoxButtons.OK, MessageBoxIcon.Error );
   }
   return null;
} // end HttpPost 

Intermediate webrequest usage:

using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;
using System.IO;
 
namespace BaseClassNameSpace.Web.BaseServices
{

//This base class provides implementation of request 

//and response methods during Http Calls.
      public class HttpBaseClass
      {
 
            private string UserName;
            private string UserPwd;
            private string ProxyServer;
            private int ProxyPort;
            private string Request;
            
            public HttpBaseClass(string HttpUserName, 
              string HttpUserPwd, string HttpProxyServer, 
              int HttpProxyPort, string HttpRequest)
            {
                  UserName = HttpUserName;
                  UserPwd = HttpUserPwd;
                  ProxyServer = HttpProxyServer;
                  ProxyPort = HttpProxyPort;
                  Request = HttpRequest;
            }
 
/// <summary>

// This method creates secure/non secure web
// request based on the parameters passed.
            public virtual HttpWebRequest CreateWebRequest(string uri, 
              NameValueCollection collHeader, 
              string RequestMethod, bool NwCred)
            {
                  HttpWebRequest webrequest = 
                   (HttpWebRequest) WebRequest.Create(uri);
                  webrequest.KeepAlive = false;
                  webrequest.Method = RequestMethod;
 
                  int iCount = collHeader.Count;
                  string key;
                  string keyvalue;
 
                  for (int i=0; i < iCount; i++)
                  {
                        key = collHeader.Keys[i];
                        keyvalue = collHeader[i];
                        webrequest.Headers.Add(key, keyvalue);
                  }
                  
                  webrequest.ContentType = "text/html"; 
                  //"application/x-www-form-urlencoded";

                  if (ProxyServer.Length > 0)
                  {
                     webrequest.Proxy = new 
                      WebProxy(ProxyServer,ProxyPort);
                  }
                  webrequest.AllowAutoRedirect = false;
 
                  if (NwCred)
                  {
                      CredentialCache wrCache = 
                              new CredentialCache();
                      wrCache.Add(new Uri(uri),"Basic",
                        new NetworkCredential(UserName,UserPwd));
                      webrequest.Credentials = wrCache;
                  }
                  //Remove collection elements

                  collHeader.Clear();
                  return webrequest;
            }//End of secure CreateWebRequest

            
            // This method retreives redirected URL from

            // response header and also passes back

            // any cookie (if there is any)

            public virtual string GetRedirectURL(HttpWebResponse 
                 webresponse, ref string Cookie)
            {
                  string uri="";
 
                  WebHeaderCollection headers = webresponse.Headers;
                  
                  if ((webresponse.StatusCode == HttpStatusCode.Found) || 
                    (webresponse.StatusCode == HttpStatusCode.Redirect) ||
                    (webresponse.StatusCode == HttpStatusCode.Moved) ||
                    (webresponse.StatusCode == HttpStatusCode.MovedPermanently))
                  {
                        // Get redirected uri

                        uri = headers["Location"] ;
                        uri = uri.Trim();
                  }
 
                  //Check for any cookies

                  if (headers["Set-Cookie"] != null)
                  {
                        Cookie = headers["Set-Cookie"];  
                  }
                  //                string StartURI = "http:/";

//                if (uri.Length > 0 && uri.StartsWith(StartURI)==false)

//                {

//                      uri = StartURI + uri;

//                }

                  return uri;
            }//End of GetRedirectURL method

            public virtual string GetFinalResponse(string ReUri, 
             string Cookie, string RequestMethod, bool NwCred)
            {
                  NameValueCollection collHeader = 
                        new NameValueCollection();
 
                  if (Cookie.Length > 0)
                  {
                        collHeader.Add("Cookie",Cookie);
                  }
 
                  HttpWebRequest webrequest = 
                    CreateWebRequest(ReUri,collHeader, 
                    RequestMethod, NwCred);
                        
                  BuildReqStream(ref webrequest);
 
                  HttpWebResponse webresponse;
 
                  webresponse = (HttpWebResponse)webrequest.GetResponse();
 
                  Encoding enc = System.Text.Encoding.GetEncoding(1252);
                  StreamReader loResponseStream = new 
                    StreamReader(webresponse.GetResponseStream(),enc);
 
                  string Response = loResponseStream.ReadToEnd();
 
                  loResponseStream.Close();
                  webresponse.Close();
                  
                  return Response;
            }
 
            private void BuildReqStream(ref HttpWebRequest webrequest)
            {
                  byte[] bytes = Encoding.ASCII.GetBytes(Request);
                  webrequest.ContentLength=bytes.Length;
 
                  Stream oStreamOut = webrequest.GetRequestStream();
                  oStreamOut.Write(bytes,0,bytes.Length);
                  oStreamOut.Close();
            }
      }
}//End of HttpBaseClass class

References:
Csharp-online, “HTTP Post”, http://en.csharp-online.net/HTTP_Post
Codeproject, “How to use HttpWebRequest and HttpWebResponse in .NET”, http://www.codeproject.com/KB/IP/httpwebrequest_response.aspx

URL Encode in .Net

C#: (ASP .Net)

System.Web.HttpUtility.UrlEncode()

C#: (Client/Server Environment)

Uri.EscapeUriString()

References
MSDN, WebUtility Classhttp://msdn.microsoft.com/en-us/library/system.net.webutility.aspx
MSDN, Uri Classhttp://msdn.microsoft.com/en-us/library/system.uri.escapeuristring.aspx
MSDN blogs, http://blogs.msdn.com/b/yangxind/archive/2006/11/09/don-t-use-net-system-uri-unescapedatastring-in-url-decoding.aspx

Quick .Net Encryption Reference

The code below represents a very basic .NET encryption class which has been tested and should work in your application – simply plug and play. :)

Contains two static methods that can be called without needing to instantiate the class.

Keep in mind the initialization vector below (indicated by rgbIV) is generic, and you will need to come up with your own. Remember not to share this. Even if the password is compromised, the attacker would also need to know the initialization vector to crack your value.

Also note the code which has been commented out. This illustrates cases where passwords and/or IV can be statically set in the class and/or shared based on value passed in for password parameter.

Sharing IV and password or storing either statically is a security risk and could cause errors depending on byte differences of the values. If you statically store these values, you will still create secure cipher text, but it will be much easier to crack.

Enjoy. ;)

using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

namespace AIS.Common.Crypto
{

public static class Rijndael
{
    public static string Encrypt(string ClearText,string password)
    {

        byte[] clearTextBytes = Encoding.UTF8.GetBytes(ClearText);

        System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();

        MemoryStream ms = new MemoryStream();
        
        byte[] rgbIV = Encoding.ASCII.GetBytes("example");
        //byte[] key = Encoding.ASCII.GetBytes("longerexample");

        //byte[] rgbIV = Encoding.ASCII.GetBytes(password);
        byte[] key = Encoding.ASCII.GetBytes(password);

        CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV),
   CryptoStreamMode.Write);

        cs.Write(clearTextBytes, 0, clearTextBytes.Length);

        cs.Close();

        return Convert.ToBase64String(ms.ToArray());
    }

    public static string Decrypt(string EncryptedText, string password)
    {
        byte[] encryptedTextBytes = Convert.FromBase64String(EncryptedText);

        MemoryStream ms = new MemoryStream();

        System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();


        byte[] rgbIV = Encoding.ASCII.GetBytes("example");
        //byte[] key = Encoding.ASCII.GetBytes("longerexample");

        //byte[] rgbIV = Encoding.ASCII.GetBytes(password);
        byte[] key = Encoding.ASCII.GetBytes(password);

        CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(key, rgbIV),
        CryptoStreamMode.Write);

        cs.Write(encryptedTextBytes, 0, encryptedTextBytes.Length);

        cs.Close();

        return Encoding.UTF8.GetString(ms.ToArray());

    }

}
}

References:
Wikipedia – Encryption, http://en.wikipedia.org/wiki/Encryption

Quick .Net Email Reference

I’ve done a bit of encapsulation here to abstract the concept into clearer functionality, IMO.

Make sure to add “using” reference directives for System.Threading and System.Net.Mail accordingly, when necessary.

Note usage of basic boolean “sync lock” style logic in place of static members for thread safety.

(This code is purely illustration of concept and functionality is not assured. Correctness of code is coincidental. :) )

C#:

private Automailer mailer;

private void StartEmailAutomailer() {
      int interval = 100000;
                    System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
                    //set host, port, etc from your data layer
                    List<System.Net.Mail.MailAddress> recipients = DataAccess.MailInfo.recipients;

                    if (mailer == null)
                    {    
                        mailer = new Automailer(interval,client,recipients);
                    }
                    else
                    {
                        mailer.AccessMailInterval = interval;
                        mailer.AccessMailClient = client;
                        mailer.AccessMailRecipients = recipients;
                    }
                    mailer.Start();
}

//contain in job/agent type definitions
public class Automailer
    {
        private System.Timers.Timer mailerthread;

        public bool IsRunning { get; private set; }
        private bool sending { get; set; }

        public double AccessMailInterval
        {
            get
            {
                return mailerthread.Interval;
            }
            set
            {
                if (sending == false)
                {
                    mailerthread.Interval = AccessMailInterval;
                }
                else
                {
                    utils.cout("Cannot modify interval while mail cycle is processing.");
                }
            }
        }

        private SmtpClient MailClient;
        public SmtpClient AccessMailClient { 
            get {
                    return MailClient;
        }
            set
            {
                if (sending == false)
                {
                    MailClient = AccessMailClient;
                }
                else
                {
                    utils.cout("Cannot modify mail client while mail cycle is processing.");
                }
            }
        }

        private List<MailAddress> MailRecipients;
        public List<MailAddress> AccessMailRecipients { 
            get {
                    return MailRecipients;
        } 
            set {
                if (sending == false)
                {
                    MailRecipients = AccessMailRecipients;
                }
                else
                {
                    utils.cout("Cannot modify mail recipients while mail cycle is processing.");
                }

            } 
        }

        /// Must be manually started / stopped.
        public Automailer(double interval,SmtpClient client,List<MailAddress> recipients)
        {
            try
            {
                MailClient = client;
                MailRecipients = recipients;

                sending = false;
                mailerthread = new System.Timers.Timer(interval);
                mailerthread.Elapsed += new System.Timers.ElapsedEventHandler(SendMail);
            }
            catch (Exception ex)
            {
                utils.cout("Error sending email. Details:" + "\r\n" + ex.ToString());
            }
        }

        public void Start() {
            if (IsRunning)
            {
                utils.cout("Automailer agent already running.");
            }
            else
            {
                utils.cout("Starting automailer agent...");
                mailerthread.Start();
                IsRunning = true;
                utils.cout("Initialized.");
            }
        }
        
        public void Stop() {
            if (IsRunning)
            {
                utils.cout("Sending halt and exit command to automailer agent...");
                mailerthread.Stop();
                utils.cout("Stopped.");

                if (sending)
                {
                    utils.cout("Warning: automailer stopped during mail cycle.");
                }
            }
            else
            {
                utils.cout("Automailer agent is not running.");
            }
            
        }

        /// Fires on timer or can be called manually.
        public void SendMail(object source, System.Timers.ElapsedEventArgs e)
        {
            if (sending == false)
            {
                sending = true;
                int successcount = 0;
                try
                {
                    utils.cout("Starting mail cycle...");
                    int rollingcount = 0;
                    foreach (MailAddress address in MailRecipients)
                    {
                        rollingcount += 1;
                        utils.cout(String.Format("Sending email {0} of {1}.", rollingcount, MailRecipients.Count));

                        MailMessage message = new MailMessage();

                        try
                        {
                            message.Body = DataAccess.MailInfo.body;
                            message.IsBodyHtml = DataAccess.MailInfo.ishtml;
                        }
                        catch (Exception ex4)
                        {
                            utils.cout("Could not populate body from template. Message will be sent using defaults. Details:" + "\r\n" + ex4.ToString());
                            message.IsBodyHtml = true;
                            message.Body = String.Format("Thank-you! <br /><br /> \r\n \r\n - {0}",DataAccess.LicenseInfo.company);
                        }

                        try
                        {
                            message.To.Add(address);

                            try
                            {
                                MailClient.Send(message);
                                utils.cout(String.Format("Email sent to {0}.",address.Address));
                                successcount += 1;
                                //async can be used alternatively
                                //MailClient.SendAsync(message,)
                                //MailClient.SendCompleted += new SendCompletedEventHandler(SendMailComplete);
                            }
                            catch (Exception ex2)
                            {
                                utils.cout(String.Format("Could not send to {0}. Details:", address.Address) + "\r\n" + ex2.ToString());
                            }
                        }
                        catch (Exception ex3)
                        {
                            utils.cout(String.Format("Unable to add address {0} to the list. Details:", address.Address) + "\r\n" + ex3.ToString());
                        }

                        message.Dispose();
                    }
                   
                }
                catch (Exception ex)
                {
                    utils.cout("Error sending email. Details:" + "\r\n" + ex.ToString());
                }

                utils.cout(String.Format("Mail cycle complete. {0} sent successful, {1} failed to send.", successcount.ToString(), (MailRecipients.Count - successcount).ToString()));

                sending = false;
            }
        }

        //not used, can be used to engage on asyc calls
        private void SendMailComplete(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            
        }
    }

//data layer
public static class DataAccess {
public static class Mailinfo {
//contains static methods and properties for retrieving data from database or file, etc
}
}

//in a generic lib
public static class utils {
public static void cout(string outputtext) {
//output text to console, window, form, etc
}
}

JQuery Grid Themes

Useful links to JQuery grids utilizing (mostly) standard UI themes and/or very little code.

Google!
http://jquery-ui.googlecode.com/svn/branches/labs/grid/tests/static/grid/default.html

Datatables.Net:
http://www.datatables.net/styling/themes/smoothness

Ke-Cai:
http://www.ke-cai.net/2010/01/theme-your-table-with-jquery-ui.html

Trirand:
http://www.trirand.com/blog/jqgrid/jqgrid.html

Stackoverflow:
http://stackoverflow.com/questions/2613632/jquery-ui-themes-and-html-tables

Follow

Get every new post delivered to your Inbox.