C# RedisCacheDependency Class

If you need a Fast and out of process Redis Server based Cache Dependency in your ASP.Net application, you can use my RedisCacheDependency class

class RedisCacheDependency : CacheDependency
{
  public RedisCacheDependency(string key) : base()
  {
    // http://redis.io/topics/notifications
    // https://github.com/StackExchange/StackExchange.Redis
    // http://habrahabr.ru/post/240269/
    RedisClient.GetSubscriber().Subscribe(key, (c, v) =>
    {
        this.NotifyDependencyChanged(new object(), EventArgs.Empty);
    });
  }
}

All you need is to define RedisClient some where in your Global.asax Application_Start like

RedisClient = ConnectionMultiplexer.Connect(ConfigurationManager.AppSettings["RedisConfigurationString"]);

XMLViewer

In past couple weeks I was working on some data conversion projects which required loading data to DataSet with lots of DataTables and then using Linq I tried to join those tables and generate the results.

Mu problem was I sometimes to look at the DataSet and its DataTables in some database view, I mean like tables of a SQL Server database. I used DataSet.WriteXml to generate an Xml file from my import process so when ever I want to convert again I wouldn’t have to go through import process again.

Continue reading “XMLViewer”

DataTable with a ColumnName same as TableName

If you add a column to a DataTable with ColumnName set as TableName, and then save it as Xml using DataSet.WriteXml and then load it from Xml using DataSet.ReadXml, you’ll be surprised by that .Net automatically removed the column and added two more columns with this naming:

Assume that the TableName is “MyName” so the ColumnName is also “MyName”, after saving and loading you’ll lose “MyName” column and all the data in all rows, but you’ll have two new columns “MyName_Id” and “MyName_Id_0” both with data type set to Int32.

Continue reading “DataTable with a ColumnName same as TableName”

Did you know?

Did you know that in C# you can cast any number to any enum????
 
Look at the example:
 
public enum EnmYesNo
{
Yes = 1,
No = 2
}
 
int temp = 0;
EnmYesNo yesNo = (EnmYesNo)temp; // No error will shown
MessageBox.Show(yesNo.ToString()); // Will show ‘0’
 
temp = 154842;

EnmYesNo yesNo = (EnmYesNo)temp; // No error will shown
MessageBox.Show(yesNo.ToString()); // Will show ‘154842’
 
 
WOW!!!! I didn’t know about that, so the solution:
 
public static T ConvertEnum<T>(int t)
{
  if (Enum.IsDefined(typeof(T), t))
    return (T)Enum.Parse(typeof(T), t.ToString());
  else
    throw new Exception("Undefined Enum");
}
 
temp = 154842;

EnmYesNo yesNo = ConvertEnum<EnmYesNo>(temp); // An Exception will show up
MessageBox.Show(yesNo.ToString()); // unreachable code 🙂
 
Sadjad Bahmanpour
 

Visual C++ and Sorting std::list

Today I just feel like bloging (I think this is my 3rd today) so I feel lucky just see I had 2 comments on my blog this is best for today, so I’ll keep writing cause I think this is working (Donot try to disappoint me just if these helps post me comment :D)!!!
 
so If you look at my last blog in this Catagory youill see some Utils/ Wrapper on "std::list , std::hash_map , std::pair , std::string" some of them of slower than the MFC counterparts and some of them are lot faster (String is 1500% faster WOW! but List is slower but I like it!) but by being faster or slower I mean about 1000000 time operation which you never make :D.
 
Anyway today I’m gonna show you 2 new Utils:
 
1) First the way to sort the List of Referenece types like: List<int *>
 
This is the way:
 
    template<class Type>
    struct ReferenceTypeLess
      : public std::less<Type>
    {
      virtual bool operator()(const Type _Left, const Type _Right) const
      {
        return *_Left < *_Right;
      }
    };
 
just use it in this way:
 
  List<int *> listOfInts;
  … // (fill it here)
  listOfInts.sort(ReferenceTypeLess<int *>());
 
It will also work for References to class/ struct like: List<MyClass *> , just remember to override the "operator <" in the "MyClass".
 
 
2) The second is nothing special (DO you think all the rest was special?? :D) but helped me, hope help you to:
 
    //—————————————————————————
    template <class ValueType1, class ValueType2 = ValueType1, class ValueType3 = ValueType1, class ValueType4 = ValueType1>
    struct Rectangle
    {
      ValueType1 top;
      ValueType2 begin;
      ValueType3 bottom;
      ValueType4 end;
      Rectangle() { }
      Rectangle(ValueType1 top, ValueType2 begin, ValueType3 bottom, ValueType4 end) : top(top), begin(begin), bottom(bottom), end(end) { }
    };
    //—————————————————————————
    template <class ValueType>
    struct SymmetricalRectangle
      : public Rectangle<ValueType, ValueType, ValueType, ValueType>
    {
      SymmetricalRectangle() { }
      SymmetricalRectangle(ValueType top, ValueType begin, ValueType bottom, ValueType end) : Rectangle(top, begin, bottom, end) { }
      SymmetricalRectangle(ValueType value)
      {
        SetAll(value);
      }
      void SetAll(ValueType value)
      {
        top = value;
        begin = value;
        bottom = value;
        end = value;
      }
    };
    //—————————————————————————
    struct FloatRectangle
      : public SymmetricalRectangle<float>
    {
    public:
      FloatRectangle() : SymmetricalRectangle(0.0f) { }
      float Width() { return end – begin; }
      float Height() { return bottom – top; }
    };
    //—————————————————————————
    struct IntRectangle
      : public SymmetricalRectangle<int>
    {
    public:
      IntRectangle() : SymmetricalRectangle(0) { }
      int Width() { return end – begin; }
      int Height() { return bottom – top; }
    };
    //—————————————————————————
Those were Rectangle of everything.
 
 
Hope these will help,
 
Sadjad Bahmanpour
 

Visual C++ and Hashmap

This is my first entry on "Programming Tips" which I think there will be more on this, cause I think I more expert on this than anything else in computer science.
 
Anyway, today I tired to use some of MFC classes to build some Hashtable & List & Pair just equal to the C#. I has lots of problem which MFX so I tried to use the STD counterparts. The most problemy thing about Hashmap (std::hash_map) is that you cannot have a hash_map<CString> I mean having a Hashmap/ hashtable which key is CString, so this is how I wrote it (It is not all by me!):
 
    //—————————————————————————
    template <class KEY, class ARG_KEY = KEY, class TRAITS = std::less<KEY> >
    class HashCompare
      : public stdext::hash_compare<KEY, TRAITS>
    {
    public:
      using stdext::hash_compare<KEY, TRAITS>::operator();
      size_t operator()(const KEY& Key) const
      {
        return static_cast<size_t>(HashKey<ARG_KEY>(Key));
      }
    };
    //—————————————————————————
    template <class KEY, class VALUE, class HashCompareARG_KEY = KEY>
    class HashMap
      : public stdext::hash_map<KEY, VALUE, HashCompare<KEY, HashCompareARG_KEY> >
    {
    public:
      HashMap() : hash_map() { }
      virtual bool Add(KEY key, VALUE value)
      {
        std::pair<iterator, bool> pr;
        pr = insert(value_type(key, value));
        return pr.second;
      }
       // Be aware of that you have to delete the replaced value by yourself
      virtual bool Replace(KEY key, VALUE newValue)
      {
        iterator iter = find(key);
        if (iter != end()) // key found
        {
          iter->second = newValue;
          return true;
        }
        else
          return false;
      }
      virtual value_type *Find(KEY key)
      {
        iterator iter = find(key);
        if (iter != end()) // key found
          return &(*iter);
        else
          return NULL;
      }
    };
    //—————————————————————————
    template <class VALUE>
    class StringHashMap
      : public HashMap<CString, VALUE, LPCTSTR>
    {
    public:
      StringHashMap() : HashMap() { }
      virtual value_type *FindCaseInsensitive(CString key)
      {
        iterator iter = begin();
        while (iter != end())
        {
          if (!iter->first.CompareNoCase(key))
            return &(*iter);
          iter++;
        }
        return NULL;
      }
    };
    //—————————————————————————
    typedef StringHashMap<CString> StringStringHashMap;
    //—————————————————————————
After that I create the my own list which is something betwean std:list and CList:
 
    //—————————————————————————
    template<class _Ty, class FindKey = _Ty, class _Ax = std::allocator<_Ty>>
    class List
      : public std::list<_Ty, _Ax>
    {
    public:
      List() : list() { }
      virtual _Ty *Find(FindKey findKey)
      {
        for (iterator iter = begin(); iter != end(); iter++)
          if ((*iter) == findKey)
            return &(*iter);
        return NULL;
      }
      virtual _Ty *operator[](const unsigned int& index)
      {
        if (index < size())
        {
          int cnt = 0;
          for (iterator iter = begin(); iter != end(); iter++, cnt++)
            if (cnt == index)
              return &(*iter);
        }
        return NULL;
      }
      virtual iterator Add(const _Ty &element)
      {
        push_back(element);
        return –end();
      }
      virtual iterator Add(const List<_Ty, FindKey, _Ax> &list)
      {
        insert(end(), list.begin(), list.end());
        return –end();
      }
      virtual bool Remove(FindKey findKey, bool removeAllInstances = false)
      {
        bool retVal = false;
        iterator iterEnd = end();
        for (iterator iter = begin(); iter != iterEnd; iter++)
          if ((*iter) == findKey)
          {
            erase(iter);
            retVal = true;
            if (!removeAllInstances)
              break;
          }
        return retVal;
      }
    };
    //—————————————————————————
    template<class _Ty, class FindKey = _Ty, class _Ax = std::allocator<_Ty>>
    class SortedList
      : public List<_Ty, FindKey, _Ax>
    {
    public:
      iterator Add(const _Ty &element) override
      {
        iterator iterEnd = end();
        for (iterator iter = begin(); iter != iterEnd; iter++)
          if ((*iter) < element)
            return insert(iter, element);
        return List::Add(element);
      }
    };
    //—————————————————————————
    class StringList
      : public List<CString>
    {
    public:
      StringList() : List() { }
      virtual CString *FindCaseInsensitive(CString findKey)
      {
        iterator iterEnd = end();
        for (iterator iter = begin(); iter != iterEnd; iter++)
          if ((*iter).CompareNoCase(findKey))
            return &(*iter);
        return NULL;
      }
    };
    //—————————————————————————
    class SortedStringList
      : public SortedList<CString>
    {
    public:
      SortedStringList() : SortedList() { }
      virtual CString *FindCaseInsensitive(CString findKey)
      {
        iterator iterEnd = end();
        for (iterator iter = begin(); iter != iterEnd; iter++)
          if ((*iter).CompareNoCase(findKey))
            return &(*iter);
        return NULL;
      }
    };
    //—————————————————————————
 
and then Pair:
 
    //—————————————————————————
    template<class Type1, class Type2>
    class Pair
      : public std::pair<Type1, Type2>
    {
    public:
     Pair() : pair() { }
      Pair(const Type1& _Val1, const Type2& _Val2) : pair(_Val1, _Val2) { }
      virtual bool operator==(const Type1 &other) const
      {
        return (first == other);
      }
      virtual bool operator < (const Type1& other) const
      {
        return (first < other);
      }
    };
    //—————————————————————————
    class StringPair
      : public Pair<CString, CString>
    {
    public:
      StringPair() : Pair() { }
      StringPair(CString first, CString second) : Pair(first, second) { }
      virtual int CompareNoCase(CString psz)
      {
        return first.CompareNoCase(psz);
      }
    };
    //—————————————————————————
and the Pair list:
 
    //—————————————————————————
    class StringPairList
      : public List<StringPair, CString>
    {
    public:
      StringPairList() : List() { }
      virtual StringPair *FindCaseInsensitive(CString findKey)
      {
        iterator iterEnd = end();
        for (iterator iter = begin(); iter != iterEnd; iter++)
          if ((*iter).CompareNoCase(findKey))
            return &(*iter);
        return NULL;
      }
    };
    //—————————————————————————
 
 
with some more attention you’ll find out how to make a struct in the list to be sorted on one key (That’s way I use the findkey).
 
And the last but not the least my best String (which is 1500% faster than CString):
 
    //—————————————————————————
    class String
//      : public std::basic_string<wchar_t>
      : public std::basic_string<char>
    {
    protected:
      enum { _MAX_CHARS = 256 };
      value_type buffer[_MAX_CHARS + 1];
    public:
      String() : basic_string() { }
     
      String(const String& arg) : basic_string(arg) { }
      String(const value_type arg) : basic_string() { (*this) = arg;  }
      String(const value_type* arg) : basic_string(arg) { }
/*     String& operator=(const String& arg)     { assign(arg.c_str()); return (*this); }
      String& operator=(const value_type pArg) { assign(pArg); return (*this); }
      String& operator=(const value_type* pArg) { assign(pArg); return (*this); }*/
      //—————————————————————————
      virtual bool operator==(const String &other)     { return (this->compare(other) == 0); }
      virtual bool operator==(const value_type *other) { return (this->compare(other) == 0); }
      virtual bool operator> (const String &other)     { return (this->compare(other) >  0); }
      virtual bool operator> (const value_type *other) { return (this->compare(other) >  0); }
      virtual bool operator>=(const String &other)     { return (this->compare(other) >= 0); }
      virtual bool operator>=(const value_type *other) { return (this->compare(other) >= 0); }
      virtual bool operator< (const String &other)     { return (this->compare(other) <  0); }
      virtual bool operator< (const value_type *other) { return (this->compare(other) <  0); }
      virtual bool operator<=(const String &other)     { return (this->compare(other) <= 0); }
      virtual bool operator<=(const value_type *other) { return (this->compare(other) <= 0); }
      virtual operator const value_type *()            { return c_str(); }
      virtual String &operator+=(const String &other)     { append(other); return (*this); }
      virtual String &operator+=(const value_type other) { append(1, other); return (*this); }
      virtual String &operator+=(const value_type *other) { append(other); return (*this); }
      virtual String &operator+=(const int &other)        { AppendFormat("%d", other); return (*this); }
      //—————————————————————————
      virtual void ToUpper()                        { transform(begin(), end(), begin(), toupper); }
     virtual void ToLower()                        { transform(begin(), end(), begin(), tolower); }
      virtual bool IsEmpty() { return (this->compare(_T("")) == 0); }
      virtual void Format(const value_type *szFormat, …)
     {
      va_list argList;
      va_start(argList, szFormat); // Initialize variable arguments.
//        int ret = _vsnwprintf_s(buffer, _MAX_CHARS, _MAX_CHARS, szFormat, argList);
      int ret = _vsnprintf_s(buffer, _MAX_CHARS, _MAX_CHARS, szFormat, argList);
        if (ret > 0)
        assign(buffer, ret);
      va_end(argList); // Reset variable arguments.
     }
      //—————————————————————————
      virtual void AppendFormat(const value_type* szFormat, …)
     {
      va_list argList;
      va_start(argList, szFormat); // Initialize variable arguments.
//      int ret = _vsnwprintf_s(buffer, _MAX_CHARS, _MAX_CHARS, szFormat, argList);
      int ret = _vsnprintf_s(buffer, _MAX_CHARS, _MAX_CHARS, szFormat, argList);
        if (ret > 0)
          append(buffer, ret);
        va_end(argList); // Reset variable arguments.
     }
      //—————————————————————————
    };
    //—————————————————————————
    inline String operator+(const String& s1, const String& s2)
    {
      String retVal(s1);
      retVal += s2;
      return retVal;
    }
    inline String operator+(const String& s1, const String::value_type s2)
    {
      String retVal(s1);
      retVal += s2;
      return retVal;
    }
    inline String operator+(const String& s1, const String::value_type *s2)
    {
      String retVal(s1);
      retVal += s2;
      return retVal;
    }
    inline String operator+(const String::value_type s1, const String& s2)
    {
      String retVal(s1);
      retVal += s2;
      return retVal;
    }
    inline String operator+(const String::value_type *s1, const String& s2)
    {
      String retVal(s1);
      retVal += s2;
      return retVal;
    }
    //—————————————————————————
 
Hope these are will help,
just leave a message if you need help on those,
 
Sadjad Bahmanpour