C#: Remove line from textfile

by Pieter Brinkman 26. January 2010 03:29

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:c#]

string configFile = @"C:\dev\web.config";
List<string> lineList = File.ReadAllLines(configFile).ToList();
lineList = lineList.Where(x => x.IndexOf("<!--") <= 0).ToList();
File.WriteAllLines(configFile, lineList.ToArray());

[/code]

 

Tags: , ,

ASP.Net | Linq | C#

LINQ: Creating a if statement in Linq query

by Pieter Brinkman 30. July 2009 10:24

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: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<Blogger> personList = new List<Blogger>{
 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: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 + ")<br/>");
}

//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:c#]

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

[/code]

 

Tags: , ,

ASP.Net | Linq

Linq to Xml: Generate Google Sitemap with sitemap-protocol

by Pieter Brinkman 8. July 2009 02:22

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

[code:c#]

//create datasource

List<string> blogPosts = new List<string>{
 "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:xml]
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">  <url>    <loc>http://blog.newguid.net/mypost1.aspx</loc>  </url>  <url>    <loc>http://blog.newguid.net/mypost_about_Net.aspx</loc>  </url>  <url>    <loc>http://blog.newguid.net/morePosts.aspx</loc>  </url>  <url>    <loc>http://blog.newguid.net/andEvenMorePosts.aspx</loc>  </url></urlset>
[/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.

Tags: , , , , ,

ASP.Net | Google | Linq | XML

Linq Casting: ToDictionary()

by Pieter Brinkman 23. June 2009 04:03

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

This example will use the following Blogger class.

[code: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:c#]

// DECLARE PERSONLIST

List<Blogger> personList = new List<Blogger>();
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<string, int> AgeDictionary =
 personList.ToDictionary(x => x.FirstName + " " + x.LastName,
       x => x.Age,
       StringComparer.OrdinalIgnoreCase);


// GENERATE OUTPUT

foreach (KeyValuePair<string, int> item in AgeDictionary)
 Response.Write("key: " + item.Key + " - value: " + item.Value + "<br />");


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

[/code]

 Hope it helps.

Tags: , , ,

Linq

WCF webservice error with DBML objects

by Pieter Brinkman 7. May 2009 05:34

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

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.

 

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.

Tags: , , , ,

ASP.Net | Linq | Silverlight

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

by Pieter Brinkman 15. January 2009 06:04

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).

 

Employee employee;

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

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

string companyName = employee.Company.Name;

 

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

Enjoy.

 

Tags: , ,

ASP.Net | Linq | MSSQL

Convert XmlElement to XElement (Extension Method)

by Pieter Brinkman 8. December 2008 05:31

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.

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

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

   return XElement.Parse(doc.InnerXml);

}


You use the Extension Method like this:

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


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

Cheers,
Pieter

Tags: , , , , , , ,

Linq | XML

Load rss (xml) with Linq to XML on medium trust hosting

by Pieter Brinkman 26. November 2008 05:39

For a new project I needed to implement show data from RSS. The site will be hosted on a shared hosting environment with medium trust.

I load the rss with the following code:

XElement rssFeed = XElement.Load("[REPLACE WITH URL TO RSS]");
var posts = from item in rssFeed.Descendants("item")
                  select new
                  {
                       Title = item.Element("title").Value,
                       Description = item.Element("description").Value
                  };


This normally works fine for me... But apparently not with medium trust :-(! I got the following error.

Security Exception

Description: The application attempted to perform an operation not allowed by the security policy.  To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.

Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Net.WebPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.


After reading a bit and playing with the web.config setting <TRUST /> I found the solution. The solution is putting a ".*" in the originUrl parameter of the trust node.

<trust level="Medium" originUrl=".*" />


So an easy solution for a annoying problem what took me to much time. So I hope this post will help somebody out there :-)

Tags: , , , ,

ASP.Net | Linq

Linq to Sql: Change connectionstring to load from Web.config

by Pieter Brinkman 2. September 2008 05:25

Update 20 may 2009: New easy sollution

Set the Connection -> Application Settings property True. This will generate a connection string in your app.config.

 

Copy this connection string to your web.config and your all set!

 

================================================================= 

Old post: 

If you want to use your connectionstring from the web.config with Linq to Sql (dbml) you have to add the following partial class to your project:

namespace Your.Namespace
{
  partial class yourDataContext
  {
    partial void OnCreated()
    {
       ConnectionStringSettings s = ConfigurationManager.ConnectionStrings["YourConnectionString"];
       if (s != null)
         Connection.ConnectionString = s.ConnectionString;
    }
  }
}

Don't forget to change the Your.Namespace, yourDataContext and YourConnectionString to fit your project.

Hope this helps.

Tags: , , ,

ASP.Net | Linq | MSSQL

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen

About Me

My name is Pieter Brinkman I am a .NET Software Engineer for Achmea IT in De Meern, The Netherlands. My interests are mainly web applications created with ASP.NET, MSSQL and Silverlight.

Calendar

<<  September 2010  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar

RecentComments

Comment RSS

Most comments

club penguin cheats club penguin cheats
4 comments
us United States
Web Design Company Web Design Company
2 comments
Web design Web design
2 comments
gb United Kingdom