sábado, 31 de enero de 2009

LADP con C#



Cuentas veces hemos tenido la necesidad de conectarnos al Active Directory y obtener los usuarios definidos en el servidor, para poder usarlos en nuestras aplicaciones en diferentes formas y la mas usual es en la seguridad para validar usuarios, les presento aqui un codigo sencillo que encontre en la red y que me sirvio mucho y lo publico para que lo pueden usar y que les de ideas para que entren mas a fondo en este tema de mucho interes.

using System.Security.Principal;
using System.DirectoryServices;
using System.Net.NetworkInformation;



namespace AS.Utilities
{
public class ActiveDirectory
{
public enum LDAPFilterType
{
UsersAndGroups,
OnlyUsers,
OnlyGroups
}
public static string
getLDAPFilterString(LDAPFilterType Type, string Filter)
{
string FilterByName = "(samAccountName=*{0}*)";
string f = string.Empty;
switch (Type)
{
case LDAPFilterType.OnlyUsers:
f = "(&(objectCategory=person)(objectClass=user){0})";
break;
case LDAPFilterType.OnlyGroups:
f = "(&(objectCategory=Group){0})";
break;
case LDAPFilterType.UsersAndGroups:
f = "((&(objectCategory=person)(objectClass=user){0})(&(objectCategory=Group){0}))";
break;
}
if (Filter == string.Empty)
{
return string.Format(f, string.Empty);
}
else
{
return string.Format(f, string.Format(FilterByName, Filter));
}
}
public static string
getDomainName()
{
return IPGlobalProperties.GetIPGlobalProperties().DomainName;
}
public static string
getLDAPDomainName(string domainName)
{
StringBuilder sb = new StringBuilder();
string[] dcItems = domainName.Split(".".ToCharArray());
sb.Append("LDAP://");
foreach (string item in dcItems)
{
sb.AppendFormat("DC={0},", item);
}
return sb.ToString().Substring(0, sb.ToString().Length - 1);
}
public static List
getUserLDAPProperties(string LDAPURL)
{
List properties = new List();
DirectoryEntry entries = new DirectoryEntry(LDAPURL);
DirectorySearcher searcher = new DirectorySearcher(
entries, "(&(objectCategory=person)(objectClass=user))");
try
{
foreach (SearchResult result in searcher.FindAll())
{
foreach (string property in
result.GetDirectoryEntry().Properties.PropertyNames)
{
properties.Add(property);
}
break;
}
}
catch (Exception ex)
{
throw ex;
}
return properties;
}
public static string
getNTAccountName(string wksid)
{
SecurityIdentifier sid = new SecurityIdentifier(wksid);
NTAccount account = (NTAccount)sid.Translate(typeof(NTAccount));
return account.Value;
}
public static string
sIDtoString(byte[] sidBinary)
{
SecurityIdentifier sid = new SecurityIdentifier(sidBinary, 0);
return sid.ToString();
}
public static Dictionary
getADUserMemberOf(IntPtr logonToken)
{
Dictionary groups =
new Dictionary();
WindowsIdentity user = new WindowsIdentity(logonToken);
IdentityReferenceCollection irc = user.Groups;
foreach (IdentityReference ir in irc)
{
groups.Add(getNTAccountName(ir.Value), ir);
}
return groups;
}
public static string
getUserProperties(IntPtr logonToken)
{
WindowsIdentity user = new WindowsIdentity(logonToken);
string propertyDescription = string.Format("The Windows identity named {0}: ", user.Name);
if (!user.IsAnonymous)
propertyDescription += ", is not an Anonymous account";
if (user.IsAuthenticated)
propertyDescription += ", is authenticated";
if (user.IsSystem)
propertyDescription += ", is a System account";
if (user.IsGuest)
propertyDescription += ", is a Guest account";
string authenticationType = user.AuthenticationType;
if ((authenticationType != null))
{
propertyDescription += ", and uses " + authenticationType;
propertyDescription += " authentication type.";
}
propertyDescription += Environment.NewLine;
propertyDescription += "The SID for the owner is : " + user.Owner.ToString();
propertyDescription += Environment.NewLine;
propertyDescription += "Display the SIDs and names for the groups the current user belongs to:";
propertyDescription += Environment.NewLine;
IdentityReferenceCollection irc;
irc = user.Groups;
foreach (IdentityReference ir in irc)
{
propertyDescription += string.Format("Group {0}, SID: {1}{2}",
getNTAccountName(ir.Value), ir.Value, Environment.NewLine);
}
TokenImpersonationLevel token;
token = user.ImpersonationLevel;
propertyDescription += "The impersonation level for the current user is : " + token.ToString();
return propertyDescription;
}
public static List
getItemsInLDAP(string LDAPURL, LDAPFilterType type, string criteria)
{
List items = new List();
DirectoryEntry entries = new DirectoryEntry(LDAPURL);
string filter = getLDAPFilterString(type, criteria);
DirectorySearcher searcher = new DirectorySearcher(
entries, filter);
try
{
foreach (SearchResult result in searcher.FindAll())
{
items.Add((string)result.Properties["samAccountName"][0]);
}
}
catch (Exception ex)
{
throw ex;
}
return items;
}














viernes, 30 de enero de 2009

Obtener información de los objetos sql server

Este codigo sql, nos permite tener información como tipo de dato, longitud y si es un identity,
esto nos permite acercarnos mas al sql server y si miramos un poco mas a fondo podemos sacar provecho de esta informacion. Espero les ayude.


SELECT
DISTINCT C.colid AS IdCol, C.name AS ColName, T.name AS Type,
C.Length, C.Prec, C.Scale, C.IsNullable,
COLUMNPROPERTY(C.id, C.name, 'IsIdentity') AS [Identity],
COLUMNPROPERTY(C.id, C.name, 'IsComputed') AS Computed
FROM syscolumns C
INNER JOIN systypes T on C.xtype = T.xtype and T.xtype=T.xuserType



Tomando como ejemplo la base de datos AdventureWorks, obtendremos el siguiente resultado:

Trabajar con imagenes en .net C#


public byte[] ImageArray(Image objImage)
{
string sTempFile = Path.GetTempFileName();
FileStream fileStream = new FileStream(sTempFile, FileMode.OpenOrCreate, FileAccess.ReadWrite);
objImage.Save(fileStream, System.Drawing.Imaging.ImageFormat.Png);
fileStream.Position = 0;
int _Length = Convert.ToInt32(fileStream.Length);
byte[] bytes = new byte[_Length];
fileStream.Read(bytes, 0, _Length);
fileStream.Close();
return bytes;
}
public Image GetImage(byte[] byteArray)
{
if (byteArray == null) return null;
MemoryStream memoryStream = new MemoryStream(byteArray);
Bitmap _bitmap = null;
try
{
_bitmap = new Bitmap(memoryStream);
}
catch (Exception ex)
{
new ArgumentException(ex.Message);
}
return _bitmap;
}