C#: Remove line from textfile

With the following code you can remove a line from a textfile (web.config). If the string is within a line the line will be removed.

[code language=’c#’]
string configFile = @”C:devweb.config”;
List lineList = File.ReadAllLines(configFile).ToList();
lineList = lineList.Where(x => x.IndexOf(“<!–") <= 0).ToList();
File.WriteAllLines(configFile, lineList.ToArray());

[/code]

LINQ: Creating a if statement in Linq query

A lot of times I need to check a statement within my LINQ-query and I wish there was a possibility of a IF statement within LINQ.

The following code is the solution to my IF problem. I use a temporary variable (let isOlderThen30) to check if a statement is true. Then in my WHERE statement I use the temporary variable in a INFLINE IF.

For this example I use my Blogger class with some data

[code language=’c#’]

public class Blogger
{
 public string FirstName { get; set; }
 public string LastName { get; set; }
 public int Age { get; set; }
 public string Blog { get; set; }
}

List personList = new List{
 new Blogger { FirstName = “Pieter”, LastName = “Brinkman”, Age = 27, Blog = “http://blog.newguid.net” },
 new Blogger { FirstName = “Mark”, LastName = “van Aalst”, Age = 26, Blog = “http://www.markvanaalst.com” },
 new Blogger { FirstName = “Bas”, LastName = “Hammendorp”, Age = 32, Blog = “http://www.hammendorp.net” }
};

[/code]

It’s kind of hard to think of a easy good example, but here it is. In this example I want to set the Age property to “Older then 30” when the Blogger is older then 30 (how useful!).

[code language=’c#’]
//If a blogger is older then set Age text to “Older then 30”

var rawList = from item in personList
  let isOlderThen30 = item.Age > 30
  select new
  {
   Name = item.FirstName,
   Age = (isOlderThen30 ? “Older then 30″ : item.Age.ToString()),
  };

//GENERATE OUTPUT

foreach (var item in rawList)
{
 Response.Write(item.Name + ” (” + item.Age + “)
“);
}

//OUTPUT
//Pieter (27)
//Mark (26)
//Bas (Older then 30)

[/code]

Hope that the example is clear. If you have any questions let me know.

// UPDATE (3 aug 2009) //

I thought about the codeexample and offcourse you can do it shorter (but less readable with complex queries).

[code language=’c#’]
var rawList = from item in personList
  select new
  {
   Name = item.FirstName,
   Age = (item.Age > 30 ? “Older then 30” : item.Age.ToString()),
  };

[/code]

Linq to Xml: Generate Google Sitemap with sitemap-protocol

In this example I will generate a XML site-map that complies with the sitemap-protocol XML schema.

[code language=’c#’]
//create datasource

List blogPosts = new List{
 “http://blog.newguid.net/mypost1.aspx”,
 “http://blog.newguid.net/mypost_about_Net.aspx”,
 “http://blog.newguid.net/morePosts.aspx”,
 “http://blog.newguid.net/andEvenMorePosts.aspx”
};

//Create namespace for sitemap-protocol

XNamespace xmlNS = “http://www.sitemaps.org/schemas/sitemap/0.9”;
XDocument xmlDoc =
 new XDocument(
  new XDeclaration(“1.0”, “UTF-8”, null),
  new XElement(xmlNS + “urlset”,
   from blogPostUrl in blogPosts
   select
    new XElement(xmlNS + “url”,
    new XElement(xmlNS + “loc”, blogPostUrl))
    ));

//Show output

Response.Write(xmlDoc);

[/code]

This example will give the following output:

[code language=’xml’]
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9“>
 
    http://blog.newguid.net/mypost1.aspx
 
 
    http://blog.newguid.net/mypost_about_Net.aspx
 
 
    http://blog.newguid.net/morePosts.aspx
 
 
    http://blog.newguid.net/andEvenMorePosts.aspx
 

[/code]

To keep the example as simple as possible I only use the LOC element of the URL node. In the real world you can implement the lastmod, changefreq and priority node.

More information about the sitemap-protocol.

Linq Casting: ToDictionary()

In this post I will give an example how to cast a GenericList to Dictionary.

This example will use the following Blogger class.

[code language=’c#’]
public class Blogger
{
 public string FirstName { get; set; }
 public string LastName { get; set; }
 public int Age { get; set; }
 public string Blog { get; set; }
}

[/code]

The example will cast a List<Blogger> to a dictionary with key FirstName, Lastname and value the Age of the blogger.

[code language=’c#’]
// DECLARE PERSONLIST

List personList = new List();
personList.Add(new Blogger { FirstName = “Pieter”, LastName = “Brinkman”, Age = 27, Blog = “http://blog.newguid.net” });
personList.Add(new Blogger { FirstName = “Mark”, LastName = “van Aalst”, Age = 26, Blog = “http://www.markvanaalst.com/” });
personList.Add(new Blogger { FirstName = “Bas”, LastName = “Hammendorp”, Age = 32, Blog = “http://www.hammendorp.net/” });

// CREATE NEW DICTIONARY FROM LIST
// with key FirstName + LastName and value Age

Dictionary AgeDictionary =
 personList.ToDictionary(x => x.FirstName + ” ” + x.LastName,
       x => x.Age,
       StringComparer.OrdinalIgnoreCase);

// GENERATE OUTPUT

foreach (KeyValuePair item in AgeDictionary)
 Response.Write(“key: ” + item.Key + ” – value: ” + item.Value + “
“);

//// OUTPUT
//key: Pieter Brinkman – value: 27
//key: Mark van Aalst – value: 26
//key: Bas Hammendorp – value: 32

[/code]

 Hope it helps.

WCF webservice error with DBML objects

When deploying a WCF webservice for a Silverligh application I got the following error:

[code language=’html’]
An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is:
System.InvalidOperationException: An exception was thrown in a call to a WSDL export extension: System.ServiceModel.Description.DataContractSerializerOperationBehavior
 contract: http://tempuri.org/:IWebService —-> System.Runtime.Serialization.InvalidDataContractException: Type ‘Project.service.HU_BACH.ScPlacemark’ cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute.

[/code]

As you can see from the error you need to add the [Serializable] attribute to all objects that are used within the webservice. After I did this I got the same error for my Linq to Sql objects generated within my DBML. You can make your Linq to Sql objects serializable by changing the dbml setting Serialization Mode to Unidirectional.

 
Hope it helps.

Linq to Sql: Retrieve properties from related data (LoadWith)

You have to specify which related-data you want to retrieve from a object so you can access them outside the Linq data-context. You can achieve this by using the LoadWith method of the DataLoadOptions Class. The LoadWith method accepts an lambda expression that specifies which object you want to retrieve.

In the following example I have a employee table that has a relation with the company table. In my code I want to show the employee with the company name (outside the DataContext).

[code language=’c#’]
Employee employee;

using (LinqDataContext db = new (LinqDataContext())
{
   DataLoadOptions dlo = new DataLoadOptions(); 
   dlo.LoadWith(e => e.Company);
   db.LoadOptions = dlo;

   employee = from item in db.Employees
                      select item).First();
}

string companyName = employee.Company.Name;

[/code]

Because of the DataLoadOptions I can now use the company properties to print the company name outside the DataContext.

Enjoy.

Convert XmlElement to XElement (Extension Method)

I was using some web-services that returned there values in an XmlElement. I needed to convert this XmlElement to something that I can use with LINQ. I didn't find good solutions on the internet. So I started building my own convert logic. After all kinds of solutions I ended up with creating an new XmlDocument, adding the XmlElement to the XmlDocument and then convert the innerXml of the XmlDocument to an XElement. Not really nice but it does the trick.

I've rewritten the code into a Extension Method for the XmlElement.

[code:c#]

public static XElement ToXElement(this XmlElement xml)
{
   XmlDocument doc = new XmlDocument();

   doc.AppendChild(doc.ImportNode(xml, true));

   return XElement.Parse(doc.InnerXml);

}

[/code]


You use the Extension Method like this:

[code:c#]

XmlElement xmlElement = wsClient.DoWebServiceRequest();
XElement xml = xmlElement.ToXElement();

[/code]


Please tell me if you have a better way of doing this!

Cheers,
Pieter