How to get the current Database and Log Filesize using MSSQL

To get the current Database and Log Filesize using MSSQL you can use the snippet below. Tested using SQL Server 2012.

Sample MSSQL

with database_files_CTE as
(
    select
        name, type_desc, physical_name, size_mb = convert(decimal(11, 2), size * 8.0 / 1024),
        space_used_mb = convert(decimal(11, 2), fileproperty(name, 'spaceused') * 8.0 / 1024) from sys.database_files
)
select name,type_desc as [type],physical_name as [path],size_mb as [Filesize],space_used_mb as [Filesize used],
case size_mb when 0 then 0 else convert(decimal(5, 2), space_used_mb / size_mb * 100) end as [Filesize used %]  from database_files_CTE;

Sample Output

Query Results Filesizes




How to map Objects with Constructor parameters using Automapper

To map Objects that need Constructor Parameters using Automapper you need to use the ConstructUsing Method while Creating the Map.
See the Sample Console Applications below.

Sample Console Application C#

using System;
using AutoMapper;

namespace de.Fesslersoft.AutomapperConstructorTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Mapper.CreateMap<Item, Product>()
                .ConstructUsing(x => new Product(x.Id,x.Price)) //without this line there will be an System.Argumentexception
                .ForMember(destination => destination.Number, x => x.MapFrom(source => source.Id))
                .ForMember(destination => destination.Price, x => x.MapFrom(source => source.Price));

            var item = new Item {Id = "Testitem", Price = new decimal(145.69)};
            var product = Mapper.Map<Item, Product>(item);

            Console.WriteLine(product.Number); //prints Testitem
            Console.WriteLine(product.Price); //prints 145.69

            Console.Read();
        }

        internal class Item
        {
            public string Id { get; set; }
            public decimal Price { get; set; }
        }

        internal class Product
        {
            public string Number { get; set; }
            public decimal Price { get; set; }

            public Product(string number, decimal price)
            {
                Number = number;
                Price = price;
            }
        }
    }
}

Sample Console Application VB.NET (autoconverted code)

Imports AutoMapper

Namespace de.Fesslersoft.AutomapperConstructorTest
	Class Program
		Private Shared Sub Main(args As String())
			'without this line there will be an System.Argumentexception
			Mapper.CreateMap(Of Item, Product)().ConstructUsing(Function(x) New Product(x.Id, x.Price)).ForMember(Function(destination) destination.Number, Function(x) x.MapFrom(Function(source) source.Id)).ForMember(Function(destination) destination.Price, Function(x) x.MapFrom(Function(source) source.Price))

			Dim item = New Item() With { _
				Key .Id = "Testitem", _
				Key .Price = New Decimal(145.69) _
			}
			Dim product = Mapper.Map(Of Item, Product)(item)

			Console.WriteLine(product.Number)
			'prints Testitem
			Console.WriteLine(product.Price)
			'prints 145.69
			Console.Read()
		End Sub

		Friend Class Item
			Public Property Id() As String
				Get
					Return m_Id
				End Get
				Set
					m_Id = Value
				End Set
			End Property
			Private m_Id As String
			Public Property Price() As Decimal
				Get
					Return m_Price
				End Get
				Set
					m_Price = Value
				End Set
			End Property
			Private m_Price As Decimal
		End Class

		Friend Class Product
			Public Property Number() As String
				Get
					Return m_Number
				End Get
				Set
					m_Number = Value
				End Set
			End Property
			Private m_Number As String
			Public Property Price() As Decimal
				Get
					Return m_Price
				End Get
				Set
					m_Price = Value
				End Set
			End Property
			Private m_Price As Decimal

			Public Sub New(number__1 As String, price__2 As Decimal)
				Number = number__1
				Price = price__2
			End Sub
		End Class
	End Class
End Namespace




How to select a item on rightclick using devexpress ListboxControl

To select a item on rightclick using devexpress ListboxControl you need to use the MouseDown Event.
See the samples below.

Sample C#

private void listBoxControl1_MouseDown(object sender, MouseEventArgs e)
{
	listBoxControl1.SelectedIndex = listBoxControl1.IndexFromPoint(new Point(e.X, e.Y));
}

Sample VB.NET

Private Sub listBoxControl1_MouseDown(sender As Object, e As MouseEventArgs)
	listBoxControl1.SelectedIndex = listBoxControl1.IndexFromPoint(New Point(e.X, e.Y))
End Sub




How to change the BackgroundColor of a XtraGrid Grouprow using C# or VB.NET

To change the BackgroundColor of a XtraGrid Grouprow you need to use the Gridviews CustomDrawGroupRow Event.

Sample C#

private void gridView1_CustomDrawGroupRow(object sender, RowObjectCustomDrawEventArgs e)
{
	var converter = new ColorConverter();
	var convertFromString = converter.ConvertFromString("#ebebeb");
	if (convertFromString != null)
	{
		e.Appearance.BackColor = (Color) convertFromString;
	}
}

Sample VB.NET

Private Sub gridView1_CustomDrawGroupRow(sender As Object, e As RowObjectCustomDrawEventArgs)
	Dim converter = New ColorConverter()
	Dim convertFromString = converter.ConvertFromString("#ebebeb")
	If convertFromString IsNot Nothing Then
		e.Appearance.BackColor = DirectCast(convertFromString, Color)
	End If
End Sub




How to get all Description Attributes of an Enum using C# or VB.NET

To get all Description Attributes of an Enum using C# or VB.NET you can use the snippet below.

Sample C# – Class

public class DescriptionAttributes<T>
    {
        protected List<DescriptionAttribute> Attributes = new List<DescriptionAttribute>();
        public List<string> Descriptions { get; set; }

        public DescriptionAttributes()
        {
            RetrieveAttributes();
            Descriptions = Attributes.Select(x => x.Description).ToList();
        }

        private void RetrieveAttributes()
        {
            foreach (var attribute in typeof(T).GetMembers().SelectMany(member => member.GetCustomAttributes(typeof(DescriptionAttribute), true).Cast<DescriptionAttribute>()))
            {
                Attributes.Add(attribute);
            }
        }
    }

Usage C#

class Program
    {
        public enum TestEnum
        {
            [Description("An apple a day keeps the doctor away")]
            Apple=0,
            [Description("Yummie Strawberry")]
            Strawberry=1,
            [Description("Banana for scale")]
            Banana=2
        }

        static void Main(string[] args)
        {
            var descriptions = new DescriptionAttributes<TestEnum>().Descriptions.ToList();
            foreach (var description in descriptions)
            {
                Console.WriteLine(description);
            }
            Console.Read();
        }
    }

Sample VB.NET – Class

Public Class DescriptionAttributes(Of T)
	Protected Attributes As New List(Of DescriptionAttribute)()
	Public Property Descriptions() As List(Of String)
		Get
			Return m_Descriptions
		End Get
		Set
			m_Descriptions = Value
		End Set
	End Property
	Private m_Descriptions As List(Of String)

	Public Sub New()
		RetrieveAttributes()
		Descriptions = Attributes.[Select](Function(x) x.Description).ToList()
	End Sub

	Private Sub RetrieveAttributes()
		For Each attribute As var In GetType(T).GetMembers().SelectMany(Function(member) member.GetCustomAttributes(GetType(DescriptionAttribute), True).Cast(Of DescriptionAttribute)())
			Attributes.Add(attribute)
		Next
	End Sub
End Class

Usage VB.NET

Class Program
	Public Enum TestEnum
		<Description("An apple a day keeps the doctor away")> _
		Apple = 0
		<Description("Yummie Strawberry")> _
		Strawberry = 1
		<Description("Banana for scale")> _
		Banana = 2
	End Enum

	Private Shared Sub Main(args As String())
		Dim descriptions = New DescriptionAttributes(Of TestEnum)().Descriptions.ToList()
		For Each description As var In descriptions
			Console.WriteLine(description)
		Next
		Console.Read()
	End Sub
End Class

Result / Output

Enum Descriptions

Enum Descriptions




How to XSL transform a XDocument in C# and VB.NET with custom namespaces

This snippet will help you to xsl transform xml files with custom namespaces. A Basic snippet which does only work without custom namespaces can be found HERE. The snippet will return a path to a temporary file (transformed xml).

Sample C#

private static string TransformXDocument(string inputXml, string xslFile)
        {
            try
            {
                var xslt = new XslCompiledTransform();
                xslt.Load(xslFile);
                string tempFile = string.Empty;
                using (var sr = new StreamReader(inputXml, Encoding.Default))
                {
                    var xDoc = XDocument.Load(xslFile);
                    if (xDoc.Root != null)
                    {
                        var result = xDoc.Root.Attributes().Where(a => a.IsNamespaceDeclaration).GroupBy(a => a.Name.Namespace == XNamespace.None ? String.Empty : a.Name.LocalName, a => XNamespace.Get(a.Value)).ToDictionary(g => g.Key,g => g.First());
                        var nt = new NameTable();
                        var mgr = new XmlNamespaceManager(nt);
                        foreach (var ns in result.Where(ns => ns.Key != "xsl" && ns.Value != "http://www.w3.org/1999/XSL/Transform"))
                        {
                            mgr.AddNamespace(ns.Key, ns.Value.ToString());
                        }
                        var xpc = new XmlParserContext(nt, mgr, "", XmlSpace.Default);
                        var rds = new XmlReaderSettings {ConformanceLevel = ConformanceLevel.Document};
                        using (var rd = XmlReader.Create(sr, rds, xpc))
                        {
                            tempFile = Path.GetTempFileName();
                            using (var wr = new StreamWriter(tempFile))
                            {
                                xslt.Transform(rd, new XsltArgumentList(), wr);
                                wr.Flush();
                                wr.Close();
                            }
                            rd.Close();
                        }
                    }
                }
                return tempFile;

            }
            catch (Exception ex)
            {
                //handle the exception your way
                return string.Empty;
            }
        }

Sample VB.NET

Private Shared Function TransformXDocument(inputXml As String, xslFile As String) As String
	Try
		Dim xslt = New XslCompiledTransform()
		xslt.Load(xslFile)
		Dim tempFile As String = String.Empty
		Using sr = New StreamReader(inputXml, Encoding.Default)
			Dim xDoc = XDocument.Load(xslFile)
			If xDoc.Root IsNot Nothing Then
				Dim result = xDoc.Root.Attributes().Where(Function(a) a.IsNamespaceDeclaration).GroupBy(Function(a) If(a.Name.[Namespace] = XNamespace.None, [String].Empty, a.Name.LocalName), Function(a) XNamespace.[Get](a.Value)).ToDictionary(Function(g) g.Key, Function(g) g.First())
				Dim nt = New NameTable()
				Dim mgr = New XmlNamespaceManager(nt)
				For Each ns As var In result.Where(Function(ns) ns.Key <> "xsl" AndAlso ns.Value <> "http://www.w3.org/1999/XSL/Transform")
					mgr.AddNamespace(ns.Key, ns.Value.ToString())
				Next
				Dim xpc = New XmlParserContext(nt, mgr, "", XmlSpace.[Default])
				Dim rds = New XmlReaderSettings() With { _
					Key .ConformanceLevel = ConformanceLevel.Document _
				}
				Using rd = XmlReader.Create(sr, rds, xpc)
					tempFile = Path.GetTempFileName()
					Using wr = New StreamWriter(tempFile)
						xslt.Transform(rd, New XsltArgumentList(), wr)
						wr.Flush()
						wr.Close()
					End Using
					rd.Close()
				End Using
			End If
		End Using

		Return tempFile
	Catch ex As Exception
		'handle the exception your way
		Return String.Empty
	End Try
End Function




Simple Type Percent for XSD Files

To use the simply type percent (xs:decimal), see the snippet below.

<xs:simpleType name="percent">
  <xs:annotation>
    <xs:documentation>The percent type specifies a value from 0 to 100.</xs:documentation>
  </xs:annotation>
  <xs:restriction base="xs:decimal">
    <xs:minInclusive value="0"/>
    <xs:maxInclusive value="100"/>
  </xs:restriction>
</xs:simpleType>




How to get the selected row index in Devexpress Xtragrid Control using C# and VB.NET

To get the selected row index in Devexpress Xtragrid Control using C# and VB.NET you can use the snippet below.

Sample C#

var selectedRowIndex = gridView1.FocusedRowHandle;

Sample VB.NET

Dim selectedRowIndex = gridView1.FocusedRowHandle




Top 10 reads of April 2015

These are the Top 10 reads of April 2015.


  • How to search stored procedures using MS-SQL
  • How to manually populate a multicolumn devexpress TreeList using C# and VB.NET
  • How to download a file using Python
  • How to drop Primary Key of a Table using MSSQL
  • How to read a String to Textreader using C# and VB.NET
  • How to add or remove a class on hover using jQuery
  • How to use the HTML5 datalist tag
  • How to reload a ViewController in IOS using Objective-C
  • How to get current Domain of the PC in C# and VB.NET
  • What is the difference between typeof(), GetType() and IS in C# and VB.NET



  • thanks to all visitors, bookmark us, share us, talk about us, Follow us!, Like us! let’s grow bigger!