Skip to main content

Posts

Showing posts from 2012

WinForms, paging the DataGridView the right way

I know this may sound like old history, but in the enterprise world there is still a lot of WinForms development. Just a couple of days ago, I had to implement a custom DataGridView capable to work over a butt load of data (100K+ records) and keep responses times acceptables. I thought paging will be a good way to go, and as WinForms is pretty old nowadays, I supposed it will be easy to find a couple examples on the web. While in fact I found examples, all of them were incompletes and/or they wouldn't perform well in real world apps... So I decided to roll my own component and post it online. Hopefully, someone else will find it useful ;). The bread and butter of this solution relies on LINQ and deferred execution. As LINQ takes care of all complicated work, it was quite easy to implement. This component also supports conditional format, sorting and some search capabilities, but in this post I will concentrate on paging only (I'll cover the rest of the features in f

CSFR attacks, ASP.NET MVC 4

CSRF stands for Cross Site Request Forgery and is a technique employed to fooling a website by executing commands on behalf of a trusted (authenticated) user. How it works Commonly a malicious user sends a link to another user that maybe is authenticated on the target site and uses their session to execute commands like transfer money, change the email address and stuff like that. CSRF in action This time I’ll be working on a web site that allows authenticated users buy pastries at the online store. In this case, the goal of the attacker is to get a bunch of muffins on somebody else’s Mastercard. The target site has a couple of web pages that allow users to logon, buy products and see their orders history: Before going on, something to worth to mention is that after a user is successfully authenticated to a  website, the web browser will be sending the authentication cookie on every subsequent request to the server until the session expire (usually after 2

Roslyn shopping cart DSL – Part 4

Why Source to source translation? In order to answer that question, I wanna provide some background on what are the choices that we have when building a DSL on .NET (at least the most common that I’ve used). Prior to the “magic lambda” era, there were few choices, the one I've used the most, was a hand written parser that creates syntax trees and a code generator that traverses those trees generating MSIL code using Reflection.Emit. This solution was OK but it was also a lot of work, even for a simple "Hello World DSL". It’s definitely a path I wouldn't take nowadays. When .NET 3.5 saw the light, we had more options, back then it was possible to use linq expressions to represent our programs and traverse those expressions in order to emit target code. It wasn’t  the easyest thing, but at least the days were we have to build a bunch of classes to represent or compose expressions were gone. Then we had the lambda compiler and linq statements which allowed

Roslyn shopping cart DSL – Part 3

An effective way to create a DSL is by building a thin layer that runs on top of a façade that interacts with the domain objects. This is how those components looks in the sample app of this post. In this case, the DSL only talk to the façade and the façade is in charge of talking with domains objects (or services or whatever component that goes underneath). This makes things really easy to implement and fit perfectly to work with Roslyn, because if we use the façade as the Roslyn script engine’s host object, the engine will let us access directly from our DSL syntax to any member of the façade's public API. By looking at this unit test you will see how to wire up the components, execute the DSL script and modify the order state (the domain object) right from the DSL. * If this were a real app, the order will continue with the processing pipeline. So far so good, now how to go from our DSL syntax to façade calls? * Notice that the facade exposes the

Roslyn shopping cart DSL - Part 2

In this post I will be reviewing some considerations that I usually have in mind while designing a DSL. The audience When you are working on a DSL, the first and most important thing to have in mind is the audience you are aiming for. It’s gonna be technical people, business executives, sales people, etc…, etc…. The syntax If the audience is not a bunch of techies, here is set of design rules that you should follow (at least, they've worked out for me): The syntax should be as much as closest to the domain terms that the user uses on a daily basis. Use sentences like “ when something_happen :” instead of “ if (somethingHappen){..} ”. Use logical operators like “ and ”, “ or ” instead of “ && ”, “ || ”. Don't make your syntax case sensitive. snake_case works better than PascalCase. When syntax error happen (and it will happen) provide useful messages that lead the user to the right path. Try to avoid the use of parentheses as much as you can. (our

Roslyn shopping cart DSL - Part 1

Lately, a lot of people where asking on mailing lists and users groups, how to dynamically load and execute C# code. This code maybe be stored as expressions in the database or will be entered by the user in some sort editor or whatever they want to use, but the important thing is that the app should compile and execute the code at runtime. Unlike Ruby or Python, C# does not support this kind of stuff right out of the box. Fortunately, the Redmond guys had implemented a nice library called Roslyn, which allows us to do this and a lot of other crazy stuff. Whereas this was possible in the past by using reflection or the CodeDomProvider, it were a lot of work (complex and error prone work), so, very few people did it. In this post I’m going to show a little app that uses Roslyn to compile and execute C# code at runtime . Instead of work with expressions like 2+2 or a>b (a.k.a. the classic “hello world!” example), I’ll work with something more close to a DSL. This DSL w

Migrating an ASP.NET MVC 4 app from Azure websites to WinHost

About a week ago I've to migrate an ASP.NET MVC 4/EF5 application from Azure websites to WinHost. While the process was really smooth, there were some caveats related to database connections that I want to share with you. Create and setup the ftp profile on VS and configure the connection string was really easy, WinHost provide you those values and there is nothing special here. But once you deploy your website and try to see it online, you may get the “yellow screen of dead” with the message: "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)" Assuming you wrote the connection string properly, this happens because you cannot use the default connection name in your web.c

How to create MS Word documents from Office templates using C#

The OpenXML SDK allows you to do pretty much anything you want with office files such as Excel, Word, etc… While many people like this library, I found it complex, unintuitive and poorly documented, not to mention the awful xml format that uses under the hood to represent the documents, styles, etc. So I decided not to use it and build my own solution. If you, like me, don’t like that library, you will find in this post an alternative approach to build word documents from templates using c#. A neat trick to work with Office is to use the macro recorder to understand how things work. The macro recorder allows you to start a macro, do something by hand, stop it, and then take a look at the generated VBA code. Once you do this, you are pretty much set. This is how it looks the template I’am going to use. Note: save the file as a Word template (.dotx) This is the code to create Word documents from C#: By running the code, you should get a document that looks

How to authenticate a console app to an ASP.NET MVC 4 web site

In this post I will show you how to authenticate an application to an ASP.NET MVC web site that uses forms authentication. This sounds a bit weird, but as I found out on the web, this is a fairly common thing to do these days. The most common scenario where people want to do this is, is when they want to consume an ASP.NET MVC web site as if it was a Web API, to get resources that are already in place and are accessible thru controller’s actions. There is couple of ways of doing this, and it is pretty easy until you need to authenticate the request in order to get those resources.   The web site we are working on uses Forms Authentication, this means that when a request arrives, the ASP.NET infrastructure is going to see if this request is authenticated or not, if is not, it will redirect the request to the login page. While this works fine for web pages, is not so good for APIs. Down below I’ll show how to authenticate a client to a login page using the HttpClient class.

Hacking the Kindle Fire's keyboard layout

If you bought a Kindle Fire and want to use it only for reading, don’t worry you will be fine, but if you want to use it as a tablet, as soon as you try to write something in a language other than English, you will realize that you gave to yourself a pretty expensive brick ;).  The Kindle Fire comes with an autocomplete feature (that cannot be disabled) that inserts matching words when you press the space bar, while this is arguable a nice thing, if you are writing in a language such as Spanish it’s a bit of a pain in the ass. You have to erase and retype all of the words inserted by this feature. Surfing the web you will find a lots of comments saying that is not possible to change the Kindle Fire's keyboard layout, while this is true based upon the Fire’s defaults options, there is a guy who hacked the system and give us a neat way to change it. This guy is Gero Zahn and this is how he did it http://blog.gerozahn.de/2011/11/kindle-fire-keyboard-layouts-solved/ T

Bending reports with NRapid

In a previous post we saw how to override report’s default format using the SetRawStyle extension method. This allows us to modify the layout and do quick fixes without touching style sheet. That’s quite handy, but if you have to add a lot of format your code will end up looking messy. In this post I’ll work with a shipping report and show you how to bend reports using the NRapid’s fluent API. So let get started. This is the first draft And the output should look something like this: As you can see we have some sort of shipping info of customer's orders. I don’t know if I've covered how to add footers in previous posts, I’ll check on that later and if I didn’t, I will. But for now, let just concentrate on formatting only. First of all I don’t like the way the footer is formatted by default. I cannot see the difference between footers and standard rows, so I’m gonna format the footer’s text to bold, just for start. Now this is the output: That’s a l

Printing html using the embedded web browser control

In this post I’ll try to answer some questions about the web browser control and provide some workarounds for known issues involved in the printing process. I'm assuming that you have some experience with the web browser control and basic knowledge of COM and hosting APIs. So I’m not going to cover those topics. At the bottom of this page I’ve added the links to download a small library I wrote that takes care of printing HTML and a demo app so you can try it out without having to write any code by yourself. Using the code The HtmlPrinter class will allow you to print html from an URL or just passing the html as string, you can also specify the title and the number of copies you want to print. The code may look something like this: Now that we know how to use the API let get answer some questions. Why my app crashes when I try to print multiple copies of a page? Well, apparently when you send a lot of print commands to the web browser control, ther

Working with unattended reports

In this post I‘ll show you how to create reports that NRapid will execute into an unattended mode. I strongly recommend using this kind of reports in automation scenarios only , and let the user see the print preview dialog in the rest of cases. The only difference between this reports and the standard ones, is that you will cannot make use of dialogs, the runtime will always pass in empty views to the ConfigureReport method. The ConfigureReport method will be executed, but you will have to grab the arguments from somewhere else. The execution pipeline is the same that NRapid uses for standard reports. This is the code to print out the whole list of categories in a dialogless mode. Notice that this report inherits from UnattendedReport class, this class tells to NRapid “run the report unattended”. Also notice that this class comes with a convenience method to configure the report with no arguments. You still can override the one that gets the view data but you will always

Nrapid, working with page breaks and report options

So far we been working with reports and exploring a couple of options on how to group data, customize dialogs and so on, but we never talk about printing. While there isn’t much to say about printing when it comes to standard reports, I mean, you execute the report, press print and you are pretty much set.  When it comes to complex reports, we have a couple of options. In this post I’m going to talk about page breaks and how they behave in reports that contain grouped data. Continuing with the categories and products example, we want to print each category in her own page (a group per page) this means that we need a page break after each group of data. By default, NRapid will not going to add page breaks after groups, because internally doesn’t knows what a group is. It just going to emit standard html based on the default style sheet or the specified raw style. The easiest way to insert page breaks, is by building the report using the “table per group” approach, and

Raw styling reports with NRapid

Raw styling reports is s technique that allows us to override the NRapid’s default style sheet without worrying about css.  I commonly use it for quick fixes and generally work really well. But if you want to affect the global aspect of your reports, though, the way to go is modifying the nrapid-default.css file, not raw styling a report at a time.  A common scenario where you can apply this technique is when you add a table per group in your report. For instance, when you list products by category, grouped by category, you can add a table for each category (this is quite handy when it comes to printing options, more on this in futures posts) and populate that table with the corresponding group of products. So far, so good, but when you run the report you see something like this: As you may notice, the columns are not aligned across the different groups and the report looks sloppy, but don’t worry, this can be fixed with a couple of lines of code Here I just adj

NRapid cascade filtering take 2

In a previous post I’ve shown how to cascade filter an autocomplete's datasource.  The code looked really ugly, so I promised to take a look at the NRapid's code and see if I can do something about it. As it turns out, I can, so now you have a neat way to work with cascade filtering. This is how it works before: This is how it works now: The mayor change from the client code perspective is that now you get the whole view data in the method call responsible for filtering, instead of the object id, as it was in the previous version. And of course, you don't have to write those cryptic functions ;) You can get the source code of NRapid from  here And the sample app from  here The Northwind database is available from download at  http://www.microsoft.com/en-us/download/details.aspx?id=23654

NRapid, cascade filtering with autocompletes

When working with large sets of hierarchical data sometimes you need to provide some sort a cascade filter mechanism. For instance, in a travel agency system, you may want to be able to select a destination, like country or a region, and based on that selection, get some data sets with travel options such as hotel deals, car rentals, and so on…. Continuing with our example (products and categories) I’ll create a dialog with two autocompletes. One will give you whole list of categories and the other a filtered set of products based on the selected category. Doing this is not so hard but requires a bit of an explanation. *In this post I’ll be using a nice C#’s feature called partial application. If you don’t know what does this means, don’t worry; just look at it as a magical lambda ;). When configuring an Autocomplete it’s possible to specify a function to be executed every time the selection changes, this can be done by using the NRapid’s fluent API, and we are going to