Iniciar Castle Active Record con Singleton

using Castle.ActiveRecord;
using Castle.ActiveRecord.Framework.Config;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Haruna_Core.Dao
{
/// <summary>
/// this class initialize ActiveRecordFramework
/// =================================================
/// </summary>
public class HarunaActiveRecord
{
/// <summary>
/// Variable estática para la instancia, se necesita utilizar una función lambda
/// ya que el constructor es privado
/// ===============================================
/// </summary>
private static readonly Lazy<HarunaActiveRecord> instance = new Lazy<HarunaActiveRecord>(() => new HarunaActiveRecord());

/// <summary>
/// Constructor privado para evitar la instanciación directa
/// ================================================
/// </summary>
private HarunaActiveRecord()
{
ActiveRecordStarter.Initialize(ActiveRecordSectionHandler.Instance, typeof(OpcionDao),
typeof(PerfilDao),
typeof(OpcionPerfilDao),
typeof(OrganizacionDao),
typeof(UsuarioDao),
typeof(UsuarioPerfilDao));
bool sw = ActiveRecordStarter.IsInitialized;
}

/// <summary>
/// Propiedad para acceder a la instancia
/// =================================================
/// </summary>
public static HarunaActiveRecord Instance
{
get
{
return instance.Value;
}
}
}
}

Convertir List a DataTable

public DataTable ConvertToDataTable<T>(IList<T> data)
    {
        PropertyDescriptorCollection properties =
           TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        foreach (PropertyDescriptor prop in properties)
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        foreach (T item in data)
        {
            DataRow row = table.NewRow();
            foreach (PropertyDescriptor prop in properties)
                row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
            table.Rows.Add(row);
        }
        return table;

    }

Leer y Escribir colas MQ Series en C#

Lo primero es tener instalado el cliente de MQSeries… Una vez instalado la siguiente clase permite conectar, escribir y leer de una Cola MQ

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IBM.WMQ;
using ClienteMQ_Core.Util;
namespace ClienteMQ_Core.Logic
{
/// <summary>
/// Clase que contiene la logica de conexion y
/// ===============================================================
/// </summary>
public class ConectorMQ
{
MQQueueManager queueManager;
MQQueue queue;
MQMessage queueMessage;
MQPutMessageOptions queuePutMessageOptions;
MQGetMessageOptions queueGetMessageOptions;
static string QueueName;
static string QueueManagerName;
static string ChannelInfo;
string channelName;
string transportType;
string connectionName;
string message;
/// <summary>
/// Conecta a MQ SERIES
/// ===============================================================================
/// </summary>
/// <param name=”strQueueManagerName”></param>
/// <param name=”strQueueName”></param>
/// <param name=”strChannelInfo”></param>
/// <returns></returns>
public string ConnectMQ(string strQueueManagerName, string strQueueName,string strChannelInfo)
{
QueueManagerName = strQueueManagerName;
QueueName = strQueueName;
ChannelInfo = strChannelInfo;
char[] separator = { ‘/’ };
string[] ChannelParams;
ChannelParams = ChannelInfo.Split(separator);
channelName = ChannelParams[0];
transportType = ChannelParams[1];
connectionName = ChannelParams[2];
String strReturn = “”;
try
{
queueManager = new MQQueueManager(QueueManagerName,
channelName, connectionName);
strReturn = “Connected Successfully”;
}
catch (MQException exp)
{
throw new ClienteMQException(exp);
}
return strReturn;
}
/// <summary>
/// Escribe un mensaje en la cola MQ conectada
/// ===============================================================================
/// </summary>
/// <param name=”strInputMsg”></param>
public void WriteMsg(string strInputMsg)
{
try
{
queue = queueManager.AccessQueue(QueueName,
MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING);
message = strInputMsg;
queueMessage = new MQMessage();
queueMessage.WriteString(message);
queueMessage.Format = MQC.MQFMT_STRING;
queuePutMessageOptions = new MQPutMessageOptions();
queue.Put(queueMessage, queuePutMessageOptions);
}
catch (MQException MQexp)
{
throw new ClienteMQException(MQexp);
}
catch (Exception exp)
{
throw new ClienteMQException(exp);
}
}
/// <summary>
/// Lee un mensaje de la cola seleccionada
/// ===============================================================================
/// </summary>
/// <returns></returns>
public string ReadMsg()
{
String strReturn = “”;
try
{
queue = queueManager.AccessQueue(QueueName,
MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING);
queueMessage = new MQMessage();
queueMessage.Format = MQC.MQFMT_STRING;
queueGetMessageOptions = new MQGetMessageOptions();
queue.Get(queueMessage, queueGetMessageOptions);
strReturn = queueMessage.ReadString(queueMessage.MessageLength);
}
catch (MQException MQexp)
{
throw new ClienteMQException(MQexp);
}
catch (Exception exp)
{
throw new ClienteMQException(exp);
}
return strReturn;
}
}
}

Suerte 🙂

Conocer la estructura de una BD SQL

–TABLAS y COLUMNAS

SELECT SO.NAME, SC.NAME
FROM sys.objects SO INNER JOIN sys.columns SC
ON SO.OBJECT_ID = SC.OBJECT_ID
WHERE SO.TYPE = ‘U’
ORDER BY SO.NAME, SC.NAME

–TABLAS
SELECT SO.NAME
FROM sys.objects SO
WHERE SO.TYPE = ‘U’
ORDER BY SO.NAME

–COLUMANS Y TIPO
SELECT COLUMN_NAME AS NombreCampo,DATA_TYPE as TIPO FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = ‘Audit_Trails’

— FK
EXEC sp_fkeys ‘Clientes’

–FK por query
select distinct name from sys.objects where object_id in
( select fk.constraint_object_id from sys.foreign_key_columns as fk
where fk.referenced_object_id =
(select object_id from sys.tables where name = ‘Clientes’)
)

–TABLAS QUE TIENEN FK A UNA TABLA
select t.name as TableWithForeignKey, fk.constraint_column_id as FK_PartNo , c.name as ForeignKeyColumn
from sys.foreign_key_columns as fk
inner join sys.tables as t on fk.parent_object_id = t.object_id
inner join sys.columns as c on fk.parent_object_id = c.object_id and fk.parent_column_id = c.column_id
where fk.referenced_object_id = (select object_id from sys.tables where name = ‘Clientes’)
order by TableWithForeignKey, FK_PartNo

–PRIMARY KEY
SELECT column_name
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), ‘IsPrimaryKey’) = 1
AND table_name = ‘Clientes’

Obtener los Triggers de una BD SQL

La siguiente query permite obtener todos los Triggers de una Base de Datos, es bastante util cuando recibes una BD llenas de Triggers 🙂

SELECT
sysobjects.name AS trigger_name
,USER_NAME(sysobjects.uid) AS trigger_owner
,s.name AS table_schema
,OBJECT_NAME(parent_obj) AS table_name
,OBJECTPROPERTY( id, ‘ExecIsUpdateTrigger’) AS isupdate
,OBJECTPROPERTY( id, ‘ExecIsDeleteTrigger’) AS isdelete
,OBJECTPROPERTY( id, ‘ExecIsInsertTrigger’) AS isinsert
,OBJECTPROPERTY( id, ‘ExecIsAfterTrigger’) AS isafter
,OBJECTPROPERTY( id, ‘ExecIsInsteadOfTrigger’) AS isinsteadof
,OBJECTPROPERTY(id, ‘ExecIsTriggerDisabled’) AS [disabled]
FROM sysobjects
INNER JOIN sys.tables t
ON sysobjects.parent_obj = t.object_id

INNER JOIN sys.schemas s
ON t.schema_id = s.schema_id
WHERE sysobjects.type = ‘TR’
order by 1

Trabajar con appSetting en los archivos .config

Los archivos .config son un muy buen lugar para guardar información que no queremos que quede “en duro” y que nos sirve para parametrizar nuestra aplicación. Normalmente tenemos valores del tipo

<add key=”Llave” value=”valor”/>

Pero que pasa si queremos modificar en tiempo de ejecución dichos valores?

bueno lo podemos hacer de la siguiente manera.

Para leer usamos una clase del namespace System.Configuration

string miValor = ConfigurationManager.AppSettings[“llave”];

Para agregar un nuevo valor pordemos usar los siguiente

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Add(“llave”, “valor”);
config.Save(ConfigurationSaveMode.Modified);

y para actualizar un valor lo siguiente.

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings[“llave”].Value = “Nuevo Valor”
config.Save(ConfigurationSaveMode.Modified);

🙂

 

 

 

Microsoft JScript runtime error: Object doesn’t support this property or method con Dev Express

Estoy en un proyecto que usa DevExpress 9.3 y tuve el siguiente error al probar desde IE 8

Microsoft JScript runtime error: Object doesn’t support this property or method

en uno de los archivos dinámicos que genera DevEpress. Pero desde otro equipo no se daba.

Despues de mucho googlear el error se da en esa versión al estar instalado chrome framework.

Hay dos opciones para solucionarlo, desinstalar chrome framwork o actualizar DevExpress 10.2.3 o superior.

 

saludos

Cambiar colores en un RichTextBox

Estaba haciendo un editor xml y necesitaba resaltar pabras reservadas

lo hice con este pequeño snipet.

 

public void definirSintaxis()
{
txtXML.SelectAll();
txtXML.SelectionColor = Color.Black;
string cadena = txtXML.Text;
Configuraciones conf = new Configuraciones();
foreach(string valor in conf.sintaxis)
{
int posicion = 0;
int numero = 1;
while (numero != 0)
{
posicion = Convert.ToInt16(Strings.InStr(numero, txtXML.Text, valor));
if (posicion > 0)
{
txtXML.SelectionStart = posicion – 1;
txtXML.SelectionLength = valor.Length;
txtXML.SelectionColor = Color.Red;
numero += 1;
}
else
{
numero = 0;
}
}
}
txtXML.SelectionStart = txtXML.TextLength;
}

conf.sintaxis es un arreglo con las palabras que queria destacar

saludos 🙂