The blog has moved to a new address. The blog is now located at http://devintelligence.com
Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Wednesday, March 12, 2008

System.Reflection - how to access and invoke private methods,fields or properties

For demonstration purpose I've created a class that contains only private methods,fields and properties

/// <summary>
/// Holds blog information
/// </summary>
public class Blog
{
/// <summary>
/// Gets the posts count.
/// </summary>
private static int PostsCount
{
get
{
return 10000;
}
}

/// <summary>
/// Gets the description.
/// </summary>
/// <returns></returns>
private string GetDescription()
{
return @"A weblog dedicated to obsessively profiling
reviewing new Internet products and companies"
;
}


/// <summary>
/// Changes the name of the blog.
/// </summary>
/// <param name="newName">The new name.</param>
private string ChangeBlogName(string newName)
{
name = newName;
return name;
}


string url = "http://techcrunch.com";
string name = "Tech Crunch";
}



 



To access private fields I used the System.Reflection.FieldInfo class .For private properties I used System.Reflection.PropertyInfo .Note if you want to work with private members you should use System.Reflection.BindingFlags enum as shown in the example below .So for non-static class members the flags should looks like BindingFlags.NonPublic | BindingFlags.Instance .For static don't forget to add BindingFlags.Static .




class Program
{
static void Main(string[] args)
{



Blog blog = new Blog();
Type type = typeof(Blog);
//create reflection bindings - will be used to retrive private fields,methods or properties
BindingFlags privateBindings = BindingFlags.NonPublic | BindingFlags.Instance;

// retrive private fields from our class
FieldInfo[] fieldInfos = type.GetFields(privateBindings);

// retrive private fields metadata
foreach (FieldInfo fieldInfo in fieldInfos)
{
Console.WriteLine(fieldInfo.Name +" "+ fieldInfo.GetValue(blog));
}


PropertyInfo [] propertyInfos = type.GetProperties(privateBindings|BindingFlags.Static);
// retrive private static properties metadata
foreach (PropertyInfo propertyInfo in propertyInfos)
{
// note that no instance need for static property to retrive it's value
Console.WriteLine(propertyInfo.Name + " " + propertyInfo.GetValue(null,null) );
}

// call method using MethodInfo object
MethodInfo miGetDescription = type.GetMethod("GetDescription", privateBindings);
object retObj = miGetDescription.Invoke(blog, new object[]{});
Console.WriteLine(retObj);

// call method using MethodInfo object with input parameters
MethodInfo miChangeBlogName = type.GetMethod("ChangeBlogName", privateBindings);
retObj = miChangeBlogName.Invoke(blog, new object[] { "Yahoo blog" });
Console.WriteLine(retObj);

Console.ReadLine();



}



 



The console output fallows



image



Technorati Tags: ,,

Wednesday, October 10, 2007

SVN via MS IIS

SVN-IIS gives access to Subversion via MS IIS
The main goal of this project is to make a direct interface from a SVN repository to WebDav interface running on MS IIS.

Features

  • Practically no overhead
  • Tested on IIS5.x and IIS6.x
  • Tested on http and https (used a test certificate)
  • Support for HTTP 1.1 Chunked encoding
  • Runs on Windows XP\2000\2003\Vista
  • Apache like logging

Prerequisites

  • .NET Framework
  • Access from the IIS to a running Apache webserver, interfacing a SVN repository

 

[Via dotnetkicks.com]

Saturday, September 15, 2007

The set of useful methods that can make developer life easer

Take a look at a list below and you may find a few methods that save your time.The sources  and documentation are here.

Array

GetMissingItems
Gets a list of the items in an array missing from a second array.

RemoveDups
Removes any duplicate items for a list of items.

StringArrayToString
Converts an array of strings into a string.

Collection

CollectionToHtmlTable
Converts a collection to an html string having a table.

Color

ColorToHtml
Converts a color into an html hexadecimal string.

GetColorTable
Get an html table listing color, html hexadecimal, and color name.

GetRandomColor
Gets a random color.

DataSet

ArrayToDataTable
Converts an array of strings to a DataTable.

DataTable2ExcelString
Coverts a DataTable into an Excel string.

DataTableToArray
Creates a string array from a DataTable.

DataTableToString
Converts a DataTable to a string with an html table.

FilterSortData
Filter and sort a dataset.

DateTime

CountWeekdays
Counts the number of weekdays between two dates.

CountWeekends
Counts the number of weekends between two dates.

IsDate
Checks whether an object is a date.

IsWeekDay
Returns true of day is weekday, otherwise false.

IsWeekEnd
Returns true of day is weekend, otherwise false.

TimeBreakdown
Returns a string that enumerates years, months, days, etc.

File

ArrayToFile
Saves a string array as a text file.

FileToArray
Converts the contents of a file to a string array.

GetDirectoryFileInfo
Gets information about the files in a directory and puts it in an array of strings.

GetDirectoryInfo
Gets information about a directory and puts it in an array of strings.

GetFileInfo
Gets information about a file and puts it in an array of strings.

ReadFromFile
Reads from a text file, puts the contents of the file in a string, and returns the string.

WriteToFile
Writes the passed in string to a file.

Forms

SetCheckboxesSelect
Adds a check to the checkboxes whose values are passed in.

SetComboSelectedIndex
Sets which item is selected in a DropDownList.

Math

Triangulate
Sums the numbers from 1 to n.

UnTriangulate
Undoes the Triangulate method.

Network

DNSLookup
Gets DNS information about a url and puts it in an array of strings.

GetHttpHeaders
Gets Http Headers and puts them in an array of strings.

GetImages
Gets the images from a webpage.

GetLinks
Gets the links from a webpage.

GetServerVariables
Gets the ServerVariables and puts them in a string.

ReadWebPage
Reads a web page and returns a string with the contents.

SendMail
Sends an e-mail message.

SendNetSend
Sends a net send message.

Numbers

GetDoubles
Gets an array of double values from the start value to the end value.

GetInts
Gets an array of int values from the start value to the end value.

GetRandomNumber
Gets a random number.

IsNumeric
Check whether an object is numeric.

Stats

GetAvg
Gets the average of an array of doubles or an array of ints.

GetCorrelation
Gets the Correlation between two arrays of numbers.

GetStandardDeviation
Gets the standard deviation of a list of numbers.

Strings

CountStrings
Count how many times a string appears.

GetASCII
Gets a string with ASCII characters.

ProperCase
Converts a string to proper case.

RemoveWhiteSpace
Remove extra white space in a string.

Monday, July 23, 2007

Cyclomatic complexity measurement tool

ccm is a tool that analyzes C/C++ and C# code and reports back on Cyclomatic Complexity.Cyclomatic complexity is computed using a graph that describes the control flow of the program. The nodes of the graph correspond to the function of a program. A directed edge connects two nodes if the second function might be executed immediately after the first function. This technique is useful to determine how complex the function of code is.

ccm is a command line tool that accepts the path to directory you want to analyze. Using an /XML switch it will output the result as XML, making it easy to integrate with other tools, such as CruiseControl.NET, etc.

 

Usage

Running ccm without any parameters tells you about the available switches.

C:\Dev\ccm\bin>ccm
Missing parameters.

Usage:
 ccm directory [/r] [/xml] [/n:x] [/e:folderlist] [/v]
   switches:
     r            - act recursively on folders
     xml          - output into xml
     n:x          - list n-number of metrics (defaults to 30)
     v            - verbose
     e:folderlist - comma-separated list of folders or paths to exclude

ccm.exe ..\..\relativepath-to-sources /n:15

Download ccm

Thursday, May 31, 2007

A new beta of JetBrains refactoring tool is available for download

Now providing unparalleled support for C#, Visual Basic .NET, XML, XAML, and ASP.NET, including comprehensive cross-language functionality.

New Features

  • Unit Test Explorer
  • Go To Symbol
  • To-do List
  • XML and XAML Support
    • Various quick-fixes and context actions in XML
    • Code completion in XML
  • Code Analysis for C# Code

 

ReSharper 3.0 Beta is only a pre-release build of ReSharper 3.0. The final version 3.0 release is scheduled for the end of June, 2007. If you purchase ReSharper for VS .NET 2003 or ReSharper for VS 2005 now, you will qualify for free upgrade to version 3.0 when it becomes available.

Download Full Edition

Download C# Edition

Download Visual Basic Edition