Archive

Posts Tagged ‘.net’

Is POCO the right choice when working with entity framework?

The main benefit of a POCO is that you can pass it to a class, library or assembly that doesn’t need to know anything about Entity Framework to do its job.

Remember the Single Responsibility Principle – your DAL should know about EF, but your Domain should not, and neither should your presentation layer, because EF deals with data access and those layers do not. Passing EF generated class objects up to those layers generally means you need to make those layers aware of EF, breaking the SRP and making it harder to unit test those layers in isolation.

In more complex applications, you will want to split the logic up into separate concerns – data access, business logic, presentation (and perhaps a lot more).

As entity framework deals with data access, it resides in the data access layer – here, you will see little difference between POCOs and EF generated classes. This is fine, because this layer already knows about Entity Framework.

However, you may want to pass data up to the business logic layer – if you do this with EF generated classes, then your business logic layer must also know about Entity Framework because the EF classes rely on a lot of things EF provides specially. What this does is remove the isolation that your business logic layer should have – you need this isolation so you can unit test it correctly by injecting known data into the class from a fake data access layer, which is incredibly hard to do if you let the business logic layer know about EF.

With unit testing, you should be testing the layers functionality, not the functionality of third party libraries – but with EF you end up testing a lot of EF’s functionality, or your own functionality which relies very heavily on that of EF’s. This isn’t good, and it can mask errors or issues.

Removing the business logics dependency on EF generated classes also allows you to move the layer to as remote a location as you like from the data access layer – you can even stick it behind a web service and it would be completely happy. But you can only do this with POCOs, you cannot do this with EF generated classes.

POCO’s really come into their own in large, complex multi layered applications – if you aren’t layering your app, then you won’t see a whole load of benefits.

Print html page in .net windows application

You can use the WebBrowser control to do so. It will allow you to show HTML inside your WinForms.

The DocumentText proprety will allow you to set a String that represent the HTML you want to show.

For example:

webBrowser.DocumentText = "<html><body><p>I like StackOverflow</p><body></html>";

Afterward if you want to print the page, you’ll have to wait until the Document is completed and call the Print method of the WebBrowser. MSDN shows an easy way to do it:

 private void PrintHelpPage()
{
    // Create a WebBrowser instance. 
    WebBrowser webBrowserForPrinting = new WebBrowser();

    // Add an event handler that prints the document after it loads.
    webBrowserForPrinting.DocumentCompleted +=
        new WebBrowserDocumentCompletedEventHandler(PrintDocument);

    // Set the Url property to load the document.
    webBrowserForPrinting.Url = new Uri(@"\\myshare\help.html");
}

private void PrintDocument(object sender,
    WebBrowserDocumentCompletedEventArgs e)
{
    // Print the document now that it is fully loaded.
    ((WebBrowser)sender).Print();

    // Dispose the WebBrowser now that the task is complete. 
    ((WebBrowser)sender).Dispose();
}

Method Override vs Method Overload

February 19, 2012 Leave a comment

Some people might get confused between method overriding and method overloading, here i will explain the differences between these two methods and how each one of them is used:

Method Overriding means that you have 2 methods in 2 different classes with the same name, same parameters (signatures) but with different implementations in each class, mostly this happen between a base (abstract) class and derived class. Here is an example for method overriding:

Base Class:

Class Animal

protected string Name;

public string WhatAmI()

{

return “I am an animal”;

}

Derived Class:

Class Dog: Animal

public string WhatAmI()

{

return “I am a dog”;

}

Method Overloading means that you have 2 methods in the same class with the same name but different parameters (signatures), example for method overloading:

class Calculations
{
public static int Add(int number1, int number2)
{
return number1 + number2 ;
}

public static int Add(int number1, int number2, int number3)
{
return number1 + number2 + number3;
}
}

Cannot access a closed file

October 14, 2011 Leave a comment

This Error occured usually when trying to upload a file which is more than a 100 kb.

The solution of this error is:
Add this line in the web.config after <custom errors> [<httpRuntime executionTimeout=”90″ maxRequestLength=”20000″ useFullyQualifiedRedirectUrl=”false” requestLengthDiskThreshold=”8192″/>]

P.S. Please note that 20000 are in KB.

Smart Navigation

September 28, 2011 Leave a comment

Before going deeper in smart navigation, please not that it is no longer supported in asp.net versions after 2.0 and The SetFocus and MaintainScrollPositionOnPostBack are used instead.

Smart Navigation basically enhances a web page performance by doing the following:

  •  It eliminates the flash caused during navigation
  • It persists element focus during postbacks
  • It persists scroll position during postbacks between pages
  • It retains the lasts page information in the history of the browser

SmartNavigation is a feature provided by asp.net. When enabled this makes sure your pages are shown smoothly and last position of cursor location, scroll etc are restored effortlessly

It allows Internet Explorer to handle PostBacks in a very clever way. You don’t have to worry about having a long site – it will return to the point where you have been before. Or if you define some events – SmartNavigation will enable you to invoke the handlers without posting the page back to the server.

But: If you are going to program a serious website for users of different browsers (Netscape, Opera, Konqueror or Safari) you need to turn SmartNavigation off, because it simply doesn’t work with this kind of browsers.

  •    How to use:
  1. Add the yellow highlighted line in your application web.config file(be sure you don’t have this attribute before).
    <configuration>
    <system.web>
    <pages smartNavigation=”true”/> 
    </system.web>
    </configuration>
  2. Or on a specific page where we can add this property in the page directive like this:
    <%@ Page Language=”VB” SmartNavigation=”true” %>
  • Why To Use:
  1. Saves the position of your scroll state after redirecting the page, for example if you have a page that has a scroll and at the end of the page there is a delete button which will also shows a message like “are you sure you want to delete this item?”.this message will appear at the bottom of the page also after redirecting the page will goes to top and the user will not know what happened unless he scrolls down again and reads the message, using Smart Navigation will allow you to keep that scroll.

  2. Keeps focus on server controls (textboxes and buttons…) after redirecting also.

Asp.net String properties

September 23, 2011 Leave a comment

Checking string emptiness

Checking the length of the string (if str.length = 0) is faster than (if str = “”) in three times, so off course it is more likely to use.

StringBuilder VS String

String builder is faster than strings when the number concatenations exceeded 3, but if it is less than that than normal string is a little bit faster.

Comparing Strings

Usually we compare strings in the normal way which is (if str1 = str2 then…) but It is faster to compare strings in his way:

Dim str1 As String = “”

   Dim str2 As String = “”

   If str1.Equals(str2) Then

    ‘ here comes your code

   End If

Introducing LINQ

December 8, 2010 Leave a comment

What is LINQ

LINQ (Language Integrated Query) is a Microsoft programming model and methodology that essentially adds formal query capabilities into Microsoft .NET-based programming languages. LINQ offers a compact, expressive, and intelligible syntax for manipulating data. The real value of LINQ comes from its ability to apply the same query to an SQL database, a DataSet, an array of objects in memory and to many other types of data as well. LINQ requires the presence of specific language extensions.
LINQ uses an SQL-like syntax to make query expressions well beyond the capabilities of embedded SQL as implemented in programming languages. That’s because embedded SQL uses a simplified, streamlined syntax to add SQL statements to other programming languages, where there’s no attempt to integrate such statements into the native syntax and typing mechanisms. Thus, you can’t invoke native language structures such as functions in embedded SQL statements, as you can using LINQ, because it is implemented to use native syntax, structures, and typing mechanisms. Furthermore, LINQ may be used to access all kinds of data, whereas embedded SQL is limited to addressing only databases that can handle SQL queries.

Why LINQ

1. Speed
Linq is faster in rendering data from the database in most cases, especially when using the default way in reading from datarreader: dr(“FieldName”)

2. Easy Maintenance when updating database
This is a very complex issue, especially when it comes to large projects with large databases, adding a field in any table will take a minimum of 2 hours, since won’t anymore exist when using linq.

3. More querying capabilities.

4. Very easy custom paging.

var query =
from c in db.Customers
where c.Name.StartsWith ("A")
orderby c.Name
select c.Name.ToUpper();
var thirdPage = query.Skip(20).Take(10);

5. No SQL logical run time errors
Since all erros will appear at design time.