Reading filestream asynchronously in .NET 4.5

Microsoft .NET 4.5 makes all Stream-based communication support entirely asynchronous opertaions by adding Async methods to the Stream class. int chunkSize = 4096; var buffer = new byte[chunkSize];   var fileStream = new FileStream(filename, FileMode.Open);   var task = fileStream.ReadAsync(buffer, 0, buffer.Length); task.ContinueWith((readTask) => { int amountRead = readTask.Result; fileStream.Dispose(); Console.WriteLine("Async(Simple) read {0} bytes", amountRead); […]
Continue reading…

Enjoyed this post? Share it!

 
 

Break to stop the loop in parallel foreach

The below sample code iterates over a string list and uses the Break call to stop the loop at an arbitrary location. Parallel.ForEach(urls, (url, loopState) => { if (url.Contains("w3mentor")) { loopState.Break(); } results[url] = client.DownloadString(url); });
Continue reading…

Enjoyed this post? Share it!

 
 

Download webpages parallelly with c#

We can use the C# task parallel library with the ConcurrentDictionary to retrieve a list of known addresses in parallel. var urls = new List<string> { @"http://www.w3mentor.com", @"http://www.storewala.com", @"http://reviewable.in" }; var results = new ConcurrentDictionary<string,string>(); var client = new System.Net.WebClient();   Parallel.ForEach(urls, url => results[url] = client.DownloadString(url));
Continue reading…

Enjoyed this post? Share it!

 
 

Adding Cache headers to OData calls

For every request, the OData framework calls OnStartProcessingRequest method. We can take advantage of this call to add various cache headers. protected override void OnStartProcessingRequest(ProcessRequestArgs args) { base.OnStartProcessingRequest(args); HttpContext context = HttpContext.Current; HttpCachePolicy c = HttpContext.Current.Response.Cache; c.SetCacheability(HttpCacheability.ServerAndPrivate); c.SetExpires(HttpContext.Current.Timestamp.AddSeconds(60)); c.VaryByHeaders["Accept"] = true; c.VaryByHeaders["Accept-Charset"] = true; c.VaryByHeaders["Accept-Encoding"] = true; c.VaryByParams["*"] = true; }
Continue reading…

Enjoyed this post? Share it!

 
 

Parallel matrix multiplication in C# using task parallel library

static double[][] MatrixMultiplication(double[][] matrixOne, double[][] matrixTwo) { //aRows = rows in matrixOne //bCols = columns in matrixTwo double[][] result = CreateMatrix(aRows, bCols); Parallel.For(0, aRows, i => { for (int j = 0; j < bCols; ++j) for (int k = 0; k < aCols; ++k) result[i][j] += matrixOne[i][k] * matrixTwo[k][j]; } ); return result; } […]
Continue reading…

Enjoyed this post? Share it!

 
 

Matrix multiplication in C#

static double[][] MatrixMultiplication(double[][] matrixOne, double[][] matrixTwo) { int aRows = matrixOne.Length; int aCols = matrixOne[0].Length; int bRows = matrixTwo.Length; int bCols = matrixTwo[0].Length; if (aCols != bRows) throw new Exception("Out of shape matrices"); double[][] result = CreateMatrix(aRows, bCols); for (int i = 0; i < aRows; ++i) // each row of MatrixOne for (int j […]
Continue reading…

Enjoyed this post? Share it!

 
 

What are c# Tuples?

In C#, a tuple represents a set of data in a single data structure. Tuples can: 1. Provide easy access and manipulation of a set of data. 2. Return multiple values from a method. 3. Pass multiple values to a method in a single parameter. Example: var myTuple = Tuple.Create("w3mentor", new DateTime(2009, 12, 8)); Console.WriteLine("{0} […]
Continue reading…

Enjoyed this post? Share it!

 
 

Applying LINQ Queries to Collection Objects in C#

class Bike { public string Name {get; set;} public string Color {get; set;} public int Speed {get; set;} public string Make {get; set;} } static void Main(string[] args) { Console.WriteLine("***** LINQ over Generic Collections *****\n");   // Make a List<> of Bike objects. List<Bike> myBikes = new List<Bike>() { new Bike{ PetName = "bike1", Color […]
Continue reading…

Enjoyed this post? Share it!

 
 

Using Indexer Definitions in C# Interfaces

Interface with Indexer: public interface IStringDef { string this[int index] { get; set; } } Class implementing the interface: class MyClass : IStringDef { private List<string> allStrings = new List<string>();   public string this[int index] { get { return allStrings[index]; } set { allStrings.Insert(index, value); } } }
Continue reading…

Enjoyed this post? Share it!

 
 

Indexing Data Using String Values in C#

public class PersonCollection : IEnumerable { private Dictionary<string, Person> listOfPeople = new Dictionary<string, Person>();   // This indexer returns a person based on a string index. public Person this[string name] { get { return (Person)listOfPeople[name]; } set { listOfPeople[name] = value; } }   public void ClearPeople() { listOfPeople.Clear(); }   public int Count { […]
Continue reading…

Enjoyed this post? Share it!

 
 

Indexer Methods in C#

// Indexers allow you to access items in an array-like fashion. class Program { static void Main(string[] args) {   PersonCollection allPeople = new PersonCollection();   // Add objects with indexer syntax. allPeople[0] = new Person("Homer", "Simpson", 40); allPeople[1] = new Person("Marge", "Simpson", 38); allPeople[2] = new Person("Lisa", "Simpson", 9); allPeople[3] = new Person("Bart", "Simpson", […]
Continue reading…

Enjoyed this post? Share it!

 
 

Using the index operator in a simple array

static void Main(string[] args) { // Loop over incoming command-line arguments // using index operator. for(int i = 0; i < args.Length; i++) Console.WriteLine("Args: {0}", args[i]);   // Declare an array of local integers. int[] myInts = { 10, 9, 100, 432, 9874};   // Use the index operator to access each element. for(int j […]
Continue reading…

Enjoyed this post? Share it!

 
 

Set FM Radio frequency in windows phone 7

try { FMRadio myRadio = FMRadio.Instance; myRadio.PowerMode = RadioPowerMode.On; myRadio.CurrentRegion = RadioRegion.Europe; myRadio.Frequency = 91.5;   if (FMRadio.Instance.SignalStrength == 0.0) { MessageBox.Show("FM radio cannot run on emulator"); } } catch (Exception ex) { MessageBox.Show("FM Radio has thrown exception" + ex.Message); }   The RadioRegion enumeration only support 3 frequency bands for FM Radio tuning. 1. […]
Continue reading…

Enjoyed this post? Share it!