C# : Override Operators == and != along with .Equals : Reference Types

When comparing “reference” types in c# with operators == and !=, we should overwrite these operators to perform comparison checks on the reference type’s specific value field or multiple fields. C# provides operators == and != to compare reference types by checking if they point to the same object in memory versus comparing if the two objects are equal. If we would like to design our comparison operators of == and != to return a comparison of the objects specific field then we must overwrite the operators our self.

Best Practice

** Overwrite the Equals method from the base class “Object” as well. This will keep the equality operators in sync for other developers that may use your class and its compare features. It is also best practice to always use the “Equals” method to check the equality of any reference type. Using operators causes issues when using generics.

private string _name;

public static bool operator == (Product prod1, Product prod2)
{
    if(prod1.Name.Equals(prod2.Name)){
        return true;
    } else {
        return false;
    }
}

public static bool operator != (Product prod1, Product prod2)
{
    if(!prod1.Name.Equals(prod2.Name)){
        return true;
    } else {
        return false;
    }
}

public overwrite bool Equals(Product first, Product second)
{
   if(first == null || second == null){
     return false;
   }

   if(first.Name == second.Name){
     return true;
   } else {
     return false;
   }
}

public string Name {
    get {
        return _name;
    }
    set {
        this._name = value.ToUpper();
    }
}

Upload Images to Amazon S3 Server using Node and Express.js

The code below will walk you through the process to get a working example created for uploading an image file to your Amazon S3 Server. You should already have a bucket created and have your key and secret on hand. We will add those strings to a config file. Once your done you will be able to upload an image file to your Amazon S3 server and verify the image was uploaded by refreshing your S3 Admin portal or view the image from your returned code.

Get the code from Github : https://github.com/wesleyduff/AmazonS3FileUpload

Continue reading

Use of !! in JavaScript

BANG BANG

Want to find out if something is false if it is a string, number, obj etc….


var x = “No”
typeof x
// string

var xBools = !!x;
//true – because variable x has a string of No, could be a string of false as well. A string is an object and that object has alpha characters
typeof xBools
// boolean

var emptyString = “”;
typeof emptyString 
// string

var emptyStringBools = !!emptyString;
//false – because the string is empty
typeof emptyStringBools 
// Boolean

var nulls = null;
typeof nulls
// object

var nullsBools = !!nulls;
//false
typeof nullsBools
// boolean

var under;
typeof under
// undefined

var underBools = !!under;
//false
typeof underBools
// boolean

Check to see if a variable has a value and if that value is usable.

How To: Submit Your Form Data as JSON data to be Consumed by a RESTful Service (Node.js & Express.js)

I need to obtain a JSON object that cantains all of my form data as key value pairs {name : value}.

Answer :

  • Use jQuery SerializeArray
    • This will not give you what you need right off. It will send back something like this
    • [{name: 'key', value = 'value'}]
  • Use the result from SerializeArray and run it through the custom SerializedArrayToJSON method described below
    • Pass the serialized array as a parameter to the SerializedArrayToJSON method.
      • The SerializedArrayToJSON will return a formatted javaScript object you can pass in your POST method.
      • Inside your route the req.body will contain each piece of your form data as ‘key : value’ pairs.

Example :


 var serializedArrayData= $('form').serializeArray();

 function SerializedArrayToJSON (serializedArrayData){
   //reformat formData
   var holder = [], returnData = {};

   for(var i = 0; i < serializedArrayData.length; i++){
    for(_key in serializedArrayData[i]){
       if(serializedArrayData[i].hasOwnProperty(_key)){
          holder.push(serializedArrayData[i][_key]);
       }
     }
   }
   for(var j = 0; j < holder.length; j++){
     if(j % 2 == 0 ){
       returnData[""+holder[j]+""] = holder[j + 1];
     }
   }

   return returnData;
};

How to : Add custom validation to a Mongoose Model

I need to add a custom validation to my mongoose model before I save to my Mongo Database.

Answer –

  • Custom validation is declared by passing a validation function.

Example

  • Note* Custom validation – method signature = validate(obj, [errorMsg])
 

var phoneValidator = [
 function(_value){ 
   return /d{3}-d{3}-d{4}/.test(v); 
 },
 "Please provide a valid phone number"
];

var customerSchema = new Schema(
 { 
   phone : 
   { 
     type: String, 
     validate: phoneValidator 
   }
 }
); 

var Customer = mongoose.model('customer', customerSchema);  

How to invoke a method that needs a generic type parameter through reflection

problem:

How to invoke a method that needs a generic type parameter through reflection

answer:

  1. Use the “Getinfo” of that type and pass it the a parameter of the name of the method you want to call.
  2. Convert the method that you assigned to a variable to a generic method using “MakeGenericMethod”
  3. Invoke the method with the parameters needed for that method
var person = new Person();
var personType = typeof(Person);
var methodInfo = personType.GetMethod('Speak');
methodInfo = methodInfo.MakeGenericMethod(typeof(DateTime));
methodInfo.Invoke(person, null);

//NOTE 
public void Speak<T>()
{
    //Name is a public property on the Person class
    Console.Write(typeof(T).Name);
}

How to create a dynamic collection in C#

problem:

I need to instantiate many collections. How can I do this dynamically with reflection?

answer:

Use the typeof to get the type of your collection and what kind of collection it will become. Pass those as parameters to a custom method to convert your parameters into a collection using “MakeGenericType” for your collection type and pass in the parameter of what object the collection should contain. Now use C#’s Activator class to create an instance of your collection and return it.

class Program
{
    static void Main(string[], args)
    {
        var myList = CreateCollection(typeof(List<>), typeof(Employee));
        // do more stuff here ...
    }

    private static object CreateCollection(Type collectionType, Type iteType)
    {
        var closedType = collectionType.MakeGenericType(itemType);
        return Activator.CreateInstance(closedType);
    }
}

How to capture a query string in a RESTful Get Request

problem:

I need to access the query parameter in the RESTful GET URL.

answer:

We overwrite our current GET method with another GET method that accepts a parameter. This parameter will be your query string. Then use LINQ to process your Enumerable object and return a filtered collection.

public IEnumerable<Product> Get(string queryString) { 
  var repository = new Repository(); 
  var products = repository.Retrieve(); 
  return products.Where(p => p.ProductId.Contains(queryString)); 
}