Weblogs Código

RecorteX

» fjmp76
73 usuarios y 243 recortes de código
Usuario

Contraseña
Crear cuenta
Estás viendo los recortes del usuario fjmp76

RSS
Recortes: 42
Registrado: 30/8/2006

Etiquetas:
vbnet (24)
csharp (18)
xml (7)
sql (4)
SQLServer (2)
fk (1)
js (1)
2005 (1)
aspnet (1)

Escribir al Log de eventos

 
  public static void WriteToEventLog(string message)
        {
            string cs = "BkSso";
            EventLog elog = new EventLog();
            if (!EventLog.SourceExists(cs))
            {
                EventLog.CreateEventSource(cs, cs);
            }
            elog.Source = cs;
            elog.EnableRaisingEvents = true;
            elog.WriteEntry(message);
        }
 

Encontrar texto entre parentesis

Encontrar texto entre parentesis

 
  string output = txt.Split(new char[] { '(', ')' })[1];
 

SortableBindingList para Winforms

SortableBindingList para Winforms

hay que agregar el evento ColumnHeaderMouseClick al dataGridView

 
        private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            SortOrder order = this.dataGridView1.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection;
            ListSortDirection _direction = (order == SortOrder.Descending) ? ListSortDirection.Descending : ListSortDirection.Ascending;
            this.dataGridView1.Sort(dataGridView1.Columns[e.ColumnIndex], _direction);
        }
 

Y la lista que usemos será la SortableBindingList del objeto

 
      public class SortableBindingList<T> : BindingList<T>
    {
        private ArrayList sortedList;
        private bool isSortedValue;
 
        public SortableBindingList()
        {
        }
 
        public SortableBindingList(IList<T> list)
        {
            foreach (object o in list)
            {
                this.Add((T)o);
            }
        }
 
        protected override bool SupportsSortingCore
        {
            get { return true; }
        }
 
 
        protected override bool IsSortedCore
        {
            get { return isSortedValue; }
        }
 
        ListSortDirection sortDirectionValue;
        PropertyDescriptor sortPropertyValue;
 
        protected override void ApplySortCore(PropertyDescriptor prop,
            ListSortDirection direction)
        {
            sortedList = new ArrayList();
 
            Type interfaceType = prop.PropertyType.GetInterface("IComparable");
 
            if (interfaceType == null && prop.PropertyType.IsValueType)
            {
                Type underlyingType = Nullable.GetUnderlyingType(prop.PropertyType);
 
                if (underlyingType != null)
                {
                    interfaceType = underlyingType.GetInterface("IComparable");
                }
            }
 
            if (interfaceType != null)
            {
                sortPropertyValue = prop;
                sortDirectionValue = direction;
 
                IEnumerable<T> query = base.Items;
                if (direction == ListSortDirection.Ascending)
                {
                    query = query.OrderBy(i => prop.GetValue(i));
                }
                else
                {
                    query = query.OrderByDescending(i => prop.GetValue(i));
                }
                int newIndex = 0;
                foreach (object item in query)
                {
                    this.Items[newIndex] = (T)item;
                    newIndex++;
                }
                isSortedValue = true;
                this.OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
 
            }
            else
            {
                throw new NotSupportedException("Cannot sort by " + prop.Name +
                    ". This" + prop.PropertyType.ToString() +
                    " does not implement IComparable");
            }
        }
 
        protected override PropertyDescriptor SortPropertyCore
        {
            get { return sortPropertyValue; }
        }
 
        protected override ListSortDirection SortDirectionCore
        {
            get { return sortDirectionValue; }
        }
 
    }
 

Redirect and Post in asp.net

Algo como Response.Redirect, pero para metodos post en vez de get

 
public static void RedirectAndPOST(Page page, string destinationUrl, NameValueCollection data)
{
//Prepare the Posting form
string strForm = PreparePOSTForm(destinationUrl, data);
//Add a literal control the specified page holding 
//the Post Form, this is to submit the Posting form with the request.
page.Controls.Add(new LiteralControl(strForm));
}
 
private static String PreparePOSTForm(string url, NameValueCollection data)
{
    //Set a name for the form
    string formID = "PostForm";
    //Build the form using the specified data to be posted.
    StringBuilder strForm = new StringBuilder();
    strForm.Append("<form id=\"" + formID + "\" name=\"" + 
                   formID + "\" action=\"" + url + 
                   "\" method=\"POST\">");
 
    foreach (string key in data)
    {
        strForm.Append("<input type=\"hidden\" name=\"" + key + 
                       "\" value=\"" + data[key] + "\">");
    }
 
    strForm.Append("</form>");
    //Build the JavaScript which will do the Posting operation.
    StringBuilder strScript = new StringBuilder();
    strScript.Append("<script language='javascript'>");
    strScript.Append("var v" + formID + " = document." + 
                     formID + ";");
    strScript.Append("v" + formID + ".submit();");
    strScript.Append("</script>");
    //Return the form and the script concatenated.
    //(The order is important, Form then JavaScript)
    return strForm.ToString() + strScript.ToString();
}
 

Serializar y deserializar a xml cualquier objeto

 
//Serializar a XML (UTF-8) un objeto cualquiera 
//Create our own namespaces for the output
//Add an empty namespace and empty value
                ns.Add("", ""//Deserializar un XML a un objeto T 
 

Cambiar de string a byte[] de byte[] a string

 
static byte[] GetBytes(string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}
 
static string GetString(byte[] bytes)
{
    char[] chars = new char[bytes.Length / sizeof(char)];
    System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
    return new string(chars);
}
 

Ver foreign keys en la bd

Escribe aquí el texto

 
  
SELECT f.name AS ForeignKey,
OBJECT_NAME(f.parent_object_id) AS TableName,
COL_NAME(fc.parent_object_id,
fc.parent_column_id) AS ColumnName,
OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName,
COL_NAME(fc.referenced_object_id,
fc.referenced_column_id) AS ReferenceColumnName
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc
ON f.OBJECT_ID = fc.constraint_object_id
 

Una clase para simular (en parte) el objeto My de Visual Basic 2005

Una clase para simular (en parte) el objeto My de Visual Basic 2005

 
// Una clase para simular (en parte) el objeto My de Visual Basic 2005
static class My
{
    public static Properties.Settings Settings
    {
        get
        {
            return Properties.Settings.Default;
        }
    }
}
 

Remover declaracion de xml

xml es XmlDocument

 
foreach(XmlNode n in xml.ChildNodes)
{ 
    if (n.NodeType == XmlNodeType.XmlDeclaration)
       n.ParentNode.RemoveChild(n);
}
 

Coleccion de datos en net

Esto se usa para hacer una coleccion de un mismo objeto

 
  Public Class ProcesosBase
    Inherits CollectionBase
 
    Public Sub New()
    End Sub
 
    Public ReadOnly Property Item(ByVal index As Integer) As CLASE_A_USAR
        Get
           Return CType(List.Item(index), CLASE_A_USAR)
        End Get
    End Property
 
    Public Function Add(ByVal value As CLASE_A_USAR) As Integer
        Dim res As Integer
        res = List.Add(value)
        Return res
    End Function
 
End Class
 
Proyecto: Juanjo Navarro, 2006 - Diseño: Albin