How to iterate through TileView items in XtraGrid?

This is related to DevExpress question - How to loop through tiles in TileView, which help me to achieve the required functionality in the XtraGrid using the TileView. I require to implement the selection process for TileView similar to GridView in XtraGrid, but I require to iterate through all the TileView items. TileView actually use TileViewControl internally so it require to access under laying  tileview control items to access more information about the TileViewItems. See the below code snippet:

private void HandleTileItemSelection(TileViewItem tileViewItem)
{
    if ((ModifierKeys & Keys.Control) != Keys.Control)
    {
        Dictionary visibleTiles = ((tileView1.GetViewInfo() as ITileControl).ViewInfo as TileViewInfoCore).VisibleItems;
        int alternateCheckedItemsCount = 0;
        foreach (KeyValuePair item in visibleTiles)
        {
            if (item.Value != tileViewItem && item.Value.Checked)
            {
                alternateCheckedItemsCount++;
                item.Value.Checked = false;
                tileView1.SetRowCellValue(item.Value.RowHandle, "CheckedStatus", false);
            }
        }
    }        
}

RANDBETWEEN(m,n) in Sql Server?

Today I have to find random number between two numbers lots of the time in the stored procedures So I tried to create a function which return random numbers between two boundary numbers m and n. I tried to look for the solution and got below logic to implement the function.

Let m = 5 and n = 500 and method call would be RANDBETWEEN(5, 500). Then logic to find the random number would be as below:

  • Use RAND() (which returns a value between 0 and 1 (exclusive).
  • multiply by 298 (since you want a dynamic range of [300-3] = 297 + 1)
  • add 3 to Offset
  • and cast to INT?
Usage:
SELECT CAST(RAND() * 298 + 3 AS INT)
A Stored Procedure can be written like this if it supposed to be reuse in code more often:
CREATE PROCEDURE [dbo].[RANDBETWEEN]
@LowerBound int = 0 ,
@UpperBound int = 1 , 
@ret int OUT
AS
    BEGIN
    SET NOCOUNT ON;
    SELECT @ret = (CAST((RAND() * (@UpperBound - @LowerBound)) + @LowerBound AS INT));
RETURN ;
END;

Call can be made like this:

DECLARE @tmp INT;
EXECUTE [dbo].[RANDBETWEEN] 0,10, @ret=@tmp OUT ;
SELECT @tmp

To create a function I found that I have to create a View that make random method call and then function will do remaining operation to get the random number.

CREATE VIEW Get_RAND
AS
SELECT RAND() AS RANDNumber
GO



Then you can create a function like this (accessing the view with the SELECT RandomNumber... ) :
CREATE FUNCTION RANDBETWEEN(@LowerBound INT, @UpperBound INT)
RETURNS INT
AS
BEGIN
    DECLARE @TMP FLOAT;
    SELECT @TMP = (SELECT RandomNumber FROM Get_RAND);
    RETURN CAST(@TMP* (@UpperBound - @LowerBound) + @LowerBound AS INT);
END
GO

Then this function can be called as below:

SELECT [dbo].[RANDBETWEEN](1,10)

WCF or ASP.NET Web APIs for web services??

This is a interesting question for everyone and especially for me too. Whenever I got chance to dig for these technologies to create service, I found myself little confuse that which one should I choose.

It may be the “WCF vs ASP.NET Web API” contest for choosing in particular scenario and requirement of client. I got lots of reference and comparison related these two things which are discussed below:

The ASP.NET Web API is a continuation of the previous WCF Web API project (Conceptual changes are described on Codeplex WCF documentation - How to Migrate from WCF Web API to ASP.NET Web API).

Here is comparison from MSDN - WCF and ASP.NET Web API:
WCFvsWebAPI

ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.

WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.

In the scenarios listed below you should go for WCF:

  1. If you need to send data on protocols like TCP, MSMQ or MIME
  2. If the consuming client just knows how to consume SOAP messages

We can expose REST endpoints on WCF services as well.

WEB API is a framework for developing RESTful/HTTP services.

There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.Although WCF provides some support for writing REST-style services, the support for REST in ASP.NET Web API is more complete and all future REST feature improvements will be made in ASP.NET Web API.

Here are few nice articles and reference:
WCF or ASP.NET Web APIs? My two cents on the subject
Scott Hanselman’s - Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block

What is the correct way to handle exceptions and UnobservedTaskException in the TPL?

Information from: A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was

If you create a Task, and you don't ever call task.Wait() or try to retrieve the result of a Task<T>, when the task is collected by the garbage collector, it will tear down your application during finalization. For details, see MSDN's page on Exception Handling in the TPL.

The best option here is to "handle" the exception. This can be done via a continuation - you can attach a continuation to the task, and log/swallow/etc the exception that occurs. This provides a clean way to log task exceptions, and can be written as a simple extension method, ie:

public static void LogExceptions(this Task task)
{
    task.ContinueWith( t =>
    {
         var aggException = t.Exception.Flatten();
         foreach(var exception in aggException.InnerExceptions)
             LogException(exception);
    }, 
    TaskContinuationOptions.OnlyOnFaulted);
}

With the above, you can prevent any task from tearing down the app, and logging it, via:
Task.Factory.StartNew( () => 
   { 
       // Do your work...
   }).LogExceptions();

Alternatively, you can subscribe to the TaskScheduler.UnobservedTaskException and handle it there. 

Continuation of the task could determine the status of the parent task whether it get faulted or completed to success. A continuation can find out if an exception was thrown by the antecedent Task by the antecedent task's exception property. The following code snippet will print the results of a NullReferenceException to the console.

Task task1 = Task.Factory.StartNew (() => { throw null; });
Task task2 = task1.ContinueWith (ant => Console.Write(ant.Exception());

If task1 throws an exception and this exception is not captured/queried by the continuation then it is considered unhandled and the application get halted. With continuations it is enough to establish the result of the task via the Status property.
asyncTask.ContinueWith(task =>
{
    // Check task status.
    switch (task.Status)
    {
        // Handle any exceptions to prevent UnobservedTaskException.             
        case TaskStatus.RanToCompletion:
            if (asyncTask.Result)
            {
                // Do stuff...
            }
            break;
        case TaskStatus.Faulted:
            if (task.Exception != null)
                mainForm.progressRightLabelText = task.Exception.InnerException.Message;
            else
                mainForm.progressRightLabelText = "Operation failed!";
        default:
            break;
    }
}


If you don't use continuations you either have to wait on the task in a try/catch block or query a task's Result in a try/catch block. See below code snippet:
int x = 0;
Task task = Task.Factory.StartNew (() => 7 / x);
try
{
    task.Wait();
    // OR.
    int result = task.Result;
}
catch (AggregateException aggEx)
{
    Console.WriteLine(aggEx.InnerException.Message);
}

How to close a MessageBox after several seconds?

Related to: Close a MessageBox after several seconds.
Scenario:
I need to create a message box or Popup which must be visible for specified time and close automatically after then.

Solution:
There is not inbuilt feature in .net framework to do this. You need to create your custom logic that message box close after a specific time. To do this create a custom message box class which have a timer which close the raised pop message when elapsed time equal to specified time to make it visible to the user.
Here is the custom class:

public class AutoClosingMessageBox {
    System.Threading.Timer _timeoutTimer;
    string _caption;
    AutoClosingMessageBox(string text, string caption, int timeout) {
        _caption = caption;
        _timeoutTimer = new System.Threading.Timer(OnTimerElapsed,
            null, timeout, System.Threading.Timeout.Infinite);
        MessageBox.Show(text, caption);
    }
    public static void Show(string text, string caption, int timeout) {
        new AutoClosingMessageBox(text, caption, timeout);
    }
    void OnTimerElapsed(object state) {
        IntPtr mbWnd = FindWindow(null, _caption);
        if(mbWnd != IntPtr.Zero)
            SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
        _timeoutTimer.Dispose();
    }
    const int WM_CLOSE = 0x0010;
    [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
    static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
}

It can be called as below:

AutoClosingMessageBox.Show("Text", "Caption", 1000);
 

How to prevent selection change in drop down from key press when UltraComboEditor’s DropdownStyle set to DropDownList?

Scenario:
Current requirement is that user can select option from drop down from mouse selection only, but whenever use type anything in the drop down it automatically raise control’s ComboBox.SelectionChangeCommitted event with first match that satisfies auto complete condition of the control. As required we need
ignore the key press to raise the ComboBox.SelectionChangeCommitted event of the combo box and it only allow selection only on mouse.

Solution:

 

To do this, I set the control’s DropdownStyle set to DropDownList, but no work correctly. Along this I have to suppress combo box’s key press by handling KeyDown event as below.

LibraryListDropdown libDropdown = null;
public Form1()
{
    InitializeComponent();
    libDropdown = new LibraryListDropdown();
    this.libDropdown.DropDownStyle = DropDownStyle.DropDownList;
    libDropdown.Name = "cmbObjectType";
    libDropdown.SelectionChangeCommitted += new EventHandler(libDropdown_SelectionChangeCommitted);
    libDropdown.KeyDown += libDropdown_KeyDown;
    this.Controls.Add(libDropdown);
    libDropdown.PopulateLibraries();
}

void libDropdown_KeyDown(object sender, KeyEventArgs e)
{
    e.SuppressKeyPress = true;
}

private void libDropdown_SelectionChangeCommitted(object sender, EventArgs e)
{
    
}

How to display tooltip on mouse hover in particular cell or column cell?

Scenario:  

Today I got an assignment to display tooltip on particular column cell depending on its text that contain some specific prefix to create different tool tip text.  The grid control was used is Infragistics UltraWinGrid to populate data to user.

Solution/Description:

Most of the time I work with DevExpress controls and default win form controls, there we have different approach to get the grid element when hovering mouse over the grid element.  These controls use HitTestInfo to determine that which grid element currently hovered. While looking for the solution I found one Stackoverflow thread - DataGridView.HitTestInfo equivalent in Infragistics UltraWinGrid? . I am also hunting for the same question’s answer that does Infragistics’s UltraGrid control provides functionality similar to that of DataGridView.HitTestInfo?

Source - Task-based Tutorial - How to use ToolTips with the Infragistics UltraWinGrid

 I found out that Infragistics controls don't convert the coordinates, but they use a special Infragistics grid event (MouseEnterElement) to get the element, which the mouse currently hovers over. Also with the Infragistics UltraWinGrid-control it required to keep track of the grid-row, over which the cursor is hovering. In contrast to our generic solution, the position is stored in a data-type provided by the UltraWinGrid-control and not in a Point-structure: 

Public Class Form1
    Inherits System.Windows.Forms.Form 
   ...  
    'Holds the row/column-coordinates of the cell on which
    'the mouse is hovering...
    Private mCurrentCell As Infragistics.Win _ 
                .UltraWinGrid.UltraGridCell = Nothing
  ...

The way of implement for the generic grid-control (in the section on "How to use ToolTips with grid-controls"), the whole logic, to keep track of the current mouse-position in terms of grid-coordinates (row/column) and to provide the tooltip with the content of the current grid-element, is located in the MouseEnterMouseLeave and MouseMove event-handlers. This is slightly different for the UltraWinGrid-control. Of course, the needed logic is also coupled to mouse-events, but the UltraWinGrid-control provides additional mouse-related events, which make the integration even easier. 

 

Code snippet to show tooltip while using UltraWinGrid:

private void ultraGrid1_MouseEnterElement(object sender, UIElementEventArgs e)
{
    if (e.Element is RowUIElement)
    {
        if (e.Element.SelectableItem is UltraGridRow)
        {
            UltraGridRow ultraGridRow = (UltraGridRow)e.Element.SelectableItem;

            if (ultraGridRow.Band.Key == PaletteZoneHVACGroupingConstants.BAND_PARENT)
            {
                toolTip.ToolTipText = "Drag-n-drop here";
                toolTip.Show();
            }
        }                
    }
    else if(e.Element is CellUIElement)
    {
        // Get a refernce to the column.
        UltraGridColumn column = (UltraGridColumn)e.Element.GetContext();
        if (column != null && column.Key == ColumnName.DESIGNTEMPLATE)
        {
            UltraGridCell cell = e.Element.SelectableItem as UltraGridCell;
            if (cell.Row.Band.Key == Constants.BAND_PARENT)
            {
                string toolTipMessage = string.Empty;
                if (cell.Text.StartsWith(Constants.TextDesginChangePrefix))
                {
                    toolTipMessage = ResourceMessage.GetMessage(ResourceConstants. DESGINS_CHANGE);
                }
                else if (cell.Text.StartsWith(Constants.TextParametersChangePrefix))
                {
                    toolTipMessage = ResourceMessage.GetMessage(ResourceConstants.DESGINS_PARAMETERS_CHANGE);
                }
                
                if (!string.IsNullOrWhiteSpace(toolTipMessage))
                {
                    toolTip.ToolTipText = toolTipMessage;
                    toolTip.Show();
                }
            }
        }
    }
}

private void ultraGrid1_MouseLeaveElement(object sender, UIElementEventArgs e)
{
    toolTip.Hide();
}

 

References:

How to set UltraToolTipeInfo in perticular row in win ultra grid control.

display tooltip on mouse hover in cell

 

Debugging Threads with Concurrency Visualizer

Features of Concurrency Visualizer:

  • Shift+Alt+F5
  • Fast processing, faster loading
           o Supports big traces
  • Supports big traces
  • Support s EventSource and custom markers
            o Built-in support for TPL, PLINQ, Sync Data Structures, and Dataflow
            o Built-in support for your own EventSource types
                    § Also provides Visual Studio markers API
  • New Visualizations
             o e.g. defender view

Demo:

Here are few steps to know that how to utilize “Concurrency Visualizer” for multithreaded applications.

  1. Create a Console project.
  2. Create custom EventSource to trace in the visualizer as below:
    [EventSource(Guid = "7BBB4E52-7DA7-45EB-B6C2-C01D460A087C")]
    class MyEventSource : EventSource
    {
        internal static MyEventSource log = new MyEventSource();
    
        [Event(1)]
        public void SomeEventHandled(int data)
        {
            WriteEvent(1, data);
        }
    }

    To provide GUID to the event source use “guidgen” and copy newly generated GUID. Then put it in the attribute of the EventSource class.



  3. Now complete the test code to proceed the demo.

    Full code snippet:
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace ConcurrencyVisualizerDemo
    {
        class Program
        {
            static void Main(string[] args)
            {
                var list = new List<Task>();
                for (int i = 0; i < 10; i++)
                {
                    list.Add(Task.Run(() =>
                        {
                            //Loging here
                            MyEventSource.log.SomeEventHandled(21);
                            Thread.SpinWait(1000000);
                        }));
                }
                Task.WaitAll(list.ToArray());
            }
    
            [EventSource(Guid = "7BBB4E52-7DA7-45EB-B6C2-C01D460A087C")]
            class MyEventSource : EventSource
            {
                internal static MyEventSource log = new MyEventSource();
    
                [Event(1)]
                public void SomeEventHandled(int data)
                {
                    WriteEvent(1, data);
                }
            }
        }
    }
  4. There is optional extension “Concurrency Visualizer” for visual studio, which visual all the data to debug the concurrency between the treads. After installing this, you can find the option under Analyze menu. See image below:

    clip_image004
  5. Now copy the GUID  of MyEventSource and go to the Concurrency Visualizer’s settings. Then add new provider and put this copied guid in the provider.
    Analyze->Concurrency Visualizer->Advance Settings->Markers

    image

    Provide name and paste copied guid in the Privider GUID field. Click ok to complete provider addition.
  6. Now start Concurrency Visualizer by pressing Shift+Alt+F5 and it will start Shift+Alt+F5. Now it will start generating reports. See the below images:

    image

    image

    image

    image

 

Welcome to BlogEngine.NET 3.1

If you see this post it means that BlogEngine.NET is running and the hard part of creating your own blog is done. There is only a few things left to do.

Write Permissions

To be able to log in, write posts and customize blog, you need to enable write permissions on the App_Data and Custom folders. If your blog is hosted at a hosting provider, you can either log into your account’s admin page or call the support.

If you wish to use a database to store your blog data, we still encourage you to enable this write access for an images you may wish to store for your blog posts.  If you are interested in using Microsoft SQL Server, MySQL, SQL CE, or other databases, please see the BlogEngine docs to get started.

Security

When you've got write permissions set, you need to change the username and password. Find the sign-in link located either at the bottom or top of the page depending on your current theme and click it. Now enter "admin" in both the username and password fields and click the button. You will now see an admin menu appear. It has a link to the "Users" admin page. From there you can change password, create new users and set roles and permissions. Passwords are hashed by default so you better configure email in settings for password recovery to work or learn how to do it manually.

Configuration and Profile

Now that you have your blog secured, take a look through the settings and give your new blog a title.  BlogEngine.NET is set up to take full advantage of many semantic formats and technologies such as FOAF, SIOC and APML. It means that the content stored in your BlogEngine.NET installation will be fully portable and auto-discoverable.  Be sure to fill in your author profile to take better advantage of this.

Themes, Widgets & Extensions

One last thing to consider is customizing the look and behavior of your blog. We have themes, widgets and extensions available right out of the box. You can install more right from admin panel under Custom/Gallery.

On the web

You can find news about BlogEngine.NET on the official website. For tutorials, documentation, tips and tricks visit our docs site. The ongoing development of BlogEngine.NET can be followed at CodePlex where the daily builds will be published for anyone to download.

Good luck and happy writing.

The BlogEngine.NET team

What is the use of AsyncCallback in Client server programs and GUI improvements? why should we use it?

When the async method finishes processing, the AsyncCallback method is automatically called, where post processing statements can be executed. With this technique there is no need to poll or wait for the asyn thread to complete.

This is some explanation on Aynsc Call back usage:

Callback Model: The callback model requires that we specify a method to callback on and include any state that we need in the callback method to complete the call. The callback model can be seen in the following example:

static byte[] buffer = new byte[100];

static void TestCallbackAPM()
{
    string filename = System.IO.Path.Combine (System.Environment.CurrentDirectory, "mfc71.pdb");

    FileStream strm = new FileStream(filename,
        FileMode.Open, FileAccess.Read, FileShare.Read, 1024,
        FileOptions.Asynchronous);

    // Make the asynchronous call
    IAsyncResult result = strm.BeginRead(buffer, 0, buffer.Length,
        new AsyncCallback(CompleteRead), strm);
}

In this model, we are creating a new AsyncCallback delegate, specifying a method to call (on another thread) when the operation is complete. In addition, we are specifying some object that we might need as the state of the call. For this example, we are sending the stream object in because we will need to call EndRead and close the stream.

The method that we create to be called at the end of the call would look somewhat like this:

static void CompleteRead(IAsyncResult result)
{
    Console.WriteLine("Read Completed");

    FileStream strm = (FileStream) result.AsyncState;

    // Finished, so we can call EndRead and it will return without blocking
    int numBytes = strm.EndRead(result);

    // Don't forget to close the stream
    strm.Close();

    Console.WriteLine("Read {0} Bytes", numBytes);
    Console.WriteLine(BitConverter.ToString(buffer));
}

Other techniques are wait-until-done and pollback

Wait-Until-Done Model The wait-until-done model allows you to start the asynchronous call and perform other work. Once the other work is done, you can attempt to end the call and it will block until the asynchronous call is complete.

// Make the asynchronous call
strm.Read(buffer, 0, buffer.Length);
IAsyncResult result = strm.BeginRead(buffer, 0, buffer.Length, null, null);

// Do some work here while you wait

// Calling EndRead will block until the Async work is complete
int numBytes = strm.EndRead(result);

Or you can use wait handles.

result.AsyncWaitHandle.WaitOne();

Polling Model The polling method is similar, with the exception that the code will poll the IAsyncResult to see whether it has completed.

// Make the asynchronous call
IAsyncResult result = strm.BeginRead(buffer, 0, buffer.Length, null, null);

// Poll testing to see if complete
while (!result.IsCompleted)
{
    // Do more work here if the call isn't complete
    Thread.Sleep(100);
}