Wednesday, August 24, 2011

How to do vertical alignment for UILabels

I wrote something about that but I don't remember where :). Anyway, the easiest way is to add a method to the UILabel class.

Include in your file (or create a new one) this interface to extend the current UILabel one:
@interface UILabel (VerticalAlign)
- (void)alignTop;
@end
Add the method code in the .m file:
- (void)alignTop {
    CGSize fontSize = [self.text sizeWithFont:self.font];
    double finalHeight = fontSize.height * self.numberOfLines;
    double finalWidth = self.frame.size.width;    
    CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];
    int newLinesToPad =
(finalHeight  - theStringSize.height) / fontSize.height;
    for(int i=0; i
        self.text = [self.text stringByAppendingString:@"\n "];
}

Done, now you can use this new method
[YourUILabel alignTop];

Hope help!

Wednesday, August 17, 2011

How to install ImageMagick in a Mac for MAMP

Hello,

First of all we need some tools:

For installing MacPort download the last version and on a terminal write:
$ sudo port selfupdate
If it doesn't work it's because you need to add the new path to the system PATH variable, ie:
$ export PATH=$PATH:/opt/local/bin
$ export MANPATH=$MANPATH:/opt/local/share/man
$ export INFOPATH=$INFOPATH:/opt/local/share/info
Now, we can install the ImageMagick and GhostScript
$ sudo port install ImageMagick
$ sudo port install ghostscript
Now it's time to configure the MAMP
$ vi /Applications/MAMP/Library/bin/envvars
and comments the lines

#DYLD_LIBRARY_PATH="/Applications/MAMP/Library/lib:$DYLD_LIBRARY_PATH"
#export DYLD_LIBRARY_PATH
and add a new line at the end of the file
export PATH="$PATH:/opt/local/bin"
and done!!!

Try it out
exec(‘convert -resize 640×480 -quality 70 test.eps test.jpg’);

Hope help!

Friday, July 15, 2011

How to connect using PHP to Oracle DB

Hi again. Today an brief explanation about how to install OCI8 for PHP.

1) We need to install PEAR

$sudo apt-get install php-pear libaio1 php5-dev

php-pear the PHP extensión
libaoi1 is th Linux kernel AIO access library
php5-dev because we need the command phpize

2) Download the Oracle Instant Client from the official Oracle website (you need to create an account) and download the files

instantclient-basic-linux32-XX.X.X.X.X.zip
instantclient-sdk-linux32-XX.X.X.X.X.zip

3) Create your own tree of directories

$ sudo mkdir -p /opt/oracle
$ sudo cd /opt/oracle
$ sudo unzip instantclient-basic-linux32-XX.X.X.X.X.zip
$ sudo unzip instantclient-sdk-linux32-XX.X.X.X.X.zip
$ sudo mv instantclient_XX_X instanclient

4) Set some soft links
$ sudo ln -s libclntsh.so.10.1 libclntsh.so
$ sudo ln -s libocci.so.10.1 libocci.so

5) Install the OCI module (needs php5-dev)
$sudo pecl install oci8
...
[path]: instantclient,/opt/oracle/instantclient

6) Add to /etc/php5/apache/php.ini the line
extension=oci8.so

7) Reset apache services and... voila!!

Hope help

Tuesday, July 5, 2011

iPhone: Determining available memory programmatically

Hi, here it's the way I use to determine the available memory in my apps. I have a class with an static method where I use the Mach VM statistics


#import <mach/mach.h>
#import <mach/mach_host.h>

+(void) print_free_memory {
mach_port_t host_port;
mach_msg_type_number_t host_size;
vm_size_t pagesize;

host_port = mach_host_self();
host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
host_page_size(host_port, &pagesize);

vm_statistics_data_t vm_stat;

if (host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size) != KERN_SUCCESS)
NSLog(@"Failed to fetch vm statistics");

/* Stats in bytes */
natural_t mem_used = (vm_stat.active_count +
vm_stat.inactive_count +
vm_stat.wire_count) * pagesize;
natural_t mem_free = vm_stat.free_count * pagesize;
natural_t mem_total = mem_used + mem_free;
NSLog(@"used: %u free: %u total: %u", mem_used, mem_free, mem_total);
}


The original code version was created by Landon Fuller.

Hope help.

How to remove subviews from a UIScrollView

Easy peasy,

The only thing we need to do is go through all subviews and remove from superview. For example:



NSArray* subviews = [NSArray arrayWithArray: scroll.subviews];
for (UIView* view in subviews) {
if ([view isKindOfClass [UIImageView class]]) {
[view removeFromSuperview];
}
}
[subviews release];


Hope help!!

Sergio

Wednesday, June 29, 2011

Formating date and time in a datagridview in C#

Hi,
The easiest way to format a datetime variable on a datagridview is to set the cell style. For example:



dataGridView1.Columns[1].DefaultCellStyle.Format = "dd'/'MM'/'yyyy hh:mm:ss tt";


If we only need the time, this is my case, we will write


dataGridView1.Columns[1].HeaderText = "Time";
dataGridView1.Columns[1].DefaultCellStyle.Format = "hh:mm";


Hope help!

Sunday, June 12, 2011

iPhone Notifications with NSNotificationCenter

Hi,

How can we send a message to a function when some event happen? For example, today I was writing a function which download an XML file and when it finish send a notification to another function indicating "hey! do something, I've finished my job".

Well, it's very easy:

1) Add an observer to the defaultCenter
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectorDoSomething) name:@"DoSomething" object:nil];

...

-(void) SelectorDoSomething {
// Code here
}

...


- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}



2) Post the notification from other function (or class)
[[NSNotificationCenter defaultCenter] postNotificationName:@"DoSomething" object:self userInfo:nil];



And... done! You have your notifications working.

Hope help

Friday, May 27, 2011

MySQL backup on Linux using CRON

Hi,

I'm goint to show you how to set up an automatic mySQL backup script using Shell script, Perl and CRON.

First of all, we must create an user with the minimum privileges for using only mysqldump so I will set the LOCK TABLES privilege for the database which I want to dump. The command I use is:

mysqldump -uUSER -pPASSWORD --opt DATABASE > /backupfile.sql


Next step is to compress the resulting file, por example using

tar -czf BACKUPFILECOMPRESSED.tar.gz backupfile.sql


Now we can move our file wherever we want or sent it by email...

The final step is to include the script into the cron config file /etc/crontab. FOr example, I want to execute my scripts from Monday to Saturday three times per day at 11:15, 14:15 and 18:15.

15 11,14,18 * * 1-6 USER /PATH/SCRIPT


restart the cron services

/etc/init.d/cron restart


and done!.

Hope help

Wednesday, May 25, 2011

IPTABLES and pure-ftpd

Hello,

Today I've needed to set up a server using ssh with NO ftp and NO web servers. First of all, I've configured the ftp server for upload my files. More problems... my pc is on a secure network and I cannot use ssh so... I've used a ssh connection under a vpn.

I've decided to set up a pure-ftpd server on a JEOS linux distribution:

#apt-get install pure-ftpd


To give access to my server I've opened the 21 port using IPTABLEs

iptables -I INPUT 2 -p tcp --dport 21 -j ACCEPT
iptables -I INPUT 2 -p udp --dport 21 -j ACCEP
T

If you want to set it forever you can create a firewall script in your /etc/init.d folder, for example something like

#!/bin/sh
PATH=/bin:/usr/bin:/sbin:/usr/sbin

IPTABLES=/sbin/iptables

$IPTABLES -P INPUT ACCEPT
$IPTABLES -P OUTPUT ACCEPT
$IPTABLES -P FORWARD ACCEPT

# Delete old rules
$IPTABLES -F

echo -n "Setting firewall rules... "
test $# -eq 1 && test $1 = "stop" && echo "stopped." && exit 0

###### ICMP
$IPTABLES -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
$IPTABLES -A OUTPUT -p icmp --icmp-type echo-request -j ACCEPT
$IPTABLES -A INPUT -p icmp --icmp-type echo-reply -j ACCEPT
$IPTABLES -A OUTPUT -p icmp --icmp-type echo-reply -j ACCEPT
$IPTABLES -A INPUT -p icmp -m state --state INVALID -j DROP
$IPTABLES -A OUTPUT -p icmp -m state --state INVALID -j DROP
$IPTABLES -A INPUT -p icmp -j DROP
$IPTABLES -A OUTPUT -p icmp -j DROP
######

$IPTABLES -A INPUT -s localhost -j ACCEPT
$IPTABLES -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Web and FTP
$IPTABLES -A INPUT -p tcp -m state --state NEW --dport 80 -j ACCEPT
$IPTABLES -A INPUT -p tcp -m state --state NEW --dport 21 -j ACCEPT
$IPTABLES -A INPUT -p udp -m state --state NEW --dport 21 -j ACCEPT

... more rules ...

# Deny the rest
$IPTABLES -P INPUT DROP

echo " [done]"


We can use nmap for checking if the port is open from another computer

#nmap -p 21 SERVER_IP


and the rules from our server

#iptables -L -n -v


or see our net status

#netstat -putan


Next step is to configure the users, so I've created a new system user

adduser NEW_USER

and I add this user to the pure-ftp list of users

pure-pw user add NEW_USER -u NEW_USER -d /home/NEW_USER

That's all. Everything is working now.

Hope help

Sunday, May 15, 2011

Problem with self.window.rootViewController on iPad 3.2

Today I've needed to fix a graphical mistake in one application. The problem is that this application must work on different iOS versions and I can not use the rootViewController in the app delegate in the way:

self.window.rootViewController = self.viewController;


Finally, I found the solution doing the next.

1) Change this line in the app delegate and replace it by

[self.window addSubview:self.viewController.view];


2) Open MainWindow.xib and select the UIViewController. Check "Resize View From XIB" in the attributes inspector

3) Set the view’s frame to applicationFrame programmatically. For example:

CGRect appFrame = [[UIScreen mainScreen] applicationFrame];
appFrame = CGRectMake(0, 20, appFrame.size.width, appFrame.size.height);

self.viewController.view.frame=appFrame;


Next time I will explain how to know which iOS version is running in our device.

Hope help!

Saturday, May 7, 2011

How to convert NSData to NSString

Hi,

Today I need to extract and XML string from a NSData and it's something easy but not trivial

NSString* string = [[NSString alloc] initWithData:theData encoding:NSASCIIStringEncoding];


Hope help

Friday, April 22, 2011

Set UIColor from Hex Color in iPhone

We define the HexColor in our .h file

#define HexColor(color) [UIColor
colorWithRed:((color)&0xFF)/255.0
green:((color>>8)&0xFF)/255.0
blue:((color>>16)&0xFF)/255.0
alpha:((color>>24)&0xFF)/255.0]


Then we can set the color from the hex color string

unsigned int colorValue;

[[NSScanner scannerWithString: colorString] scanHexInt: &colorValue];
UIColor *color = HexColor(colorValue);


being the colorString AARRGGBB where

AA = alpha
RR = red
GG = gren
BB = blue

Another options I've seen on the Internet


// As a C function:
UIColor* UIColorFromRGB(NSInteger rgbValue) {
return [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0
green:((float)((rgbValue & 0xFF00) >> 8))/255.0
blue:((float)(rgbValue & 0xFF))/255.0
alpha:1.0];
}



// As an Objective-C function:
- (UIColor *)UIColorFromRGB:(NSInteger)rgbValue {
return [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0
green:((float)((rgbValue & 0xFF00) >> 8))/255.0
blue:((float)(rgbValue & 0xFF))/255.0
alpha:1.0];
}



Cheers!

Wednesday, April 13, 2011

Combobox in datagridviews binding classes and structures

Hi, my problem today is how to show the list of data from an structure into a datagridview using combobox in some columns.

First of all I was surfing on the internet and I found this for enums:

//CF: set to null before setting it to the current to
//clear out previous results
this.bindingSource1.DataSource = null;

this.bindingSource1.DataSource = MyDal.GetDataTable();

void _formatStatusColumn()
{
DataTable dt = new DataTable("Status");

//CF: actually how it's stored in the db.
dt.Columns.Add("Status", typeof(int));
dt.Columns.Add("Status_Name", typeof(string));

//CF: this way I can add or remove enum values, and
//the combo will always reflect the correct values.
foreach(int index in Enum.GetValues(typeof(Status)){
dt.Rows.Add(index, Enum.GetName(typeof(Status), index));
}

//CF: now for the UI column
DataGridViewComboBoxColumn statusColumn =
new DataGridViewComboBoxColumn();

//CF: seems to control where the column is placed.
statusColumn.DisplayIndex = 3;
statusColumn.HeaderText = "Status";

statusColumn.DataPropertyName = "Status";
statusColumn.DataSource = dt;
statusColumn.DisplayMember = "Status_Name";
statusColumn.ValueMember = "Status";

this.dataGridView1.Columns.Add(statusColumn);
}


This was very useful but I need something easier. I have to read a list and show the field in the combobox, so I've changed the code like that:

public void FormatResidenceColumn()
{
if (this.dataGridView1.Columns.Count > 0)
{
DataTable dt = new DataTable("Residence");

dt.Columns.Add("Residence", typeof(int));
dt.Columns.Add("Residence_Name", typeof(string));

this.dataGridView1.Columns.Remove("Residence");

if (Globals.ListOfResidences.Count > 0)
{
foreach (Residence obj in Globals.ListOfResidences)
{
dt.Rows.Add(obj.Id - 1, obj.Alias);
}
}
else
{
// Empty
dt.Rows.Add(0, "Empty");
}

//CF: now for the UI column
DataGridViewComboBoxColumn combColumn =
new DataGridViewComboBoxColumn();

//CF: seems to control where the column is placed.
combColumn.DisplayIndex = 4;
combColumn.HeaderText = "Residencia";

combColumn.DataPropertyName = "Residence";
combColumn.DataSource = dt;
combColumn.DisplayMember = "Residence_Name";
combColumn.ValueMember = "Residence";

this.dataGridView1.Columns.Add(combColumn);
}
}


where I use an global variable named ListOfResidence in this example.

Hope help!!

Sunday, April 3, 2011

How to launch Apple Store from my iphone code

Hi,

Today I will show you a simple function that launches the App Store from your application.

First of all you need to know your app's link for example looking for it in iTunes. And then write a code like this:


-(IBAction) gotoFlightInstrument {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://itunes.apple.com/es/app/instrumental-flight-vuelo/id413551896?mt=8"]];
}


where
"http://itunes.apple.com/es/app/instrumental-flight-vuelo/id413551896?mt=8

is my iTunes app link.

Hope help!

Bye

Saturday, February 26, 2011

Hidden status bar in iphone programatically

Something easy this time. Only one line

[[UIApplication sharedApplication] setStatusBarHidden:YES];


Hope help

Thursday, February 24, 2011

Seting up free Borland C++ 5.5 compile

Hi, Today I need to use the Borland compiler and I've decided to set it up.

If you want to compile from your development directory the way is to create two new files:

bcc32.cfg

-I"C:\Borland\BCC55\Include"
-L"C:\Borland\BCC55\Lib"


ilink32.cfg

-L"C:\Borland\BCC55\Lib"


Now we can compile using:

bcc32 our_file.cpp


Of course, I'm using the default installation path and I set the local variables before.

Bye

Friday, January 28, 2011

Time delay in a iphone development

The easiest way is to delay the thread like this:

[NSThread sleepForTimeInterval:2.0];


Hope help

How to write a UILabel programmatically

I need to add a label that shows a loading string. One way to do it is


UILabel *scoreLabel = [ [UILabel alloc ] initWithFrame:CGRectMake((self.bounds.size.width / 2)-75, 0.0, 150.0, 43.0) ];
scoreLabel.textAlignment = UITextAlignmentCenter;
scoreLabel.textColor = [UIColor whiteColor];
scoreLabel.backgroundColor = [UIColor blackColor];
scoreLabel.font = [UIFont fontWithName:@"Arial Rounded MT Bold" size:(18.0)];
[self addSubview:scoreLabel];
scoreLabel.text = [NSString stringWithFormat: @"%d", @"Loading..."];


Bye

Sunday, January 16, 2011

How to write text in an iPhone CGContextShowTextAtPoint

Hi,

Today I need to write a text in my iPhone using the CGContextShowTextAtPoint. First problem is that by default the text will appear inverted so we need to tranform it. The solution is for exmaple:

void drawText (CGContextRef myContext, char *title, int x, int y, int w, int h)
{
CGContextSelectFont (myContext, "Arial", h/10, kCGEncodingMacRoman);
CGContextSetRGBFillColor (myContext, 0, 0, 0, 0.99);
CGContextSetTextMatrix(myContext, CGAffineTransformMake(1.0,0.0, 0.0, -1.0, 0.0, 0.0));
CGContextShowTextAtPoint (myContext, x, y, title, strlen(title));
}


The key is on the
CGAffineTransformMake(1.0,0.0, 0.0, -1.0, 0.0, 0.0)
transformation.

Hope help!!

Tuesday, January 11, 2011

Subversion back-up

Today's problem is how to make a svn backup??

Easy pissy! Only two commands:

svnadmin dump path/to/repository | gzip > dumpfile.gz


for generate the backup file and

gunzip -c dumpfile.gz | svnadmin load path/to/repository


for restore the back-up copy.

If we want to export without version numbers (production copy):

svn export svn+ssh://usuario@server.com/home/usuario/svn/project/trunk /local/path


Nothing more for today!!

Have a nice day

Sunday, January 2, 2011

How to convert iphone accelerometer raw data to degrees

Hello and Happy new year!!

Someone asked me yesterday how can we convert the iphone accelerometer outputs to degrees. Well, it's easy. We are going to use the function

CGFloat RadiansToDegrees(CGFloat radians) {return radians * 180/M_PI;};


and then, the only thing we need to do is

CGFloat angleXY=RadiansToDegrees(atan2(acceleration.y, acceleration.x));


For example, if we want to show this data in a UITextField called textXY

textXY.text=[NSString stringWithFormat:@"%f", angleXY];


Hope help!!