Search This Blog

Wednesday, May 20, 2015

Print PictureBox Image C# Example Using PrintDocument

C# > Print  > PrintDocument

PrintDocument sends out to the printer.


Example

Print image



using System;
using System.Drawing;
using System.Windows.Forms;

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

        private void button1_Click(object sender, EventArgs e)
        {
            printPreviewDialog1.Document = printDocument1;
            printPreviewDialog1.ShowDialog();
        }

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            e.Graphics.DrawImage(pictureBox1.Image, 100, 100, 700, 600);
        }
    }
}





Tuesday, May 19, 2015

System tables SQL Server

SQL Server > System tables








Monday, May 18, 2015

Subtract SQL Server example

SQL Server > Operators > Subtract

- Operator (minus) subtracts two numbers or a number (in days) from date.





Example

1. Subtracts values from 2 numeric columns

create table #test(value int, fee int)
insert into #test(value, fee) values (500,50),(100,10)
  select 
   value - fee as 'diff'
  from 
   #test
drop table #test

Result
diff
450
90

2. Subtracts from date

SELECT getdate() - 1 AS 'Subtract Date';





C# unit test using Moq verify property has been set

C# > Unit test > Moq > Verify property has been set

SetupSet : Specifies a setup on the mocked type for a call to a property setter.
VerifySet : Verifies that a property has been set on the mock, regardless of its value.

Example

using System;

namespace UnitTestProject1
{
    public interface Interface1
    {
        int Id { get; set; }
    }
}

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            var mocker = new Mock<Interface1>();
            mocker.SetupSet(x => x.Id = 1);
            mocker.Object.Id = 1;
            mocker.VerifySet(x => x.Id);
        }
    }
}





Friday, May 15, 2015

Convert string to date C# example

C# > System Namespace > DateTime > Parse

Parse converts string to a date.


Example


string value = "5/15/2015";

var dte = DateTime.Parse(value, CultureInfo.InvariantCulture); // {5/15/2015 12:00:00 AM}




Thursday, May 14, 2015

Find last row Telerik RadGridView

Telerik > RadGridView > Find last row
GridViewRowInfo lastRow = radGridView.Rows[radGridView.Rows.Count - 1];
lastRow.IsSelected = true;






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 { }