Search This Blog

Friday, December 5, 2014

Dynamic Object Runtime C# Example

C# > Sytem.Dynamic > DynamicObject

DynamicObject specifies dynamic behavior at run time.






Example:

Create dynamic object in runtime.

Dynamically Add C# Properties at Runtime.


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

namespace WindowsFormsApplication26
{
    public class MyDynamicObject : DynamicObject
    {
        Dictionary<string, object> dictionary = new Dictionary<string, object>();
        public object this[string propertyName]
        {
            get
            {
                return dictionary[propertyName];
            }
            set
            {
                dictionary[propertyName] = value;
            }
        }
        public override bool TryGetMember(
            GetMemberBinder binder, out object result)
        {
            return dictionary.TryGetValue(binder.Name, out result);
        }
        public override bool TrySetMember(
            SetMemberBinder binder, object value)
        {
            dictionary[binder.Name] = value;
            return true;
        }
      
        public override bool TrySetIndex(
            SetIndexBinder binder, object[] indexes, object value)
        {
            int index = (int)indexes[0];
            if (dictionary.ContainsKey("Property" + index))
                dictionary["Property" + index] = value;
            else
                dictionary.Add("Property" + index, value);
            return true;
        }
    }
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            dynamic obj = new MyDynamicObject();
            obj["column1"] = 1;
            obj.column2 = 2;

            var v1 = obj["column1"];
            var v2 = obj.column2;
        }
    }
}







Wednesday, November 19, 2014

Telerik RadTimePicker Get Selected Time

Telerik > RadTimePicker > Get Time


Get selected time from RadTimePicker c#.


DateTime dt = radTimePicker.SelectedDate.Value;
string time = dt.ToString("HH:mm:ss");






Monday, November 17, 2014

Call one constructor from another c#

CKeywords > ThisCall one constructor from another 



      public Constructor1()
      {
      }

      public Constructor2(string writer) : this()
      {
      }









Thursday, November 6, 2014

Lambda Expressions in a Query C#

C# > Operators > Lambda > Query

We use  lambda expressions in method calls not directly in query syntax.

Simple Example

     int[] wages = { 1000, 1200, 1500, 1800, 2000, 2500 };
    int highWagesCount = wages.Where(n => n >= 2000).Count(); 









Wednesday, November 5, 2014

DataGridView Windows Forms Control

Windows Forms >  DataGridView Control

You can use a DataGridView control to display data with or without an underlying data source. 
DataGridView contains cells, rows, columns, and borders.
Without specifying a data source, you can create columns and rows that contain data and add them directly to the DataGridView using the Rows and Columns properties. 






HyperLink ASP.NET Example

ASP.NET > System.WebWeb Controls > HyperLink

Displays a link to another Web page.

Events



Example

<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/WebForm1.aspx">HyperLink</asp:HyperLink>




Web Controls ASP.NET

ASP.NET > System.Web > Web Controls

Web server controls run on the server.









ASP.NET Hyperlink OnClick Code Behind

ASP.NET > System.Web > Web Controls > > onClick

Script

<script br="" gt="" language="javascript" type="text/javascript">

function onClick(obj) {

}
lgt;/script>

C# Code behind

HyperLink1.Attributes.Add("onclick", "return onClick(this)");





Tuesday, November 4, 2014

Transact-SQL SQL Server

SQL Server > Transact-SQL

Transact-SQL is Microsoft's proprietary extension to SQL (Structured Query Language).
All applications that communicate with SQL Server use Transact-SQL to send statements to the server, regardless of the user interface of the application.

SET Statements



Mnagements Commands






Code Collaborator Add Changes To Review Number

Code Collaborator > Add changes to review


addhgdiffs - Uploads diffs generated by hg diff command

Example

Upload from Mercurial


3883 is the review number
-r difference from revision 0 to 1

ccollab addhgdiffs 3883 -r 0 -r 1

-c specific revision id

ccollab addhgdiffs codereviewid -c revisionid









Monday, November 3, 2014

PARSE SQL Server Example

SQL Server > Built-in Functions > PARSE

Translates an expression to the requested data type.

Example


SELECT PARSE('3-11-2014' AS datetime USING 'en-US') AS Result_En
Result_En
2014-03-11 00:00:00.000

SELECT PARSE('3-11-2014' AS datetime USING 'de-DE') AS Result_De
Result_De
2014-11-03 00:00:00.000





Friday, October 24, 2014

Telerik Reporting Binding C# Example

Telerik > Reporting > ObjectDataSource

ObjectDataSource component represents the middle-tier object and provides data retrieval capabilities. 
Example


var ods = new Telerik.Reporting.ObjectDataSource();
ods.DataSource = GetData();
ods.DataMember = "Products"; //table to bind to        
Telerik.Reporting.Report report = new Telerik.Reporting.Report();
report.DataSource = ods;
Telerik.Reporting.InstanceReportSource reportSource = new Telerik.Reporting.InstanceReportSource();
reportSource.ReportDocument = report;
reportViewer1.ReportSource = reportSource;
reportViewer1.RefreshReport();





Thursday, October 23, 2014

Get Computer Name C#

C#  > System > Environment ClassMachineName

Returns the computer's name. This is established at system start up when the name is read from the registry. 

Example



   string _name = Environment.MachineName;





ADO.NET LINQ to SQL

ADO.NET LINQ to SQL

Is a component for managing relational data as objects. 

  • the data model of a relational database is mapped to an object model  
  • translates into SQL the language-integrated queries in the object model and sends them to the database for execution
  • translates database result  back to objects 
Methods





Tuesday, October 21, 2014

VB.NET LINQ TO SQL Delete Rows From Database

ADO.NET > LINQ TO SQL > Delete rows from database

DeleteOnSubmit removes entity, but does not disappear from the query results until after SubmitChanges is called. 

Example


C#

var deleteData =
    from details in db.GetDetails
    where details.ID == 1
    select details;

foreach (var detail in deleteData )
{
    db.Details.DeleteOnSubmit(detail);
}

try
{
    db.SubmitChanges();
}
catch (Exception e)
{
}



VB.Net

Dim deleteData = _
    From details In db.GetDetails() _
    Where details.ID = 1 _
    Select details

For Each detail As Detail In deleteData
    db.Details.DeleteOnSubmit(detail)
Next 

Try
    db.SubmitChanges()
Catch ex As Exception

End Try





Friday, October 17, 2014

Check Deny Access File C#

C# > System.Security > AccessControlAuthorizationRuleCollection 

AuthorizationRuleCollection 

Represents a collection of AuthorizationRule objects.

Example


Check Deny Access File C#

public bool CheckDenyAccessFile(string filePath)
{
       FileSecurity fs = File.GetAccessControl(filePath);
       AuthorizationRuleCollection acl = fs.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
       bool deny = false;
       for (int x = 0; x < acl.Count; x++)
       {
              FileSystemAccessRule currentRule = (FileSystemAccessRule)acl[x];
              AccessControlType accessType = currentRule.AccessControlType;
              if (accessType == AccessControlType.Deny && (currentRule.FileSystemRights & FileSystemRights.ListDirectory) == FileSystemRights.ListDirectory)
                {
                    deny = true;
                    break;
                }
        }
        return deny;
}





Writes lines to text file C#

C# > IO  > FileInfo > CreateText

Writes text a new text file.

Example


Writes lines to text file C#


string path = Path.GetTempFileName();
FileInfo fi = new FileInfo(path);

using (StreamWriter sw = fi.CreateText())
{
      sw.WriteLine("Line1");
      sw.WriteLine("Line2");
      sw.WriteLine("Line3");
      sw.WriteLine("Line4");


}      





FileInfo Class C#

C# > IO  > FileInfo Class

FileInfo

Use this class for working with files: create, open, delete, 

move, rename.

Methods

Properties






Thursday, October 16, 2014

String IsNullOrEmpty C# Example

C# > String > Methods > IsNullOrEmpty

With this method you can test simultaneously test whether a String is null or its value is Empty.

Example


string s = "test";
bool b = String.IsNullOrEmpty(s); // false
           
s = null;
b = String.IsNullOrEmpty(s); // true
           
s = "";
b = String.IsNullOrEmpty(s); // true

s = " ";

b = String.IsNullOrEmpty(s); // false








Wednesday, October 15, 2014

CONVERT SQL Server Example

SQL Server > Built-in Functions > CONVERT

CONVERT converts an expression of one data type to another.
Example

select CONVERT(nvarchar(30), GETDATE(), 100)

result
Oct 15 2014  9:54AM

Other examples: