jueves, 27 de septiembre de 2012

How to populate a dropdown from XML

Dim oTemp As New Temp
Dim path As String path = HttpContext.Current.Request.Url.OriginalString.Substring(0, HttpContext.Current.Request.Url.OriginalString.LastIndexOf("/"))
path = path + "/XMLInfo/ConfigCompany.xml"

Dim Ds As New System.Data.DataSet Ds.ReadXml(path) RadcbCpnyId.DataSource =
Ds.Tables(0).DefaultView
RadcbCpnyId.DataTextField = "CpnyId" RadcbCpnyId.DataValueField = "ConStr" RadcbCpnyId.DataBind()

 XML SAmple




 
    CpnyId1
    ConStr1
 
 
    CpnyId3
    ConStr3
 
 
    CpnyId4
    ConStr4
 

viernes, 27 de julio de 2012

SQL Server 2008 y Windows 7: Attach Database. Error: No se puede abrir el archivo físico. Problemas con el UAC (User Account Control)


Apareció un nuevo problema en mi utilización de SQL2008 y Windows 7 a la hora de adjuntar una base de datos 
Con la base de ejemplo AdventureWorksLT2008 (la puedes descargar por aquí) descargue el .mdf y el .ldf para “attacharlos”
El script:
USE [master]
GO
CREATE DATABASE [AdventureWorksLT2008] ON 
( FILENAME = N'C:\SQLDATA\AdventureWorksLT2008_Data.mdf' ),
( FILENAME = N'C:\SQLDATA\AdventureWorksLT2008_Log.ldf' )
 FOR ATTACH
GO

Mensaje de Error:
Msg 5120, Level 16, State 101, Line 1
No se puede abrir el archivo físico "C:\SQLDATA\AdventureWorksLT2008_Data.mdf". Error del sistema operativo 5: "5(failed to retrieve text for this error. Reason: 15105)".

Solución 1:

Ejecutar el SSMS como Administrador.
  

Solución 2

La anterior solución nos da la idea que nos falta algo de permisos

desde TECHNET:

(…)El programa de instalación de SQL Server crea grupos de servicio local para los diferentes servicios de SQL Server y agrega las cuentas de servicio o los SID de servicio a estos grupos según sea necesario. Estos grupos simplifican la concesión de los permisos necesarios para ejecutar los servicios de SQL Server y otros ejecutables, y ayudan a proteger los archivos de SQL Server.(…) (mas info)

Grupo de Usuarios:
  •  
    • Instancia predeterminada: SQLServerMSSQLUser$nombreDeEquipo$MSSQLSERVER
    • Instancia con nombre: SQLServerMSSQLUser$nombreDeEquipo$nombreDeInstancia


jueves, 26 de julio de 2012

Hidden Fields with labels CRM4


Field
crmForm.all.ppc_address1_pais_txt.style.visibility = "hidden";

Label
crmForm.all.ppc_address1_pais_txt_c.style.visibility = "hidden";

After Convert Text Field to a Picklist include an OnChange event


Instead of clicking in on the field, to define the change event, you define it on form load.
Here is an example, where I have declared a change event in form load:


state.onchange = function(){
crmForm.all.ppc_address1_ciudad_txt.DataValue = state.SelectedText;
}


jueves, 5 de julio de 2012

CrmService.Retrieve Method Using JScript CRM4

/*-----------------Parent Accountid---------------------------*/
 if (crmForm.all.parentaccountid.DataValue != null && crmForm.all.ppc_rfc_para_fact.DataValue==2) {
 var parentacct = crmForm.all.parentaccountid;
 var entidad = "account";
 var atributo1 = "ppc_numeronit";
 var atributo2 ="ppc_actualizado";
 try {
 var parentaccountid = parentacct.DataValue[0].id;
 var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); xmlhttp.open("POST", "/mscrmservices/2007/crmservice.asmx", false);
 xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8"); xmlhttp.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Retrieve"); //xmlhttp.setRequestHeader("Content-Length", xml.length); var soapBody = "" + "" + "" + entidad + "" + "" + parentaccountid + "" + "" + "" + "" + atributo1 + "" + "" + atributo2 + "" + "" + "" + "" + ""; var soapXml = ""; soapXml += GenerateAuthenticationHeader(); soapXml += soapBody; soapXml += ""; xmlhttp.setRequestHeader("Content-Length", soapXml.length);
xmlhttp.send(soapXml);
 // Capture the result.
 var resultXml = xmlhttp.responseXML; // Check for errors.
 var errorCount = resultXml.selectNodes('//error').length;
 if (errorCount != 0) {
 var msg = resultXml.selectSingleNode('//description').nodeTypedValue; alert(msg);
 } // Display the retrieved value.
 else {
 //alert(resultXml.selectSingleNode('//q1:'+atributo1).nodeTypedValue); //alert(resultXml.selectSingleNode('//q1:'+atributo2).nodeTypedValue);
 if (resultXml.selectSingleNode('//q1:' + atributo2).nodeTypedValue == 1)
{
 crmForm.all.ppc_num_nit_cc_fact.DataValue = resultXml.selectSingleNode('//q1:' + atributo1).nodeTypedValue;
 } else {
 alert('La cuenta la cuenta Primaria no ha \n sido enviada a Solomon.');                           crmForm.all.ppc_num_nit_cc_fact.DataValue = '';
     }
   }
 }
 catch (e) {
   alert(e.message);
  }
}

martes, 29 de mayo de 2012

Creates a dh file based on the current definition of a table Solomon


/****** Object:  StoredProcedure [dbo].[ut_dhcreate]    Script Date: 05/29/2012 20:13:09 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

ALTER proc [dbo].[ut_dhcreate] @tabname varchar(50),
                      @path    varchar(20),
                      @dhname       varchar(36)
as
/********************************************************************************
*             Copyright TLB, Inc. 1991, 1994 All Rights Reserved
*
* Proc Name     : ut_dhcreate
*
* Narrative     : Creates a dh file based on the current definition of a table.
*
* Inputs        : tabname     ie. APDoc
*                 path        This is the destination of the dh file. This is
*                             relative to the sqlserver box, not the client.
*                             For example,  C:\temp\    will put in on the
*                             database servers C drive.
*                 dhname      name of "dh" file to create, usually same as table
*                                 name with ".dh" suffix. (ie. APDoc.dh)
*
********************************************************************************
* #  Init  Date     Change
********************************************************************************
*001  CLS   06/29/98  Initial Creation
*********************************************************************************
*/

declare @command varchar(255),          @temp_colname varchar(32),
        @col_name  char(32),
        @col_type  varchar(65),
        @col_length char(15)

/*** Build Header stuff ***/
/***                    ***/
set @tabname = ltrim(rtrim(@tabname))

select @command='echo Option Explicit> '+@path+@dhname
exec master.dbo.xp_cmdshell @command

select @command='echo. >> '+@path+@dhname
exec master.dbo.xp_cmdshell @command

select @command='echo Attribute VB_Name = "' + @tabname + 'DH">> '+@path+@dhname
exec master.dbo.xp_cmdshell @command

select @command='echo Type ' + @tabname + '>> '+@path+@dhname
exec master.dbo.xp_cmdshell @command

declare col_cursor scroll cursor for
select  sc.name ,
        case
          /* Convert db types to vb types.                    */
          /* All converts are straightforward except date/time         */
          /* which converts as follows.                                */
          /*     If a field name ends in "datetime" ===> sdate         */
          /*     If a field name ends in "time"                        */
          /*                  other than "datetime" ===> stime         */  
          when (t.name = 'char')   then 'As String * '
          when (t.name = 'smallint')       then 'As Integer'
          when (t.name = 'float')          then 'As Double'
          when (t.name = 'Decimal')          then 'As Decimal'
          when (t.name = 'smalldatetime'
            and (sc.name like '%time%'
                   and sc.name not like '%datetime%'))
                                          then 'As Stime'
          when (t.name = 'smalldatetime'
            and (sc.name not like '%time%'
                   or sc.name like '%datetime%'))      
                                          then 'As Sdate'
          when (t.name = 'int')   then 'As Long'
          when (t.name = 'image')          then 'As String * 1900'
          when (t.name = 'text')           then 'As String * 1900'
          else 'Unknown type ' + t.name
        end type,
        case t.name
          when 'char' then substring(ltrim(str(sc.length)),1,datalength(convert(varchar,sc.length)))
          else ''
        end length
        from syscolumns sc,
             systypes   t
       where sc.id=object_id(@tabname)
         and t.usertype = sc.usertype
         and t.name <> 'timestamp'
    order by sc.colid

open col_cursor

fetch col_cursor into
      @col_name,
      @col_type,
      @col_length

while (@@fetch_status = 0)
  begin

   /*** Check for arrays ***/
   /*** Arrays will be identified for now as         ***/
   /*** columns ending with a two position number    ***/
   /*** with a column name other than S4Future       ***/

  if (@col_name not like 'S4Future%' and
     substring(@col_name,datalength(rtrim(@col_name))-1,2) = '00' )
  begin
     select @temp_colname = substring(@col_name,1,datalength(rtrim(@col_name))-2)      
     while (@@fetch_status = 0 and
            substring(@col_name,1,datalength(rtrim(@col_name))-2) = @temp_colname)
     begin
        fetch col_cursor into
          @col_name,
          @col_type,
          @col_length
     end        
     fetch prior from col_cursor into
          @col_name,
          @col_type,
          @col_length
     select @col_name = substring(@col_name,1,datalength(rtrim(@col_name))-2) + '(0 To '+
             substring(substring(@col_name,datalength(rtrim(@col_name))-1,2),
                       patindex('%0%',substring(@col_name,datalength(rtrim(@col_name))-1,1))+1,
                     2 - patindex('%0%',substring(@col_name,datalength(rtrim(@col_name))-1,1))) +
            ')' +Space(30)        

  end
     
  select @command='echo     ' + rtrim(@col_name + @col_type + '' + @col_length)+ ' >> ' + @path+@dhname


exec master.dbo.xp_cmdshell @command
  fetch next from col_cursor into
      @col_name,
      @col_type,
      @col_length      
end
close col_cursor
deallocate col_cursor

/*** print footer stuff ***/

select @command='echo End Type>> '+@path+@dhname
exec master.dbo.xp_cmdshell @command


select @command='echo. >> '+@path+@dhname
exec master.dbo.xp_cmdshell @command

select @command='echo Public b' + @tabname + ' As ' + @tabname + ', n' + @tabname + ' As ' + @tabname + '>> '+@path+@dhname
exec master.dbo.xp_cmdshell @command


Adding custom table in standard screen SL Dynamics 6.5



Private Sub Form1_Load()
    Call VBA_SetAddr("bxtEquipment", bxtEquipment, nxtEquipment, LenB(bxtEquipment))
    Call SqlCursorEx(Csr_xtEquipment, NOLEVEL, "Csr_xtEquipment", "xtEquipment", "xtEquipment")
End Sub


Private Sub cEquipID_Chk(ChkStrg As String, retval As Integer)
    Dim CpnyID As String
    CpnyID = GetObjectValue("cCpnyId")
    SqlStr = "SELECT * FROM xtEquipment WHERE EquipmentID = " + SParm(Trim(ChkStrg))
    serr1 = SqlFetch1(Csr_xtEquipment, SqlStr, bxtEquipment, LenB(bxtEquipment))
    If serr1 = NOTFOUND Then
        bxtEquipment = nxtEquipment
        bxtEquipment.EquipmentID = ChkStrg
        bxtEquipment.CpnyID = CpnyID
        bxtEquipment.StatusNew = "N"
    End If
  
End Sub

Private Sub Update1_OnDelete(Level As Integer, retval As Integer)
    Dim EquipID As String

    If Level = LEVEL0 Then
        EquipID = Trim(GetObjectValue("cEquipID"))
        SqlStr = "Delete xtEquipment WHERE EquipmentID = " + SParm(Trim(EquipID))
        Call sql(c1, SqlStr)
        Call SqlFree(c1)
    End If

End Sub

Private Sub Update1_OnUpdate(Level As Integer, InsertFlg As Integer, retval As Integer)
    Dim CpnyID As String
    CpnyID = GetObjectValue("cCpnyId")

    If Level = 0 Then 'If Level = Finished Then
        Dim Equipment As String
        Dim EquipmentNE As String
        Dim EquipNEType As String
        Dim StatusNew As String
        Equipment = GetObjectValue("cEquipID")
        EquipmentNE = GetObjectValue("xEquipNE")
        EquipNEType = GetObjectValue("xEquipNEType")
        StatusNew = bxtEquipment.StatusNew
        SqlStr = "xsUPDate_Equipment " + _ 'Update Procedure
                SParm(Trim(CpnyID)) + _
                SParm(Trim(Equipment)) + _
                SParm(Trim(EquipmentNE)) + _
                SParm(Trim(EquipNEType)) + _
                SParm(Trim(StatusNew))
        Call sql(c1, SqlStr)
        Call SqlFree(c1)
        SqlStr = "SELECT * FROM xtEquipment WHERE EquipmentID = " + SParm(Trim(Equipment)) 
        serr1 = SqlFetch1(Csr_xtEquipment, SqlStr, bxtEquipment, LenB(bxtEquipment))
        Call DispFields("Form1", "cEquipID")
        Call DispFields("Form1", "xEquipNE")
        Call DispFields("Form1", "xEquipNEType")
       
    End If
        
End Sub

jueves, 24 de mayo de 2012

Crystal report connection


public CrystalDecisions.CrystalReports.Engine.ReportClass GetReport(string stringFromDate, string stringToDate, string stringOfficeID)
{
        try {
                // Create an instance of the report and set it's datasource.
                string sType = "ReportsNameSpace.Report";
                Type reportType = Type.GetType(sType, true, true);
                if (reportType != null) {
                        // Create an instance of the report and set it's datasource.
                        CrystalDecisions.CrystalReports.Engine.ReportClass rpt = (CrystalDecisions.CrystalReports.Engine.ReportClass)Activator.CreateInstance(reportType);
                        ParameterFieldDefinitions crParameterFieldDefinitions = default(ParameterFieldDefinitions);
                        crParameterFieldDefinitions = rpt.DataDefinition.ParameterFields;
                        SCRCollectionEnumerator en = crParameterFieldDefinitions.GetEnumerator();
                        while ((en.MoveNext())) {
                                ParameterFieldDefinition param = default(ParameterFieldDefinition);
                                param = en.Current;
                                ParameterValues crValue = new ParameterValues();
                                // you have to check for parameter name
                                // and pass values
                                if ((param.Name == "@FromDate")) {
                                        crValue.AddValue(stringFromDate);
                                        param.ApplyCurrentValues(crValue);
                                } else if ((param.Name == "@ToDate")) {
                                        crValue.AddValue(stringToDate);
                                        param.ApplyCurrentValues(crValue);
                                }
                        }
                        TableLogOnInfo logOnInfo = new TableLogOnInfo();
                        // I am assuming that you have crystal server database
                        // connection strings in your web.config
                        logOnInfo.ConnectionInfo.ServerName = ConfigurationManager.AppSettings("CrystalServer").ToString();
                        logOnInfo.ConnectionInfo.UserID = ConfigurationManager.AppSettings("CrystalUser").ToString();
                        logOnInfo.ConnectionInfo.Password = ConfigurationManager.AppSettings("CrystalPassword").ToString();
                        TableLogOnInfo login = default(TableLogOnInfo);
                        foreach (CrystalDecisions.CrystalReports.Engine.Table tbl in rpt.Database.Tables) {
                                login = tbl.LogOnInfo;
                                login.ConnectionInfo.ServerName = ConfigurationManager.AppSettings("CrystalServer").ToString();
                                login.ConnectionInfo.UserID = ConfigurationManager.AppSettings("CrystalUser").ToString();
                                login.ConnectionInfo.Password = ConfigurationManager.AppSettings("CrystalPassword").ToString();
                                tbl.ApplyLogOnInfo(login);
                        }
                        return rpt;
                } else {
                        return null;
                }
        } catch (Exception ex) {
                throw ex;
        }
}

Fuente: http://forums.asp.net/p/1584368/4000328.aspx

For dynamic Database connection Crystal Reports


Database connection Crystal Reports doesn´t works!!!
            crConnectionInfo.ServerName = "YOUR SERVER NAME";
            crConnectionInfo.DatabaseName = "YOUR DATABASE NAME";
            crConnectionInfo.UserID = "YOUR DATABASE USERNAME";
            crConnectionInfo.Password = "YOUR DATABASE PASSWORD";

            CrTables = cryRpt.Database.Tables ;
            foreach (CrystalDecisions.CrystalReports.Engine.Table CrTable in CrTables)
            {
                crtableLogoninfo = CrTable.LogOnInfo;
                crtableLogoninfo.ConnectionInfo = crConnectionInfo;
                CrTable.ApplyLogOnInfo(crtableLogoninfo);
            }
but this Works fine!
foreach (Table crTable in objRpt.Database.Tables)
            {
                TableLogOnInfo logOnInfo = new TableLogOnInfo();
                logOnInfo = objRpt.Database.Tables[crTable.Name].LogOnInfo;
 
                // Set the connection information for the table in the report.
                logOnInfo.ConnectionInfo.ServerName = server.Trim();
                logOnInfo.ConnectionInfo.DatabaseName = database.Trim();
                logOnInfo.ConnectionInfo.UserID = username;
                logOnInfo.ConnectionInfo.Password = password;
                objRpt.Database.Tables[crTable.Name].ApplyLogOnInfo(logOnInfo);
}

miércoles, 23 de mayo de 2012

Send email with c#


 private void sendEmail()
        {
            //Declarando Variables
            try
            {
                string From;
                string To;
                string Message;
                string Subject;
                System.Net.Mail.MailMessage Email;

                //Aplicando los campos a cada variable

                From = ;/*correo origen*/
                To = ;/*correo destinatario*/
                Message = ;/*Mensaje*/;
                Subject =;/*Asunto*/
                //Establesco El Email

                Email = new System.Net.Mail.MailMessage(From, To, Subject, Message);
                System.Net.Mail.SmtpClient smtpMail = new System.Net.Mail.SmtpClient("smtp.gmail.com");
                Email.IsBodyHtml = false;
                System.Net.Mail.Attachment attachment;
                txtattach.Text = "";/*File Path*/;
                attachment = new System.Net.Mail.Attachment(txtattach.Text.Trim());
                Email.Attachments.Add(attachment);
                smtpMail.EnableSsl = true;
                smtpMail.UseDefaultCredentials = false;
                smtpMail.Port = 25;
                smtpMail.Credentials = new System.Net.NetworkCredential(/*USER*/,/*PASS*/);
                //smtpMail.ClientCertificates.
                ServicePointManager.ServerCertificateValidationCallback =
                delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)

                { return true; };
                smtpMail.Send(Email);
                attachment.Dispose();
             
                MessageBox.Show("enviado con exito");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

sábado, 11 de febrero de 2012

Validación de RFC , CRM



function validaRFC(cual)
{
mensaje = "Debes poner un formato LLLL-999999-XXX"
pat = /[a-z]|[A-Z]/
pat2 = /[a-z]|[A-Z]|[0-9]/
val = cual.split("-")
if (val.length == 3){
if(val[0].length == 4){
if(!comp(val[0],pat)){
alert( mensaje)
return false
}
}
if(val[1].length == 6){
if(isNaN(val[1])){
alert('no es un numero')
return false
}
}
if(val[2].length == 3){
if(!comp(val[2],pat2)){
alert(mensaje)
return false
}
}
else{
alert(mensaje)
return false
}
}
else{
alert(mensaje)
return false
}
return true
}


function comp(cual,pa){
for ( m = 0 ; m < cual.length ; m++ ) {
if(!pa.test(cual.charAt(m))){
return false
break
}
}
return true
}

domingo, 29 de enero de 2012

Read txt file with c#


 public ArrayList ReadtxtFile(string txtPath)
        {
            StreamReader objReader = new StreamReader(txtPath);
            string sLine = "";
            ArrayList arrText = new ArrayList();

            while (sLine != null)
            {
                sLine = objReader.ReadLine();
                if (sLine != null)
                {
                    if (sLine != "")
                        arrText.Add(sLine);
                }
            }
            objReader.Close();
            return arrText;

        }

fill a Data table dynamically with the results of Xml query


Here you can fill a Data table dynamically with the results of Xml query (Prev. Post)
var dtRowsElements = objData.SelectAllfromTable(ElementTable);
IEnumerable dtRows = (IEnumerable)dtRowsElements;
DataTable objDTable = objData.FillDataTable(dtRows);

/*Function to create the Data Table.*/


 public DataTable FillDataTable(IEnumerable dtRows)
        {
            /*Crea Datatable a partir de lo que Elementos obtenidos de dtRows "Consulta XML que es un IEnumerable"*/
            DataTable dtDescrValue = new DataTable();
            try
            {

                foreach (XElement dtColumn in dtRows.First().Elements())
                {
                    //Crea Columnas
                    dtDescrValue.Columns.Add(dtColumn.Name.ToString(), typeof(string));
                }

                foreach (XElement dtRow in dtRows)
                {
                    //Crea cada registro "Row"
                    DataRow dtDescrRow = dtDescrValue.NewRow();
                    foreach (XElement dtColumn in dtRows.First().Elements())
                    { //Asigna valores de cada column de "Row"
                        dtDescrRow[dtColumn.Name.ToString()] = dtRow.Element(dtColumn.Name.ToString()).Value;
                    }
                    dtDescrValue.Rows.Add(dtDescrRow);
                }

            }
            catch (Exception e)
            {//En caso de Error regresa un Data table con Id: "Error", Descr: Message de error.
                dtDescrValue.Columns.Add("Descr", typeof(string));
                dtDescrValue.Columns.Add("Id", typeof(string));

                DataRow dtDescrRow = dtDescrValue.NewRow();
                dtDescrRow["Descr"] = e.Message;//"No data...";
                dtDescrRow["Id"] = "Error";
                dtDescrValue.Rows.Add(dtDescrRow);
            }
            return dtDescrValue;
        }

XML Query whit Linq C#


Whit this lines you can get all elements from "Task"
string ElementTable = "Task";

 var dtRowsElements = objData.SelectAllfromTable(ElementTable);
IEnumerable dtRows = (IEnumerable)dtRowsElements;


/*Function*/
public IEnumerable SelectAllfromTable(string Table)
        { /*Selecciona Todos los campos de la tabla en el .XML*/
            string DBFile = string.Empty;
            DBFile = "DB\\TrackTimeDB.xml";
            try
            {
                XElement TracktTimeDB = XElement.Load(DBFile);

                var AllData = from c in TracktTimeDB.Descendants(Table)
                              select c;
                return AllData;
            }
            catch (Exception er)
            {
                return null;
            }
        }


 

martes, 17 de enero de 2012

HTML CSS XML JAVASCRIPT ASP PHP SQL MORE...

Sin duda este es un buen sitio donde puedes encontrar todo para aprender y certificarte de manera rápida y sencilla. 


Todo depende de ti realmente. 

saludos.