26 Mayıs 2010 Çarşamba

C# notes

class DelegateTests
{
public void Run()
{
// there are many ways to call method Test
// 1, declare Func<int, string> delegate
Func<int, string> func1 = MyFunc;
Test(func1);

// 2, implicit delegate
Test(MyFunc);

// 3, inline delegate
Test(delegate(int i) { return i.ToString(); });

// 4, lambda expression
Test(n => n.ToString());
}

public void Test(Func<int, string> func)
{
Console.WriteLine(func(
123));
}

private string MyFunc(int i)
{
return i.ToString();
}
}

List Join

+++ Program that joins List of strings (C# .NET 4.0) +++

using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
// Create a List of three strings.
var list = new List<string>() { "cat", "dog", "rat" };
// Join the strings from the List.
string joined = string.Join<string>("*", list);
// Display.
Console.WriteLine(joined);
}
}


 



   1.
IEnumerable
<long> ids = new long[]{1,3,4,5};
2.
string delimitedIds = string.Join(",", ids.Select(x => x.ToString()).ToArray());



 



            // Array ToString "," separated
int[] intArray = { 1, 2, 3 };
Console.WriteLine(intArray.ToString(
","));
// output: 1,2,3

// ArrayList ToString ":" separated
ArrayList arrayList = new ArrayList() { 1, 2, 3 };
Console.WriteLine(arrayList.ToString(
":"));
// output 1:2:3

// A class object List ToString " - " separated
List<Foo> foos = new List<Foo>()
{
new Foo() { Name = "foo1", Number = 1 },
new Foo() { Name = "foo2", Number = 2 },
new Foo() { Name = "foo3", Number = 3 },
};
Console.WriteLine(foos.ToString(
" - "));
// output 'foo1 1' - 'foo2 2' - 'foo3 3'

// A struct List ToString "||" separated
List<StructFoo> sfoos = new List< StructFoo >()
{
new StructFoo() { Name = "sfoo1", Number = 1 },
new StructFoo() { Name = "sfoo2", Number = 2 },
new StructFoo() { Name = "sfoo3", Number = 3 },
};
Console.WriteLine(sfoos.ToString(
"||"));
// output 'sfoo1 1'||'sfoo2 2'||'sfoo3 3'

// A generic dictionary ToString "," separated
Dictionary< int, Foo > dictionary = new Dictionary< int, Foo >()
{
{
1, new Foo() { Name = "foo1", Number = 1 }},
{
2, new Foo() { Name = "foo2", Number = 2 }},
{
3, new Foo() { Name = "foo3", Number = 3 }},
};
Console.WriteLine(dictionary.ToString(
","));
// output: [1, 'foo1 1'],[2, 'foo2 2'],[3, 'foo3 3']

// string as IEnumerable char
string text = "abcdefg";
Console.WriteLine(text.ToString(
","));
// output: a,b,c,d,e,f,g

Dynamic sitemap in ASP.NET MVC

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class MVCUrlAttribute : ActionFilterAttribute
{
public string Url { get; private set; }

public MVCUrlAttribute(string url)
{
this.Url = url;
}

public override void OnResultExecuting(ResultExecutingContext filterContext)
{
// Put this 'canonical url' into the model (which feeds the view)
// to help search engines with issues of duplicate content
filterContext.Controller.ViewData["CanonicalUrl"] = url;
base.OnResultExecuting(filterContext);
}
}


// Find all the MVC Routes
Log.Debug("*** FINDING ALL MVC ROUTES MARKED FOR INCLUSION IN SITEMAP");
var allControllers
= Assembly.GetExecutingAssembly().GetTypes().Where(t => t.IsSubclassOf(typeof(Controller)));
Log.DebugFormat(
"Found {0} controllers", allControllers.Count());

foreach (var controllerType in allControllers)
{
var allPublicMethodsOnController
= controllerType.GetMethods(BindingFlags.Public | BindingFlags.Instance);
Log.DebugFormat(
"Found {0} public methods on {1}", allPublicMethodsOnController.Count(), controllerType.Name);

foreach (var publicMethod in allPublicMethodsOnController)
{
var mvcurlattr
= publicMethod.GetCustomAttributes(true).OfType<MVCUrlAttribute>().FirstOrDefault();
if (mvcurlattr != null)
{
string url = mvcurlattr.Url;
Log.Debug(
"Found " + controllerType.Name + "." + publicMethod.Name + " <-- " + url);
Global.SiteMapUrls.Add(url);
//<-- your code here using url
}
}
}


 



 



 




protected string GetUrl(object routeValues)
{
RouteValueDictionary values
= new RouteValueDictionary(routeValues);
RequestContext context
= new RequestContext(HttpContext, RouteData);

string url = RouteTable.Routes.GetVirtualPath(context, values).VirtualPath;

return new Uri(Request.Url, url).AbsoluteUri;
}

List
<string> urlList = new List<string>();
urlList.Add(GetUrl(
new { controller = "Help", action = "Edit" }));
urlList.Add(GetUrl(
new { controller = "Help", action = "Create" }));
urlList.Add(GetUrl(
new { controller = "About", action = "Company" }));
urlList.Add(GetUrl(
new { controller = "About", action = "Management" }));

23 Mayıs 2010 Pazar

MVC business layer

public void Save(EmployeeViewModel employeeViewModel)
{
var employee
= (from emp in dataContext.Employees
where emp.EmployeeID == employeeViewModel.EmployeeID
select emp).SingleOrDefault();


if (employee != null)
{

employee.Address
= employeeViewModel.Address;
employee.Salary
= employeeViewModel.Salary;
employee.Title
= employeeViewModel.Title;
}
dataContext.SubmitChanges();
}

public void Save(EmployeeViewModel employeeViewModel)
{

var employee
= (from emp in dataContext.Employees
where emp.EmployeeID == employeeViewModel.EmployeeID
select emp).SingleOrDefault();

if (employee != null)
{
ModelCopier.CopyModel(employeeViewModel, employee);
}
dataContext.SubmitChanges();

}


 



refer :http://weblogs.asp.net/rajbk/archive/2010/03/31/easy-way-to-update-models-in-your-asp-net-mvc-business-layer.aspx

22 Mayıs 2010 Cumartesi

What is MEF?

 

The Managed Extensibility Framework (or MEF for short) simplifies the creation of extensible applications. MEF offers discovery and composition capabilities that you can leverage to load application extensions.

What problems does MEF solve?

MEF presents a simple solution for the runtime extensibility problem. Until now, any application that wanted to support a plugin model needed to create its own infrastructure from scratch. Those plugins would often be application-specific and could not be reused across multiple implementations.
    MEF provides a standard way for the host application to expose itself and consume external extensions. Extensions, by their nature, can be reused amongst different applications. However, an extension could still be implemented in a way that is application-specific. Extensions themselves can depend on one another and MEF will make sure they are wired together in the correct order (another thing you won't have to worry about). MEF offers a set of discovery approaches for your application to locate and load available extensions. MEF allows tagging extensions with additonal metadata which facilitates rich querying and filtering</LI>

How does MEF work?

Roughly speaking, MEF's core is comprised of a catalog and a CompositionContainer. A catalog is responsible for discovering extensions and the container coordinates creation and satisfies dependencies.
    MEF's first-class citizen is a ComposablePart (see Parts). A composable part offers up one or more Exports, and may also depend on one or more externally provided services or Imports. A composable part also manages an instance, which can be an object instance of a given type (it is in the default MEF implementation). MEF, however, is extensible and additonal ComposablePart implementations can be provided as long as they adhere to the Import/Export contracts. Exports and imports each have a Contract. Contracts are the bridge between exports and imports. An export contract can consist of further metadata that can be used to filter on its discovery. For example, it might indicate a specific capability that the export offers. MEF's container interacts with Catalogs to have access to composable parts. The container itself resolves a part's dependencies and exposes Exports to the outside world. You're free to add composable part instances directly to the container if you wish. A ComposablePart returned by a catalog will likely be an extension to your application. It might have Imports (dependencies) on components the host application offers, and it's likely to Export others. The default MEF composable part implementation uses attribute-based metadata to declare exports and imports. This allows MEF to determine which parts, imports, and exports are available completely throug

      21 Mayıs 2010 Cuma

      MVC

      object o=new{name="Rob", type="quack"}

      //This evaluates to "name=\"Rob\" type=\"quack\" "
      string myList=o.ToAttributeList()


       




      <form action="<%=Url.Action(new{controller="Home", action="Index"})%> method=post>



       




      <%=Html.RenderUserControl("~/UserControls/ForumList.ascx")%>
      <%=Html.RenderUserControl("~/UserControls/ForumList.ascx", new{GroupID=2})%>



       




      <%using(Html.Form("Home","Index"))%>
      ...
      <%}%>

      <%using(Html.Form("Home","Index"), FormExtensions.FormMethod.get)%>
      ...
      <%}%>

      <%=Html.Submit("Save")%>
      <%=Html.SubmitImage("~/Images/SaveButton.gif")%>

      Object.UpdateFrom(Request.Form)
      Controller.ReadFromRequest(
      string key)

      Product p
      =new Product();
      p.UpdateFrom(Request.Form);

      20 Mayıs 2010 Perşembe

      XML C# samples

      XDocument xdoc = XDocument.Load("data.xml");
      var lv1s = xdoc.Root.Descendants("level1");
      var lvs = lv1s.SelectMany(l=>
      new string[]{ l.Attribute("name").Value }
      .Union(
      l.Descendants("level2")
      .Select(l2=>" " + l2.Attribute("name").Value)
      )
      );
      foreach (var lv in lvs)
      {
      result.AppendLine(lv);
      }


      void Main()
      {
      XElement rootElement = XElement.Load(@"c:\events\test.xml");

      Console.WriteLine(GetOutline(0, rootElement));
      }

      private string GetOutline(int indentLevel, XElement element)
      {
      StringBuilder result = new StringBuilder();

      if (element.Attribute("name") != null)
      {
      result = result.AppendLine(new string(' ', indentLevel * 2) + element.Attribute("name").Value);
      }

      foreach (XElement childElement in element.Elements())
      {
      result.Append(GetOutline(indentLevel + 1, childElement));
      }

      return result.ToString();
      }


      XDocument xdoc = XDocument.Load("data.xml"));
      var lv1s = from lv1 in xdoc.Descendants("level1")
      select new {
      Header = lv1.Attribute("name").Value,
      Children = lv1.Descendants("level2")
      };


      foreach (var lv1 in lv1s){
      result.AppendLine(lv1.Header);
      foreach(var lv2 in lv1.Children)
      result.AppendLine(" " + lv2.Attribute("name").Value);
      }

      16 Mayıs 2010 Pazar

      Determine ChildWindow Position At Runtime

        private FrameworkElement root;
      private FrameworkElement contentroot;
      private FrameworkElement chrome;

      private Point childWindowOffset;


       



      public MyChildWindow()
      {
      InitializeComponent();
      Loaded
      += new RoutedEventHandler(ThisChildWindow_Loaded);
      }


       



      In the RoutedEventHandler ThisChildWindow_Loaded we get access with VisualTreeHelper on the VisualTree of the control template and doing so we assign to our three variables root, contentroot and chrome the corresponding element parts of the control template. To the MouseButtonEventHandler of the chrome we add a further MouseLeftButtonUpEvent called Chrome_MouseLeftButtonUp using AddHandler, in which we later add our code to determine the position.



      private void ThisChildWindow_Loaded  (object sender, RoutedEventArgs e )
      {
      if (VisualTreeHelper.GetChildrenCount(this) == 0)
      {
      Dispatcher.BeginInvoke(()
      => ThisChildWindow_Loaded(this, e));
      return;
      }
      root
      = (FrameworkElement)VisualTreeHelper.GetChild(this, 0);
      contentroot
      = root.FindName("ContentRoot") as FrameworkElement;
      chrome
      = root.FindName("Chrome") as FrameworkElement;
      if (chrome != null)
      {
      chrome.AddHandler(MouseLeftButtonUpEvent,
      new MouseButtonEventHandler(Chrome_MouseLeftButtonUp), true);
      }
      }


       



      Then we must build our routine Chrome_MouseLeftButtonUp where we will call the function GetChildWindowOffset. The actual calculation of the new location takes place in the function GetChildWindowOffset. Here is the code for GetChildWindowOffset:



      private void Chrome_MouseLeftButtonUp
      (
      object sender,
      MouseButtonEventArgs e
      )
      {
      this.childWindowOffset =
      GetChildWindowOffset
      (
      e.GetPosition(root),
      e.GetPosition(contentroot)
      );
      }


       



      To calculate the new position in the function GetChildWindowOffset the values of X and Y of ContentRootMousePosition is subtracted from the value of X and Y value of RootMousePosition respectively:



        result.X = RootMousePosition.X - ContentrootMousePosition.X;
      result.Y = RootMousePosition.Y - ContentrootMousePosition.Y;



       



      reference: http://blogs.windowsclient.net/silverlaw/archive/2010/04/15/how-to-determine-new-childwindow-position-at-runtime-silverlight-3.aspx

      Silverlight GridSplitter Control

      <UserControl
      xmlns:basics="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
      x:Class="GridSplitter2.Page"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      Width="400" Height="300">
      <Grid x:Name="LayoutRoot" ShowGridLines="True" Background="White" Width="400" Height="300">
      <Grid.RowDefinitions>
      <RowDefinition />
      </Grid.RowDefinitions>
      <Grid.ColumnDefinitions>
      <ColumnDefinition />
      <ColumnDefinition Width="Auto"/>
      <ColumnDefinition />
      </Grid.ColumnDefinitions>
      <basics:GridSplitter x:Name="grsplSplitter" Grid.Row="0" Grid.Column="1" VerticalAlignment
      ="Stretch" HorizontalAlignment="Center" Background="Aqua" Width="5"></basics:GridSplitter>
      </Grid>
      </UserControl>



       



      Capture1



      <Grid.ColumnDefinitions>
      <ColumnDefinition />
      <ColumnDefinition Width="25"/>
      <ColumnDefinition />
      </Grid.ColumnDefinitions>


       



      Capture2



      <UserControl
      xmlns:basics="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
      x:Class
      ="GridSplitter2.Page"
      xmlns
      ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x
      ="http://schemas.microsoft.com/winfx/2006/xaml"
      Width
      ="400" Height="300">
      <Grid x:Name="LayoutRoot" ShowGridLines="True" Background="White" Width="400" Height="300">
      <Grid.RowDefinitions>
      <RowDefinition />
      <RowDefinition Height="Auto" />
      <RowDefinition />
      </Grid.RowDefinitions>
      <Grid.ColumnDefinitions>
      <ColumnDefinition />
      </Grid.ColumnDefinitions>
      <basics:GridSplitter x:Name="grsplSplitter" Grid.Row="1" Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Stretch" Background="Aqua" Height="5"></basics:GridSplitter>
      </Grid>
      </UserControl>


       



      <basics:GridSplitter ShowsPreview="True" x:Name="grsplSplitter" Grid.Row="0" Grid.Column="1" VerticalAlignment="Stretch" HorizontalAlignment="Center" Background="Aqua" Width="5"></basics:GridSplitter>


       



      Capture5



       



      refernce: http://www.silverlightshow.net/items/Using-the-GridSplitter-control-in-Silverlight-2-Beta-1.aspx

      Silverlight Grid Control

      <Grid x:Name="LayoutRoot" Background="White" ShowGridLines="True">
              <Grid.RowDefinitions>
                  <RowDefinition></RowDefinition>
                  <RowDefinition></RowDefinition>
                  <RowDefinition></RowDefinition>
              </Grid.RowDefinitions>
              <Grid.ColumnDefinitions>
                  <ColumnDefinition></ColumnDefinition>
                  <ColumnDefinition></ColumnDefinition>
                  <ColumnDefinition></ColumnDefinition>
              </Grid.ColumnDefinitions>
      </Grid>

      sample1_thumb

      <Grid x:Name="LayoutRoot" Background="White" ShowGridLines="True">
              <Grid.RowDefinitions>
                  <RowDefinition Height="Auto"></RowDefinition>
                  <RowDefinition Height="100"></RowDefinition>
                  <RowDefinition Height="*"></RowDefinition>
              </Grid.RowDefinitions>
              <Grid.ColumnDefinitions>
                  <ColumnDefinition></ColumnDefinition>
                  <ColumnDefinition></ColumnDefinition>
                  <ColumnDefinition></ColumnDefinition>
              </Grid.ColumnDefinitions>
              <Button Content="Auto Size" Height="150" Grid.Row="0" Grid.Column="0" ></Button>
              <Button Content="Pixel Size" Height="150" Grid.Row="1" Grid.Column="1"></Button>
              <Button Content="Star Size" Height="150" Grid.Row="2" Grid.Column="2"></Button>
      </Grid>

      sample2_thumb

      <RowDefinition Height="30*"></RowDefinition>
      <RowDefinition Height="40*"></RowDefinition>

      sample3_thumb

      <Button Content="Auto Size" Height="150" Width="300" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" ></Button>

       

      reference : http://www.silverlightshow.net/items/Using-Silverlight-Grid-Control.aspx

      13 Mayıs 2010 Perşembe

      Silverlight xap caching?

      You can turn the Enable Content Expiration HTTP header option on for your XAP file. Open IIS Manager, goto Default Web Site and find your Web site for the silverlight project. Find the XAP file under ClientBin. Goto the properties page of the XAP file, on HTTP Headers Tab, Turn on "Enable Content Expiration", click the "Expire Immediately" radio button. Save the change.

      This way the new XAP (only there is a new XAP) will get downloaded when you refresh your page without having to close the browser.

      4 Mayıs 2010 Salı

      HTTP Error 500.21 - Internal Server Error

      Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list

       

      C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe –i

      .net 4.0 for admin writes in microsoft windows 7 press

      ctrl + shift + enter at start menu run command : )