Monthly Archives: March 2013

T-SQL: STR Function

The STR function is another way to perform a specific conversion: It returns a string from a numeric expression:

The optional length and decimal parameters offer more flexibility than CAST or CONVERT when converting decimal data to character data, which enables explicit control over formatting. The following query uses STR to create a character string that is six characters long (with padding at the beginning of the string), and one decimal place:

The Figure below shows the first few rows of the output in a text window, where you can see that the numbers have leading spaces to align them on the right side.

Using STR to convert a number to a string

Needing to handle data conversion issues isn’t anything new or all that different in T-SQL compared to other programming languages that use strong typing. For the most part, you should avoid relying on T-SQL for implicit conversions. This will help you avoid troublesome bugs and make your code more readable, definitely a win-win situation!


ldn-expertdkielyThis post is an excerpt from the online courseware for our SQL Server 2012: Introduction to T-SQL
course written by expert Don Kiely.

Don Kiely is a featured instructor on many of our SQL Server and Visual Studio courses. He is a nationally recognized author, instructor and consultant who travels the country sharing his expertise in SQL Server and security.

Transact-SQL and Data Types

Some programming languages are quite forgiving about implicitly converting data types in expressions and computations. However, like other languages with strict typing, T-SQL requires explicit conversion between incompatible data types.

For example, if you execute the following script, it will raise an error because T-SQL can’t implicitly convert a character string varchar to an int, as shown in the Figure below.

T-SQL errorThe moral of the story is: Always perform explicit conversions when you work with different data types. You do that in T-SQL with CAST and CONVERT.

CAST and CONVERT

T-SQL supports two functions for data type conversion, CAST and CONVERT. CAST conforms to the ANSI standard, but CONVERT offers extra functionality. Here’s the syntax for each:

The following examples use CAST and CONVERT to perform explicit data type conversion to make the previous code sample work. Here it is explicitly casting or converting the value 2+2 to a string. The PRINT statement displays the output in the results pane, as shown in the Figure below.

result of casting and converting

NOTE: The main use for the PRINT statement is troubleshooting Transact-SQL code. You can also use it for sending informational error messages to client applications, but RAISERROR is preferable because it allows you to return errors with a greater severity level and also gives you more control over the error message. If you want the result returned to the calling code, use SELECT or the return value of a stored procedure instead.


Thumbnail for 566This post is an excerpt from the online courseware for our SQL Server 2012: Introduction to T-SQL
course written by expert Don Kiely.

Don Kiely is a featured instructor on many of our SQL Server and Visual Studio courses. He is a nationally recognized author, instructor and consultant who travels the country sharing his expertise in SQL Server and security.

More Evidence that C# is Poised to Become the Mobile Development Language of Choice

c video course

If you need further proof that C# is poised to become the mobile application programming language of the future, ZDNet is reporting that Xamarin, the Boston-based software company, will now start allowing iOS coders to use Microsoft’s Visual Studio.

This is important news because according to Xamarin, it is the first time any software company has enabled developers to build iOS applications using Visual Studio. That’s because the company – along with other development experts – believe that C# is the optimal language for mobile development.

Developers looking for a job or to switch careers should take note. After all, the future of the Internet is increasingly mobile, and C# is poised to take center stage. Just take a cursory look at any job board and you’ll see disproportionate amount of C# openings. Fortunately, our C# tutorial video library enables you to learn the language in the comfort of your home and at your own pace.

The mobile future is coming, whether you like it or not. Make sure you’re ready.

learnc

 

Thousands of developers worldwide use LearnNowOnline to gain the technical skills they need to succeed on the job and advance their career.

Transact-SQL Programming: Batches and Scripts

A batch is a collection of SQL statements that SQL Server processes as a single unit. SQL Server compiles a single execution plan for each batch; all the optimized steps necessary to perform the statements are built into the plan. If one of the statements contains a compile error, none of the statements in the batch will execute. You can execute batches directly in Management Studio, but they can also reside in external files, which you can execute by using the sqlcmd utility from the command line.

The following example shows two data definition language (DDL) statements that create a table and a view. You must process these statements as separate batches. If you attempt to process them as a single unit, you will receive an error message that ‘CREATE VIEW’ must be the first statement in a query batch, as you can see in the Figure below.

TIP: Recall that you can select a set of statements in the query editor in Management Studio and click the Execute button, and SQL Server will execute only those statements as a batch, even if there are other statements in the code file. This is an incredibly handy feature, one that we’ll use repeatedly throughout this course.

SQL create viewIf you look at the TSQL.sql file in Management Studio, you’ll see that there is a red squiggly line under the CREATE VIEW statement. As you can see in the Figure below, if you hover your mouse over the statement, you’ll see what the problem is.

Getting information about a T-SQL error

NOTE: It’s interesting that the error message you get when you attempt to run the previous T-SQL batch gives the error message “’CREATE VIEW’ must be the first statement in a query batch,” and the IntelliSense error is “Incorrect syntax: ‘CREATE VIEW’ must be the only statement in the batch.” According to the Books Online entry for the CREATE VIEW statement, it must be the first statement in the batch, so it appears that is the correct error and the “only statement” error message is incorrect.

The following code succeeds because it contains a GO statement before it creates the view.

The GO keyword signals the end of a T-SQL batch to the various tools that execute T-SQL code, including Management Studio. GO is not a T-SQL statement as such. Instead, it is a command recognized by code execution tools. GO indicates that the tool should send the batch to the instance of SQL Server it is connected to and execute the statements. A little used feature of the GO command is that you can optionally pass it an integer argument, and SQL Server will execute the statements in the batch the specified number of times.


Thumbnail for 566This post is an excerpt from the online courseware for our SQL Server 2012: Introduction to T-SQL
course written by expert Don Kiely.

Don Kiely is a featured instructor on many of our SQL Server and Visual Studio courses. He is a nationally recognized author, instructor and consultant who travels the country sharing his expertise in SQL Server and security.

Putting Java’s Recent Troubles in Context– And How It Can Affect Your Career

java256pxJava has been in the news quite a bit recently – and it’s not all good.

As you may have heard, the language has been hit by multiple attacks across the past few years; the bad guys have ranged from the Anonymous hackers to foreign cyber-criminals. Underscoring this problem, Oracle released the fifth Java update in just two months while the US Department of Homeland Security warned US users to completely disable the software.

So what to make of the future of Java? Naturally, the long-term prognosis for the language should be a concern for programmers considering a Java tutorial video or other training regimens.

This article does a great job of putting Java’s recent woes in context. For example, the reason why Java’s being attacked isn’t due to any inherent flaw in the language; rather, it’s simply the most popular language out there. It’s the same reason why PCs, and not Macs, have been the target of hackers for the last 30 years. But as Macs become increasingly popular, especially in the corporate world, they’re now seeing an increase of attacks.

Bottom line: if Java is central to your current or future career plans, the article is a must-read.

Thumbnail for 637

 

Thousands of developers worldwide use LearnNowOnline to gain the technical skills they need to succeed on the job and advance their career.

ASP.NET Web API: Self-Hosting

aspnet tutorial1

Building a service-oriented architecture with the ASP.NET Web API does not restrict you to IIS deployment. This may come as a surprise to those who have worked with Microsoft technologies for a long time. Many Microsoft technologies for the web are designed to be deployed on IIS and become erratic or completely non-functional if deployed in some other way. The Web API, however, does not need to be deployed in IIS, or even deployed to a web server. Microsoft has put the tools in the framework necessary to host Web API services out of any application you write.

Hosting Web API services in your own process is called self-hosting. You might think that self-hosting is an intensely involved process that has to manage sockets, multiple threads, etc. However, the framework has two objects that wrap up most of this complexity for you: HttpSelfHostConfiguration and HttpSelfHostServer.

The HttpSelfHostConfiguration object provides information to the framework on how you want the host to work. At the very least, this includes specifying the root URL that the host will use for HTTP requests and the routing rule(s) used. If all you intend to host are Web API services, then you can simply copy and paste the routing rule from the Global.asax of a Web API application.

WARNING! Make sure the application that you’re writing has adequate permissions to commandeer ports. Also, make sure that the machine running your application can receive HTTP requests from other machines on your network or outside your network depending on your needs. If your application can process requests made on that machine but not from any others, that could be a sign that the machine can’t be accessed from the outside. Finally, make sure your application’s build is targeted for the .NET 4 Framework and not the .NET 4 Framework Client Profile.

The HttpSelfHostServer takes in the second object: an HttpSelfHostConfiguration object. In your code, simply use the OpenAsync and Wait methods of this object for it to start listening for HTTP requests. Any HTTP requests that hit the URL defined in the HttpSelfHostConfiguration will run through the routing rules also defined in that configuration and get routed accordingly. From that point, everything works just like a normal Web API application. It’s almost as if you’ve written your own miniature web server as part of some other program. This code is quite simple considering the complexity of what you’re actually doing. Self-hosting can be useful in situations where IIS is not an option, where you have a very tightly-focused application that needs to handle everything internally, or you have various applications that need to communicate with each other across HTTP.

TIP: In order to use these objects, it is important that you have the MVC4 and selfhosting DLLs available to your code. The easiest way to get them is from the NuGet package Microsoft.AspNet.WebApi.SelfHost.


ldn-pledgerwoodThis post is an excerpt from the online courseware for our
ASP.NET Web API Hosting and Dependency Resolution course written by expert Philip Ledgerwood.

Philip Ledgerwood has been a software developer for fifteen years. He currently works primarily in .NET technologies producing custom software for organizations of all sizes. He has also done extensive training for those same organizations in both technical and business process topics.

What are the Most In-Demand Programming Languages?

url3If you’re a programmer, sometimes it’s a good idea to occasionally read up on job reports that illustrate the most popular languages on the job market. Doing so accomplishes two things. One, it allows you to keep place with your fellow programmer peers; and two, it may make you consider a change in your area of as proficiency. C#, for example, is in demand, and as a result, you may consider a C# video tutorial to help get you up to speed.

That said, don’t take these reports as the entire gospel truth. For example, look at where the data is collected. Some studies, for example, look at programming job openings on Twitter. This is all well and good, but as this article notes, Twitter is disproportionately used by start-ups. In other words, blue chip companies post their programming jobs elsewhere, which can skew the results.

This reality underscores the importance of knowing where you want to be. If you’re aiming for a start-up, then you probably won’t be surprised if like-minded surveys tout JavaScript. But if you’re angling for a blue chip company, languages like .NET are likely in greater demand.

Thumbnail for 637

Thousands of developers worldwide use LearnNowOnline to gain the technical skills they need to succeed on the job and advance their career.

Dependency Resolution and Hosting: Dependency Injection

There’s a sense in which the entire idea behind having consumable services such as the ASP.NET Web API provides is a decoupled, reusable architecture. You want to have a body of data and business logic decoupled from a client application so it can be used by a variety of client applications. Testability is also an important architectural issue. A unit of code must be decoupled from its dependencies in order to write automated tests against it.

Practices like Test Driven Development (TDD) virtually force writing code this way. In software development, all code should be written with these principles in mind, including our client applications and the services, themselves.

Dependency Injection is one way to help achieve decoupling, reusability, and testability in Web API services. With this in mind, the Web API framework was designed to facilitate this technique.

Inversion of Control

In a broad sense, Inversion of Control is the concept of allowing something outside of a system to control it. In other words, the system doesn’t run itself but something or someone on the outside invokes it when it is needed. In a very broad sense, things like a web-based interface over a database could be an example of Inversion of Control. In object-oriented software development, Inversion of Control means that, instead of tightly coupling objects to other objects in code, objects are pulled together at runtime by some outside mechanism.

If you go to a pizza restaurant, you’ll see people making pizzas. What you probably won’t see are people growing tomatoes for the sauce, milking cows to make the cheese, or processing cardboard to make the pizza boxes. The pizza shop needs all those things, but they are not responsible for creating them. Someone else creates them and gives them to the pizza shop to use to get their job done. This is roughly analogous to Inversion of Control in software development.

For instance, if you are writing a repository class that will save products to the database, it will need some kind of data access object to perform the database operations. One way to do this is simply to instantiate a data access object in your repository code. However, this will tightly couple your repository code to that data access object.

With Inversion of Control, you code the repository to an abstraction (usually an interface) that represents the data access object and you rely on some outside mechanism to instantiate a data access object and give it to your repository at runtime. By doing this, your repository is now decoupled from any particular data access object. This allows you to reuse the repository code with various data access components as well as making it testable (by giving the repository a “mock” data access object).

There are various techniques that give you Inversion of Control in software development and one of the more common and prominent ones is Dependency Injection.

Using Dependency Injection

Many classes that you write need other objects to do their jobs, and nowhere is this more true than in a services layer. Many services need objects to access data, process business rules, perform validation, handle logging, and a wide array of functionality that the services layer tends to coordinate.

With Dependency Injection, programmers code their classes assuming that these objects will be instantiated from an entity outside their class and passed into it. Sometimes, this is done by exposing properties that can be set from the outside. A very common way to set up for Dependency Injection, however, is to handle it in the constructor.

In the previous example, there is a Logger class that needs a file writer object. In tightly-coupled code, the Logger would just instantiate its own file writer:

However, this would bind the Logger class to a specific FileWriter object. By allowing an object that implements IFileWriter to be passed into the constructor, you can now reuse this class for various kinds of file writers. Also, this code is very testable because you can pass in a fake file writer for testing purposes—perhaps one that writes to a test file or even does nothing at all.

If code is written to receive its dependencies from the outside, these objects have to come from somewhere. Something on the outside needs to instantiate these objects and pass them into the objects that require them. Some mechanism needs to inject these dependencies. There’s more than one way to do this, but this is such a common issue in software development that common libraries have been written to solve this problem. They are often called IoC (Inversion of Control) Containers or DI (Dependency Injection) frameworks.

This post is an excerpt from the online courseware for our ASP.NET Web API Hosting and Dependency Resolution course written by expert Philip Ledgerwood.

ldn-pledgerwoodPhilip Ledgerwood has been a software developer for fifteen years. He currently works primarily in .NET technologies producing custom software for organizations of all sizes. He has also done extensive training for those same organizations in both technical and business process topics.

New SharePoint Features Will Boost Adoption, Creating a Demand for Proficient IT Workers

en-usFor the past 20 years, IT has struggled with the perception that it is a utility, rather than a “strategic partner” to the business. By “utility” we mean something akin to an electric company – an entity that helps the company “keep the lights on,” but nothing more.

Because of this perception, two things happen. One, IT fails to secure a “seat at the table” with other business partners, and two, IT workers are viewed, occasionally, as disposable.

Of course, some IT jobs are purely technical. But more and more technologies are breaking down walls between the IT function and the business. Case in point: platforms like SharePoint that access the cloud to enable business users to collaborate.

This recent article in CIO Magazine looks at the platform’s new functionality, plus integration challenges surrounding mobile devices and social media. And it’s precisely because of this improved functionality that SharePoint adoption will only increase over time.

So for technical programmers looking to make a transition towards more business-focused applications, a SharePoint tutorial is a great place to start.

Thousands of developers worldwide use LearnNowOnline to gain the technical skills they need to succeed on the job and advance their career.

Requesting Other MIME Types

MIME originally stood for Multipurpose Internet Mail Extensions to refer to the fact that emails would sometimes carry data that wasn’t text, such as attached graphics or spreadsheets. MIME types were a way for email clients to recognize the different types of data coming across and handle them appropriately.

When dealing with web applications today, MIME types (also referred to as Content-Types) refer to all kinds of data that web clients access over the Internet. A common MIME type is text/html, but there’s also text/css, application/xml, and even non-textual types such as application/pdf or image/gif.

JSON is the default MIME type that Web API services return, and it might fit a great many needs for web services, but what if your application needs to get XML from a service, or a comma-delimited file, or even a graphic or a spreadsheet?

XML

XML is an extremely common data exchange format for web services and, as such, the Web API can support returning XML data with no code changes. All that needs to happen is that the HTTP request has to specify a Content-Type of application/xml.

If a Web API service gets an HTTP request with a Content-Type of application/xml, it will automatically serialize and return data as XML rather than JSON. Nothing special needs to be done to make this happen unless you want to provide a different XML serializer.

NOTE: At the time of this writing, the ASP.NET Web API uses the DataContractSerializer in the .NET Framework behind the scenes to do XML serialization. You can set a different serializer in the Web API’s configuration.

Other MIME Types

JSON and XML are the only MIME types the Web API handles out of the box. However, the Web API can send back virtually any MIME type out there. If you want a Web API service to return something besides JSON or XML, you must first write your own “serializer” for the data you want to return. In Web API parlance, this is called a Media Formatter. This Media Formatter needs to be registered in the Web API configuration. Once this is done, any requests for that data that have a Content-Type of the MIME type of the appropriate Media Formatter will receive that type of data back from the service.

ldn-pledgerwoodThis post is an excerpt from the online courseware for our ASP.NET Web API Model Binding and Media Formats course written by expert Philip Ledgerwood.

Philip Ledgerwood has been a software developer for fifteen years. He currently works primarily in .NET technologies producing custom software for organizations of all sizes. He has also done extensive training for those same organizations in both technical and business process topics.