This quick tip will show how you can write a custom view for a custom controller action in Orchard that does not use the current theme, but that still retains the ability to use shapes, as well as zones, Script and Style helpers.
The controller action, first, needs to opt out of theming:
[Themed(false)]
public ActionResult Index() {}
Then, we still want to use a shape as the view model, because Clay is so awesome:
private readonly dynamic _shapeFactory;
public MyController(IShapeFactory shapeFactory) {
_shapeFactory = shapeFactory;
}
[Themed(false)]
public ActionResult Index() {
return View(_shapeFactory.MyShapeName(
Foo: 42,
Bar: "baz"
));
}
As you can see, we injected a shape factory, and that enables us to build our shape from our action and inject that into the view as the model.
Finally, in the view (that would in Views/MyController/Index.cshtml here), just use helpers as usual. The only gotcha is that you need to use “Layout” in order to declare zones, and that two of those zones, Head and Tail, are mandatory for the top and bottom scripts and stylesheets to be injected properly. Names are important here.
@{
Style.Include("somestylesheet.css");
Script.Require("jQuery");
Script.Include("somescript.js");
using(Script.Foot()) {
<script type="text/javascript">
$(function () {
// Do stuff
})
</script>
}
}
<!DOCTYPE html>
<html>
<head>
<title>My unthemed page</title>
@Display(Layout.Head)
</head>
<body>
<h1>My unthemed page</h1>
<div>@Model.Foo is the answer.</div>
</body>
@Display(Layout.Tail)
</html>
Note that if you define your own zones using @Display(Layout.SomeZone) in your view, you can perfectly well send additional shapes to them from your controller action, if you injected an instance of IWorkContextAccessor:
_workContextAccessor.GetContext().Layout
.SomeZone.Add(_shapeFactory.SomeOtherShape());
Of course, you’ll need to write a SomeOtherShape.cshtml template for that shape but I think this is pretty neat.
Anders published a video of his new project today, which aims at creating a superset of JavaScript, that compiles down to regular current JavaScript. Anders is a tremendously clever guy, and it always shows in his work. There is much to like in the enterprise (good code completion, refactoring and adoption of the module pattern instead of namespaces to name three), but a few things made me rise an eyebrow.
First, there is no mention of CoffeeScript or Dart, but he does talk briefly about Script# and GWT. This is probably because the target audience seems to be the same as the audience for the latter two, i.e. developers who are more comfortable with statically-typed languages such as C# and Java than dynamic languages such as JavaScript. I don’t think he’s aiming at JavaScript developers. Classes and interfaces, although well executed, are not especially appealing.
Second, as any code generation tool (and this is true of CoffeeScript as well), you’d better like the generated code. I didn’t, unfortunately. The code that I saw is not the code I would have written. What’s more, I didn’t always find the TypeScript code especially more expressive than what it gets compiled to.
I also have a few questions.
Is it possible to duck-type interfaces? For example, if I have an IPoint2D interface with x and y coordinates, can I pass any object that has x and y into a function that expects IPoint2D or do I need to necessarily create a class that implements that interface, and new up an instance that explicitly declares its contract? The appeal of dynamic languages is the ability to make objects as you go. This needs to be kept intact.
UPDATE: this works.
More technical: why are generated variables and functions prefixed with _ rather than the $ that the EcmaScript spec recommends for machine-generated variables?
In conclusion, while this is a good contribution to the set of ideas around JavaScript evolution, I don’t expect a lot of adoption outside of the devoted Microsoft developers, but maybe some influence on the language itself. But I’m often wrong. I would certainly not use it because I disagree with the central motivation for doing this: Anders explicitly says he built this because “writing application-scale JavaScript is hard”. I would restate that “writing application-scale JavaScript is hard for people who are used to statically-typed languages”. The community has built a set of good practices over the last few years that do scale quite well, and many people are successfully developing and maintaining impressive applications directly in JavaScript.
You can play with TypeScript here: http://www.typescriptlang.org
Jeff Atwood has an interesting post today where he says his current laptop may be the last one he buys. The argument is that tablets are a better option now, with longer battery life, less lap overheating, and a nicer form factor. But well, tablets are not for me. I always need a keyboard, a full version of Windows, I rarely need to run on the battery for very long, and the tablet form factor just doesn’t work for me. I like my screen to stand on its own, even on my lap, and having a separated keyboard is just clumsy. The surface looks like an interesting compromise, but the lack of a robust hinge makes it a no-go for me. Also, I want a single machine that works for everything I do.
I usually buy my desktop machines with a very different approach from the Atwoods and Hanselmans of the world: they seem to always go for the best and change them often, whereas I go for older, cheaper parts that I swap out to make the computers last as long as possible. Buying lots of new devices all the time feels icky to the environmentalist in me.
The last machine I retired was twenty years old and the only reason I changed it was that I got a case for free with the replacement parts I needed. Granted, the case was the only remaining original part. But still, I’ve made it last by swapping old parts with new ones as needed, and it’s been a very economical solution. I never go for the top-of-the-line, makes-your-eyes-bleed-with-ecstasy graphics cards, processors and memory. Instead, I buy year-old-ish parts, in that sweet spot where they have gotten extremely inexpensive but are still the equivalent of last year’s best. Last year was awesome last year, remember? And before you ask, I do most of my gaming on Xbox, so I really don’t need a gaming type of PC.
Laptops are different however: you can’t swap parts so easily. A couple of years ago, I started using my laptop as my main machine. This has the advantage that I can work anywhere with the same tools and data, even if I’m not connected. In my home office, in my rocker in front of the TV, in a coffee house or on the plane. Nothing to copy onto it before I leave, it’s all already there, always, like a little cloud that follows me everywhere I go. Laptops are awesomely light and small nowadays, and they can still pack all the power that I need. When I started working freelance last year, I shopped around and after considering a MacBook Air, I settled on a Samsung Series 9 with 6GB of RAM and 256GB of SSD. I did not want to have to change anything on the machine, and the Samsung was the only machine that reached out of the box all my requirements, one of which was to be very small, and another that I could hook it to a large external screen.
A year after, I still love that machine. I’ve had an issue with the quality of the plastics, and had to replace the piece that surrounds the keyboard after it cracked (covered under the awesome 3-year warranty), and I do resent the lack of anything else than HDMI when I talk at conferences, but overall it’s a fantastic piece of technology and a near-perfect fit for me.
Would I surrender the advantages of having everything I need in a form factor that I like for a hipper tablet? Of course not. As I said, tablets are not for me. They may be fantastic devices, but I need my Visual Studio, my keyboard and my hinge.
Is it the ultimate laptop? Of course not. I wouldn’t mind a retina-like screen, double the SSD, and a little more battery juice.
So why am I telling you all that? In today’s hardware market, we have more variety and form factors than we ever had before: phones, tablets, hybrids, laptops, ridiculously small and cheap microcontrollers that can output HD video, and of course desktops. That’s choice, people, and if you can handle it, it’s a wonderful thing to have. Pick what fits your life and work styles (and make it last).
To those of us who have been around for a while, namespaces have been part of the landscape. One could even say that they have been defining the large-scale features of the landscape in question.
However, something happened fairly recently that I think makes this venerable structure obsolete. Before I explain this development and why it’s a superior concept to namespaces, let me recapitulate what namespaces are and why they’ve been so good to us over the years…
Namespaces are used for a few different things:
- Scope: a namespace delimits the portion of code where a name (for a class, sub-namespace, etc.) has the specified meaning. Namespaces are usually the highest-level scoping structures in a software package.
- Collision prevention: name collisions are a universal problem. Some systems, such as jQuery, wave it away, but the problem remains. Namespaces provide a reasonable approach to global uniqueness (and in some implementations such as XML, enforce it). In .NET, there are ways to relocate a namespace to avoid those rare collision cases.
- Hierarchy: programmers like neat little boxes, and especially boxes within boxes within boxes. For some reason. Regular human beings on the other hand, tend to think linearly, which is why the Windows explorer for example has tried in a few different ways to flatten the file system hierarchy for the user.
1 is clearly useful because we need to protect our code from bleeding effects from the rest of the application (and vice versa). A language with only global constructs may be what some of us started programming on, but it’s not desirable in any way today.
2 may not be always reasonably worth the trouble (jQuery is doing fine with its global plug-in namespace), but we still need it in many cases. One should note however that globally unique names are not the only possible implementation. In fact, they are a rather extreme solution. What we really care about is collision prevention within our application. What happens outside is irrelevant.
3 is, more than anything, an aesthetical choice. A common convention has been to encode the whole pedigree of the code into the namespace. Come to think about it, we never think we need to import “Microsoft.SqlServer.Management.Smo.Agent” and that would be very hard to remember. What we want to do is bring nHibernate into our app.
And this is precisely what you’ll do with modern package managers and module loaders. I want to take the specific example of RequireJS, which is commonly used with Node.
Here is how you import a module with RequireJS:
var http = require("http");
This is of course importing a HTTP stack module into the code. There is no noise here. Let’s break this down.
Scope (1) is provided by the one scoping mechanism in JavaScript: the closure surrounding the module’s code. Whatever scoping mechanism is provided by the language would be fine here.
Collision prevention (2) is very elegantly handled. Whereas relocating is an afterthought, and an exceptional measure with namespaces, it is here on the frontline. You always relocate, using an extremely familiar pattern: variable assignment. We are very much used to managing our local variable names and any possible collision will get solved very easily by picking a different name.
Wait a minute, I hear some of you say. This is only taking care of collisions on the client-side, on the left of that assignment. What if I have two libraries with the name “http”? Well, You can better qualify the path to the module, which is what the require parameter really is.
As for hierarchical organization, you don’t really want that, do you?
RequireJS’ module pattern does elegantly cover the bases that namespaces used to cover, but it also promotes additional good practices.
First, it promotes usage of self-contained, single responsibility units of code through the closure-based, stricter scoping mechanism. Namespaces are somewhat more porous, as using/import statements can be used bi-directionally, which leads us to my second point…
Sane dependency graphs are easier to achieve and sustain with such a structure. With namespaces, it is easy to construct dependency cycles (that’s bad, mmkay?). With this pattern, the equivalent would be to build mega-components, which are an easier problem to spot than a decay into inter-dependent namespaces, for which you need specialized tools.
I really like this pattern very much, and I would like to see more environments implement it. One could argue that dependency injection has some commonalities with this for example. What do you think? This is the half-baked result of some morning shower reflections, and I’d love to read your thoughts about it. What am I missing?
With the imminent release of Orchard 1.5, the number of built-in modules in the default distribution is getting quite impressive, if not intimidating. Now may be a good time to give new and old users a tour of what comes out of the box. Who knows, we may discover a hidden nugget or two along the way…
I just finished writing a massive documentation topic that describes all Orchard features that come with the source code and WebPI distributions:
All built-in Orchard modules described
I added the guide to the official Orchard documentation site. It details what modules come in the default package, which are only available from the source code package or from the gallery, and also mentions which are enabled by default.
Documentation, like everything in Orchard, is open source, so you can contribute to this topic and others: Edit this topic.
I hope this helps.
By default, when Orchard displays a content item such as a blog post in a list, it uses a very basic summary template that removes all markup and then extracts the first 200 characters. Removing the markup has the unfortunate effect of removing all styles and images, in particular the image I like to add to the beginning of my posts.
Fortunately, overriding templates in Orchard is a piece of cake. Here is the Common.Body.Summary.cshtml file that I drop into the Views/Parts folder of pretty much all Orchard themes I build:
@{
Orchard.ContentManagement.ContentItem contentItem =
Model.ContentPart.ContentItem;
var bodyHtml = Model.Html.ToString();
var more = bodyHtml.IndexOf("<!--more-->");
if (more != -1) {
bodyHtml = bodyHtml.Substring(0, more);
}
else {
var firstP = bodyHtml.IndexOf("<p>");
var firstSlashP = bodyHtml.IndexOf("</p>");
if (firstP >=0 && firstSlashP > firstP) {
bodyHtml = bodyHtml.Substring(firstP, firstSlashP + 4 - firstP);
}
}
var body = new HtmlString(bodyHtml);
}
<p>@body</p>
<p>@Html.ItemDisplayLink(T("Read more...").ToString(), contentItem)</p>
This template does not remove any tags, but instead looks for an HTML comment delimiting the end of the post’s intro:
<!--more-->
This is the same convention that is being used in WordPress, and it’s easy to add from the source view in TinyMCE or Live Writer.
If such a comment is not found, the template will extract the first paragraph (delimited by <p> and </p> tags) as the summary.
And if it finds neither, it will use the whole post.
The template also adds a localizable link to the full post.
It should be quite obvious: drawing requires constant visual feedback. Why is it then that we still draw with code in so many situations? Of course it’s because the low-level APIs always come first, and design tools are built after and on top of those. Existing design tools also don’t typically include complex UI elements such as buttons.
When we launched our Touch Display module for Netduino Go!, we naturally built APIs that made it easy to draw on the screen from code, but very soon, we felt the limitations and tedium of drawing in code. In particular, any modification requires a modification of the code, followed by compilation and deployment. When trying to set-up buttons at pixel precision, the process is not optimal.
On the other hand, code is irreplaceable as a way to automate repetitive tasks. While tools like Illustrator have ways to repeat graphical elements, they do so in a way that is a little alien and counter-intuitive to my developer mind. From these reflections, I knew that I wanted a design tool that would be structurally code-centric but that would still enable immediate feedback and mouse adjustments.
While thinking about the best way to achieve this goal, I saw this fantastic video by Bret Victor:
The key to the magic in all these demos is permanent execution of the code being edited. Whenever a parameter is being modified, everything is re-executed immediately so that the impact of the modification is instantaneously visible. If you do this all the time, the code and the result of its execution fuse in the mind of the user into dual representations of a single object. All mental barriers disappear. It’s like magic.
The tool I built, Nutshell, is just another implementation of this principle. It manipulates a list of graphical operations on the screen. Each operation has a nice editor, and translates into a bit of code. Any modification to the parameters of the operation will modify the bit of generated code and trigger a re-execution of the whole program. This happens so fast that it feels like the drawing reacts instantaneously to all changes.
The order of the operations is also the order in which the code gets executed. So if you want to bring objects to the front, move them down in the list, and up if you want to move them to the back:
But where it gets really fun is when you start applying code constructs such as loops to the design tool. The elements that you put inside of a loop can use the loop counter in expressions, enabling crazy scenarios while retaining the real-time edition features.
When you’re done building, you can just deploy the code to the device and see it run in its native environment:
This works thanks to two code generators. The first code generator is building JavaScript that is executed in the browser to build the canvas view in the web page hosting the tool. The second code generator is building the C# code that will run on the Netduino Go! microcontroller and that will drive the display module.
The possibilities are fascinating, even if you don’t care about driving small touch screens from microcontrollers: it is now possible, within a reasonable budget, to build specialized design tools for very vertical applications. Direct feedback is a powerful ally in many domains. Code generation driven by visual designers has become more approachable than ever thanks to extraordinary JavaScript libraries and to the powerful development platform that modern browsers provide.
I encourage you to tinker with Nutshell and let it open your eyes to new possibilities that you may not have considered before. It’s open source. And of course, my company, Nwazet, can help you develop your own custom browser-based direct feedback design tools. This is real visual programming…
A quick tip for all you new enthusiastic users of the amazing new Azure. I struggled for a few minutes finding this, so I thought I’d share. The Azure dashboard doesn’t seem to give easy access to your FTP credentials, and they are not the login and password you use everywhere else. What Azure does give you though is a Publish Profile that you can download:
This is a plain XML file that should look something like this:
<publishData>
<publishProfile
profileName="nameofyoursite - Web Deploy"
publishMethod="MSDeploy"
publishUrl="waws-prod-blu-001.publish.azurewebsites.windows.net:443"
msdeploySite="nameofyoursite"
userName="$NameOfYourSite"
userPWD="sOmeCrYPTicL00kIngStr1nG"
destinationAppUrl="http://nameofyoursite.azurewebsites.net"
SQLServerDBConnectionString=""
mySQLDBConnectionString=""
hostingProviderForumLink=""
controlPanelLink="http://windows.azure.com">
<databases/>
</publishProfile>
<publishProfile
profileName="nameofyoursite - FTP"
publishMethod="FTP"
publishUrl="ftp://waws-prod-blu-001.ftp.azurewebsites.windows.net/site/wwwroot"
ftpPassiveMode="True"
userName="nameofyoursite\$nameofyoursite"
userPWD="sOmeCrYPTicL00kIngStr1nG"
destinationAppUrl="http://nameofyoursite.azurewebsites.net"
SQLServerDBConnectionString=""
mySQLDBConnectionString=""
hostingProviderForumLink=""
controlPanelLink="http://windows.azure.com">
<databases/>
</publishProfile>
</publishData>
I’ve highlighted the FTP server name, user name and password. This is what you need to use in Filezilla or whatever you use to access your site remotely. Notice how the password looks encrypted. Well, it’s not really encrypted in fact. This is your password in clear text. It’s just crypto-random gibberish, which is the best kind of password.
UPDATE: About 2 minutes after I posted that, David Ebbo mentioned to me on Twitter that if you've configured publishing credentials (for Git typically) those will work too. Don't forget to include the full user name though, which should be of the form nameofthesite\username. The password is the one you defined.
That’s it. Enjoy.
Netduino Go is designed for much more than toy projects, but one has to recognize that toy projects are fun and also great learning experiences. Today, I want to take you through the process of reproducing the behavior of a famous toy that you will surely recognize. That toy, that has helped many of us realize what poor motor skills we possess, has two knobs that control the horizontal and vertical coordinates of a pen that draws into the dust on the back of a simple screen. It’s a great mechanical device that is part of western culture.
Our version will use two potentiometers, a 320x240 LCD display, a button to erase the screen, and of course a Netduino Go. The hardware setup looks like the following:
We connected the button to port 2 (but it doesn’t matter as there’s only one), the two potentiometers to ports 3 and 4, and the display to port 5.
We can initialize this setup with the following code:
private Potentiometer Vertical = new Potentiometer(GoSockets.Socket3);
private Potentiometer Horizontal = new Potentiometer(GoSockets.Socket4);
private Button Button = new Button();
private VirtualCanvas Canvas = new VirtualCanvas();
To initialize the display, I wrote this method, which initializes a VirtualCanvas object on socket 5, sets the orientation of the display to landscape, fills the screen with white and flushes the command buffer:
public void InitCanvas() {
Canvas.Initialize(GoSockets.Socket5);
Canvas.SetOrientation(Orientation.Landscape);
Canvas.DrawFill(white);
Canvas.Execute();
}
The VirtualCanvas object can be seen as the driver for the display. It’s a simple vector API, but a crucial point is that these vector drawing primitives are not executed on the Netduino. Instead, they are serialized, sent to the display and executed there. This keeps communication between the microcontroller and the screen to a minimum, and frees the Netduino main board computing power. Essentially, you have a graphics coprocessor bundled with that screen. This is also why you need to call Execute when you want a command batch to be sent to the display and drawn.
To do the actual drawing, all we need is to read the values from both potentiometers and convert them into screen coordinates:
public int ReadY() {
return (int)(Vertical.GetValue() * Canvas.Height);
}
public int ReadX() {
return (int)(Horizontal.GetValue() * Canvas.Width);
}
And then render that on the screen:
Canvas.DrawLine(currentX, currentY, x, y, black);
Canvas.Execute();
I’m using DrawLine here and not DrawPixel so that the drawing looks continuous even if the potentiometers are rotated very fast. This requires remembering the previous coordinates, which is fairly simple to do.
All this is pretty easy really. You can see it in action in the following video. To keep things exciting, I threw in some debugging and live command drawing…
The source code for this can be downloaded here:
http://weblogs.asp.net/blogs/bleroy/Telecran.zip
All parts used in this demo can be purchased from Nwazet.
Wouldn’t it be great if you could build your own stuff? Microcontrollers let you do that, but they usually require dealing with a lot of complexity and unknowns. If you’re a software developer, chances are you don’t really know how to use a capacitor, or how a transistor works, even though it is at the heart of all computers.
Well there is a way now to develop awesome hardware projects without knowledge of electronics, just by connecting modules together. Netduino Go is a platform that allows for that without constraining the types of projects you can build. Today the number of available modules is still limited (the platform was released only this month), but it is expected to grow fast.
In this post, I’ll introduce you to the platform, with the assumption that you know programming but not electronics.
So let’s get started. What you need to follow along this post is the following:
First we’ll create a new project, selecting the Netduino Go Application project type:
This creates a new project with references to assemblies managing the .NET Micro Framework, the Go Bus and the Netduino’s ports:
We still need to add specific support for the two modules we’re going to use, the RGB LED and the Potentiometer. For that, let’s right-click on References and add the two assemblies we need:
Once that is done, we can start creating objects representing our modules:
using System;
using NetduinoGo;
namespace FirstStepsWithNetduinoGo {
public class Program {
public static void Main() {
var led = new RgbLed();
var pot = new Potentiometer();
}
}
}
This code works without specifying a port because Netduino Go knows to take the first module it finds that identifies as the right module type. Each constructor has an overload that takes a GoSockets enumeration so we could have written:
using System;
using SecretLabs.NETMF.Hardware.NetduinoGo;
using NetduinoGo;
namespace FirstStepsWithNetduinoGo {
public class Program {
public static void Main() {
var led = new RgbLed(GoSockets.Socket2);
var pot = new Potentiometer(GoSockets.Socket1);
}
}
}
We now have objects representing our module, but we still need to do something with them. Let’s start by turning on that LED. But before we do, let’s review our hardware setup:
The potentiometer is connected to socket #1 on the Netduino, and the RGB LED is on socket #2. Now we need to connect a micro-USB cable between the computer and the Go. This will both power the whole thing and give us the channel we need to deploy and debug our code. The first time you do that, it will also install the driver for the Go on your computer.
Let’s code:
led.SetColor(255, 212, 42);
In order to deploy that code, we need first to make sure that the project properties are set to deploy on USB:
Once this is done, we can hit F5 and see that LED turn on…
And… You should have gone blind by now. That LED is incredibly bright. Our next step is going to add some code so that the potentiometer can control the intensity of that light:
var led = new RgbLed();
var pot = new Potentiometer();
int red = 255, green = 212, blue = 42;
while (true) {
var intensity = pot.GetValue();
led.SetColor(
(byte)(red * intensity),
(byte)(green * intensity),
(byte)(blue * intensity));
}
Deploying this code gives the following result:
And of course, this is visual Studio, so we have full debugging support, as can be seen in the video.
And that’s it for today. This should get you started with Netduino Go. And we didn’t have to solder anything… Next time, we’ll play with a touch screen.
More Posts
« Previous page -
Next page »