An unhandled exception of type 'System.StackOverflowException' occurred in Unknown Module.

by sunil ravulapalli /14. June 2011 21:37 /asp.net-mvc /Comments (1)

I go this error recently:

"An unhandled exception of type 'System.StackOverflowException' occurred in Unknown Module."

I narrowed it down to the Html.Action( Html.RenderAction ) call in _Layout.cshtml.

The Html.Action in _Layout.cshtml looked like this:

@{ Html.Action("List", "Categories"); }

My controller method looked like this:

public ActionResult List()
{
            List categories = categoriesRepository.Categories.ToList();
            List navLinks = new List();

            foreach (Category cat in categories)
                navLinks.Add(makeLink(cat));

            return View(navLinks);
}

Turns out the proper way to design this is to do the following:

here

Directory lookup for the file**** failed with the operating system error 2(The system cannot find the file specified.)

by sunil ravulapalli /24. May 2011 21:28 /asp.net /Comments (0)

Directory lookup for the file**** failed with the operating system error 2(The system cannot find the file specified.).\r\nCREATE DATABASE failed. Some file names listed could not be created. Check related errors."
I got this error recently while playing with EF code first.

 

This was my web.config, pointing to get to "|DataDirectory" which is "App_Data" folder in your solution.
But I forgot to create it before execution, so make sure u have App_Data set up already.

Understanding sql connections

by sunil ravulapalli /11. May 2011 21:43 /.net /Comments (0)
When you do conn.open() IIS opens a physical connection to the DB.
When you do conn.close() IIS moves the connection to the connection pool.
If some request is made using the same connection string IIS will re-use the connection from the pool.
 
Now, lets say in an App you do this:
conn.open
//Do stuff
conn.close
 
and then you do this:
conn1.open
//Do stuff
conn1.close
 
In this case, IIS uses the same physical connection.
 
But lets say if you do this:
conn1.open
conn2.open
 
IIS will open two physical connections.
 
You can return the 2 connections to pool
conn1.close
conn2.close
 
However, if u do not close the connections conn1 and conn2 will remain open for a long time(10 second is still a long time) and won't return to connection pool.
 
So if there are new connections like conn3 and conn4, IIS will have a total 4 physical connections
If your website hits traffic on black friday, there will be hundreds of such connections and your site will crash :)
 

Windows Phone 7 App - Traffic Trips

by sunil ravulapalli /4. January 2011 18:15 /windows-phone /Comments (0)

I am getting my feet wet in application development for Windows Phone 7.
My first App accepted into Market Place is "Traffic Tips".

1. If you have a windows phone, search for "Traffic tips" in marketplace.

2. External websites: http://www.freewarepocketpc.net/wp7/download-traffic-tips.html

3. Review(Look for traffic Tips)
http://www.pocket-lint.com/news/37048/best-windows-phone-7-navigation-apps

4. If you have Zune try: http://social.zune.net/redirect?type=phoneApp&id=5d6d614c-bbf6-df11-9264-00237de2db9e

Linq XML samples

by sunil ravulapalli /5. November 2010 15:39 /c# /Comments (0)

Sample XML:

  
    ChapterOne-SectionOne
    ChapterOne-SectionTwo
    ChapterOne-SectionThree
    ChapterOne-SectionFour
    ChapterOne-SectionFive
  
  
    ChapterTwo-SectionOne
    ChapterTwo-SectionTwo
    ChapterTwo-SectionThree
    ChapterTwo-SectionFour
    ChapterTwo-SectionFive
  
	

Lets say, I want to print out contents of Chapter 2-Section 4:

XElement data = 
XElement.Load(Request.PhysicalApplicationPath + "book.xml");

XElement chapterElement =
     (
        from chapter in data.Elements("chapter")
        where chapter.Attribute("id").Value == "2"
        select chapter
     ).Single();


XElement sectionElement =
     (
        from section in chapterElement.Elements("section")
        where section.Attribute("id").Value == "4"
        select section
     ).Single();

Response.Write(sectionElement .Value);

(I could complicate matters and write some embedded queries, but I chose to be more readable)

Bing maps rest api in windows phone 7

by sunil ravulapalli /25. October 2010 22:30 /windows-phone /Comments (1)

Get a Bing maps developer account here http://www.microsoft.com/maps/developers/web.aspx so that you can get your own Bing maps key.
If you want to get the route between two points, the code to call the web service looks like this:

 string bingUri
  ="http://dev.virtualearth.net/REST/V1/Routes?
  wp.0={0}&wp.1={1}&output=xml&key={2}&optimize={3}";
 
 string homeAddress;
 
 string workAddress;
 
 string fullUri;
 
 const string bingKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

 fullUri = String.Format(bingUri,homeAddress,workAddress,bingKey,"time" );
 
 WebClient proxy = new WebClient();
 
 proxy.OpenReadCompleted += 
     new OpenReadCompletedEventHandler(proxy_OpenReadCompleted);
 
 proxy.OpenReadAsync(new Uri(fullUri));

proxy_OpenReadCompleted looks like this: (The following code also extracts traffic information)

uction = instruction; this.warnings = warnings; } } public class Warning { public string severity; public string desc; public Warning(string severity, string desc) { this.severity = severity; this.desc = desc; } }

If you want to loop through the results use this model:

foreach (ItineraryItem itineraryItem in itineraryItems)
{
  foreach (Warning warning in itineraryItem.warnings)
  {
                  
  }
}

You can find more options for REST API here: http://msdn.microsoft.com/en-us/library/ff701722.aspx

How to make a classic asp page show up as a 500?

by sunil ravulapalli /4. October 2010 20:02 /classic-asp /Comments (0)

If you have classic asp redirect page which shows a friendly message to the customer in case of an error, normally this shows up as regular page request in the web server logs. If you want this page to show up as 500 you can use

(Server side javascript)

Response.Status = 500;

Code design:Advanced use of interfaces

by sunil ravulapalli /9. August 2010 17:37 /software-design /Comments (0)

Suppose, I have a class like this

public class EmployeeRepository
{
  public DataSet GetAll()
  {
    string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=***.mdf;
    Integrated Security=True;User Instance=True";
    DataSet employee = new DataSet();
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
      string queryString = "SELECT EmpId, EmpName FROM Employee";
      SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
      adapter.Fill(employee, "Employees");
      return employee;
    }
  }
}

Lets assume, I use it like this "several times" all over my implementaion code:

EmployeeRepository repository = new EmployeeRepository();
DataSet dataset = repository.GetAll();

Now, lets say we have a new class called UppercaseEmployeeRespository which looks like this. It is only slightly different from "EmployeeRepository".(notice i changed the query string):

public class UppercaseEmployeeRespository
{
  public DataSet GetAll()
  {
    string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=***.mdf;
    Integrated Security=True;User Instance=True";
    DataSet employee = new DataSet();
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
      string queryString = "SELECT EmpId, UPPER(EmpName) FROM Employee";
      SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);

      adapter.Fill(employee, "Employees");
      return employee;
    }
  }
}

Now, I need to globally replace the use of "EmployeeRespository" with "UppercaseEmployeeRespository"? How do I do that? Simple, globally Find & Replace, "EmployeeRespository" with "UppercaseEmployeeRespository"? :) Well, in a badly designed solution, thats all you can do. But lets say we have chance to Re-Arch our solution, how can we restructure this code?Stage 1: Extract the interface and make the class implement the interface.

public interface IRepository
{
  DataSet GetAll();
}
public class EmployeeRepository : IRepository
{
  public DataSet GetAll()
  {
     string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=***.mdf;
     Integrated Security=True;User Instance=True";
     DataSet employee = new DataSet();
     using (SqlConnection connection = new SqlConnection(connectionString))
     {
       string queryString = "SELECT EmpId, EmpName FROM Employee";
       SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);

       adapter.Fill(employee, "Employees");
       return employee;
     }
  }
}

Now, the implementaion code changes to

IRepository repository = new EmployeeRepository();
DataSet dataset = repository.GetAll();

Whoever gives you a new class, has to implement IRepository, the new class now looks like this:

public class UppercaseEmployeeRespository : IRepository
{
  public DataSet GetAll()
  {
    string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=***.mdf;
    Integrated Security=True;User Instance=True";
    DataSet employee = new DataSet();
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
      string queryString = "SELECT EmpId, UPPER(EmpName) FROM Employee";
      SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);

      adapter.Fill(employee, "Employees");
      return employee;
    }
  }
}

Now, if you want to swap, you still have to globally Find & Replace "EmployeeRepository" with "UppercaseEmployeeRespository".

IRepository repository = new UppercaseEmployeeRespository();
DataSet dataset = repository.GetAll();

But, thats no good. What else can we do? Lets change our implementation code a little bit.Stage 2: Restructure the implementaion codeLets replace "new EmployeeRepository()" with a method call "RepositoryInstance.GetInstance()"where "GetInstance()" is a static method.

IRepository repository = new EmployeeRepository();
DataSet dataset = repository.GetAll();

becomes

IRepository repository = RepositoryInstance.GetInstance();
DataSet dataset = repository.GetAll();

where the class "RepositoryInstance" looks like this:

public static class RepositoryInstance
{
  public static IRepository GetInstance()
  {
    return new EmployeeRepository();
  }
}

The static function GetInstance() currently returns an instance of EmployeeRepository. This looks great! Now, if I want to swap out all "EmployeeRepository" with "UppercaseEmployeeRespository" all I have to replace is one line of code in "GetInstance()". Replace "return new EmployeeRepository()" with "return new UppercaseEmployeeRespository()"; Thats it!!Final, code recap:

public interface IRepository
{
  DataSet GetAll();
}

public class EmployeeRepository : IRepository
{
  public DataSet GetAll()
  {
    string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=***.mdf;
    Integrated Security=True;User Instance=True";
    DataSet employee = new DataSet();
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
      string queryString = "SELECT EmpId, EmpName FROM Employee";
      SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
      adapter.Fill(employee, "Employees");
      return employee;
    }
  }
}


public class UppercaseEmployeeRespository : IRepository
{
  public DataSet GetAll()
  {
    string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=***.mdf;
    Integrated Security=True;User Instance=True";
    DataSet employee = new DataSet();
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
      string queryString = "SELECT EmpId, UPPER(EmpName) FROM Employee";
      SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);

      adapter.Fill(employee, "Employees");
      return employee;
    }
  }
}

IRepository repository = RepositoryInstance.GetInstance();
DataSet dataset = repository.GetAll();

public static class RepositoryInstance
{
  public static IRepository GetInstance()
  {
    return new UppercaseEmployeeRespository();
  }
}

Code design:Static methods

by sunil ravulapalli /9. August 2010 16:24 /software-design /Comments (0)

Static methods are methods which belong to a class and not an instance of a class.

Normally, if you have a class like this:

public class Utility
{
 public string GetConnectionString()
 {
  return @"Data Source=.\SQLEXPRESS;AttachDbFilename=|***.mdf;Integrated Security=True;User Instance=True";
 }
}

you will use it like this:

Utility u = new Utility();
string conString = u.GetConnectionString();


But, lets say you want to use this all over your code and don't want to create an instance each time, you can redesign it like this:

public class Utility
{
 public static string GetConnectionString()
 {
  return @"Data Source=.\SQLEXPRESS;AttachDbFilename=***.mdf;Integrated Security=True;User Instance=True";
 }
}

you can just use it like this everywhere:

string conString = Utility.GetConnectionString();


Look, no instance!

Code design:Simple use of interfaces

by sunil ravulapalli /6. July 2010 20:00 /software-design /Comments (0)

In short, the answer is 'flexibility'. I am not going to go into any complex detailed examples in this post. This post will just set up a base for future posts on interfaces. Lets begin with 2 classes as show below.

public class EmployeeRepository
{
  public DataSet GetAll()
  {
     string connectionString = "*********"
     DataSet employee = new DataSet();   
     using (SqlConnection connection = new SqlConnection(connectionString))
     {
        string queryString = "SELECT EmpId, EmpName FROM Employee";
        SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);

        adapter.Fill(employee, "Employees");
        return employee;
     }
  }
}

public class CustomersRepository
{
  public DataSet GetAll()
  {
     string connectionString = "*********"
     DataSet customers = new DataSet();
     using (SqlConnection connection = new SqlConnection(connectionString))
     {
        string queryString = "SELECT CustomerId, CustomerName, FROM Customer";
        SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);

        adapter.Fill(customers, "Customers");
        return customers;
     }
  }
}

Normally, we would use these classes like this:

EmployeeRepository employeerepository = new EmployeeRepository();
DataSet dataset = repository.GetAll();

and

CustomerRepository customerrepository = new CustomerRepository();
DataSet dataset = repository.GetAll();

Now, lets redesign our classes using interfaces?How do we do that? Notice, that both our classes have the same method called "GetAll()" with the "same return type". With that observation lets make an interface. It looks like this

public interface IRepository
{
    DataSet GetAll();
}

Now, our classes can be made to look like this:

public class EmployeeRepository : IRepository
{
   public DataSet GetAll()
   {
      //Same as before
   }
}
public class CustomersRepository : IRepository
{
   public DataSet GetAll()
   {
     //Same as before
   }
}

Great, we are now using interfaces! But wait, what good is it? It just added more code to my program! The real good will come in how we can instantiate our classes and then call our methods. Look at the following implementaion code:

IRepository repository = new EmployeeRepository();
DataSet dataset = repository.GetAll();

and

IRepository repository = new CustomerRepository();
DataSet dataset = repository.GetAll();

Notice, that we are now using IRepository for both implementations rather EmployeeRepository and CustomerRepository to call our "GetAll()" method i.e. we are now using a common interface rather than a concrete class. Although this may not be a "blow your mind" example of interface usage, it definitely forms basis for understanding things such as "Dependency Injection(DI)" etc. which will "blow your mind"!.