Sometimes when you move a database to another server it is necessary to change the login for a user to match the new environment. You can use the alter user command to do this. Do something like the following:
ALTER USER [THE_USER_NAME] WITH NAME = NEW_USER_NAME, LOGIN = [MACHINENAME\NEW_USER_NAME];
Not really complicated, but handy when you need it.
We use the following script to have our linux machine automatically start playing audio at startup. Every day another radio station will be played with a random choice for some days. It could use some functions to make it a bit tidier, but I’m satisfied with it at this point.
#!/bin/bash
# Arrow Classic Rock
radio_stations[0]=http://www.garnierstreamingmedia.com/asx/streamerswitch.asp?stream=205
# City FM
radio_stations[1]=http://streams.cityfm.nl:8043/listen.pls
# QMusic
radio_stations[2]=http://vip2.str.reasonnet.com/qmusic.mp3.96
# Eagle FM
radio_stations[3]=http://www.181.fm/asx.php?station=181-eagle
#current day of week, 0 is sunday
curr_day_of_week=$(date +%w)
case $curr_day_of_week in
0)
number=$RANDOM
let "number %= ${#radio_stations[@]}"
/usr/bin/vlc ${radio_stations[$number]}
;;
1)
/usr/bin/vlc ${radio_stations[0]}
;;
2)
/usr/bin/vlc ${radio_stations[1]}
;;
3)
/usr/bin/vlc ${radio_stations[2]}
;;
4)
/usr/bin/vlc ${radio_stations[3]}
;;
5)
number=$RANDOM
let "number %= ${#radio_stations[@]}"
/usr/bin/vlc ${radio_stations[$number]}
;;
6)
number=$RANDOM
let "number %= ${#radio_stations[@]}"
/usr/bin/vlc ${radio_stations[$number]}
;;
esac
Here is a short macro that will attach the debugger to the first w3wp.exe process it can find in the process list. (Script assumes a w3wp.exe process is running. Expect error messages if it doesn’t
)
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics
Public Module Famvdploeg
'Attach the debugger to a w3wp.exe process
Sub AttachDebugger()
Try
'Get your hostname
Dim hostname As String = System.Net.Dns.GetHostName
'Load the debugger interface
Dim debugger As EnvDTE80.Debugger2 = DTE.Debugger
'Get a local transport, (this is the "Default")
Dim trans As EnvDTE80.Transport = debugger.Transports.Item("Default")
'Attach to the first w3wp.exe command which we find
Dim dbgeng(3) As EnvDTE80.Engine
dbgeng(0) = trans.Engines.Item("T-SQL")
dbgeng(1) = trans.Engines.Item("T-SQL")
dbgeng(2) = trans.Engines.Item("Managed")
Dim process As EnvDTE80.Process2 = debugger.GetProcesses(trans, hostname).Item("w3wp.exe")
process.Attach2(dbgeng)
Catch ex As System.Exception
MsgBox(ex.Message)
End Try
End Sub
End Module
Made up this extension method for XDocuments to be able to return an Expando object on which the properties of the XML can be navigated. This is still a little bit rough. I found out there is a ElasticObject that probably works a lot better. But this is just a little ‘proof of concept’.
Note that attributes in the XML are not bound in the Expando object.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
using System.Xml.Linq;
namespace Famvdploeg.Com
{
public static class XDocumentExtensions
{
public static dynamic ToExpandoObject(this XDocument document)
{
return ParseNode(document.Root);
}
private static dynamic ParseNode(XElement item)
{
dynamic expando = new ExpandoObject();
var props = expando as IDictionary<string, object>;
/* Properties of current node. Single and Lists are created here dynamic */
IEnumerable<IGrouping<string, XElement>> groupedProperties = item.Elements().Where(element => !element.HasElements).GroupBy(x => x.Name.ToString());
foreach (IGrouping<string, XElement> propertyGroup in groupedProperties)
{
int nrElements = propertyGroup.Count();
if (nrElements == 1)
{
props[propertyGroup.Key.ToValidPropertyName()] = propertyGroup.First().Value;
}
else
{
var multipleValues = new List<string>();
foreach (XElement element in propertyGroup)
{
multipleValues.Add(element.Value);
}
props[propertyGroup.Key.ToValidPropertyName()] = multipleValues;
}
}
/* Children of current node. Single and Lists are created here dynamic */
IEnumerable<IGrouping<string, XElement>> groupedElements = item.Elements().Where(element => element.HasElements).GroupBy(x => x.Name.ToString());
foreach (IGrouping<string, XElement> elementGroup in groupedElements)
{
int nrElements = elementGroup.Count();
if (nrElements == 1)
{
props[elementGroup.Key.ToValidPropertyName()] = ParseNode(elementGroup.First());
}
else
{
var multipleElements = new List<dynamic>();
foreach (XElement element in elementGroup)
{
multipleElements.Add(ParseNode(element));
}
props[elementGroup.Key.ToValidPropertyName()] = multipleElements;
}
}
return expando;
}
}
}
September 26th, 2011
Wytze
This is supposed to be a cheatsheet for some common elements in Grails.
It’s a little bare at the moment but I hope that in time it will be a nice mashup of different Grails elements.
Grails Cheatsheet
Constraints
static constraints = {
propertyName(
blank: false,
nullable: false,
inList: ['a', 'b'], //Or reference property here
matches: '[0-9]+',
minSize: 1,
maxSize: 10,
min: 1,
max: 10,
range: 1..10,
unique: true,
url: true,
email: true,
notEqual: "passwd", //Or reference property here
validator: { val, obj ->
return val != obj.propertyName
},
/* Display Options */
attributes: [year: 2000..2011], //Adds extra attributes to item when rendered.
password: true, //Indicate that this is a password field
widget: 'textarea', //Choose what widget will be used to render this item.
//textField, hiddenField, submitButton, field, textArea, form, actionSubmit, actionSubmitImage, datePicker, renderNoSelectionOption, timeZoneSelect, localeSelect, currencySelect, select, checkBox, radio
display: false //Hide this item when scaffolding
)
}
Persistence Callbacks
- beforeInsert – Executed before an object is initially persisted to the database
- beforeUpdate – Executed before an object is updated
- beforeDelete – Executed before an object is deleted
- beforeValidate – Executed before an object is validated
- afterInsert – Executed after an object is persisted to the database
- afterUpdate – Executed after an object has been updated
- afterDelete – Executed after an object has been deleted
- onLoad – Executed when an object is loaded from the database
Sample:
def beforeInsert() {
doSomething()
}
def beforeUpdate() {
if (isDirty('fieldName')) {
doSomething()
}
}
Showing SQL-queries
Edit the DataSource.groovy file in the Configuration directory and add the following to the hibernate section (preferably in non-production environments):
hibernate {
show_sql = true
}
September 18th, 2011
Wytze
First install tomcat and tomcat on your ubuntu machine if you have not already done so.
sudo apt-get install tomcat6 tomcat6-admin postgresql
Setup the required PostgreSQL database on ubuntu. We will connect to it as a JNDI DataSource later on.
-- Connect to the database from command line
psql -d postgres
CREATE USER userName WITH PASSWORD 'yourPassword';
CREATE DATABASE databaseName;
GRANT ALL PRIVILEGES ON DATABASE databaseName TO userName;
Get the postgreSQL JDBC driver.
cd /usr/share/tomcat6/lib
sudo wget http://jdbc.postgresql.org/download/postgresql-9.1-901.jdbc3.jar
Create a Tomcat Context configuration for your grails webapp.
sudo vi /etc/tomcat6/Catalina/localhost/yourappname.xml
Fill it with something like the following, (adapted to your webapps name / context root of course)
<Context path="/yourContextPath" reloadable="false">
<Resource name="jdbc/yourName" auth="Container"
type="javax.sql.DataSource" driverClassName="org.postgresql.Driver"
url="jdbc:postgresql://127.0.0.1:5432/mydb"
username="myuser" password="mypasswd" maxActive="20" maxIdle="10"
maxWait="-1"/>
</Context>
We’re almost there. Update DataSource.groovy
production {
dataSource {
dbCreate = "update"
jndiName = "java:comp/env/jdbc/yourName"
}
}
Awesome! Restart tomcat (sudo /etc/init.d/tomcat6 restart). Build (grails prod war) and deploy (copy file to /var/lib/tomcat6/webapps) your grails webapp and go bananas!
November 30th, 2010
Wytze
Trailing spaces or tabs is something I dislike. Using the combination CTRL+R, CTRL+W you can show the whitespace distribution in VS. But screening the lines one by one is a tedious job. That’s why we are going to use regular expressions. Regular expressions in VS are a bit of an odd duck as the syntax is not nice and Perly.
You can read more about regular expressions in Visual Studio here.
Putting this together we get the following:
Find what: ^{.@}:b+$
Replace with: \1
This will seach those nasty trailing whitespaces and remove them.
{.@} -> Match everything, non-greedy. This is our capturing group.
:b+$ -> Match one or more spaces or tabs before the end of the line.
Optionally:
You can add the following macro to Visual Studio (and bind some keystroke):
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics
Public Module Famvdploeg
'Remove trailing whitespace from document
Sub RemoveTrailingWhitespace()
DTE.Find.FindReplace(vsFindAction.vsFindActionReplaceAll, "( |\t)+$", vsFindOptions.vsFindOptionsRegularExpression, String.Empty, vsFindTarget.vsFindTargetCurrentDocument, , , )
End Sub
End Module
November 18th, 2010
Wytze
Here’s a small example how you can update a table from a select statement.
UPDATE Contact
SET Contact.Surname = x.Surname
FROM (
SELECT Id, SUBSTRING(Surname, Len(Insertion) + 2, LEN(Surname) - Len(Insertion)) AS Surname
FROM Contact
WHERE Insertion IS NOT NULL
AND Insertion <> ''
AND CHARINDEX(Insertion + ' ', Surname) = 1) x
WHERE Contact.Id = x.Id;
Using a join is also possible.
UPDATE c
SET c.Body = x.Body, c.Summary = x.Summary
FROM Content c
JOIN PageContent x ON c.ID = x.ID;
There are several ways to do this I guess. What I wanted was a default css class which I could apply to an anchor tag and have a specific part of the content loaded in fancybox. This is what I came up with. It is also possible to do this with the ajax property of fancybox itself I suppose.
$(function () {
$("a.ajaxcontent").click(
function (event) {
event.preventDefault();
var url = jQuery(this).attr("href");
$.get(
url,
function (data) {
var content = jQuery(data).find("#content");
$.fancybox(content);
}
);
}
);
});
Although you can use the export tool from microsoft. I just wrote a small C# app to do the same thing. Below is the code.
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.IO;
namespace ExportImages
{
public class Program
{
static void Main(string[] args)
{
Program program = new Program();
program.ExportImages();
}
private void ExportImages()
{
string connectionString = String.Format("Server=<servername>; Database=<databasename>; Integrated Security=SSPI");
using (SqlConnection connection =
new SqlConnection(connectionString))
{
try
{
connection.Open();
SqlDataAdapter data = new SqlDataAdapter(
@"select Id, Thumbnail from Images", connection);
DataSet ds = new DataSet("images");
int recordsFound = data.Fill(ds);
for (int index = 0; index < recordsFound; index++)
{
int id = (int) ds.Tables[0].Rows[index]["Id"];
byte[] imageData = (byte[]) ds.Tables[0].Rows[index]["Thumbnail"];
int imageSize = imageData.GetUpperBound(0);
FileStream fs = new FileStream(@"F:\images\" + id + "_thumbnail.jpg", FileMode.OpenOrCreate, FileAccess.Write);
fs.Write(imageData, 0, imageSize);
fs.Close();
}
}
catch (SqlException e)
{
Console.WriteLine(e.Message);
}
finally
{
if (connection.State != ConnectionState.Closed)
{
connection.Close();
}
}
}
}
}
}