Search This Blog

Wednesday, May 13, 2015

C# Generic Interface Example

C# > Generics > Generic Interface 

Example


class Serializer1 { public string Name { get; set; } };
class Serializer2 { public string Name { get; set; } };

interface GenericSerializer<T>
{
      string Name(T tValue);
}

class Serializer<T>: GenericSerializer<T>
{
public string Name(T tValue)
        {
            var prop = tValue.GetType().GetProperty("Name");
            return prop.GetValue(tValue, null) as string;
        }
}

Serializer1 s1 = new Serializer1() { Name = "Serializer1" };
Serializer2 s2 = new Serializer2() { Name = "Serializer2" };

Serializer<Serializer1> serializer1 = new Serializer<Serializer1>();
string name1 = serializer1.Name(s1);

Serializer<Serializer2> serializer2 = new Serializer<Serializer2>();

string name2 = serializer2.Name(s2);






Thursday, April 23, 2015

LINQ Average excluding or including zeros c#

C# > LINQ > Average


Average computes the average of a sequence of numeric values.

Example


int[] int_array = new int[] { 5, 4, 2, 8, 10, 0 };

// linq average excluding zeros

double avg =
       (from ord in int_array
        where ord > 0
        select ord).Average();  // 5.8

// linq average including zeros 
avg =
       (from ord in int_array
       select ord).Average();    // 4.83





Wednesday, April 8, 2015

UPDATE SQL Server Example

SQL Server > DML > UPDATE

Changes existing data in a table or view.


Example


update
   person
set
   name = 'Bill'
where 
   id = 1



Wednesday, April 1, 2015

Reflection to find all classes implementing interface c#

C# > Reflection Find classes implementing interface

var iTtype = typeof(Interface);
var types = AppDomain.CurrentDomain.GetAssemblies()
           .SelectMany(a => a.GetTypes())
           .Where(t => iTtype.IsAssignableFrom(t));





Telerik GridViewCheckBoxColumn Alignment

Telerik > Windows Forms > RadGridView > GridViewCheckBoxColumn

GridViewCheckBoxColumn displays and allows editing of 

boolean data.

Example

GridViewCheckBoxColumn Alignment


<telerik:GridViewCheckBoxColumn DataMemberBinding="{Binding IsManager}" >
    <telerik:GridViewCheckBoxColumn.CellStyle>
        <Style TargetType="telerik:GridViewCell">
            <Setter Property="HorizontalContentAlignment" Value="Center" />
        </Style>
    </telerik:GridViewCheckBoxColumn.CellStyle>


</telerik:GridViewCheckBoxColumn>




Calculate SQL Server row size for a table

SQL Server > Scripts > Row Size


create table ##RowSize (tableName nvarchar(50), rowSize int)
exec sp_msforeachtable 'INSERT INTO ##RowSize Select ''?'' As tableName, SUM(c.Length) from dbo.SysColumns c where c.id = object_id(''?'') '
select * from ##RowSize order by rowSize  desc
drop table ##RowSize






Wednesday, March 18, 2015

Remove database SQL Server with sp_dbremove

SQL Server > System Stored Procedures > sp_dbremove

Removes a database.

Example

EXEC sp_dbremove HR;




Thursday, February 19, 2015

Write, read XML to memory stream using XmlWriter and XmlReader C#

C# > XML > XmlWriter

XmlWriter  writes XML data to a file, stream,, text reader, or string.
It is fast, noncached and forward only.

Example
Write/read XML to memory stream.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            MemoryStream stream = new MemoryStream();

            XmlWriter writer = XmlWriter.Create(stream);

            writer.WriteStartDocument();
            writer.WriteStartElement("Root");
            writer.WriteElementString("Child", "1");
            writer.WriteEndElement();
            writer.WriteEndDocument();

            writer.Flush();
            writer.Close();

            stream.Position = 0; // Resets the position to 0 so we can read.
            XmlReader reader = XmlReader.Create(stream);
            while (reader.Read())
            {
                //
            }
            reader.Close();

        }
    }
}




Monday, February 16, 2015

Select DataTable rows with where LINQ C#

C# > LINQ > Where

Where filters a sequence of values based on a predicate. 

Example

Select DataTable rows with where.


DataTable dt = new DataTable();
dt.Columns.Add("name", typeof(string));
dt.Rows.Add("john");
dt.Rows.Add("dan");

var filteredRows = dt.Rows
                  .Cast<DataRow>()
                  .Where(r => r["name"] == "dan").ToList();




Wednesday, February 11, 2015

Create new directory with DirectoryInfo C#

C# > Files > DirectoryInfo Class

Use this class for create, move and enumerating directories and subdirectories. 

Example 

Create new directory

DirectoryInfo directoryInfo = new DirectoryInfo(@"c:\Yourdir");
try
{
if (!directoryInfo.Exists)
       {
              directoryInfo.Create();
       }
}
catch (Exception ex)
{
MessageBox.Show("DirectoryInfo error: {0}", ex.ToString());
}
finally { }





Monday, February 2, 2015

Get Directory Size C#

C# > IO  > FileInfo > Length

Get the size of the file in bytes. 

Example

Get Directory Size C#


public long DirectorySize(DirectoryInfo dir)
{
       long size = 0;
       foreach (FileInfo file in dir.GetFiles())
       {
              size += file.Length;
       }
      foreach (DirectoryInfo directory in dir.GetDirectories())
       {
              size += DirectorySize(directory);
       }
       return size;
 }

DirectoryInfo dir = new DirectoryInfo(@"C:\Temp");
long size = DirectorySize(dir);








Monday, January 19, 2015

C# Capture Screen to PictureBox

C# > Drawing > Capture Screen

Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics graphics = Graphics.FromImage(printscreen as Image);
graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);
using (MemoryStream s = new MemoryStream())
{
printscreen.Save(s, System.Drawing.Imaging.ImageFormat.Bmp);
       picCapture.Size = new System.Drawing.Size(this.Width, this.Height);
       picCapture.Image = Image.FromStream(s);

}





XmlDocument C# Example

C# > XML > XmlDocument

Represents an XML document.

Example


XmlDocument doc = new XmlDocument();
doc.Load(xmlfile);




NetworkChange Class C#

C# > System.Net > NetworkInformation > NetworkChange

Use this class to receive notification when the IP address of a network interface changes.
Changes can appears when:

  • disconnect network cable
  • out of range of a wireless Local Area Network
  • hardware failure
Events:





    C# NetworkInformation NameSpace

    C# > System.Net > NetworkInformation


    Provides access to network address information and traffic data.

    Classes





    Thursday, January 15, 2015

    ReadAllBytes C# Example

    C# > Files > File Class > ReadAllBytes

    Opens, reads the contents of the file into a byte array, and then closes the file.

    Example

    Read bytes from jpg file and display to PictureBox.

    var bytes = File.ReadAllBytes("D:\\Pics\\1.jpg");
    pictureBox1.Image = Image.FromStream(new System.IO.MemoryStream(bytes));







    C# File Class

    C# > Files > File Class


    Use the File class for:
    • copy, move, rename, create, open, delete to a single file at a time. 
    • get and set file attributes.


    All File methods are static.


    Methods





    Tuesday, January 6, 2015

    IsNumeric equivalent in LINQ example

    C# > LINQ > IsNumeric

    IsNumeric equivalent in LINQ example.

    double value;
    var total = (from DataRow dr in dataTable.Rows
                    where double.TryParse(dr["value"], out value)
                    select Convert.ToDouble(dr["value"])).Sum();