Come aggiungere una proprietà ad una classe esistente attraverso l'uso delle categorie in Objective-C:
ASMyClass+NewProperty.h
//
// ASMyClass+NewProperty.h
// ClassCustomizing
//
// Created by Alberto Schiassi on 03/05/13.
// Copyright (c) 2013 AS-dev All rights reserved.
//
#import <Foundation/Foundation.h>
@interface ASMyClass (NewProperty)
@property (nonatomic,retain) NSString *newProperty;
@end
ASMyClass+NewProperty.m
//
// ASMyClass+NewProperty.m
// ClassCustomizing
//
// Created by Alberto Schiassi on 03/05/13.
// Copyright (c) 2013 AS-dev All rights reserved.
//
#import "ASMyClass+NewProperty.h"
#import <objc/runtime.h>
NSString * const kPropertyKey = @"kPropertyKey";
@implementation ASMyClass (NewProperty)
- (void)setNewProperty:(NSString *)newProperty
{
objc_setAssociatedObject(self, kPropertyKey, newProperty, OBJC_ASSOCIATION_COPY);
}
- (NSString*)newProperty
{
return objc_getAssociatedObject(self, kPropertyKey);
}
|
|
|
Un esempio che mostra come l'uso dei delegati può in certe condizioni generare memory leak:
class MyDummyObject
{
private UInt64 m_id;
private Byte[] bytes;
private MyObject m_myObject;
public MyDummyObject(UInt64 id, MyObject myObject)
{
m_id = id;
// Memory consuming
bytes = new Byte[1024000];
new Random().NextBytes(bytes);
m_myObject = myObject;
// attach to delegate to generate leaks
m_myObject.MyEvent += myObject_MyEvent;
Console.WriteLine("Constructor MyObject with id: {0} called", m_id);
}
private void myObject_MyEvent(object sender, EventArgs e)
{ }
~MyDummyObject()
{
Console.WriteLine("Destructor MyObject with id: {0} of: {1} called", m_id, Program.ID);
}
}
|
|
|
Come aggiungere un datepicker in una finestra di azioni:
- (void)selectDate:(id)sender {
UIActionSheet *dateActionSheet = [[UIActionSheet alloc] initWithTitle:@""
delegate:self
cancelButtonTitle:@"Cancel"
destructiveButtonTitle:nil
otherButtonTitles:@"Done", nil];
[dateActionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
[dateActionSheet showInView:self.view];
[dateActionSheet setFrame:CGRectMake(0, 100, self.view.frame.size.width, 500)];
UIDatePicker *pickerView = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 50, 300, dateActionSheet.frame.size.width)];
[pickerView setTag:kPickerTag];
[pickerView setDatePickerMode:UIDatePickerModeDate];
[pickerView setDate:self.selectedDate animated:YES];
[dateActionSheet addSubview:pickerView];
[pickerView release];
NSArray *subViews = [dateActionSheet subviews];
[[subViews objectAtIndex:SelectButtonIndex] setFrame:CGRectMake(0, 5, 80, 40)];
[[subViews objectAtIndex:CancelButtonIndex] setFrame:CGRectMake(dateActionSheet.frame.size.width - 80, 5, 80, 40)];
[dateActionSheet release];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0) {
UIDatePicker *datePicker = (UIDatePicker *)[actionSheet viewWithTag:kPickerTag];
self.selectedDate = [datePicker date];
}
}
|
|
|
La sincronizzazione dei thread mediante la classe AutoResetEvent:
private static void method1()
{
// ciclo di esecuzione del Thread1
while (true)
{
// Thread2 viene segnalato e può iniziare la propria esecuzione
_resetEvent1.Set();
Console.WriteLine(String.Format("Begin thread: {0}", System.Threading.Thread.CurrentThread.Name));
// simula le procedure che deve eseguire Thread1
Thread.Sleep(new Random().Next(2000, 5000));
// Thread1 rimane bloccato sino al termine di Thread2
_resetEvent2.WaitOne();
Console.WriteLine(String.Format("End thread: {0}", System.Threading.Thread.CurrentThread.Name));
}
}
|
|
|
Come implementare l'interfaccia IDisposable nel modo corretto (tratto da MSDN)
public class Resource : IDisposable
{
private IntPtr nativeResource = Marhsal.AllocHGlobal(100);
private AnotherResource managedResource = new AnotherResource();
// Dispose() calls Dispose(true)
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// NOTE: Leave out the finalizer altogether if this class doesn't
// own unmanaged resources itself, but leave the other methods
// exactly as they are.
~Resource()
{
// Finalizer calls Dispose(false)
Dispose(false);
}
// The bulk of the clean-up code is implemented in Dispose(bool)
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// free managed resources
if (managedResource != null)
{
managedResource.Dispose();
managedResource = null;
}
}
// free native resources if there are any.
if (nativeResource != IntPtr.Zero)
{
Marshal.FreeHGlobal(nativeResource);
nativeResource = IntPtr.Zero;
}
}
}
|
|
|
Come verificare se una porta socket e` impegnata o meno:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
namespace CheckAvailablePort
{
/*
* Appicazione che dato un numero passaro per parametro controlla
* se la porta socket con quel numero e` impegnata o libera
*/
class Program
{
static void Main(string[] args)
{
if (args.Length != 1)
Console.WriteLine("Port number is not defined");
int port = Int32.Parse(args[0]);
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();
foreach (TcpConnectionInformation tcpi in tcpConnInfoArray)
{
if (tcpi.LocalEndPoint.Port == port)
Console.WriteLine("Port: {0} is busy", port);
}
Console.WriteLine("Port: {0} is free", port);
Console.WriteLine("Press <ENTER to exit>");
Console.ReadLine();
}
}
}
|
|
|
Un semplice esempio che mostra come inviare una mail mediante .NET
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Mail;
namespace SendEmail
{
class Program
{
static void Main(string[] args)
{
var fromAddress = new MailAddress("alberto.schiassi@alice.it", "Alberto Schiassi");
var toAddress = new MailAddress("dev@albertoschiassi.it", "Dev Alberto Schiassi");
const string fromPassword = "";
const string subject = "Test send email with C#";
const string body = "This is a test";
var smtp = new SmtpClient
{
Host = "out.alice.it",
Port = 25,
EnableSsl = false,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
}
}
}
|
|
|
Per ottenere la lista dei processi che bloccano l'accesso ad un file è possibile utilizzare Process Explorer di Windows Sysinternals attraverso il menu File:
|
|
|
Per esecuzione posticipata si intende che la valutazione di un'espressione viene ritardata finché il relativo valore realizzato non risulta effettivamente necessario.
L'esecuzione posticipata può contribuire a migliorare notevolmente le prestazioni quando è necessario modificare grandi raccolte di dati, in particolare in programmi che contengono una serie di modifiche o query concatenate.
Nel migliore dei casi l'esecuzione posticipata consente di eseguire un'unica iterazione nella raccolta di origine.
L'esecuzione posticipata è supportata direttamente nel linguaggio C# tramite la parola chiave yield (sotto forma di istruzione yield-return) quando viene utilizzata all'interno di un blocco iteratore.
Tale iteratore deve restituire una raccolta di tipo IEnumerator o IEnumerator (o un tipo derivato).
// metodo che effettua la ricerca dell'elemento specificato all'interno
// di un array con esecuzione posticipata
public static IEnumerable<T> SearchDeferred<T>(this IEnumerable<T> array, T element)
{
foreach (T item in array)
{
if (item.Equals(element))
{
Console.WriteLine("Found item: {0}", element);
yield return item;
}
}
}
|
|
|
Un "Job Object" consente a gruppi di processi di essere gestiti come una singola unità.
Ad ogni Job Object può essere assegnato un nome, una protezione, i processi ad esso associati possono condividere oggetti e le operazioni eseguite su un job influenzano tutti i processi associati.

|