How to write a byte array to a file in c#

Thursday, 5 November 2009 12:04 by myro

An another piece of code that I should always remember...

public void writeByteArrayToFile(byte[] buff, string fileName)
{
 
     try
     {
               FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
               BinaryWriter bw = new BinaryWriter(fs);
               bw.Write(buff);
               bw.Close();

      }
      catch (Exception ex)
      {
              Console.WriteLine(ex.Message);
      }
}

Currently rated 4.3 by 6 people

  • Currently 4.333333/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Categories:   .NET
Actions:   Bookmark and Share | Permalink | Comments (0) | Comment RSSRSS comment feed

Add WaterMark to TextBox in Asp.Net: The simple way!

Sunday, 11 October 2009 17:17 by myro

There are different solutions on the web that describes how to implement a watermark over an asp.net TextBox. The solution I still prefer is just using JavaScript with  of asp.net's parser capabilities:

Into your ASPX markup page, try the solution posted below. solution:

<script type = "text/javascript">


// This Javascript is written by Peter Velichkov (www.creonfx.com)
// and is distributed under the following license : http://creativecommons.org/licenses/by-sa/3.0/
// Use and modify all you want just keep this comment. Thanks
// Defining array that holds the IDs or Names of the inputs and the default text to display
// If you are using Names remeber that I am taking only the first one.
// The format is : 'ID1','VALUE1','ID2','VALUE2'....
// var inputs = new Array('firstname','firstvalue','secondid','secondvalue','thirdid','thirdvalue')
// Defining "indexOf" function for Internet Explorer
// It returns the index of the first occurance of an item in the array


// As you can see i'm just inject the Asp.Net TextBoxes client side's IDs into the Javascript Code


var inputs = new Array('<%= txtSearchTerms.ClientID  %>','Search...','<%= txrLogin.ClientID  %>','Login...');

if (!Array.indexOf) {
    Array.prototype.indexOf = function(obj, start) {
        for (var i = (start || 0); i < this.length; i++) {
            if (this[i] == obj) {
                return i;
            }
        }
    }
}
 
// Defining addEvent function since Internet Explorer
 does not support the official way of adding events
 
function addEvent(obj, type, fn) {
    if (obj.addEventListener)
    obj.addEventListener(type, fn, false);
    else if (obj.attachEvent)
    {
        obj["e" + type + fn] = fn;
        obj[type + fn] = function() {
            obj["e" + type + fn](window.event);
        }
        obj.attachEvent("on" + type, obj[type + fn]);
    }
}
 
function inputWatermark() {
    if (inputs.length < 2 || inputs.length % 2 != 0) {
        alert('Wrong usage - please read the source comments!');
    }
    for (i = 0; i < inputs.length; i++) {
        if (i % 2 == 0 && (document.getElementById(inputs[i]) || document.getElementsByName(inputs[i])[0])) {
            var cur = (document.getElementById(inputs[i])) ? (document.getElementById(inputs[i])) : (document.getElementsByName(inputs[i])[0]);
            cur.value = inputs[i + 1];
            addEvent(cur, "focus", onFocusHandler);
            addEvent(cur, "blur", onBlurHandler);
        }
    }
}
 
function onFocusHandler() {
    var inpname = this.id ? this.id: this.name;
    if (this.value == '' || this.value == inputs[inputs.indexOf(inpname) + 1]) {
        this.value = '';
    }
}
 
function onBlurHandler() {
    var inpname = this.id ? this.id: this.name;
    if (this.value == '') {
        this.value = inputs[inputs.indexOf(inpname) + 1];
    }
}
 
addEvent(window, "load", inputWatermark);
</script>


<asp:TextBox ID="txtSearchTerms" runat="server" />
<asp:TextBox ID="txtLogin" runat="server" />

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:   ,
Categories:   .NET | Web
Actions:   Bookmark and Share | Permalink | Comments (0) | Comment RSSRSS comment feed

Convert DataReader to DataSet in c#

Monday, 5 October 2009 15:35 by myro

I've just founded an usefull code snippet that returns a DataSet from a DataReader. As you can see, I'm passing a DbDataReader, because I prefer to work with the DbProviderFactory instead of using directly the System.Data.Sql namespace. A replace of the DbDataReader into SqlDataReader, will work exactly the same.

public static DataSet convertDataReaderToDataSet(DbDataReader reader)
{
    DataSet dataSet = new DataSet();
    do
    {
        // Create new data table
        DataTable schemaTable = reader.GetSchemaTable();
        DataTable dataTable = new DataTable();

        if (schemaTable != null)
        {
            // A query returning records was executed
            for (int i = 0; i < schemaTable.Rows.Count; i++)
            {
                DataRow dataRow = schemaTable.Rows[i];
                // Create a column name that is unique in the data table
                string columnName = (string)dataRow["ColumnName"];
                // Add the column definition to the data table
                DataColumn column = new DataColumn(columnName, (Type)dataRow["DataType"]);
                dataTable.Columns.Add(column);
            }
            dataSet.Tables.Add(dataTable);
            // Fill the data table we just created
            while (reader.Read())
            {
                DataRow dataRow = dataTable.NewRow();

                for (int i = 0; i < reader.FieldCount; i++)
                    dataRow[i] = reader.GetValue(i);

                dataTable.Rows.Add(dataRow);
            }
        }
        else
        {
            // No records were returned
            DataColumn column = new DataColumn("RowsAffected");
            dataTable.Columns.Add(column);
            dataSet.Tables.Add(dataTable);
            DataRow dataRow = dataTable.NewRow();
            dataRow[0] = reader.RecordsAffected;
            dataTable.Rows.Add(dataRow);
        }
    }
    while (reader.NextResult());
    return dataSet;
}

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:   ,
Categories:   .NET
Actions:   Bookmark and Share | Permalink | Comments (1) | Comment RSSRSS comment feed

Use regular expressions to validate an email in c# using Regex

Sunday, 4 October 2009 18:32 by myro

If you need a simple method that validates an email address in c#, you are at the right place. The code snipped illustrated below, will check if the provided email address matches a regular expressionto and will determine if is a valid email or not.

public bool IsMailValid(string emailAddress)
{
    StringBuilder sb = new StringBuilder();
    sb.Append(@"^(([^<>()[\]\\.,;:\s@\""]+");
    sb.Append(@"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@");
    sb.Append(@"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}");
    sb.Append(@"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+");
    sb.Append(@"[a-zA-Z]{2,}))$");
    Regex reStrict = new Regex(sb.ToString());
    bool isStrictMatch = reStrict.IsMatch(emailAddress);
    return isStrictMatch;
}

Use it, paste it and share it!

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:   , ,
Categories:   .NET
Actions:   Bookmark and Share | Permalink | Comments (0) | Comment RSSRSS comment feed

Using Reflection to display object's property values in c#.

Monday, 28 September 2009 17:08 by myro

This code snippet posted below can be used to display all object's property values, by inkoing the ToString() of each property. An usefull implementation could be when you are in need of logging an object's state by writing to a log file all his properties states. 
The DisplayObjectProperties static method cycles throught the object's properties and as told before, it calls the ToString() method, which is always implemented since every class is derived from the Object class. Recuirsion is not implemented, the ToString() method will be called only at the first level.

public static class ReflectionHelper
{
    public static string DisplayObjectProperties(Object o)
    {
        StringBuilder sb = new StringBuilder();
        System.Type type = o.GetType();
        foreach (PropertyInfo p in type.GetProperties())
        {
            if (p.CanRead)
            {
                object obj = p.GetValue(o, null);
                if (obj != null)
                {
                    sb.AppendLine(String.Concat("-Property name: ", p.Name ));
                    sb.AppendLine(String.Concat("-Property value:", obj.ToString()));
                    sb.AppendLine();
                }
                else sb.Append(String.Concat(p.Name, " # Value is null"));

            }
        }
        return sb.ToString();
    }
}

Now immagine that you' ve got this sample class called PersonalAttribute:

 public class PersonalAttribute
{

    public string AttributeName { get; set; }

    public string AttributeValue { get; set; }

}

An usefull implementation could be:

public class PersonalAttribute
{

    public string AttributeName { get; set; }

    public string AttributeValue { get; set; }

    public override string ToString()
    {
        return ReflectionHelper.DisplayObjectProperties(this); 
    }

}

Now, when the ToString() method is invoked in a new PersonalAttribute's istance, the returned string is something similar to:

-Property name: AttributeName
-Property value:SiteName

-Property name: AttributeValue
-Property value:myrocode.com

Remember that using Reflection is slow compared to direct access of a property, field or method. If you are building a complex application, this could be not the best solution for you case.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:   ,
Categories:   .NET
Actions:   Bookmark and Share | Permalink | Comments (0) | Comment RSSRSS comment feed