private string GetViewPath(string[] locations, string viewName,string controllerName)
{
for (int i = 0; i < locations.Length; i++)
{
path = string.Format(System.Globalization.CultureInfo.InvariantCulture, locations[i],
new object[] { viewName, controllerName });
if (this.VirtualPathProvider.FileExists(path))
{
return path;
}
}
return null;
}
private string GetViewPath(string[] locations, string viewName,string controllerName)
{
return pPaths.Where(pp => pp.Name == controllerName && pp.ciewName= viewName ).First().Path();
}
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();
}
}
+++ 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
[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" }));
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();
}
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);
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);
}
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;