Saturday, August 30, 2014

Completely Read-Only Object as Return Value

NOTE: I am not proposing a 'secure' code. It's just to make your code dumb proof, not hack proof.
At the pinnacle of the insanity, when you have that bong affecting your normal senses, you may want to return that object from your beloved method which cannot be modified in anyway. You cannot even create a new object of the class that you are returning to have exclusive access to your return type. Anyways, whatever it can be used (?) for, it's here:
using System;
using System.Collections.ObjectModel;
using System.Security.Permissions;

public class ReadOnlyClassAsReturnValue
{
    private int sampleInt;
    // make regular property read-only by creating only 'get' call 
    public int SampleInt
    {
        get { return sampleInt; }
    }

    private bool[] sampleCollection;
    // Collections need to be made ReadOnlyCollection<T> . 
    //      NOTE: Though ReadOnlyCollection<T> can be casted as IList<T>, never 
    //          do that. It allows someone to to change collection in compilte
    //          time only to realized during runtime that it cannot be changed
    public ReadOnlyCollection<bool> SampleCollection
    {
        get { return Array.AsReadOnly(sampleCollection); } //gives ReadOnlyCollection<T>
    }

    // 'private' varialbes can only be assigned in contructor. If any variable need to be assigned after
    // object is created, it need to be made 'internal'.
    protected string sampleString = "x";
    public string SampleString
    {
        get { return sampleString; }
    }

    // Contructor is made 'protected' as this class is to be used by serious consumers only.
    // If ultimate (dumb) user is going to be outside your assembly, you can make it 
    // 'internal' instead of 'prorected' eliminating need to override this class and 
    // providing more protection than 'protected' (and 'proected internal').
    protected ReadOnlyClassAsReturnValue(int sampleInt, bool[] sampleCollection)
    {
        this.sampleInt = sampleInt;
        this.sampleCollection = sampleCollection;
    }
}

public class PrimaryUserClass
{
    // Inherit ReadOnlyClassAsReturnValue so internal methods/properties/variables can be assigned
    private class ReadOnlyObjectMaker : ReadOnlyClassAsReturnValue
    {
        public ReadOnlyObjectMaker(int sampleInt, bool[] sampleCollection)
            : base(sampleInt, sampleCollection)
        { }

        public string SampleString
        {
            set
            {
                this.sampleString = value;
            }
        }
    }

    //NO ONE CAN CHANGE THIS RETURN VALUE
    public ReadOnlyClassAsReturnValue ReadOnlyClassReturner()
    {
        ReadOnlyObjectMaker returnValue = new ReadOnlyObjectMaker(10, new bool[] { true, false });
        returnValue.SampleString = "I can assign this";
        return returnValue;
    }
}

class Program
{
    static void Main(string[] args)
    {
        var returnValue = new PrimaryUserClass().ReadOnlyClassReturner();
        //returnValue cannot be modified. Why? Just for fun. Someone has to hack it to change anythingin returnValue.
    }
}

Tuesday, February 18, 2014

Counting Number of REAL lines in Your C# Code

If you are here, it means one (or more) of the three things: 1. You are the boss, 2. Your boss told you to count number of lines 3. You are a serious programmer.
Anyways, let's come to the point. Each programer is different.  Problem with just literally counting the line has many issues which this piece of code attempts to resolve as mentioned below:
0. Comments of // and /* kind are ignored.
1. A statement written in multiple line is considered single line.
2. brackets are (i.e. '{') not considered lines.
3. 'using namespace' line are ignored.


        private int CountNumberOfLinesInCSFilesOfDirectory(string dirPath)
        {
            FileInfo[] csFiles = new DirectoryInfo(txtPath.Text.Trim())
                                        .GetFiles("*.cs", SearchOption.AllDirectories);

            int totalNumberOfLines = 0;
            Parallel.ForEach(csFiles, fo =>
            {
                Interlocked.Add(ref totalNumberOfLines, CountNumberOfLine(fo));
            });
            return totalNumberOfLines;
        }

        private int CountNumberOfLine(Object tc)
        {
            FileInfo fo = (FileInfo)tc;
            int count = 0;
            int inComment = 0;
            using (StreamReader sr = fo.OpenText())
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    if (IsRealCode(line.Trim(), ref inComment))
                        count++;
                }
            }
            return count;
        }

        private bool IsRealCode(string trimmed, ref int inComment)
        {
            if (trimmed.StartsWith("/*") && trimmed.EndsWith("*/"))
                return false;
            else if (trimmed.StartsWith("/*"))
            {
                inComment++;
                return false;
            }
            else if (trimmed.EndsWith("*/"))
            {
                inComment--;
                return false;
            }

            return
                   inComment == 0
                && !trimmed.StartsWith("//")
                && (trimmed.StartsWith("if")
                    || trimmed.StartsWith("else if")
                    || trimmed.StartsWith("using (")
                    || trimmed.StartsWith("else  if")
                    || trimmed.Contains(";")
                    || trimmed.StartsWith("public") //method signature
                    || trimmed.StartsWith("private") //method signature
                    || trimmed.StartsWith("protected") //method signature
                    );
        }


There is (literally) no solution for below (un)kind of programers:
1. Write multiple statements in single line.
2. Who declare useless variables.
3.Whose every other line is debug.write
4. Inappropriate use of compiler directive (directive itself is not considered as line btw)
5. Bulk copy programmers who suffer from schizophrenia and lives only in their set of classes. Don't trust or reuse anything else.
6. Who still likes to reinvent the wheel.

Apart from above six non-solvable issues, if you can improve my code, it will be helpful to everyone.

Thursday, April 04, 2013

Firefox 20 Feature - Click To Play

If you, my friend, are annoyed by zillions of flash advertisements running on your browser for which you haven't subscribed, have a look at the latest version of Firefox 20. It has a hidden lovable feature called "Click To Play". If enabled, it will deactivate all Flash (and Java) plugins except the one which you select to activate in a page. I've a netbook ('cheap laptop') which cannot handle the army of flash advertisements so I chose to activate this hidden Click_To_Play feature on my recently updated Firefox.

How to Enable Click_To_Play:

  1. Open a new firefox tab and type "about:config" in address bar.
  2. Click on button which says "I will be careful" etc..
  3. Now search for Click_To_Play in "Search" box.
  4. Double click preference named "plugins.click_to_play". It will change value of the preference to 'true'.
  5. You are done. Go to any web site and click only the plugin which you know you want to activate.  
Happy Browsing and don't let the Flash ads bite!

Friday, February 15, 2013

Auto Mouse Click and Drag Generator

If you are looking for a simple but powerful fast mouse clicker application, you are not alone. I am growing old and the software written by kids are too difficult for me to use, so I wrote a simple one called Auto Mouse Click and Drag Generator by myself which suite my work style - use keyboard when you automate mouse.

Here is from where you can try yourself: https://sourceforge.net/projects/superclick/files/latest/download?source=directory

Source Code can be found at project home: https://sourceforge.net/projects/superclick/?source=directory

Dedicated blog location is: http://automouseclicker.blogspot.in/
Below are the screens of the software as of today. Latest version may have more features and better UI. I don't intend to post update on this blog as the software has it's own dedicated blog.

Happy clicking and crashing others' software!



Unity3D and Vector Graphics

SVG is a popular vector graphics format. It has same limitation and advantages like any other vector graphics formats but SVG is very popular (and it's open format). Actually most modern browsers (and mobile devices) support it. Also, a graphics developer can create complex vector graphics using various tools available and need not to be programmed. They are not there to replace all raster format but in some specific cases, it may be more advantageous to use vector graphics. One of the major advantage of the vector graphics in general is that it looks crisp regardless of resolution, and they are less in size (well, not all the times). They may take same amount of memory and little more processing power but sometime they are worth it.

After thinking about all these advantages, I went look for unity plugin that can support direct rendering of SVG file or converts it to texture in runtime and show it and I found this:

http://wiki.unity3d.com/index.php?title=SVG

This one is still in its basic form and not yet practical to use. I hope something along the way come to make Unity use 2D vector rendering easier.

The other one that I stuck during my search was:
http://virtualplayground.d2.pl/?p=241
This one works with basic shapes and creates triangles out of vector forms which is more Unity friendly. It's nice thing but the implementation as of now has very limited features and most probably will not satisfy your needs.

Btw, as you may know, Flash already supports vector rendering (proprietary format) and this is the main reason why Flash games are very light in size and still looks crisp.

Tuesday, September 11, 2012

Extract BINK to PNG Sequence (with transparency)


BINK movies are widely  used in games because they provide transparency in the video from long back. Sometime you have to reverse engineer the BINK file and get the PNGs out of (not JPEG but PNG with  transparency) the movie. I've used FFMpeg to get PNGs out of BINK (.bik format) file as followed.

1. Download latest ffmpeg static build from http://ffmpeg.zeranoe.com/builds/
2. Extract the .7z build to any folder.
3. Give this command to convert “my.bik” to “output” folder and %d is sequence number in output image.  %d will auto increment by one, you have to just give %d in the command.
ffmpeg.exe -i D:\my.bik D:\output\my_%d.png
Note that this is a general command which applies to any type of movie format supported by ffmpeg. There are hell lot of more things you can with ffmpeg. For example, your popular VLC is built using ffmpeg library :) 

Tuesday, May 08, 2012

When your 'mktime' is slow as shit

While working on Vanilla Forum, I realized that dashboard was taking around 3 seconds to load on LAN. When looked further using Xdebug and cachegrind log, I realized that a method called "UnixTimestamp" (in Framework.Functions.php) was calling a stupid method called "mktime". What it does is just return the timestamp value (elapsed int value from a stupid start date of C which will create problem 2030). Not sure why on the earth this should happen, but this method is utter slow. So slow that when I wrote got the UTC time from my MySQL server (of local machine), it was 3 time fast.

Conclusion:
If your mktime is slow, throw that shit out and use stupider but faster method.. i.e. tell MySQL to do it for you. Here is what I wrote:

 
  $query = sprintf("SELECT UNIX_TIMESTAMP('%s') as UTS",
     mysql_real_escape_string($DateTime));
  $result = mysql_query($query);
  if($row = mysql_fetch_assoc($result)) {
     return $row['UTS'];
  }
May PHP god have mercy on you! Happy Coding!

Friday, March 16, 2012

SqlDateTime overflow Exception with NHibernate

SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
Exception Stacktrace:
at System.Data.SqlTypes.SqlDateTime.FromTimeSpan(TimeSpan value)
at System.Data.SqlTypes.SqlDateTime.FromDateTime(DateTime value)
at System.Data.SqlClient.MetaType.FromDateTime(DateTime dateTime, Byte cb)
at System.Data.SqlClient.TdsParser.WriteValue(Object value, MetaType type, Byte scale, Int32 actualLength, Int32 encodingByteSize, Int32 offset, TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParser.TdsExecuteRPC(_SqlRPC[] rpcArray, Int32 timeout, Boolean inSchema, SqlNotificationRequest notificationRequest, TdsParserStateObject stateObj, Boolean isCommandProc)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at NHibernate.AdoNet.AbstractBatcher.ExecuteNonQuery(IDbCommand cmd)
at NHibernate.AdoNet.NonBatchingBatcher.AddToBatch(IExpectation expectation)
at NHibernate.Persister.Entity.AbstractEntityPersister.Update(Object id, Object[] fields, Object[] oldFields, Object rowId, Boolean[] includeProperty, Int32 j, Object oldVersion, Object obj, SqlCommandInfo sql, ISessionImplementor session)
at NHibernate.Persister.Entity.AbstractEntityPersister.UpdateOrInsert(Object id, Object[] fields, Object[] oldFields, Object rowId, Boolean[] includeProperty, Int32 j, Object oldVersion, Object obj, SqlCommandInfo sql, ISessionImplementor session)
What is NOT a problem:
As always, I opned SQL Profiler and tried solve the issue but it misguided me by adding few extra zeros in millisecond part of datetime (I don't want to discuss it and it is not the problem).

What IS (or was in my case) problem:
I added an extra Datetime filed which was nullable in database. But I was mapping it to DateTime in my database. When NHibernate was converting my unset Datetime to SQLdatetime for mysterious reason, it was trying to set DateTime.Min in SQL datetime datatype which is not allowed (see exception).

Solution:
Look for any Datetime in your mappings that should be nullabe (according to database). And then use
type="System.Nullable`1[[System.DateTime, mscorlib]], mscorlib" in your mapping.

Thursday, December 01, 2011

Floating/Fixed Table Header in HTML Page or Inside DIV control

I’ve looked a lot for finding a solution were we can float a header of a table so that the header always appears on the top no matter how down do I scroll.
All the ‘floating table header’ solution ‘mostly’ worked were full HTML body is getting the scroll but none of them worked which can work inside scrolling div. None!
So I though I can create one. The concept was simple, get the ‘onScroll’ even of Div control and change CSS “top” property of table header to current scrolled position of Div. 
Unfortunately, there are many browser issues. Like mozilla doesn’t like when table cells change their position. Chrome rendering issues shows two headers rows when scrolled up.
At last, after storming through the problems, I arrived on this complex but simplified solution which is mentioned below. Copy the content in a blank HTML file and see the fun.

<html> 
    <head> 
        <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript" > </script> 
        <script  type="text/javascript"> 
            $(function() { 
                if($.browser.mozilla) 
                    //table row doean't float in firefox, div floats 
                    $(".floatingHeader" + " tr th div") 
                            .addClass("floatingStyle"); 
                else 
                    //table row can float in IE and Chrome 
                    $(".floatingHeader"+ " tr th") 
                            .addClass("floatingStyle"); 
            }); 
            function changeFloatingHeaderPosition(container, headerId) { 
                    if($.browser.webkit) //chrome rendering bug fix 
                        $("#"+headerId + " tr th") 
                            .css("visibility", "hidden"); 
                    if($.browser.mozilla) 
                        $("#"+headerId + " tr th div") 
                            .css("top", container.scrollTop); 
                    else 
                        $("#"+headerId + " tr th") 
                            .css("top", container.scrollTop); 
                    if($.browser.webkit) //chrome rendering bug fix 
                        $("#"+headerId + " tr th") 
                            .css("visibility", "visible"); 
            } 
     
      // Remove this method if you are using Jqeury earlier than 1.9
     (function() {
      var matched, browser;

      // Use of jQuery.browser is frowned upon.
      // More details: http://api.jquery.com/jQuery.browser
      // jQuery.uaMatch maintained for back-compat
      jQuery.uaMatch = function( ua ) {
   ua = ua.toLowerCase();

   var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
       /(webkit)[ \/]([\w.]+)/.exec( ua ) ||
       /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
       /(msie) ([\w.]+)/.exec( ua ) ||
       ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
       [];

   return {
       browser: match[ 1 ] || "",
       version: match[ 2 ] || "0"
   };
      };

      matched = jQuery.uaMatch( navigator.userAgent );
      browser = {};

      if ( matched.browser ) {
   browser[ matched.browser ] = true;
   browser.version = matched.version;
      }

      // Chrome is Webkit, but Webkit is also Safari.
      if ( browser.chrome ) {
   browser.webkit = true;
      } else if ( browser.webkit ) {
   browser.safari = true;
      }

      jQuery.browser = browser;
  })();
        </script> 
        <style> 
            .floatingStyle 
            { 
                position:relative; 
                background-color:#829DC0; 
                top:0px; 
            } 
        </style> 
    </head> 
<body> 
    <div class="floatingContainer"     onscroll="changeFloatingHeaderPosition(this, 'idHeader' );"      style="height:150px; width: 100px;overflow:auto;"> 
        <table cellspacing=0 cellpadding=0> 
            <thead class="floatingHeader" id="idHeader"> 
                <tr> 
                    <th><div>Col1</div></th>                     <th ><div>Col2<div></th> 
                    <th ><div>Col3<div></th> 
                </tr> 
            </thead> 
            <tbody> 
                <tr><td>first_row</td><td>first_row</td><td>first_row</td></tr> 
                <tr><td>data</td><td>data</td><td>data</td></tr> 
                <tr><td>data</td><td>data</td><td>data</td></tr> 
                <tr><td>data</td><td>data</td><td>data</td></tr> 
                <tr><td>data</td><td>data</td><td>data</td></tr> 
                <tr><td>data</td><td>data</td><td>data</td></tr> 
                <tr><td>data</td><td>data</td><td>data</td></tr> 
                <tr><td>data</td><td>data</td><td>data</td></tr>             </tbody> 
        </table> 
</div></body><html>
Note: Dan/Kenji has written plugging for the same which might be useful to you. I've not verified if it works in all case but worth having a look. You can find it: here: http://www.redkitetechnologies.com/2013/03/floatingsticky-headers-for-visualforce-pageblocktable/

Tuesday, November 15, 2011

Find Missing Foreign Key References

If you database column naming convention says all foreign key columns must end with 'ID' then this is the query for you to find missing foreign key reference. E.g. PRIZE_ID means Foreign Key reference to PRIZE table.
SELECT 
    colT.TABLE_NAME , 
    colT.COLUMN_NAME 
FROM 
    INFORMATION_SCHEMA.COLUMNS AS colT 
WHERE 
    COLUMN_NAME LIKE '%id'
    AND 
    (colT.TABLE_NAME + colT.COLUMN_NAME) NOT IN
     ( SELECT 
          KOM.TABLE_NAME + KOM.COLUMN_NAME 
      FROM 
          INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS KOM)

Monday, June 20, 2011

Amazon SimpleDB in Nutshell for those who know RDBMS Systems

Note: Latest Available Amazon SimpleDB version as of today, i.e. when I am writing this, is in Beta status with API Version: “2009-04-15”

Overview of SimpleDB
Amazon SimpleDB is a highly available, flexible, and scalable non-relational data store that offloads the work of database administration. Developers simply store and query data items via web services requests.[1]

Representation of Data with SimpleDB:

Domains— Domains are similar to tables that contain similar data.

You can execute queries against a domain, but cannot execute queries across different domains.

Attributes— They are similar to columns in RDBMS, attributes represent categories of data that can be assigned to items.

Items— Represented by rows, items represent individual objects that contain one or more attribute name-value pairs.

Values—Similar to column value, values represent instances of attributes for items. An attribute can have multiple values. There is no data typing supported for attribute and all data is treated as text data during query execution.

However, Amazon SimpleDB is not a relational database, and does not offer some features needed in certain applications, e.g. complex transactions or joins (i.e. execute queries across different domains).[1] You need to rely on duplicating the data to avoid such scenarios.[2]

Benefits of using SimpleDB

Highly Available
Amazon SimpleDB creates and manages multiple geographically distributed replicas of your data automatically to enable high availability and data durability.
Flexible
You can change your data model on the fly, and data is automatically indexed for you.
Scalability
You can access additional machine resources by spreading your data set and requests across multiple domains.

Support for Reporting
Sql Server Reporting Service (SSRS) is a popular platform to build and access reports. SSRS reports are build based on dataset that has set for a report. It is possible to build dataset from SimpleDB.[3] 

Limitation with SimpleDB

Domain (similar to table): 250 active domains per account. More can be requested by filling a form. Note that each attribute (similar to column) can hold multiple value.[4]

Attribute (similar to column) name-value pairs per item: 256[4]

Maximum response size for Select: 1 MB (large data like images can be stored separately into cloud as files and an Attribute can store URL for the resource).[4]

Maximum items per select: 2500[4]

Attribute value length: 1024 bytes[4]

No datatyping: text only. Integers and reals must be represented using leading zeros to ensure proper query comparisons.[5]

References:

[1] Amazon SimpleDB (beta)
http://aws.amazon.com/simpledb/

[2] How And Why Glue Is Using Amazon SimpleDB Instead Of A Relational Database
http://blog.getglue.com/?p=1145

[3] Accessing SimpleDB from SSRS
http://www.chrisumbel.com/article/simpledb_ssrs.aspx

[4] Amazon SimpleDB Limits, Amazon SimpleDB Developer Guide (API Latest version)
http://docs.amazonwebservices.com/AmazonSimpleDB/latest/DeveloperGuide/

[5] M/DB - A Free Open Source "plug-compatible" alternative to Amazon's SimpleDB database
http://gradvs1.mgateway.com/main/index.html?path=mdb

Thursday, April 21, 2011

How Apple's Location Services Work


Even though I like apples (specially the one which fell on Newton's head), I am not found of Apple as a corporation. Mainly because it is too secretive in its technologies and methods of doing something amazing. Location Services are one of those secretive things which need to be so secret but you can figure-out how it works.

Apple's Locations services uses (in order) A-GPS, Wi-Fi triangulation and Cell Triangulation (base on capability of your device).

Uses A-GPS
Pros
When you are outdoors, works amazingly.
Cons
Works poorly in urban environment with tall buildings. Even your vehicle roof is a problem for A-GPS. Doesn't work without GPS chip in device (case for iPod).

Uses cellular tower triangulation
Pros
Even with it's worst accuracy, sometimes it is more accurate than GPS in urban environment. This is because performance doesn't decrease in urban environments due to many towers triangulating in cities nowadays. 
Cons
Cellular tower triangulation as it is way too in accurate for the accuracy need of the day. This is option only when when no other medium of deciding location available.

Uses Wi-Fi triangulations
Pros
Works very accurate when one or more wi-fi is available in area. You need not to connect to a Wi-Fi, nether the Wi-Fi needs to know your requirement of locating your device. If the location of Wi-Fi is stored in Apple's giant database of all Wi-Fi and their co-ordinates, you are in luck. Your device contact Apple's service and based on Wi-Fi details, Apple will send you Wi-Fi coordinates. I am not sure if device triangulates the Wi-Fi once the coordinates are found or Apple's service will do it - but end result is accurate coordinates.
Cons
You need to be in range of one or more Wi-Fi. If you are using iPod, you should be connected with internet.

How Does Apple Get all Wi-Fi Locations?
Hmm... so the world need to have a database of all wi-fi and their locations. It is still guess for the people how apple has got this database? This is what I think based on recent controversies regarding Apple's privacy policy regarding sharing your iPhone location with Apple's Service:
When your device has correct location decided, it also looks for wi-fi around your device. It stores those information on iPhone and iTunes on your computer sends it to Apple. And so, this list has grown 2 fold in day and 4 fold in night (it is just saying).
Note that before to iOS 3.2, this was not the case so Apple used to use (and still using for older devices) Skyhook Wireless and Google's services for WiFi triangulations.

Now you are ready for next level: Go to Apple's Office Discloser of its Location Service and know more about it.

Friday, March 18, 2011

Good User Experience

Good user experience cannot be achieved by jazzy animations. It is these simple things that everyone wants to have.

google_attachment

Some common tips for better user experience (most of us knows but we don’t follow):

1. Use standard controls. In laymen language, text should look like text and button should look like a button.

2. Optimize for speed. Everyone want to get the things done faster. Don’t put animations which hinders speed of doing something. Your UI (specially forms) should be accessible by ‘keyboard only’ as well.

3. Think about the common mistake that user may be making while data entry. When you find something wrong, locate exact position and show understandable message to show the error.

4. Try to optimize available space. You controls should be able to adjust to larger width to avoid scrollbars if possible. Don’t put big logos of the application on each screen top.

5. Find the most used flows for your UI and optimize UI so user can complete the common tasks faster. If necessary, create different views of the same UI for different kind of user in organizational hierarchy.

Friday, February 04, 2011

Nested Transaction Handling with NHibernate

NHibernate doesn’t have inbuilt support for nested transaction (or I am not using latest version). But, with little compromises, you can create a class that enables almost everything what you really need. I am using NHibernateSessionManager which you can find here: http://www.codekeep.net/snippets/8b94e3e0-3ffd-4b59-b6ce-ed4d46158a7c.aspx
    public class SmartTransaction
    {
        bool _transactionOwner =false;
        bool _transactionActive = false;

        public bool IsActive
        {
            get
            {
                return _transactionActive;
            }
        }

        public void Begin()
        {
            if (_transactionActive) return; //return to bad programer's code

            try
            {
                _transactionOwner = !NHibernateSessionManager.Instance.HasOpenTransaction();
                if (_transactionOwner)
                    NHibernateSessionManager.Instance.BeginTransaction();
                _transactionActive = true;
            }
            catch
            {
                _transactionOwner = false;
                _transactionActive = false;
                throw;
            }
        }

        public void Commit()
        {
            if (!_transactionActive || !NHibernateSessionManager.Instance.HasOpenTransaction())
            {
                _transactionActive = false;
                return;
            }

            try
            {
                if (_transactionOwner)
                    NHibernateSessionManager.Instance.CommitTransaction();
            }
            catch //when you don't know what you are committing to.
            {
                NHibernateSessionManager.Instance.RollbackTransaction(); 
                throw;
            }
            finally
            {
                _transactionActive = false;
            }
        }

        public void Rollback()
        {
            _transactionActive = false;

            if (!NHibernateSessionManager.Instance.HasOpenTransaction())
                return;
            NHibernateSessionManager.Instance.RollbackTransaction();
        }
    }


Benefits:

1. When writing a method, you need not to worry about context of calling method. You can just begin transaction of SmartTransaction class. If calling method has started transaction already, SmartTransaction doesn’t begin the transaction, but if something goes wrong, it will rollback entire transaction (of calling method).


2. You need not to worry if method you are calling needs transaction wrapping. As with SmartTransaction class, if method you are calling needs transaction wrapping, it will have transaction wrapping using SmartTransaction class.


Sunday, November 14, 2010

iPhone Button for Navigation Bar

If you are developing iPhone application and trying to use UIButton on ‘Navigation Bar’ instead of ' ‘difficult to use’ ‘Bar Button Item’, you need a button image that exactly looks like Bar Button.

As I couldn’t find the button background on net, I created it myself using Paint.NET. Here it is for  you.

iphoneButtonBig

Sunday, August 08, 2010

What are Characteristics of Successful Innovative Idea

I’ve been associate with an Innovation Lab from quite a some time and observing for life how a genuine ideas turn into a success. Though I’ve never been able to own a killer existing idea, I can still depict some characteristics of successful innovative idea (based on guts but without example or stories - bad bad to convince people).

  • Idea that solve problem for many.
  • Idea that have feasibility to be prototyped.  Idea that can be prototyped in short duration.
  • Idea that reasons (in term of Math, Science AND Art) why the idea can be successful. Idea should reference similar success.
  • Idea that is inline with what your associated firm is trying to do.

Wednesday, July 21, 2010

Concatenation of Styles in WPF

In order to avoid confusion and/or be inline with OOP concepts, WPF style will not allow you to concatenate multiple style in one control. Instead, you can use ‘BasedOn’ property (of Style element) to inherit from the other style. It is possible to create chain of inheritance but multiple inheritance is not supported by default. Initially I though it is not possible  until I came across this amazing link: http://swdeveloper.wordpress.com/2009/01/03/wpf-xaml-multiple-style-inheritance-and-markup-extensions/

It shows use of MarkupExtension to enable inheritance from multiple styles (in actual, your triggers and setters will be merged. Duplicates will be overwritten by the second style that you define)

Happy interfacing!

Monday, June 21, 2010

Solve “You are not allowed to upload ‘FileName’. the requested file type: 'FileType’” problem on Vanilla Forum 1.x

Issue:

You get this exception when you try to upload any file in your Vanilla Forum (Version 1) using any Attachment extension :
You are not allowed to upload ‘FileName’. the requested file type: 'FileType’

Resolution 1:

Add specified type as allowed type. Steps to do so follow here:

  1. Note the 'FileType’ in the error message.
  2. Go to extensions\Attachments\default.php file in your Vanilla forum’s directory.
  3. Add appropriate entry in Context->Configuration['ATTACHMENTS_ALLOWED_FILETYPES'] list.
  4. Note that it’s also important that you give correct extensions for the mime type you are allowing as both, 'FilteType’ (i.e. mime type) and file extensions are corss checked in Framework code of vanilla forum.
  5. Save the file and test.

Resolution 2:

Remove check for allowed types. Note that this is not very safe for public forum but it’s ‘ok’ for internal forum with known and responsible user. Steps to do so follow here:

  1. Go to “library\Framework\Framework.Class.Uploader.php”  file.
  2. Find this line of code “if (!array_key_exists($FileType, $this->AllowedFileTypes))”  and comment this ‘if’ and ‘else’ of it. Yes you need to comment if AND else.
  3. Save the file and test.

Thursday, April 15, 2010

Solve Exception Message: The IAsyncResult object was not returned from the corresponding asynchronous method on this class

Recently I was got a weird error on my Windows CE code (.NET compact framework) which was asynchronously listening for UDP (or may be same for TCP) messages.

Exception Message

Error Message: The IAsyncResult object was not returned from the corresponding asynchronous method on this class.
CallStack for debug purpose:
    at System.Net.Sockets.Socket.EndReceiveFrom()
    at BallyTech.SocketListener.UdpSocketListener.OnReceive()
    at System.Net.LazyAsyncResult.InvokeCallback()
    at WorkerThread.doWork()
    at WorkerThread.doWorkI()
    at WorkItem.doWork()
    at System.Threading.Timer.ring()

Issue

When frequently Open/Close UDP sockets, above exception comes while closing one socket and start listening on another socket on the same port. OnReceive method is called (only once) for the previous (closed) socket while doing “Start Listening” on new socket on the same port. As old socket is already dereferenced and closed, you will get above socket exception on EndReceiveFrom or EndReceive method.

Solution

In short, you have to ignore the calls of your OnReceive (or similar) for Old socket which you no longer use i.e. closed sockets.

Note that when you call BeginReceiveFrom to start listening for messages, it returns an instance of IAsyncResult. Don’t ignore this and store it into class level private variable (let’s say variable name currentAsyncResult).

Now make modification into  your OnReceive method to ignore any message which is not for currentAsyncResult.

private void OnReceive(IAsyncResult ar)
{
   try
   {
      if (ar == currentAynchResult)
      {
         IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
         EndPoint epSender = (EndPoint)ipeSender;

         //Error comes here if we didn't have (ar == currentAynchResult) check
         int bytesRead = udpSocket.EndReceiveFrom(ar, ref epSender);
         //process further
      }
      else
      {
         //Ignore
      }
      BeginReceive();
   }
   catch (Exception ex)
   {
      //Log exception. Don't throw exception. Most probably BeginReceive failed.
   }
}

Notice the if (ar == currentAynchResult) check where we got currentAynchResult from BeginReceiveFrom method while starting listening from new socket.

Happy Networking!

Wednesday, March 31, 2010

Configure OpenCV 2.0 on Visual Studio 2008 for VC++

You must be hating OpenCV 2.0 by now :) But don’t worry your pain will go soon (if yes, please write a comment). The biggest pain is that you will have to compile your OpenCV using CMake and all those stuff (as explained here). But if you are content with C or C++ and not interested in debugging inside OpenCV or Python then read further.

Download and Install, Emgu which is actually .NET wrapper for OpenCV but we will just use their precious .lib files which otherwise is pain in neck to generate (Download Emgu from here: http://sourceforge.net/projects/emgucv/)

After Emgu installation, Open Visual Studio and follow these steps:

1. Go to Tool –> Options –> Projects and Solutions –> VC++ Directories

2. Now see a combobox “Show Directories for” and select “Include files” and add, “C:\Program Files\Emgu\Emgu CV\opencv\include\opencv” (verify, as program file location may differ if you are using 64 bit operating system)

3. Now in the same combobox select “Library files” and add, “C:\Program Files\Emgu\Emgu CV\lib\release

4.  Now go to your VC++ project, right click and go to Properties –> Configuration Properties –> Linker –> Input –> Additional Dependencies and add these lib files (which is at  C:\Program Files\Emgu\Emgu CV\lib\release) cv200.lib cvaux200.lib cxcore200.lib highgui200.lib (check library name, it may change according to OpenCV version used for the Emgu)

5. That’s it. Done for now. Take shot at compiling your VC++ code downloaded from internet ;)

NOTE: If you are interested in going into OpenCV library code while debugging then this may not be the best solution for you as Emgu only gives release .lib files. You will have to generate ‘debug’ lib files as described in http://mirror2image.wordpress.com/2009/10/20/switching-to-opencv-2-0-with-vs2005/

I am not sure but this same should help to configure VS 2010 also.