Monday, January 14, 2013

Back serving the dev community


On January 8th, 2013, I had the pleasure to organize and speak at the Windows 8 Dev Unleashed. The event took place at the University of Kentucky and had 60 registered attendees, mostly actually attended.
It was an intense and fun day, throughout which we cover every new aspect of developing “Windows Store” applications for Windows 8. There were lots of interesting discussions and I learned a lot during the process.

Thanks for everyone who attended and for the Facilities Management department of the university, that helped me pull this one off. They provided amazing help in the promotion and infrastructure. In addition to making a few “pro” and “RT” devices available for people to play with, they actually installed Windows 8 on several old touch-enabled laptops for attendees to use throughout the day, if they didn’t have their own machine ready.

I am looking forward to resuming serving the development community here in Lexington, KY, as I used to back in California.




Thursday, December 6, 2012

SSIS to QlikView task execution


QlikView is a BI visualization tool that has been in my tool belt for some time, and I use it as part of comprehensive BI solutions. SQLServer Integration Services is another important piece of the solution, and, in addition to the obvious ETL and data store functions, I tend to use it to orchestrate the actions of the system. Therefore, it is necessary to call QlikView functionality from within SSIS packages.
In QlikView version 11, the way to do this is through EDX (Event Driven Execution). The nice thing about this mechanism is that the API is exposed via SOAP over HTTP. It becomes easy to build a little .Net app to call the services associated to internal QlikView tasks.
If you are not a .Net developer, QlikTech’s Arthur Lee created a very nice article and .Net console application that you can use. Check out the article.

If you didn't recognize it right away, one of the benefits of having the API as a service is that you don't have to deal with the hassle of trying to execute a command-line call or batch file on a remote server. It's not as simple as running the thing because you'd be running in the calling box, not on the remote server.

It sounds very silly but I wanted to remind you about something that can save someone a lot of aggravation. When setting up your EDX triggers from within QlikView make sure there are no spaces in between words in the task names as well as no spaces at the end of the task names. Yeah… ask me how I know that.

Happy ee-tee-elling.

Tuesday, December 4, 2012

SSIS, I love you but I hate you so much

It got me again, during development I used a mapped drive throughout my project and everything works perfectly. To see those green boxes fill your screen relaxes you like nothing else. I mean, not really but it feels good like nothing else. Ok, not true, but back to the point...
Deployed the package, run it through a SQL Agent job and kaboooom. Error. Spit out the gum, straighten the back, pull the chair into the desk a little more...
After hours of agony I remembered that you should never use mapped drives with SSIS/SQL jobs, and pretty much anything else.
After using UNC paths to network shares everything is back to green.

Take away: D O    N O T    U S E    M A P P E D    D R I V E S    I N    S S I S. They don't mix well, just like oil and water...



Friday, November 23, 2012

Sleep Stats


As a father of an infant born with severe acid reflux I am up many times throughout the night and I wanted to know how many actual hours of sleep I was yielding. Since I am a proud owner of a Windows Phone, I decided to build an app to do that.
It is called Sleep Stats and it can be found here www.sleepstats.com.

It's really easy to use - just press the Sleep button when you go to sleep and the Wake Up button when you wake up. Do that throughout the night and you'll get a total number of sleeping hours, number of interruptions, average quality of sleep, etc. You can than save all this data as a .csv file to your SkyDrive and open it in Excel for even more number crunching.

The second update of the app has a couple of bug fixes and support for Portuguese.

Check it out! Night-night...



Sunday, November 11, 2012

Wasted a couple of hours (hopefully you won't)

I hope that you reach this post if you 1) are using Isolated Storage Explorer in your project, and 2) your app runs fine on the emulator but crashes on the device. Ok, by now you're thinking "Aaaaaah! Of course!" and are no longer reading.
In case you are still here, yes, you're right, you forgot the Isolated Storage Explorer registration code in the Application_Launching and Application_Activated events.

You can leave the code there but make sure you run it only when in the emulator:


if (Environment.DeviceType == DeviceType.Emulator)
      IsolatedStorageExplorer.Explorer.Start("localhost");   

Monday, November 5, 2012

Mobile Client switch for Windows Phone apps

Many of the Windows Phone apps I use have some sort of integration with SkyDrive, sometimes as a store for backup data. You can find sample code on the web on how to do this, it's pretty simple. However, I had a bit of a problem trying to get connected and the app wouldn't even show the SkyDrive login page. 
After some digging around I found that, because my app was a Windows Phone app, it requires a newer set of OAuth mechanism, and in order to use it the app needs to be marked as Mobile Client App.

To find this option log onto dev.live.com, go to "My Apps" and select API Settings:

Tuesday, October 30, 2012

Windows Phone's LinqToSql flakyness


I started doing Windows Phone development with Mango, which comes with SqlCe + LinqToSql. I had a lot of experience building WPF and Silverlight applications LinqToSql and Entity Framework against SQL Server, so I thought it all should be the same, or pretty close.
I started coding away and pretty soon realized some of the database operations, such as updates and deletes, were not working. I would have one update/SubmitChanges and, right after, re-query the entity and realized no changes were saved.
INotifyPropertyChanged was properly implemented, everything appeared to be ok.

I finally found out the culprit: lack of INotifyPropertyChangING on all properties of the table.

Yes, make sure to call your NotifyPropertyChanging before the assignment in the setter, and NotifyPropertyChanged afterwards. Something like this:

private DateTime startDateTime;
[Column]
public DateTime StartDateTime
{
    get { return startDateTime; }
    set
    {
        NotifyPropertyChanging("StartDateTime"); 
        startDateTime = value;
        NotifyPropertyChanged("StartDateTime");
    }
}

Here is my implementation of the two handlers for your convenience. This is not production-worthy because of lack of type-checking on the property name, but it's ok for illustrating my point:

public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(String propertyName)
{
    var handler = PropertyChanged;
    if (null != handler)
    {
        handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

public event PropertyChangingEventHandler PropertyChanging;
public void NotifyPropertyChanging(string propertyName)
{
    var handler = PropertyChanging;
    if (null != handler)
    {
        handler(this, new PropertyChangingEventArgs(propertyName));
    }
}

Thursday, September 6, 2012

No pasting in Remote Desktop sessions?


You're trying to copy/paste from a Remote Desktop session and it is not working... Do you then open your web-based email provider to email yourself that long script from the server? If so you're doing it wrong!

The quick fix for when Windows' Remote Desktop's "copy/paste" capabilities stop working is to kill the "RDPCLIP.EXE" process and run it again.

But if you're using another remote-desktop-like system that doesn't have this feature or stops working for other reason, my favorite tool is PiratePad (if the copying/pasting object is simple text, that is). Simply put it gives you a collaboration surface that you can leave open in multiple machines. There's no account to create, no login to worry about, etc.

Monday, August 27, 2012

SQL Server - retrieving record count instantaneously


So here it is, the first one of these not-so-original knowledge, but I didn't know until I needed it today.

In SQL Server it may take a long time to simply return a total record count using select count (*) from YourTable as the engine may decide to perform a scan instead of a seek.

Among other places this page helped me with a solution that retrieves the record count of a table instantaneously:

SQL 2005 or later
select sum (spart.rows)
from sys.partitions spart
where spart.object_id = object_id('YourTable')
and spart.index_id < 2

SQL 2000
select max(ROWS)
from sysindexes
where id = object_id('YourTable')

Your blog sucks!


Within the past 3 months two people made comments criticizing the fact my blog is dead. Not that they used to read it and then I suddenly I stopped producing content, which would be silly because the content is very very minimal.

These individuals don't even have a blog to begin with but they are right. If I had the initiative to start one why the hell didn't I keep up with it. It's been 16 months since my last post!

I believe it has to do with wanting to write something unique, or a nugget of information that is hard to find. But following the advice from one of my mentors (despite the fact he doesn't know I exist) Scott Hanselman, I will try to write anything that is useful to me, regardless if it's easily found throughout the internets.

Friday, April 22, 2011

Visual Studio 2010 SP1 - hoops to jump

I have been running Visual Studio 2010 with Resharper and Productivity Power Tools extension in a Virtual Machine (Windows 7's Windows Virtual PC). Everything has been working fine until I decided to apply Visual Studio 2010 Service Pack 1. Here are the problems I've experienced:
1) To begin with, I made a mistake of running the SP1 installation "not" as an Administrator. The setup application didn't complain at all, but it ran for a loooong time (2+ hours!). It failed and rolled back fine, but it took too long. After I right-clicked, "Run as Administrator", it ran fine and finished after 20~30min.
2) After SP1 had been applied Visual Studio was veeery slow, even freezing at times. After some research I found that the culprit could be the Productivity Power Tools not playing well with ReSharper. I have to say that shortly before installing the SP1 I installed the latest version of the extension. After "disabling" the extension and restarting Visual Studio, everything seems to be ok, performance wise.
3) I experienced some flickering in Visual Studio after applying SP1 and noticed that the "Hardware Graphics Acceleration" checkbox was unchecked (Tools - Options - Visual Experience area). I set it back to checked, restarted VS and the flickering stopped...

Hopefully this will save yout time should you have these issues as well. Enjoy normality once again.

Tuesday, July 28, 2009

iTextSharp - Sending in-memory pdf in an email attachment

I was helping a client with the good old task of printing reports in a pdf format from an Asp.Net page, without having to use a commercial tool. I did a bit of research on iTextSharp and it appears to do everything I need. For instance, one of my goals was to be able to create a pdf file in memory and send it as an email attachment. Here's the code I used to do that:
(In this example I use gmail as my smtp server, so it makes it easier for you to try it for yourself)

var doc = new Document();
MemoryStream memoryStream = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream);

doc.Open();
doc.Add(new Paragraph("First Paragraph"));
doc.Add(new Paragraph("Second Paragraph"));

//Keeps the memoryStream object open when closing the Document (doc)
writer.CloseStream = false;
doc.Close();

//Moves the pointer to the beginning of the stream. Without this
//line an empty file is generated and attached to the email.
memoryStream.Position = 0;

MailMessage mm = new MailMessage("username@gmail.com",
"username@gmail.com")
{
Subject = "subject",
IsBodyHtml = true,
Body = "body"
};

mm.Attachments.Add(new Attachment(memoryStream, "filename.pdf"));
SmtpClient smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
Credentials = new NetworkCredential("username@gmail.com",
"password")

};

smtp.Send(mm);

Friday, April 17, 2009

Using views from EDM - Entity Framework

In one of my recent projects using Entity Framework/WPF I needed to have read-only data from 10+ different tables, and I decided to have a view in SQL Server, as opposed to have the joins generated from the EDM (Entity Data Model). The view exposed both nullable and non-nullable fields, including primary keys of the underlying tables. However, since I had outer joins, some of these primary keys exposed from the view could actually be null. In this scenario one must be careful and tweak the model, so that all data returned from the database can be materialized into entities.
If I used an indexed view I wouldn't have any issues, but the query in my view had multiple self-joins, which is a limitation of indexed-views, at least in SQL Server 2005 and 2008.

When a non-indexed view is added to the EDM, the framework tries to infer one of more entity keys from the database - it generates entity keys from the non-nullable fields. In the scenario described above, I had non-nullable fields (PKs) that could actually be null (because of outer joins in the view). In this case, during the enumeration of the items in the EntitySet, the data is retrieved from the database but it would not be able to be available as an Entity. In the middle of a foreach you could get an Object Null Reference exception.

To fix this problem you need to find one field in your view that won't be null, set it as the Entity Key, and remove the other keys the system automatically generates. You'd be tempted to right-click on the entity's field and uncheck "Entity Key", or to go to properties and set the Entity Key property to false. You can do these things, but you'd be only affecting the conceptual model - the CSDL. This is not enough. You need to view the EDM in its XML format, and remove the unwanted keys from the Storage Model (SSDL) as well.

Unfortunately, this works until you need to update the EDM from the database, which will regenerate the models and you'll lose your changes. The Entity Framework team knows about these sort of problems and will most likely try to address them shortly, whenever this may be.

I hope this post can help you prevent wasted debugging time.

Tuesday, December 30, 2008

Windows Presentation Foundation Unleashed (WPF) by Adam Nathan

I have read (or tried to read) other WPF books but this one is by far the easiest one to learn from, both in terms of readability (the colors really make a difference) and contents. It feels like each page has a gem of information. If I were to buy only one book about WPF, this would be the one.

Friday, December 26, 2008

Unity

I am trying to use the Composite Application Guidance (aka Prism or Composite WPF) for an application at work. It all sounded very interesting and easy to use, but when the rubber hit the road it turned out that I needed to be educated in some of the concepts it uses. For instance, I was not familiar with Dependency Injection. Prism uses Unity as the DI container and I thought I'd highlight some examples on how to use the Unity container:

Type Mapping - registered class:

container.RegisterType<IModule, ConcreteModule>();
IModule ModuleA = container.Resolve(<IModule>);


The first line is a type mapping. Anytime you need IModule, the container will return a ConcreteModule. the ModuleA object will have an instance of ConcreteModule.


Type Mapping - non-registered class:

The following class needs an instance of IModule:

Class ModuleA
{
ModuleA(IModule module)
{
...
}
}

Using Unity you can do the following:
container.RegisterType<IModule, ConcreteModule>();
ModuleA modA = container.Resolve<ModuleA>();


The first line is a type mapping. Anytime you need IModule, the container will return a ConcreteModule.
The second line requests a new instance of ModuleA. ModuleA is not registered with the container. But Unity will look at ModuleA's constructor and see that it needs a IModule. It will then inject an instance of ConcreteModule because of the 1st line's mapping.

Type Mapping - Singleton:
container.RegisterType<IModule, ConcreteModule>(new ContainerControlledLifetimeManager());
Every time you ask for an new instance, the same one is returned.

Named instances:
container.RegisterType<Database, SQLDatabase>("Sql");
container.RegisterType<
Database, OracleDatabase>("Oracle");
This will register two mappings of type Database and name these mappings for future use.

You can access the type by the name like so:
Database db = container.Resolve<Database>("Sql");
In this case, db will be a SQLDatabase.

Resolving all named instances
container.RegisterType<Database, SQLDatabase>("Sql");
container.RegisterType<
Database, OracleDatabase>("Oracle");
IEnumerable<
Database> databases = container.ResolveAll<Database>();
The object databases will contain two objects; one of type SQLDatabase and one of type OracleDatabase.

Adding instances to the container
Use container.RegisterInstance to add pre-created objects to the container. Unity assumes that these objects are to be kept as singleton.
container.RegisterInstance<Database>(new SQLDatabase());
container.RegisterInstance<Database>("Oracle", new OracleDatabase());


Adding dependencies to pre-existing objects with attributes

Assume the following class:

public class ModuleA: Module
{
[Dependency]
public IModuleInfo ModuleInfo {get; set; }
}

In this case, ModuleA has IModuleInfo as a dependency.

Below we're registering the IModuleInfo type with the container, instantiating a new ModuleA and asking Unity to add dependencies to the object:

container.RegisterType<IModuleInfo, TISModuleInfo>();
ModuleA modA = new ModuleA();
container.BuildUp(modA);


modA will then get an instance of TISModuleInfo in its ModuleInfo property.

Specifying dependencies through configuration (no attributes)

Assume the following class:
public class GenericDatabase: Database
{
private string connectionString;
public ILogger Logger { get; set; }
public GenericDatabase(string connectionString)
{
this.connectionString = connectionString;
}
container.RegisterType<ILogger, NullLogger>();
container.RegisterType<
Database, GenericDatabase>();
string connStrFromAppConfig = ConfigurationManager.ConnectionStrings["MyConnectionString"];
container.Configure<
InjectedMembers>().ConfigureInjectionFor<GenericDatabase>( new InjectionConstructor(connStrFromAppConfig), new InjectionProperty("Logger"));
Database db = container.Resolve<Database>();
container.RegisterInstance<Database>("Oracle", new OracleDatabase());


Here we're injecting dependencies through the Configure method of the container. Since the connection string is constructor parameter, we must use the InjectionConstructor class, and because Logger is just a property in GenericDatabase, we use the InjectionProperty class.

Nested containers

If the child container doesn't have what you're asking from it, it will look at the parent container.
To register child containers:
UnityContainer parent = new UnityContainer();
IUnityContainer child1 = parent.CreateChildContainer();
IUnityContainer child2 = parent.CreateChildContainer();

parent.RegisterType<IModule, GenericModule>(new ContainerControlledLifetimeManager());
child1.RegisterType<
IModule, ModuleA>(new ContainerControlledLifetimeManager());

IModule module1 = child1.Resolve<IModule>();
IModule module2 = child2.Resolve<IModule>();


In the code above, module1 will be of type ModuleA, and module2 will be of type GenericModule, since child2 looks at the parent container because it doesn't have the type IModule registered.

Tuesday, March 25, 2008

Object Initializers and LINQ


I first saw the C#3.0's "object initializers" in March 2007, at the Microsoft MVP Summit in Redmond, WA. The feature didn't strike me as a big deal. Ok, you can save lots of lines of code
and make your code more readable, but I thought, that's about it.
After some time learning about LINQ, lambda expressions, expression trees, etc, I now realize that object initializers are a fundamental and important part of C# 3.0.
They aren't just syntactical sugar. Take a look at an example:

Class Person is a plain old class:

public class Person

{
public string FName { get; set; }
public string Country { get; set; }
}



Before C# 3.0, in order to create a list of Person and populate with 5 new Person with the properties initialized, I would have do the following:

List people = new List();
Person p1 = new Person();
p1.FName = "Mary";
p1.Country = "United States";
people.Add(p1);
Person p2 = new Person();
p2.FName = "Raul";
p2.Country = "Argetina";
people.Add(p2);
Person p3 = new Person();
p3.FName = "Sergio";
p3.Country = "Brazil";
people.Add(p3);
Person p4 = new Person();
p4.FName = "Giuseppe";
p4.Country = "Italy";
people.Add(p4);
Person p5 = new Person();
p5.FName = "Jean";
p5.Country = "France";
people.Add(p5);


With C# 3.0 we can initialize a collection of Person like so:

var people = new List {
new Person { FName="Mary", Country="United States" },
new Person { FName="Raul", Country="Argentina" },
new Person { FName="Sergio", Country="Brazil" },
new Person { FName="Giuseppe", Country="Italy" },
new Person { FName="Jean", Country="France" } };



As you can see, using object (and collection) initializers results in a much more compact and readable code. Notice that the code in between the {} is actually an expression. Therefore, we can say that object initializers give us the "ability to initialize an object in an expression context".

Now, let's see how this feature relates to LINQ. I am assuming you know what LINQ is and have at least seen LINQ queries. The result of a LINQ query is a "projection", or in other words, it is a brand new object created on the fly. The structure of the object is really unknown, and that's the reason the "var" keyword is so important in LINQ (see Anonymous Types).

You can project the entire object as is:

var FrenchPeople = from p in people
where p.Country == "France"
select p;


Or project a completely different object. In the case below, I am projecting a string (Person's first name) preceded by "Mr. ":

var FrenchPeople = from p in people
where p.Country == "France"
select "Mr. " + p.FName;

When you do these projections, all you're really doing is using an "expression that creates a new object out of existing objects".

The point I am trying to make is that, when we use expressions like these in LINQ, we are inherently using object initializers. Without them, projections in LINQ the way we know them would be impossible. The whole LINQ feature would be a lot clunkier and the code would look a lot messier.

Wednesday, March 5, 2008

Implicitly-typed variables in Resharper 4.0

By now, most of us already know that Linq is everywhere, and therefore, also are anonymous types. To make anonymous types usable with Linq, implicitly-typed variables are required.

The "var" keyword tells the compiler to infer the type from what's on the right-side of the attribution. C# is a statically-typed language, and the “var” keyword doesn't change this.

When you compile the code into IL, you'll see the type explicitly used there. So what's the harm of using "var" all over the place?

Before jumping to the answer right away, I would like to refer you to Steve McConnell's Code Complete, where he reminds us that one should strive to write code that's easy to read. it sure is nice when code is both easy to write and read (like the newly added "automatic properties" C# 3.0 feature). But readability always prevails.

So, to answer my question about the harm of using "var" everywhere, I would say that it can be really harmful to readability.

Sure, if a variable declaration is like the following, there's no problem in using "var":


var baby = new Person();


It is obvious that the variable baby is of type Person. But imagine some method, badly named GetNewOne, returning a new Person object.


var baby = GetNewOne();


How in the world would you know that baby is of type Person? I know if you're using Visual Studio, you can simple hover the mouse over it. But I think I shouldn't rely on a tool to provide me with code readability.

In the example above I definitely want my code to be like this:


Person baby = GetNewOne(); //TODO: Refactor this method name please!!!

I've been playing with ReSharper 4.0 nightly builds on Visual Studio 2008 targeting .Net 3.5, and interestingly enough, every time you use something like "Person baby = GetNewOne()", ReSharper 4.0 will put a squiggly line small green line (hint) under Person, suggesting I should use the "var" keyword instead. See below.



ReSharper 4.0 is not out yet, and maybe (hopefully) this code suggestion will not be in the final version, but I thought it was interesting and wanted to share.

Thursday, February 28, 2008

MSDN Event here in Fresno!

Last night at the user group meeting I mentioned the launch event of Windows Server 2008, Visual Studio 2008 and SQL Server 2008. I forgot to mention that all attendees will get a promotional pack containing all three new products. You can go ahead and register for it here.

C# 3.0 Cookbook 3rd Edition - I Recommend!

I had the pleasure to work as a technical reviewer on C# 3.0 Cookbook 3rd Edition, by Jay Hilyard, Stephen Teilhet (O'Reilly).
It is a wonderful book with a pragmatic approach to solve common interesting problems.
Thank you O'Reilly for inviting me to work on this book.

C# 3.0 Presentation source code

JD Conley was kind enough to post the source code on his blog of the presentation he did last night, at Fresno State, for our Central California .Net User Group.
Thank you JD!

Saturday, February 23, 2008

Central California .Net User Grop meeting - Feb/27/2008

I am looking forward to next user group meeting, which will be presented by JD Conley, who will talk about C#3.0.
For more information visit www.centralcaldotnet.com

Friday, February 22, 2008

Problem with CD/DVD drive in Vista

I am not proud of having my inaugural blog post on how to fix a bug in Windows Vista.
I have been using Vista 64 and have encountered a few problems.
It started with my old logitech webcam, which I cannot find a vista driver for. I bought a Microsoft Lifecam to replace it, and, guess what, the thing didn't work right out of the box. I had to run a patch to fix something on the USB drivers of Vista 64 bits. It worked. It was funny to buy a brand new Microsoft peripheral incompatible with Vista 64.
The next problem I had was with my CD/DVD drive. After some windows update it appeared with a warning sign in Device Manager, saying that the driver was missing. I spent several minutes trying to find a more up-to-date driver for my drive (TSSTcorp TS-L632H - came in a Inspiron 1520). Also, my U3 thumb drive didn't work.

It turns out that the solution for this problem has nothing to do with driver, after all. All you have to do is
a) Go to the registry and find [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4D36E965-E325-11CE-BFC1-08002BE10318}
b) Make sure the class = CDROM
c) Delete both UpperFilter and LowerFilter keys.
d) reboot.

After I did this, both my CD/DVD drive and my U3 thumb drive (which works like a CD) work fine!

Other than these, and not being able to run my McAfee Viruscan on Vista, I haven't had any problems with Vista 64.