DECLARE @test varchar(10)
SET @test = '12/31/2011'
DECLARE @test_date datetime
SET @test_date = CONVERT(datetime, @test, 101)
Showing posts with label tips. Show all posts
Showing posts with label tips. Show all posts
Tuesday, June 14, 2011
T-SQL Convert string to datetime
This is the kind of stuff you don't wanna waste time on - and yet ...
Friday, December 17, 2010
How to load text files with jQuery
I was looking into this to help out @tarelli with one of his crazy tasks from hell (spare you the details). Here's how you go about loading local files using jquery:
// LOAD file
$.get('file:///C:/myPath/myFile.txt', function(data) {
var lines = data.split("\n");
$.each(lines, function(n, elem) {
$('#myContainer').append('<div>' + elem + '</div>');
});
});
This will only work if you double click on the file that executes the script, obviously a web-server shouldn't allow you to go mess around in the file system (I tried on IIS and couldn't fool it, damn). Obviously the same snippet can be used to load files on a web-server by providing a url to an accessible file.
Notes:
- couldn't get it to work without specifying the file full path in format file:///C:/myPath/myFile.txt
- to get this to work on chrome you'll have launch it with the --allow-file-access-from-files cmd line arg
Wednesday, February 3, 2010
GetProperties(BindingFlags.DeclaredOnly) returns no properties
If you're trying to use reflection to retrieve a list of properties and you want only the properties declared in a given type but not the inherited ones, msdn says you need to call GetProperty passing down the DeclaredOnly binding flag.
What msdn doesn't say is that if you just pass down DeclaredOnly you'll get nothing back (and if you ended up on this post through a google search that's probably the reason why).
In order to get back the properties you're looking for you need to pass down also the Public and Instance binding flags - smt like this should work:
var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
This is probably working "as designed" but could definitely make you waste a bit of time (as it did for me).
In the spirit of human hive intelligence - hope it helps some other average Joe out there.
In the spirit of human hive intelligence - hope it helps some other average Joe out there.
Friday, December 4, 2009
[WPF] How to programmatically add databound item to ListView
In this post I'll show how to programmatically add databound items to a WPF ListView - it's actually pretty straightforward but it's not the most intuitive task if you don't have a lot of experience with WPF.
Here's your xaml - pay attention to the bindings on the grid columns:
We need to define a data class with Name and Value properties such as:
And here comes the fun - how to programmatically add items to the ListView:
If you're thinking I post boring stuff ... well, you're right. Posts like this I mainly post so that I won't forget how it's done (and hopefully will be helpful to some other occasional WPF hacker).
Here's your xaml - pay attention to the bindings on the grid columns:
<ListView.View>
<GridView>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=Name}"/>
<GridViewColumn Header="Value" DisplayMemberBinding="{Binding Path=Value}"/>
</GridView>
</ListView.View>
public class BoringData
{
public string Name { get; set; }
public string Value { get; set; }
}
//utterly boring call to generate your data item
BoringData boredom = getBoringData(index);//<-- whatever
//add the item to the listView
this.myListView.Items.Add(boredom);
Tuesday, November 24, 2009
2 Obscure Javascript Features You Probably Don't Know About
I was going through the w3c javascript tutorial (I like the try it yourself sections ... yes - I am that kind of geek) and I spotted 2 pretty basic but obscure ECMAScript Javascript features I didn't know about.
Feature 1: the '===' operator!
That's right, that's a triple equal. What's it for? Well, you know javascript is not strongly typed, so you can cast a variable from a number to a string just assigning values to it. This triple = operator checks for equality of both value and type. Smart, uh? Also kinda horrible.
Feature 2: variable re-declaration!
Apparently you can re-declare a variable and the javascript interpreter couldn't care less. Moreover, if you re-declare a variable it will retain the same value as the previous homonymous variable had. Handy uh? Except it's plain twisted wrong.
Anyway, God bless

Monday, November 16, 2009
[.NET] How to swallow warnings
Well aware this is against all best practices, here's how you suppress all warnings coming from a given region of code:
This is way beyond cool - and might help you out when you can't change your code but you're being hovered by a frustrating policy of ZERO WARNING TOLERANCE.
Go forth and get it done.
#pragma warning disable
//All the warnings in here are swallowed!
#pragma warning restore
This is way beyond cool - and might help you out when you can't change your code but you're being hovered by a frustrating policy of ZERO WARNING TOLERANCE.
Go forth and get it done.
Tuesday, November 3, 2009
Quick and Dirty WPF ListView Customization
When in need of customizing a WPF ListView without much WPF experience, chances are you'll hit the wall soon enough on pretty trivial tasks.
This is a collection of recent posts appeared on this blog on the topic. I think the list covers most of the common basic ListView customization tasks.
- Hot to set row height
- How to set selected item background color
- How to set custom alternate row colors
- How to set scrollbar width
Hope this'll spare a good share of frustration to some of you cheap guys out there, pulling your hair trying to write xaml by hand rather than using some version of Expression Blend or the likes (as I did myself 'cause the 30-days trial expired and the boss wouldn't show the money).
Sunday, November 1, 2009
[.NET] How to bring window upfront
The stuff on this post can be easily integrated with a previous post:
How to Check if App is Already Running.
Here's a static method to bring a Window upfront in a given winApp (can be easily integrated with the previous post linked above):That'd be all - knock yourself out (tested on a number of XP and Vista machines).
In order to bring a window upfront you need to mess with win32 API calls - no easy way around (if you know any please give me a shout). Here's how to import the calls we'll be using:
//Win32 API calls to raise a given processs main window
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")]
private static extern bool IsIconic(IntPtr hWnd);
private const int SW_RESTORE = 9;
static class Program
{
// all the rest of the stuff ... Main other methods etc.
public static void BringOnFront()
{
Process myProcess = Process.GetCurrentProcess();
string myAsseblyName = Assembly.GetExecutingAssembly().GetName().Name;
foreach (Process processId in Process.GetProcessesByName(myAsseblyName))
{
if (myProcess.Id != processId.Id)
{
IntPtr hWnd = processId.MainWindowHandle;
if (IsIconic(hWnd))
{
ShowWindowAsync(hWnd, SW_RESTORE);
}
SetForegroundWindow(hWnd);
break;
}
}
}
}
Sunday, October 25, 2009
[.NET] How to check if app is already running
Here's a quick and dirty snippet (and sample usage) to check if your app is already running (using a Mutex).
static class Program
{
private static Mutex mutex;
public static bool IsThisProcessAlreadyRunning()
{
bool createdNew;
mutex = new Mutex(false, Application.ProductName, out createdNew);
return !createdNew;
}
///
/// The main entry point for the application.
///
[STAThread]
static void Main()
{
if (!IsThisProcessAlreadyRunning())
{
// whatever you might be doing
// here's some default form initialization
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
else
{
// do something!
// usually smt like --> BringOnFront();
}
}
}
Bringing the app to the foreground is usually what you'll want to do next in scenarios like this. A post about that might follow soon enough.
Side note - if you're using VB.NET I believe there is a check-box you can tick under application properties somewhere that does the job. I'll avoid making jokes about VB.NET 'cause life is tough enough for the suckers who use it without me being a jerk.
EDIT: 2009-11-01 --> posted How to Bring Window Upfront
Friday, September 4, 2009
How to set WPF ListView or ScrollViewer Scrollbar width
A pretty common dirty hack to modify the scrollbars width is to set the OS value for scrollbars width to whatever you need in your app - this obviously sucks as not only your application will be affected.
In WPF you can override scrollbars width in both ListView and ScrollViewer controls pretty easily with the following XAML markup.
1) Include mscorlib with the sys prefix (or whatever prefix you want) in the page declaration:
<Page x:Class="AtlasPrototype.VehicleIdHistory"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Title="VehicleIdHistory">
2) Override vertical scrollbar width resource for the ScrollViewer (exact same for a ListView):
<ScrollViewer>
<ScrollViewer.Resources>
<sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">60</sys:Double>
</ScrollViewer.Resources>
<-- other stuff -->
</ScrollViewer>
Sounds all cool and easy but I had to beg work hard on stackoverflow to get this figured out. Show due Respect.
Thursday, September 3, 2009
How to check if WPF is using Hardware or Software Rendering?
In general, software rendering will usually kick-in if your machine doesn't support DirectX or if the drivers installed are not working correctly (for whatever reason). WPF is entirely built on Direct3D, and software rendering means your WPF app will run painfully slow.
In borderline scenarios, such as running on portable device where hardware capability is constrained, you might find yourself in a bit of a mexican standoff situation where you don't know if the bottleneck is the hardware itself or the problem is just that hardware acceleration is not working and the system falls back to software rendering. So, how do you check if software rendering is kicking in?
You can do this from code querying the RenderCapability.Tier property, as follows:
//shifting some 16 bits will do the trick
int renderCapabilityTier = (RenderCapability.Tier >> 16);
- 0 --> you're screwed - no hardware acceleration
- 1 --> you're half screwed - you got some hardware acceleration
- 2 --> you're good to go with full blown hardware acceleration
You might also wanna run the DirectX diagnostic tool (just run dxdiag.exe) to double check the state of your hardware acceleration (check the display tab) and, since we are at it, the new WPF profiler.
Wednesday, August 26, 2009
How to set WPF ListView alternate row color
Another common task you might have to tackle when working with WPF ListView is setting the background color for the rows in an alternate fashion (odd rows and even rows - you know what I mean).
This is how you do it.
First thing, create a style element in your ResourceDictionary or if you don't have one drop it on the page itself:
Now set the ItemContanerStyle on the actual ListView and set the AlternationCount attribute):
And this is all there is to it!
This is how you do it.
First thing, create a style element in your ResourceDictionary or if you don't have one drop it on the page itself:
<Style x:Key="alternatingListViewItemStyle" TargetType="{x:Type ListViewItem}">
<Style.Triggers>
<!-- setting up triggers for alternate background colors -->
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="LightGray"></Setter>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="2">
<Setter Property="Background" Value="White"></Setter>
</Trigger>
</Style.Triggers>
<!-- setting row height here -->
<Setter Property="Height" Value="30" />
</Style>
Now set the ItemContanerStyle on the actual ListView and set the AlternationCount attribute):
<ListView Name="recordContainer" ItemContainerStyle="{StaticResource alternatingListViewItemStyle}" AlternationCount="2" >
<ListView.View>
<GridView>
<!-- Just a few sample columns -->
<GridViewColumn Header="aField" />
<GridViewColumn Header="anotherField" />
<GridViewColumn Header="yetAnotherField" />
</GridView>
</ListView.View>
<!-- Whatever you might have in here -->
</ListView>
And this is all there is to it!
Friday, August 14, 2009
How to set WPF ListView selected item background color
After my last post I came across another common WPF task that could result in excruciating frustration if you're not using Expression Blend (or you just don't know enough about this shit nice framework): setting the color of the selected item in a ListView.
This is how you do it:
<ListView>
<ListView.Style>
<Style TargetType="{x:Type ListView}">
<Setter Property="BorderBrush" Value="Black"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Margin" Value="0"/>
<!-- here we go -->
<Style.Resourcesgt>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Black"/>
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Gray"/>
</Style.Resources>
</Style>
</ListView.Style>
<!-- other stuff -->
<ListView>
Hope it helps - if so you can express your gratitude by randomly upvoting some of my answers on stackoverflow.
Friday, August 7, 2009
How to set row height in WPF ListView
I've been checking out WPF lately for some prototyping work and came across something that's gotta be a very common show-stopper for beginners: I had a ListView element setup as a grid and no clue about how to set row height (without increasing font text - should go without saying).
This is a nice way of doing it (thanks stackoverflow):
<ListView>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="Height" Value="50" />
</Style>
</ListView.ItemContainerStyle>
<!-- WHATEVER -->
</ListView>
That's what you get if you try to do some WPF magic without an Expression Blend license, which reminds me the good old days of editing html manually and feeling a God (except the God part).
Tuesday, June 9, 2009
Google App-Engine Mail Service: Unauthorized Sender Error
I was messing around with the Google App-Engine mail service and I stumbled upon a little gotcha that I feel like sharing.
To cut a long story short - you can send emails though the mail service only from emails of accounts (google accounts or other Google app domains) registered as Developers from the Google app engine dashboard (Google App-Engine--> Dashboard--> Developers).
It took me a while to figure this out because:
But then - I can only blame myself 'cause the documentation clearly says:
As a matter of fact, I never read the documentation till I am desperate (who does?).
To cut a long story short - you can send emails though the mail service only from emails of accounts (google accounts or other Google app domains) registered as Developers from the Google app engine dashboard (Google App-Engine--> Dashboard--> Developers).
It took me a while to figure this out because:
- It doesn't make any sense: assume you wanna setup an admin account to send out mini-reports from your scheduled cron jobs, in this scenario you're supposed to setup your admin@yourDomain.com as a Developer!?
- I am linking this Google app deployed to appspot to a domain I have registered with Google, so I thought the app could send emails only from accounts registered as administrator of my given domain, which would make slightly more sense!
The sender must be either the address of a registered developer for the application, or the address of the user for the current request signed in with a Google Account.
Saturday, May 23, 2009
[SQLServer2005] Select from Excel Spreadsheet for SQL-Rejects
This is DBA bread and butter - not being a DBA and having no will whatsoever to become one (I am too weak) I always forget the syntax for this procedure, so here we go.
In order to be able to query an excel spreadsheet we need to enable ad hoc distributed queries, to do so follow the procedure in this other post.
Once that's sorted - assuming you have an excel spreadsheet with column names (in the example I have Column1, Column2, Column3, Column4) in the first row - this is how you go about selecting the spreadsheet content into a temporary table:
USE myDB
-- drop temp table
DROP TABLE #tempTable
-- select spreadsheet content into #tempTable
SELECT S.[Column1], S.[Column2], S.[Column3], S.[Column4]
INTO #tempTable
FROM OPENROWSET
('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\mtSpreadsheet.xls;HDR=YES',
'select * from [Query1$]') AS S;
-- check if the stuff is there
select *
from #tempTable
That's it. Hope it helps some other fellow SQL-Reject.
Wednesday, May 20, 2009
[SQLServer2005] Enable Ad hoc distributed queries
The Ad Hoc Distrubuted Queries advanced feature is disabled by default - it needs to be enabled if you wanna run OpenRowSet or OpenDataSource operations (queries on excel spreadsheets and other stuff).
To enable it run the following script and you should be OK:
-- allows you to see advaced options status
sp_configure 'show advanced options', 1
RECONFIGURE
GO
-- enables Ad Hoc Distributed Queries
sp_configure 'Ad Hoc Distributed Queries', 1
RECONFIGURE
GO
-- shows you the full list of features
sp_configure
The same result can be achieved by opening SQL Server Area Configuration tool for features and after picking Ad Hoc Distributed Queries ticking the "Enable ..." checkbox.
That'd be all.
Sunday, May 3, 2009
[Google App Engine] How to Clear SDK Datastore
To clear the SDK datastore you'll just have to delete the following file: "./WEB-INF/appengine-generated/local_db.bin". The file will be generated for you again next time you run the development server and you'll have a clear db.
This is one of the little gotchas that come in handy when you start playing with the Google Application Engine. You'll find yourself persisting objects into the datastore then changing the JDO object model for your persistable entities ending up with a obsolete data that'll make your app crash all over the place.
Thursday, April 30, 2009
[SQL] How to escape single quotes in the words of Pinal Dave
I will answer this SQL riddle in the words of Pinal Dave:
The man is a SQL master, and if you're a Jr.Developer (I am not but when it comes to SQL I am probably less than that) you gotta follow him on twitter.
Another way of injecting single quotes using CHAR(39):
I did my worst - as usual.
In case you need it (I doubt it) he also provides a great example.Jr. Developer asked me other day how to escape single quote?User can escape single quote using two single quotes (NOT double quote).
The man is a SQL master, and if you're a Jr.Developer (I am not but when it comes to SQL I am probably less than that) you gotta follow him on twitter.
Another way of injecting single quotes using CHAR(39):
DECLARE @IanQuigley as varchar(MAX)
SET @IanQuigley = 'Thanks, I don' + CHAR(39) + 't know much about SQL'
I did my worst - as usual.
Wednesday, March 4, 2009
How to figure out which SQL2000 edition is installled
I recently had the problem to understand which edition (standard/developer) was installed on an old machine. This sounds like a pretty straightforward thing to do - and it is indeed IF you know you need to run the following query:
SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')
You'd imagine you could figure this out looking at the 'about' information in enterprise manager (as in SQL2005 in SQL Management Studio) but that doesn't seem to be the case. I couldn't find any other solution.
Mysteries of MS faith.
Subscribe to:
Posts (Atom)