Thursday, July 31, 2014

How to remove chat history for a single contact from Skype?

This post is going to be a little strange compared with other posts on this blog.
In order to test some functionality on a web application I had to change the calendar date in future on my local machine.
In the while, I was using Skype and conversations were recording as of being on 8th of August (the date I experienced this). Then I return 'back from time' on current date. Well, from that time on Skype was behaving weird because it showed me conversations ordered by timespan ascending.
Well that is when you will got messed up :)

As Skype only allows you to delete all history conversation at once I had to search for a way to delete only those conversation that were 'in future' so Skype will show me last chat discussions on last row ;)

Searched around and found this solution.(it will require a little knowledge of SQL)

  1. Quit from Sype - required - otherwise you will have a sql error - database locked
  2. Go to C:\Users\PROFILE NAME\AppData\Roaming\Skype\SKYPE LOGIN ID and make a backup of main.db
  3. Go to http://sqlitebrowser.org/ and download the exe and install it on your machine.
  4. Go to: http://www.onlineconversion.com/unix_time.htm and get current timespan. - you will need it for sql query
  5. Open  SqLite and then go to OpenDatabase and choose the same database mentioned at 2)
  6. In order to make sure what you want to delete you could execute the next query   
  • SELECT * FROM "Messages" where timestamp > '1406808732'   (for timestamp you could put the one obtained at 4)  or if you want to check of an author use: author = 'authorId' ) authorId is skype Name
 If you are happy with the results that you see then execute same script with delete command:
  • DELETE FROM "Messages" where timestamp > '1406808732' --or use: (author = 'authorId')

Note that you could also filter the results by author/from_dispname or other columns of same Message table. AuthorIds could be taken from Contacts table and then skypename column .

Cheers.

Tuesday, May 27, 2014

How to remove a wrong playlist from Test Explorer in visual studio 2012?

After you create several playlists for your failing unit tests or a custom set of unit tests there will come the time when you want to remove them from the list.
So, in case you will be looking in Text Explorer(Visual Studio Professional 2012) for a way to remove/delete a playlist from your list this is what you will have to do:

1. Close solution
2. Locate your playlist where it is saved and then delete it, easy - isn't it? :)
3. Reopen your solution and re build your solution. Everything should be fine. The playlist should not appear anymore.

Caution: If you delete the playlist while the solution is still opened and then build you will get this nice error:

------ Discover test started ------
Error reading playlist file 'C:\Users\xxx\MyPlaylist.playlist'.


So that is why you need first to close solution.
I hope this helped you, I looked around and found no answer for this. I thought that as a playlist is created from Text Explorer interface it should also be removed from same place.

Have a nice day and leave a comment if this helped you.

Friday, April 25, 2014

How can I get the list of available databases on a SQL server instance?

Whenever you want to get the list of available databases on an instance you could use this query. You could also change it as will fit you better. This query it is helpful when you need a list of databases and the list is big, of course.

Query that runs well for Sql Server 2012:
SELECT * 
FROM sys.databases d
WHERE d.name NOT IN ('master', 'tempdb', 'model', 'msdb', 'ReportServer', 'ReportServerTempDB');
--or you could use a simpler condition which in my opinion is not so relevant 
--WHERE d.database_id > 4

Otherwise you could also use:
EXEC sp_databases

Cheers, Adrian

Friday, April 11, 2014

How to call for a dynamic OrderBy method for a LINQ?

As I wanted to do some experiences in Asp.Mvc 4 I needed a nice way to generate tables using Ajax calls for showing rows, edit, delete and create new item as well with filtering and paging functions. 
For that I have found this nice package jTable. You could go to http://www.jtable.org/ where you can see a demo by yourself.

Now that I have introduced the scenario I came to an issue. When implementing the sorting of columns by pressing on a column I had as an input parameter string jtSorting which had as a value: "Name ASC", so column name and ordering. Then in my controller's action I had a LINQ query that accessed also the OrderBy extension method which needs exactly the name of property. So I needed a method to order dynamically by property as a string.

Happily I found a solution. Here are my helper classes that I used in final extension method.

public static class OrderHelper
    {
        public class ColumnToSort
        {
            public string ColumnName { get; set; }
            public SortDirection Direction { get; set; }

            public ColumnToSort()
            { }

            public ColumnToSort(string columnName, SortDirection direction)
            {
                ColumnName = columnName;
                Direction = direction;
            }
        }

        public static ColumnToSort SplitJqueryFormatColumn(string sortingColumn) //assume we have as input: "Name ASC"
        {
            ColumnToSort columnToSort = new ColumnToSort();

            if (sortingColumn != null)
            {
                string[] parts = sortingColumn.Split(' ');
                if (parts.Length == 2)
                {
                    columnToSort.ColumnName = parts[0];
                    columnToSort.Direction = parts[1].ToLower() == "asc" ? SortDirection.Ascending : SortDirection.Descending;
                }
            }

            return columnToSort;
        }
    }

This is the extension method that will Order dynamically by a column string value and an sorting order.

public static class OrderExt
    {
        public static IOrderedQueryable< T > Order< T>(this IQueryable< T> source, string propertyName, SortDirection descending, bool anotherLevel = false)
        {
            var param = Expression.Parameter(typeof(T), string.Empty);
            var property = Expression.PropertyOrField(param, propertyName);
            var sort = Expression.Lambda(property, param);

            var call = Expression.Call(
                typeof(Queryable),
                (!anotherLevel ? "OrderBy" : "ThenBy") +
                (descending == SortDirection.Descending ? "Descending" : string.Empty),
                new[] { typeof(T), property.Type },
                source.Expression,
                Expression.Quote(sort));

            return (IOrderedQueryable< T>)source.Provider.CreateQuery< T>(call);
        }
    }

Here is how to use the Order extension method for List Action that is needed for JTable in ASP.NET MVC 4:

[HttpPost]
        public JsonResult List(int jtStartIndex, int jtPageSize, string jtSorting = null)
        {
            try
            {
                int totalItemsNumber = db.Authors.Count();
        
                OrderHelper.ColumnToSort columnToSort = new OrderHelper.ColumnToSort();
                if (jtSorting != null)
                    columnToSort = OrderHelper.SplitJqueryFormatColumn(jtSorting);
                else
                    columnToSort = new OrderHelper.ColumnToSort("Name", SortDirection.Ascending);

                List< author> authors = db.Authors
                                         .Order(columnToSort.ColumnName, columnToSort.Direction)
                                         .Skip(jtStartIndex)
                                         .Take(jtPageSize)
                                         .ToList();

                return Json(new { Result = "OK", Records = authors, TotalRecordCount = totalItemsNumber });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }

Hope it solved your issue, too.

Source for the extension method found at: linq-to-entities-dynamic-sorting.

App_Code classes not available in Asp.Net Mvc 4 with Microsoft Visual Studio 2012

As in the last few weeks I have started to learn Asp.Net MVC 4 I found few issues. I want to tell you about one pretty awkward.

Just for you to know I have created a project "ASP.NET MVC 4 Web Application" and then as project template I've chosen "Internet Application".


Now: as I wanted to add some of my helper classes and other utilities I created a "App_Code" folder.


Later as I said, I added few classes in that folder. Then I was surprised for I could not use those classes from Controller's folder.
I've tried to change namespace,changing from  MyDemoProject.App_Code to just MyDemoProject. No success :)

So as App_Code classes were not available(accessible) I've searched a little around and I found this solution: you have to go at Properties section of the file and then for Build Action change from Content to Compile. That is it ;)


Of course, you have to bring in the namespace MyDemoProject or MyDemoProject.App_Code as it fits your scenario.

Hope it helped you, too.

Monday, January 27, 2014

How to loop through a collection that supports IEnumerable?

Whenever you get to this issue, though it seems a really easy job to do here 2 ways how you can iterate on a collection that supports IEnumerable:

First one using a foreach statement:

foreach (var item in collection)
{
    // play with your item
}

I suggest that always when you know your object types of collection to use that type instead of var. I always try to avoid var type. It is something that my team lead advised me and I came to realize it is a good practice.

Then second way to do it is using for statement. Whenever you have a collection and you need to iterate it and according to some conditions some elements might have to be removed you cannot use foreach because you will have a nice error saying: "Collection was modified; enumeration operation may not execute" :) So that is why you need to use for statement.

for(int i = 0; i < collection.Count(); i++) 
{
    string str1 = collection.ElementAt(i);
    // play with your item
}

There might be other ways to iterate, like using GetEnumerator but is enough, for the moment :)
Have a nice day.

Monday, January 20, 2014

How to make a custom richTextBox control in winforms with C#?

During the last week I had to make a custom control that should have had a richTextBox control with a toolbar that contains: a dropdown of fonts and one with font sizes plus 3 buttons(which in fact are checkboxes with Appearance of a button) that will emulate 'make bold', 'make italic', 'make underline'. Of course there could be other improvements but client was happy with only these controls.


I will try to explain you which are the steps in the next lines:

- create a new control - ExtraRichTextBoxUC
- add 2 comboboxes with drop down style set on DropDownList: cmbFontFamily, cmbFontSize
- add 3 checkBoxes with Appearance on Button: ckbBold, ckbItalic, ckbUnderline
- finally you add a richTextBox control: txtFunctionality

Generate event methods for controls as follows: cmbFontFamily_SelectedIndexChanged, cmbFontSize_SelectedIndexChanged, ckbBold_CheckedChanged, ckbItalic_CheckedChanged, ckbUnderline_CheckedChanged.

I think that one of the most important methods from bellow is ChangeFontStyleForSelectedText. You have to understand that when you want to change font for a text you must iterate character by character and change font. First I thought that a style can be applied a word or a phrase. To issue is that styles are overwritten in such a case so you must iterate each letter.
So for each text that you want to change font you copy in a memory RichTextBox(so you won't cause flickering on current richTextBox) and set new font. Finally that rtf generated you assign to current richTextBox.

private void ChangeFontStyleForSelectedText(string familyName, float? emSize, FontStyle? fontStyle, bool? enableFontStyle)
        {
            _maskChanges = true;
            try
            {
                int txtStartPosition = txtFunctionality.SelectionStart;
                int selectionLength = txtFunctionality.SelectionLength;
                if (selectionLength > 0)
                    using (RichTextBox txtTemp = new RichTextBox())
                    {
                        txtTemp.Rtf = txtFunctionality.SelectedRtf;
                        for (int i = 0; i < selectionLength; ++i)
                        {
                            txtTemp.Select(i, 1);
                            txtTemp.SelectionFont = RenderFont(txtTemp.SelectionFont, familyName, emSize, fontStyle, enableFontStyle);
                        }

                        txtTemp.Select(0, selectionLength);
                        txtFunctionality.SelectedRtf = txtTemp.SelectedRtf;
                        txtFunctionality.Select(txtStartPosition, selectionLength);
                    }
            }
            finally
            {
                _maskChanges = false;
            }
        }
Next method important that I had to work a little on is RenderFont:
/// 
        /// Changes a font from originalFont appending other properties
        /// 
        /// Original font of text
        /// Target family name
        /// Target text Size
        /// Target font style
        /// true when enable false when disable
        /// A new font with all provided properties added/removed to original font
        private Font RenderFont(Font originalFont, string familyName, float? emSize, FontStyle? fontStyle, bool? enableFontStyle)
        {
            if (fontStyle.HasValue && fontStyle != FontStyle.Regular && fontStyle != FontStyle.Bold && fontStyle != FontStyle.Italic && fontStyle != FontStyle.Underline)
                throw new System.InvalidProgramException("Invalid style parameter to ChangeFontStyleForSelectedText");

            Font newFont;
            FontStyle? newStyle = null;
            if (fontStyle.HasValue)
            {
                if (fontStyle.HasValue && fontStyle == FontStyle.Regular)
                    newStyle = fontStyle.Value;
                else if (originalFont != null && enableFontStyle.HasValue && enableFontStyle.Value)
                    newStyle = originalFont.Style | fontStyle.Value;
                else
                    newStyle = originalFont.Style & ~fontStyle.Value;
            }

            newFont = new Font(!string.IsNullOrEmpty(familyName) ? familyName : originalFont.FontFamily.Name,
                                emSize.HasValue ? emSize.Value : originalFont.Size,
                                newStyle.HasValue ? newStyle.Value : originalFont.Style);
            return newFont;
        }

Observation: you must highlight the toolbar for your current position. For that after you load the rtf text you must position on first position of your text and according to that font you show font family, font size, if is bold - underline or italic.

In order to catch key combination of Ctrl+B, Ctrl+I, Ctrl+U you will use _KeyDown event of richTextBox control. For Control+I you must use a trick. Setting SuppressKeyPress = true will avoid executing 'Insert TAB' :)

In order to avoid flickering of text in richTextBox control especially when you delete last letter of control or when you try to detect font for first letter of textBox you have to use another trick. Use Suspend/Resume methods of next extension.

namespace System.Windows.Forms
{
    public static class ControlExtensions
    {
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        public static extern bool LockWindowUpdate(IntPtr hWndLock);

        //Method used agains flickering
        public static void Suspend(this Control control)
        {
            LockWindowUpdate(control.Handle);
        }

        public static void Resume(this Control control)
        {
            LockWindowUpdate(IntPtr.Zero);
        }
    }
}

I hope that this will help you a lot. When I searched around I did not found such as a control that will make a simple richTextBox with simple toolbar controls. If you encounter issues implementing it feel free to ask. I could also share code but I don't know a good reliable service to share files and not to be removed after a while :-? Do you?

Full code of control:

public partial class ExtraRichTextBoxUC : UserControl
    {
        private bool _maskChanges;
        public ExtraRichTextBoxUC()
        {
            InitializeComponent();
            LoadData();

            DisplayData();
        }

        private void DisplayData()
        {
//dummy data to preview
txtFunctionality.Rtf = @"{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Tahoma;}{\f1\fnil\fcharset0 Times New Roman;}}\viewkind4\uc1\pard\b\f0\fs18 W\b0 indows 8.1, Windows Server 2012 R2, \b Windows\b0  8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 \fs24 R2 (Server \fs18 Core Role \ul supported with SP1 \ulnone or later; Itanium \fs24 not supported\fs18 ).NET Framework does not support all versions of \fs26 every\f1  platform. For \f0 a list of \fs18 the supported versions, see .NET Framework System Requirements.\par}";

            GoToFirstPositionAndHighlightToolbar();
        }

        private void LoadData()
        {
            LoadRichTextEditorData();
        }

        private void LoadRichTextEditorData()
        {
            string[] availableFontFamilies;

            //check to see if fonts are installed on machine
            try
            {
                availableFontFamilies = new string[] { 
                new FontFamily("Arial").Name, 
                new FontFamily("Microsoft Sans Serif").Name, 
                new FontFamily("Tahoma").Name, 
                new FontFamily("Times New Roman").Name 
                };
            }
            catch (ArgumentException e)
            {
                throw new Exception("Font not present: " + e.Message);
            }

            List < object > availableFontSizes = new List < object >();

            for (float i = 8; i <= 14; i++)
                availableFontSizes.Add(i);

            cmbFontFamily.Items.AddRange(availableFontFamilies);
            cmbFontSize.Items.AddRange(availableFontSizes.ToArray());
        }

        private void ckbBold_CheckedChanged(object sender, EventArgs e)
        {
            if (_maskChanges)
                return;

            ChangeOrSetFont(string.Empty, null, FontStyle.Bold, ckbBold.Checked);
            txtFunctionality.Focus();
        }

        private void ckbItalic_CheckedChanged(object sender, EventArgs e)
        {
            if (_maskChanges)
                return;

            ChangeOrSetFont(string.Empty, null, FontStyle.Italic, ckbItalic.Checked);
            txtFunctionality.Focus();
        }

        private void ckbUnderline_CheckedChanged(object sender, EventArgs e)
        {
            if (_maskChanges)
                return;

            ChangeOrSetFont(string.Empty, null, FontStyle.Underline, ckbUnderline.Checked);
            txtFunctionality.Focus();
        }

        private void cmbFontFamily_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_maskChanges)
                return;

            ChangeOrSetFont(cmbFontFamily.SelectedItem.ToString(), null, null, null);
            txtFunctionality.Focus();
        }

        private void cmbFontSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_maskChanges)
                return;
            ChangeOrSetFont(null, float.Parse(cmbFontSize.SelectedItem.ToString()), null, null);
            txtFunctionality.Focus();
        }

        private void ChangeOrSetFont(string familyName, float? emSize, FontStyle? fontStyle, bool? enableFontStyle)
        {
            if (txtFunctionality.SelectionType == RichTextBoxSelectionTypes.Empty)
            {
                SetSelectionFont(familyName, emSize, fontStyle, enableFontStyle);
            }
            else
            {
                ChangeFontStyleForSelectedText(familyName, emSize, fontStyle, enableFontStyle);
            }
        }

        private void SetSelectionFont(string familyName, float? emSize, FontStyle? fontStyle, bool? enableFontStyle)
        {
            Font renderedFont = RenderFont(txtFunctionality.SelectionFont, familyName, emSize, fontStyle, enableFontStyle);
            txtFunctionality.SelectionFont = renderedFont;
        }

        private void ChangeFontStyleForSelectedText(string familyName, float? emSize, FontStyle? fontStyle, bool? enableFontStyle)
        {
            _maskChanges = true;
            try
            {
                int txtStartPosition = txtFunctionality.SelectionStart;
                int selectionLength = txtFunctionality.SelectionLength;
                if (selectionLength > 0)
                    using (RichTextBox txtTemp = new RichTextBox())
                    {
                        txtTemp.Rtf = txtFunctionality.SelectedRtf;
                        for (int i = 0; i < selectionLength; ++i)
                        {
                            txtTemp.Select(i, 1);
                            txtTemp.SelectionFont = RenderFont(txtTemp.SelectionFont, familyName, emSize, fontStyle, enableFontStyle);
                        }

                        txtTemp.Select(0, selectionLength);
                        txtFunctionality.SelectedRtf = txtTemp.SelectedRtf;
                        txtFunctionality.Select(txtStartPosition, selectionLength);
                    }
            }
            finally
            {
                _maskChanges = false;
            }
        }

        /// 
        /// Changes a font from originalFont appending other properties
        /// 
        /// Original font of text
        /// Target family name
        /// Target text Size
        /// Target font style
        /// true when enable false when disable
        /// A new font with all provided properties added/removed to original font
        private Font RenderFont(Font originalFont, string familyName, float? emSize, FontStyle? fontStyle, bool? enableFontStyle)
        {
            if (fontStyle.HasValue && fontStyle != FontStyle.Regular && fontStyle != FontStyle.Bold && fontStyle != FontStyle.Italic && fontStyle != FontStyle.Underline)
                throw new System.InvalidProgramException("Invalid style parameter to ChangeFontStyleForSelectedText");

            Font newFont;
            FontStyle? newStyle = null;
            if (fontStyle.HasValue)
            {
                if (fontStyle.HasValue && fontStyle == FontStyle.Regular)
                    newStyle = fontStyle.Value;
                else if (originalFont != null && enableFontStyle.HasValue && enableFontStyle.Value)
                    newStyle = originalFont.Style | fontStyle.Value;
                else
                    newStyle = originalFont.Style & ~fontStyle.Value;
            }

            newFont = new Font(!string.IsNullOrEmpty(familyName) ? familyName : originalFont.FontFamily.Name,
                                emSize.HasValue ? emSize.Value : originalFont.Size,
                                newStyle.HasValue ? newStyle.Value : originalFont.Style);
            return newFont;
        }

        private void txtFunctionality_SelectionChanged(object sender, EventArgs e)
        {
            if (_maskChanges)
                return;

            if (string.IsNullOrEmpty(txtFunctionality.Text))
            {
                //clear all text with its ex-formatting
                txtFunctionality.Clear();
                LoadAndSetDefaultFont();
            }
            else
            {
                ScanSelectedTextAndHighlightToolbar();
            }
        }

        private void txtFunctionality_KeyDown(object sender, KeyEventArgs e)
        {
            if (_maskChanges)
                return;

            if (e.Control && e.KeyCode == Keys.B)
            {
                ckbBold.Checked = !ckbBold.Checked;
                e.Handled = true;
            }
            else if (e.Control && e.KeyCode == Keys.I)
            {
                ckbItalic.Checked = !ckbItalic.Checked;
                e.Handled = true;
                e.SuppressKeyPress = true; //avoid executing 'Insert TAB' for CTRL + I
            }
            else if (e.Control && e.KeyCode == Keys.U)
            {
                ckbUnderline.Checked = !ckbUnderline.Checked;
                e.Handled = true;
            }
        }

        private void GoToFirstPositionAndHighlightToolbar()
        {
            _maskChanges = true;
            try
            {
                if (!string.IsNullOrEmpty(txtFunctionality.Text))
                {
                    txtFunctionality.Suspend();
                    txtFunctionality.Select(0, 1);

                    using (RichTextBox txtTemp = new RichTextBox())
                    {
                        txtTemp.Rtf = txtFunctionality.SelectedRtf;
                        Font currFont = txtTemp.SelectionFont;

                        HighlightToolbar(currFont.FontFamily.Name, currFont.Size, currFont.Bold, currFont.Italic, currFont.Underline);
                    }
                    txtFunctionality.Select(0, 0);
                    txtFunctionality.Resume();
                }
                else
                {
                    LoadAndSetDefaultFont();
                }
            }
            finally
            {
                _maskChanges = false;
            }
        }
        
        private Font GetFontFromToolbar()
        {
            FontStyle toolbarFontStyle = new FontStyle();
            if (ckbBold.Checked)
                toolbarFontStyle |= FontStyle.Bold;
            if (ckbItalic.Checked)
                toolbarFontStyle |= FontStyle.Italic;
            if (ckbUnderline.Checked)
                toolbarFontStyle |= FontStyle.Underline;

            Font font = new Font(cmbFontFamily.SelectedItem.ToString(), (float)cmbFontSize.SelectedItem, toolbarFontStyle);
            return font;
        }

        //could be changed into an extentension 
        public string TrimLastChar(string text)
        {
            if (text.Length >= 1)
                return text.Substring(0, text.Length - 1);
            else
                return text;
        }

        private void LoadAndSetDefaultFont()
        {
            Font font = txtFunctionality.Font;
            HighlightToolbar(font.FontFamily.Name, font.Size, font.Bold, font.Italic, font.Underline);

            SetSelectionFont(font.FontFamily.Name, font.Size, font.Style, null);
        }

        private void ScanSelectedTextAndHighlightToolbar()
        {
            _maskChanges = true;
            try
            {
                if (txtFunctionality.SelectionType == RichTextBoxSelectionTypes.Empty)
                {
                    int selectionStart = txtFunctionality.SelectionStart != 0 ? txtFunctionality.SelectionStart - 1 : 0;
                    int selectionEnd = txtFunctionality.SelectionStart;

                    txtFunctionality.Suspend();
                    //case when passes to a new line - it looses font style so must get from Tooolbar
                    if (TrimLastChar(txtTextContent.Text).EndsWith("\n"))
                    {
                        txtTextContent.Select(selectionStart, 1);
                        txtTextContent.SelectionFont = GetFontFromToolbar();
                        txtTextContent.Select(selectionEnd, 0);
                    }
                    else
                    {
                        txtTextContent.Select(selectionStart, 1);
                        using (RichTextBox txtTemp = new RichTextBox())
                        {
                            txtTemp.Rtf = txtTextContent.SelectedRtf;
                            Font currFont = txtTemp.SelectionFont;

                            HighlightToolbar(currFont.FontFamily.Name, (float)Math.Truncate(currFont.Size), currFont.Bold, currFont.Italic, currFont.Underline);
                            txtTextContent.SelectionFont = currFont;
                        }
                        txtTextContent.Select(selectionEnd, 0);
                    }
                    txtFunctionality.Resume();
                }
                else
                    if (!string.IsNullOrEmpty(txtFunctionality.SelectedText))
                    {
                        int txtStartPosition = txtFunctionality.SelectionStart;
                        int selectionLength = txtFunctionality.SelectionLength;

                        if (selectionLength > 0)
                            using (RichTextBox txtTemp = new RichTextBox())
                            {
                                txtTemp.Rtf = txtFunctionality.SelectedRtf;

                                if (selectionLength < 2)
                                {
                                    FontFamily firstCharFontFamily = txtTemp.SelectionFont.FontFamily;
                                    float firstCharSize = txtTemp.SelectionFont.Size;
                                    bool isBold = txtTemp.SelectionFont.Bold;
                                    bool isItalic = txtTemp.SelectionFont.Italic;
                                    bool isUnderline = txtTemp.SelectionFont.Underline;

                                    HighlightToolbar(firstCharFontFamily.Name, firstCharSize, isBold, isItalic, isUnderline);
                                }
                                else
                                {
                                    txtTemp.Select(0, 1);
                                    FontFamily firstCharFontFamily = txtTemp.SelectionFont.FontFamily;
                                    float firstCharSize = txtTemp.SelectionFont.Size;
                                    bool isBold = txtTemp.SelectionFont.Bold;
                                    bool isItalic = txtTemp.SelectionFont.Italic;
                                    bool isUnderline = txtTemp.SelectionFont.Underline;

                                    bool sameFontFamily = true, sameFontSize = true;

                                    for (int i = 1; i < selectionLength; i++)
                                    {
                                        txtTemp.Select(i, 1);
                                        sameFontFamily = txtTemp.SelectionFont.FontFamily.Name == firstCharFontFamily.Name;
                                        sameFontSize = txtTemp.SelectionFont.Size == firstCharSize;
                                        isBold = isBold && txtTemp.SelectionFont.Bold;
                                        isItalic = isItalic && txtTemp.SelectionFont.Italic;
                                        isUnderline = isUnderline && txtTemp.SelectionFont.Underline;

                                        if (!sameFontFamily && !sameFontSize && !isBold && !isItalic && !isUnderline)
                                            break;
                                    }

                                    HighlightToolbar(sameFontFamily ? firstCharFontFamily.Name : string.Empty,
                                        sameFontSize ? firstCharSize : (float?)null,
                                        isBold, isItalic, isUnderline);
                                }
                            }
                    }
            }
            finally
            {
                _maskChanges = false;
            }
        }

        private void HighlightToolbar(string commonFamilyName, float? emSize, bool? isBold, bool? isItalic, bool? isUnderline)
        {
            if (!string.IsNullOrEmpty(commonFamilyName))
                cmbFontFamily.SelectedItem = commonFamilyName;
            else
                cmbFontFamily.SelectedItem = null;

            if (emSize.HasValue)
                cmbFontSize.SelectedItem = (float)Math.Truncate(emSize.Value);
            else
                cmbFontSize.SelectedItem = null;

            if (isBold.HasValue)
            {
                ckbBold.CheckState = isBold.Value ? CheckState.Checked : CheckState.Unchecked;
            }
            else
                ckbBold.CheckState = CheckState.Unchecked;

            if (isItalic.HasValue)
            {
                ckbItalic.CheckState = isItalic.Value ? CheckState.Checked : CheckState.Unchecked;
            }
            else
                ckbItalic.CheckState = CheckState.Unchecked;

            if (isUnderline.HasValue)
            {
                ckbUnderline.CheckState = isUnderline.Value ? CheckState.Checked : CheckState.Unchecked;
            }
            else
                ckbUnderline.CheckState = CheckState.Unchecked;
        }
    }
}

namespace System.Windows.Forms
{
    public static class ControlExtensions
    {
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        public static extern bool LockWindowUpdate(IntPtr hWndLock);

        //Method used agains flickering
        public static void Suspend(this Control control)
        {
            LockWindowUpdate(control.Handle);
        }

        public static void Resume(this Control control)
        {
            LockWindowUpdate(IntPtr.Zero);
        }
    }

Monday, September 16, 2013

How to parameterize the value of a Top in a SQL query?

Supposing that you have a query like 'Select TOP x from table' and you want to parameterize x param value(in a C# method) then there is a trick which you must have in consideration if you want the query to run.
So, in Sql server 2005 and above you can use parenthesis before and after you param.
Here you go:
 

SELECT TOP (@elements) * from tableCities


It is pretty easy, isn't it?

How to calculate the next business days in C#?

There are cases when according to a business day(Monday to Friday) and number of days you have to return the computed business day. Of course the result can not be on week-end.
So if you ever encounter this scenario when you have a certain date and you want to add x days to it and then return the dateTime found you could use the next extension.
I admit that this extension is a very basic solution. I refer to the fact that I don't take into consideration holidays. If you want a more complex solution then you could go to Dynamic-Holiday-Date-Calculator. Or you could create a list of holidays and then make another method - IsHoliday() that should check if a certain date is part of your holiday calendar.

The idea of this algorithm is simple. In a while block we add one day to our original date time and as long as the result date is not in weekend we decrease number of bussiness days to add.
 
        ///
        /// Adds business days to a date
        /// 
        /// 
        /// 
        /// 
        public static DateTime AddBusinessDays(this DateTime dateTime, int businessDays)
        {
            DateTime resultDate = dateTime;
            while (businessDays > 0)
            {
                resultDate = resultDate.AddDays(1);
                if (resultDate.DayOfWeek != DayOfWeek.Saturday &&
                    resultDate.DayOfWeek != DayOfWeek.Sunday)
                    businessDays--;
            }
            return resultDate;
        }

Hope that helped you ;)

Monday, June 10, 2013

How to set the tab order for controls in a form, Microsoft Visual Studio 2010?

It might happen to you, as it happened to me to have a form with many controls. When you run the application and use only keyboard for moving from one control to another you notice that the order is random, in fact is according to the order of creation of your controls. Maybe you had to change the order after your first sketch.
My first tryout was to change the order manually. I choose from Properties the Tab Index and changed according to my plans. The problem was that I received a nice error that was saying( i don't remember exactly) that the index is already occupied, so it could not change order.

Finally, I searched a while around to see how to set the tab order index for many controls in a form of Microsoft Visual Studio. I found a nice and easy solution which tested and works for Windows Forms in Visual Studio 2010.

First step: as you are in Design View of your form in menu go to View and select Tab Order.


Second step: on your controls will appear a number that represents the Tab Order of your control. For re - setting tab order press a click in ascending order the controls that want to succeed, including Labels(even they are not selectable). I hope it is very intuitive this step for you too.You may see the image bellow.

When you have finished press Escape. Retest your application :)

Like and Share - very much appreciated ;)

Wednesday, May 29, 2013

How to set the background color of a grid column header panel, DevExpress?

If you want to set the background color of a XtraGrid control from DevExpress controls you might get into some problems. Why? Because you can indeed find property Appearance.HeaderPanel.BackColor, then you set it and however no influence on grid. Why? Because you have to make another set :) But is not specified anywhere in info places.
So how do solve this?
In order to set background color of a GridControl, winforms you have to:
-go to gridControl and set Style to Flat;
-set UseDefaultLookAndFeel to False


-go to gridview and set Appearance.HeaderPanel.BackColor - your color (this will automatically set useBackColor to true, also)


Otherwise if you want to set it by code you may use this:



  gridControl1.LookAndFeel.Style = DevExpress.LookAndFeel.LookAndFeelStyle.Flat;
  gridControl1.LookAndFeel.UseDefaultLookAndFeel = false; 

  gridView1.Appearance.HeaderPanel.Options.UseBackColor = true;
  gridView1.Appearance.HeaderPanel.BackColor = System.Drawing.Color.Red;
If this helped you, go ahead and share :)

Thursday, March 14, 2013

How to design Windows Forms with Abstract Inheritance?

It happened few days ago when I got to this nice error:

The designer must create an instance of type '... .BaseClass.TabBaseControl' but it cannot because the type is declared as abstract.


The scenario was like this: I had a Base class where a defined abstract members that where implemented in a form. When wanted to see the design of the page this warning appeared even though the application runs just fine. So how to get rid of this error:  "The designer must create an instance of type 'SchedeMaterialiDaTaglio.BaseClass.TabBaseControl' but it cannot because the type is declared as abstract. " ?
Well, searching around I got to this post http://www.platinumbay.com/blogs/dotneticated/archive/2008/01/05/designing-windows-forms-with-abstract-inheritance.aspx where I found part of the solution. 
Here it is:

 public class AbstractCommunicatorProvider : TypeDescriptionProvider
    {
        public AbstractCommunicatorProvider()
            : base(TypeDescriptor.GetProvider(typeof(UserControl)))
        {
        }
        public override Type GetReflectionType(Type objectType, object instance)
        {
            return typeof(UserControl);
        }
        public override object CreateInstance(IServiceProvider provider, Type objectType, Type[] argTypes, object[] args)
        {
            objectType = typeof(UserControl);
            return base.CreateInstance(provider, objectType, argTypes, args);
        }
    }
You define this class in inherited class(it only worked for me in this way) and you must also put this for base class and inherited class:

    [TypeDescriptionProvider(typeof(AbstractCommunicatorProvider))]
    public partial class TabUC : TabBaseControl{}

    [TypeDescriptionProvider(typeof(AbstractCommunicatorProvider))]
    public abstract class TabBaseControl : UserControl, ITabBase{}
Of course that you will have to include System.ComponentModel namespace and others just as needed.
Hope it helped. Ciao.

Friday, March 8, 2013

How to solve "Object reference not set to an instance of an object" in Design Time, Visual Studio, Winforms?

If you ever encounter this nice message then here is what you should do in order to fix "Object reference not set to an instance of an object" showing in Design Time even if code runs just fine.

I will tell you how I encountered it. I created a user control that has a property. In a page form I included this user control among others. In control's Load event I had to use that defined property. And I did not understood why it needs to know the value in design time, however it shows this nice error. It is obvious that is not set. It is only set when running.
So. Ready with long talk. The only think you need to get away of this "Object reference not set to an instance of an object" error you must use DesignMode property of the control. :)

if (!this.DesignMode)
{
   //your code here that generates the error
}
Well, hope that I helped you today with this error. Keep up the good code ;)

Friday, January 25, 2013

How to maintain the current scroll position across postbacks in Asp.Net?

It might sometimes happen that when you submit a page you want that the scroll position of the page remain the same. So how do you do that, in Asp.Net?

First I thought about some javascript code. Well you don't need some extra js functions when Asp.Net has a built in property.

Well, in order to keep scroll position of the page the same after submit you have to set in page declaration MaintainScrollPositionOnPostback  property to "true".

As I said in order to maintain the current scroll position across postbacks you can do this:
<%@ Page MaintainScrollPositionOnPostback="true" %>

Regards.

Friday, December 14, 2012

How to check CheckedListBox item with single click in Windows Forms Application?

If you want that when you check an item in CheckedListBox control in Windows Forms Application the item to be checked from first click there is a trick you need to do it.
As I developed more with Asp.Net, web applications, it was very awkward for me that when I checked the item in checkedListBox control it did not checked it but rather kind of selected it.
Well, in order to answer your question you have to make only one modification: select the control and then press Alt + Enter for Properties and then look for CheckOnClick property. Set it on True.

There you go :)
If this post helped you, leave a comment or share it :)

How to get rid of 'Saving Changes Is Not Permitted On SQL Server 2008 Management Studio'?

Well that is really annoying. Isn't it? This often happens when you want to alter a table: change data type on existing columns or change allow null on existing columns.
Good, so how do you get rid of this warning: Saving changes is not permitted ?

These are the steps:
1.Open Microsoft Sql Server Management Studio 2008 (I guess it is already opened)
2.Go to Tools(in menu) and click Options
3.Click Designers
4. and Uncheck 'Prevent saving changes that require table re-creation' option
5.Go OK and retry alter your table.

Here is a print screen.

There you go. Continue programming.

Monday, November 26, 2012

How to INSERT into a table records extracted from another table?

If you want to insert values from one table into another you can use this sql query.

insert into TBL_TARGET([USERNAME],[PASSWORD],[ACTION])
select [USERNAME] ,[PASSWORD], 'I'
from [TBL_SOURCE]


Don't use any extra 'VALUES' or parenthesis.

How to solve error 15128 in Microsoft Sql Server ?

If you ever meet this nice Sql Error, 15128 in Microsoft Sql Error you must do these next steps. At least they worked for me :)
First I want to explain which is the scenario. You are logged with Windows Authentication and you created a new sql login. Now you want to disable Enforce Password Policy. When you want to do that Sql tells you that you can not save the user, a new password must be set. Strange...so:

  • double click on new login created, leave the check boxes checked(enforce password policy and enforce password expiration) and change user's password temporally to what ever you want, click OK
  • then reopen and uncheck enforce password policy, enforce password expiration; Press OK
  • finally you reopen the user and specify the password you want
  • Test it ;)
Hope this will help you.

Wednesday, October 10, 2012

How to get total number of tables in a database in SQL?

It might happen that you will have to start working on a big database, someday. So, just out of curiosity if you ever want to find total number of tables that are in your table you can use this simple query:


SELECT COUNT(*) as TotalTables FROM sys.tables WHERE type in ('u') 

  
Of course, first you have to connect to your database. Hope it helps.

Thursday, October 4, 2012

How to get country, city, language for an ip address, in Asp.Net?

When you want to get location information about a client that visits your website according to its ip address you can use a third party service that offers this info in real time or you can use free services, which might not work 100% accurate. However, no matter which service you shall choose you can use the same workflow as I used in my project example.

I created a class that will be used to deserialize json response from api service from easyjquery.com:
 private struct GeoIPResponse
    {
//this is the response I get
        //{"IP":"127.0.0.1","continentCode":"Unknown","continentName":"Unknown",
        //"countryCode2":"Unknown","COUNTRY":"Unknown","countryCode3":"Unknown","countryName":"Unknown","regionName":"Unknown",
        //"cityName":"Unknown","cityLatitude":0,"cityLongitude":0,"countryLatitude":0,"countryLongitude":0,"localTimeZone":"Unknown",
        //"localTime":"0"}
        public string IP;
        public string continentCode;
        public string continentName;
        public string countryCode2;
        public string COUNTRY;
        public string countryCode3;
        public string countryName;
        public string regionName;
        public string cityName;
        public string cityLatitude;
        public string cityLongitude;
        public string countryLatitude;
        public string countryLongitude;
        public string localTimeZone;
        public string localTime;
    }
/*
then I defined some needful methods: 
*/

/// 
    /// Returns Client Ip Address
    /// 
    static public string ClientIpAddress
    {
        get
        {
            string _clientIPAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (!string.IsNullOrEmpty(_clientIPAddress))
            {
                string[] ipRange = _clientIPAddress.Split(',');
                _clientIPAddress = ipRange[ipRange.Length - 1];
            }
            else
            {
                _clientIPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }

            return _clientIPAddress;
        }

    }

    public string _WebRequest(string strURL)
    {
        String strResult;
        WebResponse objResponse;
        WebRequest objRequest = HttpWebRequest.Create(strURL);
        objRequest.Method = "GET";

        objResponse = objRequest.GetResponse();
        using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
        {
            strResult = sr.ReadToEnd();
            sr.Close();
        }
        return strResult;

    }
and finally this is the way I used a service from www.easyjquery.com: :
protected void Page_Load(object sender, EventArgs e)
{
        txtMessage.Text = "";
        string Result = _WebRequest("http://api.easyjquery.com/ips/?ip=" + ClientIpAddress + "&full=true");

        txtMessage.Text = Result;
        
        JavaScriptSerializer jss = new JavaScriptSerializer();
        var clientGeoLocation = jss.Deserialize < GeoIPResponse >(Result);

        lblMessage.Text = "
Your short details: " + "Country: " + clientGeoLocation.COUNTRY + ", CountryCode 2: " + clientGeoLocation.countryCode2 + ", CountryCode 3: " + clientGeoLocation.countryCode3 +
            ", TimeZone: " + clientGeoLocation.localTimeZone;
}