May 04, 2012

Detect Scroll Beyond


<script type="text/javascript">

        function hookScroll(target, percent, callback) {
            $(target).bind('scroll', function () {
                if ((($(target).scrollTop() /
                                   $(target).innerHeight()) * 100)
                                   >= percent) {
                    callback();
                }
            });
        }

        function callback() {
            //alert("Scroll");
       
        }

        hookScroll(document, 40, callback);
    </script>

Simple Slideshow


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Slide Show Example</title>
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script>
    <script src="Scripts/jquery.easing.1.3.js" type="text/javascript"></script>
    <script type="text/javascript">
        //
        //SlideShow constructor
        //name: class or id of container div
        //slidename: class name of slide inside container
        function SlideShow(name, slidename) {
            this.name = name;
            this.slideName = slidename;
            //variable to indicate first slide index
            this.firstSlideIndex = 1;
            //variable to store current slides index
            this.currentSlideIndex = this.firstSlideIndex;
            //variable to store play status of slideshow
            this._playStatus = false;
            //readonly variable to store count of number of slides in slideshow
            this._totalSlide = 0;
            //indicates delay in milliseconds between each slide
            this.slideDelay = 2000;
            //indicates whether to start auto playing the slide show
            this.autoPlay = true;
            //private function, sets display css properties and other display related setting of slideshow
            this._setDisplay = _setDisplay;
            //private function, reset all variable to initial state
            this._resetValues = _resetValues;
            //private function, to make a single slide visible
            this._showSlide = _showSlide;
            //public function, to start playing slideshow
            this.play = play;
            //
            //public function, to show next slide of show
            //return: true if next slide avialable, false if last slide of show
            this.moveNext = moveNext;
            //
            //public function, to show previous slide of show
            //return: true if previous slide avialable, false if firt slide of show
            this.movePrevious = movePrevious;
            //public function, start slide show
            this.start = start;
            this.pause = pause;
            this.stop = stop;
            //stores reference to setInterval function
            this._timerInterval = null;
        }

        function play() {
            this._playStatus = true;
            var thisContext = this;
            function timerRelay() {
                if (thisContext._playStatus) {
                    if (!thisContext.moveNext()) { thisContext._resetValues(); }
                }
            }
            //call setinterval only if function is not call before
            if (this._timerInterval == null) {
                this._timerInterval = setInterval(timerRelay, this.slideDelay);
            }

        }

        function pause() {
            this._playStatus = false;
        }

        function stop() {
            this._playStatus = false;
            this._setDisplay();
            this._resetValues();
            this._showSlide(this.firstSlideIndex);

            //clear setinterval
            if (this._timerInterval != null) {
                clearInterval(this._timerInterval);
                this._timerInterval = null;
            }
        }

        function start() {
            this._setDisplay();
            this._resetValues();
            this._showSlide(this.firstSlideIndex);
            if (this.autoPlay) {
                this.play();
            }
        }

        //
        //next slide
        //return: if true than we can move next if false than its last slide of show
        function moveNext() {
            index = this.currentSlideIndex + 1;
            if (index > this._totalSlide) index = this._totalSlide;
            this._showSlide(index);

            if (this.currentSlideIndex == this._totalSlide) {
                return false;
            }
            else {
                return true;
            }
        }

        //
        //previous slide
        //return: if true than we can move previous if false than its first slide of show
        function movePrevious() {
            index = this.currentSlideIndex - 1;
            if (index < this.firstSlideIndex) index = this.firstSlideIndex;
            this._showSlide(index);

            if (this.currentSlideIndex == this.firstSlideIndex) {
                return false;
            }
            else {
                return true;
            }
        }

        //
        //Function to set css display properties of important elements
        function _setDisplay() {
            this._totalSlide = $(this.name + " > " + this.slideName).length;
            $(this.name + " > " + this.slideName).each(function (index) {
                $(this).css("display", "none");
            });
        }

        //
        //Function to reset values to initial state
        function _resetValues() {
            this.currentSlideIndex = this.firstSlideIndex - 1;
        }

        //
        //Function hides all other slides and show one on the index provided
        function _showSlide(index) {
            if (index <= this._totalSlide && index >= this.firstSlideIndex) {
                this.currentSlideIndex = index;
                $(this.name + " > " + this.slideName).each(function (i) {
                    if (i == (index - 1)) {
                        $(this).fadeIn(900, "linear");
                    }
                    else {
                        $(this).css("display", "none");
                    }
                });
            }
        }

        var ss = new SlideShow(".slideshow", ".slide");
        $(function () {
            ss.autoPlay = false;
            ss.start();
        });
    </script>
</head>
<body>
    <button onclick="ss.movePrevious();">
        Prev</button>
    <button onclick="ss.play();">
        Play</button>
    <button onclick="ss.pause();">
        Pause</button>
    <button onclick="ss.stop();">
        Stop</button>
    <button onclick="ss.moveNext();">
        Next</button>
    <div class="slideshow" style="max-width: 500px;">
        <div class="slide" id="s1" style="width: 100px; border: 5px solid #000;">
            Slide 1 sdgf sdfg dgd gd sdgd sdgsdfg sdfgd dg dfg gdfgs dgs sdgd dfg dfgd sdg s
            dfg sdgdf gsdfg dfgdf g
        </div>
        <div class="slide" id="s2" style="height: 200px; width: 200px; border: 5px solid #000;">
            d sfgsdf gsdfg sdfg dg dfsgfgdsfgsdfg45643 6456 4364 455 64564564636 Slide 2
        </div>
        <div class="slide" id="s3" style="height: 700px; width: 300px; border: 5px solid #000;">
            Slide 3
        </div>
        <div class="slide" id="s4" style="height: 100px; width: 100px; border: 5px solid #000;">
            Slide 4jkl gh gfghfgj j gfjjgj gj
        </div>
        <div class="slide" id="s5" style="height: 100px; width: 400px; border: 5px solid #000;">
            Slide 5
        </div>
        <div class="slide" id="s6" style="height: 50px; width: 50px; border: 5px solid #000;">
            Slide 6
        </div>
        <div class="slide" id="s7" style="height: 100px; width: 100px; border: 5px solid #000;">
            Slide 7
        </div>
    </div>
</body>
</html>

April 26, 2012

Comparer Algorithm

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;

/// 
/// Summary description for ComparerWorker
/// 
public class ComparerWorker
{
    public string Source { get; set; }
    public string Target { get; set; }
    public List Result { get; set; }

    public const string DifferentColor = "#FF2A2A";
    public const string NotFoundSourceColor = "#FF2A2A";
    public const string NotFoundTargetColor = "#FF2A2A";

    public ComparerWorker()
    {
        Source = string.Empty;
        Target = string.Empty;
        Result = new List();
    }

    public void DoWork()
    {
        Result.Clear();
        string[] sourceLines = Source.Split(Environment.NewLine.ToCharArray());
        string[] targetLines = Target.Split(Environment.NewLine.ToCharArray());

        int limit = targetLines.Length;
        if (sourceLines.Length > limit) limit = sourceLines.Length;

        int i2 = 0;
        for (int i = 0; i < limit || i2 < limit; )
        {
            string s = string.Empty;
            try { s = sourceLines[i]; }
            catch { }

            string t = string.Empty;
            try { t = targetLines[i2]; }
            catch { }

            
            try
            {
                LineCompare c = GetLineDifference(s, t);
                if (c.DiffType == DifferenceType.Same || c.DiffType == DifferenceType.Different)
                {
                    Result.Add(c);
                    i = i + 2;
                    i2 = i2 + 2;
                }
                else
                {
                    string s2 = string.Empty;
                    try { s2 = sourceLines[i + 2]; }
                    catch { }

                    string t2 = string.Empty;
                    try { t2 = targetLines[i2 + 2]; }
                    catch { }

                    //Compare target line with next line from source line
                    LineCompare c1 = GetLineDifference(s2, t);

                    //Compare source list with next line from target line
                    LineCompare c2 = GetLineDifference(s, t2);

                    if ((c1.DiffType == DifferenceType.Same || c1.DiffType == DifferenceType.Different) 
                        && (c2.DiffType == DifferenceType.Same || c2.DiffType == DifferenceType.Different) ||
                        (c1.DiffType == DifferenceType.TotalMismatch && c2.DiffType == DifferenceType.TotalMismatch))
                    {
                        //Lines are interchanged probably so make one entry for each line
                        LineCompare l1 = new LineCompare();
                        l1.SourceLine = c.SourceLine;
                        l1.SourceLineHtml = c.SourceLineHtml;
                        l1.DiffType = DifferenceType.NotFoundTarget;
                        Result.Add(l1);

                        LineCompare l2 = new LineCompare();
                        l2.TargetLine = c.TargetLine;
                        l2.TargetLineHtml = c.TargetLineHtml;
                        l2.DiffType = DifferenceType.NotFoundSource;
                        Result.Add(l2);

                        i = i + 2;
                        i2 = i2 + 2;
                    }
                    else if ((c1.DiffType == DifferenceType.Same || c1.DiffType == DifferenceType.Different) && c2.DiffType == DifferenceType.TotalMismatch)
                    {
                        //source line is deleted probably so add it in result
                        LineCompare l1 = new LineCompare();
                        l1.SourceLine = c.SourceLine;
                        l1.SourceLineHtml = c.SourceLineHtml;
                        l1.DiffType = DifferenceType.NotFoundTarget;
                        Result.Add(l1);
                        i = i + 2;
                    }
                    else if (c1.DiffType == DifferenceType.TotalMismatch && (c2.DiffType == DifferenceType.Same || c2.DiffType == DifferenceType.Different))
                    {
                        //target line is inserted probably so add it in result
                        LineCompare l2 = new LineCompare();
                        l2.TargetLine = c.TargetLine;
                        l2.TargetLineHtml = c.TargetLineHtml;
                        l2.DiffType = DifferenceType.NotFoundSource;
                        Result.Add(l2);

                        i2 = i2 + 2;
                    }
                }
            }
            catch { }
        }

        return;
    }

    public LineCompare GetLineDifference(string sourceLine, string targetLine)
    {
        LineCompare result = new LineCompare();
        result.SourceLine = sourceLine;
        result.TargetLine = targetLine;
        result.DiffType = DifferenceType.TotalMismatch;

        if (string.Compare(sourceLine.Replace(" ", ""), targetLine.Replace(" ", ""), true) == 0)
        {
            result.SourceLineHtml = string.Format("
{0}
", HttpUtility.HtmlEncode(sourceLine)); result.TargetLineHtml = string.Format("
{0}
", HttpUtility.HtmlEncode(targetLine)); result.DiffType = DifferenceType.Same; return result; } else { int lresult2 = LevenshteinDistance.Compute(sourceLine, targetLine); int length = sourceLine.Length; if (targetLine.Length > length) length = targetLine.Length; result.SourceLineHtml = string.Format("
{0}
", HttpUtility.HtmlEncode(sourceLine), DifferentColor); result.TargetLineHtml = string.Format("
{0}
", HttpUtility.HtmlEncode(targetLine), DifferentColor); if (((lresult2 * 100) / length) <= 50) { result.DiffType = DifferenceType.Different; } else { result.DiffType = DifferenceType.TotalMismatch; } return result; } } } public class LineCompare { public string SourceLine { get; set; } public string TargetLine { get; set; } public DifferenceType DiffType { get; set; } public string SourceLineHtml { get; set; } public string TargetLineHtml { get; set; } } public enum DifferenceType { None, Same, Different, TotalMismatch, NotFoundSource, NotFoundTarget } public static class LevenshteinDistance { /// /// Compute the distance between two strings. /// public static int Compute(string s, string t) { int n = s.Length; int m = t.Length; int[,] d = new int[n + 1, m + 1]; // Step 1 if (n == 0) { return m; } if (m == 0) { return n; } // Step 2 for (int i = 0; i <= n; d[i, 0] = i++) { } for (int j = 0; j <= m; d[0, j] = j++) { } // Step 3 for (int i = 1; i <= n; i++) { //Step 4 for (int j = 1; j <= m; j++) { // Step 5 int cost = (t[j - 1] == s[i - 1]) ? 0 : 1; // Step 6 d[i, j] = Math.Min( Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1), d[i - 1, j - 1] + cost); } } // Step 7 return d[n, m]; } }

January 11, 2012

Welcome 2012

 

I hope that I can continue writing this year, although its been a false notion for me, but lets see.

Labels:

February 09, 2009

Shuffle or Randomize Generic List

Technorati Tags: ,,

I have been working on test paper website on which I need to shuffle the option of multiple choice questions, all options are stored as generic list. So I have written a function which will shuffle the list of option with out affecting the original list.




/// <summary>
/// Generates a shuffled list without affecting original list.
/// </summary>
/// <typeparam name="T">I am using structure</typeparam>
/// <param name="list">list to be shuffled</param>
/// <returns></returns>
public List<t> Shuffle<t>(List<t> list)

{

List<t> shuffledList = new List<t>();
//make a list of the index for list
System.Collections.ArrayList indexes = new System.Collections.ArrayList(list.Count);
for (int iCounter = 0; iCounter < rnd =" new"> 0)
{

//get a random index from the list of index

int index = rnd.Next(0, indexes.Count);

//pick the object from list based on index value stored in list of indexes

shuffledList.Add(list[(int)indexes[index]]);

//remove the selected index from list of indexes

indexes.RemoveAt(index);

}

return shuffledList;

}


Your comments are welcome to improve this code.

January 28, 2009

IIS API Filter Loading Issue - Service Unavailable

Is your IIS Api filter not loading on IIS 6, or loads but shows a red down arrow. When you try to browse any webpage, it show service unavialable. Firstly you should check for application event in event viewer. you must have an entry of error in that. Open that entry and check for the bytes in data section. Here are few possible and known entries

  • Data: 02 00 00 00
  • Data: 05 00 00 00
  • Data: 7E 00 00 00
  • Data: 7F 00 00 00

Now for all the above issues please visit - http://blogs.msdn.com/david.wang/archive/2005/06/21/HOWTO-Diagnose-and-Fix-Common-ISAPI-Filter-Installation-Failures.aspx, you will find this blog entry very informative.

But I had a issue which was strange and no way related to any of the above. b1 36 00 00

The filter wont even call GetFilterVersion function. Directly coming to the point here, the machine on which i was running the filter didn't had VC++ runtime libraries. So the filter wasn't loading. Now there might be issues with Debug mode and Release mode filter dll's as well. So its good for you to build a set up project for the filter with correct prerequisites selected. I did that and now my filter running is fine and healty.

For any more queries please leave a comment and i will try to response ASAP.

Happy Coding

Labels: ,

July 22, 2008

Standard Date Format Specifiers

Here's a list of the standard date format specifiers:
d: short date
D: long date
t: short time
T: long time
f: full Date/Time with short time
F: full Date/Time with long time
g: general Date/Time with short time
G: general Date/Time with long time
M or m: month day
R or r: RFC1123
s: sortable Date/Time that conforms to ISO 8601
u: universal sortable Date/Time
U: full Date/Time with long time. (This format is the same as F, but it uses universal GMT time.)
Y or y: year month

July 10, 2008

"Data Could Not Be Loaded" Issue in ComponentArt Web.UI 2008.1 for ASP.NET 2.0

I am using Component art Web UI tools in a website and was facing a problem from a long time.
Component Art grid and other control throw "Data Could Not Be Loaded" alert in callbacks. After some research I found that this comes when control is not able to get back the data from server during a call back. There can be many reasons for this for example session expire and error during execution of code etc.
Now for component this is not a bug in the product, this is some kind of execption situation which programmer should handle at their end while working with controls.

So I was left with nothing but find out a solution myself, now in my case the message box came up if window was left idle for long time, so it was quite clear that this is a session expire problem.
Drilling down more into the problem I found that main cause was redirection to default page in case session expired.

Solution to the problem is avoiding redirection on server side during callbacks instead use javascript to move to other page. So where ever you have written the code of redirection, try to get status whether it was a postback or a callback and if it was callback don't redirect. Now raise a custom execption like Session Expired during call backs and handle it in callbackerror event exposed by component art control.

Server Side code -
'''Procedure raises custom execption in case of session out

Public Sub RaiseErrorOnSessionTimeOut()
If Me.Session("UserLoggedIn") Is Nothing OrElse Not CBool(Me.Session("UserLoggedIn")) Then
Throw New Exception("Session TimeOut")
End If
End Sub

'''deliberatly raising execption while rebinding component art grid
Public Sub OnNeedRebind(ByVal sender As Object, ByVal oArgs As EventArgs) Handles Grid1.NeedRebind
RaiseErrorOnSessionTimeOut()
Grid1.DataBind()
End Sub

Client Side Code -

//JavaScript Function
///
///Function handles error generated by qualified and dis-qualified result grids
///
function HandleCallBackError(sender, eventArgs)
{
var errorMessage = new String();
errorMessage = eventArgs.get_errorMessage().toLowerCase();

switch (errorMessage)
{
case "session timeout":
window.location.replace("samepage.aspx")
break;
default:
alert("Due to some technical problem we are unable to process your request.");
break;
}

}


Add a client event to the grid.
<ClientEvents>
<CallbackError EventHandler="HandleCallBackError" />
</ClientEvents>

Remember you can handle any kind of situation with this, you just need to raise an execption and handle it on client side. You can use this technique with other control that support callback like combo box, tree view, call back etc.

Happy Coding

Labels: ,

May 20, 2008

Windows Application Very Slow After Migrating Database from MSDE 2000 to SQL EXPRESS 2005

I am working on a smart client application, which uses SQL Express 2005 as datastore. Previously we were using MSDE 2000 for this purpose. Ever since the application migrated to SQL Express its very slow in performing CRUD operations.


I have done some research and found that AUTO_CLOSE option of database is turned ON by defualt, so if you turn it OFF then probably it will work faster.

Select "false" from Auto Close drop down in options panel and click OK. I am using SQL Management Studio.

Although this gives slight advantage of speed but not all system, some of users are still complaining for slow speed.

Labels:

October 19, 2007

What are delegates?

Let me discuss function pointers first to make delegate a bit easier to understand.

Example of function pointer :-

int (SampleClass::*pt2function)(float) = NULL;

/* sample class for example*/
class SampleClass{
public: int DoWork(float argument){ return arguement; }
};

pt2function= &SampleClass::DoWork; //assigning function to pointer

SampleClass objInstance; int result3 = (objInstance.*pt2function)(12);

In above code pt2function is a pointer which can hold an address of a function of class SampleClass and which has same definition as specified in pt2function declaration.

Now delegates are for exactly same purpose as function pointer, only difference is we don't declare any pointers here. Instead .net has implemented it in a completely different way.

Delegates are replacements of function pointers in .Net. Delegate is a kind of class, which mimics declaration of a method that is it supports a return type and arguments Or you can say a named method signature is a delegate.


Syntax (C#) :-

delegate returntype delegate-name(arguements,...n);

Syntax (VB.Net) :-
Delegate [SubFunction] delegate-name(arguements,...n) [as returntype]

Example (VB.Net) :-

Public Delegate Function Sample(ByVal strArguement As String) As String


Example (C#) :-

delegate void Sample(String strArguement);


As we see here delegate support return type and can have arguments also.

Now lets try to pass a function to delegate. I will use the same delegates that i have provided in example above.

Example VB.Net

Public Class Class1
'declaring an object of Sample delegate
Dim t As Sample = New Sample(AddressOf CoolFunction)

Public Function CoolFunction(ByVal t As String) As String
Return t
End Function

public sub CallDelegate()
t("Raj Kiran Singh") 'or t.Invoke("Raj Kiran Singh")
End sub

End Class


Example C#

public class Class1
{
//declaring an object of Sample delegate
Sample t = new Sample(CoolFunction);

public string CoolFunction(string t)
{
return t;
}

public void CallDelegate()
{
t("Raj Kiran Singh");
//or t.Invoke("Raj Kiran Singh")
}

}

So its pretty clear from above code that we declare variables of a delegate just like any other class and we pass address of the function as an argument to the constructor.Then we can call the delegate like a function, as done in CallDelegate procedure/function.

In this post I have said that delegate are kind of class. Well, here is some arguement to support my statement. When you declare a delegate, using keyword "delegate", .net compiler treats this syntax in special way. It will create a class with same name as delegate, this class inherits System.MultiCastDelegate class. Although this will be completely hidden from the developer and is performed by the compiler internally.


So for this code -
delegate void Sample(String strArguement);

Compiler will generate a class named Sample. Sample class will have one constructor and three functions. BeginInvoke, EndInvoke and Invoke.

Delegate Class Generated by .Net Sample class extends System.MulticastDelegate class. All delegates are derived from this class. Delegate class has got a private variable which stores an integer that CLR uses to identify method which is to be called back. Delegate class also has a variable which holds the object to be referenced if the method pointer points to an instance method, in case of static or shared functions this variable is null.

When delegate has got more than one method attached to it, its called delegate chains. In this case delegate will execute each method and return the value of last method called. Delegate class has got a private variable to store the preceding delegate. This way it forms a list of delegates.

Labels: , , , ,