quinta-feira, 27 de novembro de 2008

>> CRM 4.0 - Exclusão física de registros

O serviço de exclusão física de registros no CRM 4.0 mudou desde a versão anterior (3.0). O processo de exclusão é gerenciado pelo mesmo sistema que controla Triggers de Workflows e todos os jobs de processos assíncronos, como o Duplicate Detection e a chamada de plugins assíncronos (CrmAsyncService.exe). O tempo padrão é de 1440 minutos (24 hs) para o serviço de exclusão física de registros (tabela ScaleGroupOrganizationMaintenanceJobs do BD MSCRM_CONFIG). Segue link para baixar utilitário para poder mudar este tempo.

http://code.msdn.microsoft.com/ScaleGroupJobEditor/Release/ProjectReleases.aspx?ReleaseId=676

Se desejar "forçar" a exclusão física dos registros, podemos fazer isto por executar um Update na tabela de Jobs do CRM da seguinte forma:

USE MSCRM_CONFIG
UPDATE ScaleGroupOrganizationMaintenanceJobs
SET NextRunTime = getdate() -- Right Now!
WHERE OperationType = 14 -- Deletion Service

Após o Update, reinicie o serviço assíncrono do CRM.

>> Dicas JavaScript (ASP.NET & MSCRM 4.0)

Segue abaixo códigos JavaScript úteis no desenvolvimento ASP.NET e também para uso no Microsoft Dynamics CRM 4.0:

JS ASP.NET - Função para obter o valor de algum dos parâmetros da Query String da página.

function getQueryStringParam(name)
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null ) return "";
else
return results[1];
}

JS ASP.NET - Função para Converter o primeiro caractere de toda frase em Maiúsculo.

function UCWords(str)
{
var arrStr = str.split(" ");
var strOut = "";
var i = 0;
var stringValues = "da-de-do-das-dos";
while (i < arrStr.length)
{

if (stringValues.indexOf(arrStr[i].toLowerCase()) < 0)
{
firstChar = arrStr[i].substring(0,1);
remainChar = arrStr[i].substring(1);
firstChar = firstChar.toUpperCase();
remainChar = remainChar.toLowerCase();
strOut += firstChar + remainChar + ' ';
}
else
strOut += arrStr[i] + ' ';

i++;
}
return strOut.substr(0,strOut.length - 1);
}

JS ASP.NET - Adicionar / Remover itens em um DropDownList.

function ClearDropDownList(list)
{
for(i=list.options.length-1; i>=0 ;i--)
{
list.remove(i);
}
}
function addDropDownListOption(list, text, value)
{
var optn = document.createElement("OPTION");
optn.text = text;
optn.value = value;
list.options.add(optn);
}

JS MSCRM 4.0 - Validação de campo Data via JavaScript.

if (ValidateDate(crmForm.all.requestdeliveryby))
{
// Custom code...
}

function ValidateDate(field){
var checkstr = "0123456789";
var DateField = field;
var Datevalue = "";
var DateTemp = "";
var seperator = ".";
var leap = 0;
var err = 0;
var i;
err = 0;
var day = DateField.DataValue.getDate();
var month = (DateField.DataValue.getMonth()+1);
var year = DateField.DataValue.getYear();
DateValue = day + "/" + month + "/" + year;
/* Delete all chars except 0..9 */
for (i = 0; i < DateValue.length; i++) {
if (checkstr.indexOf(DateValue.substr(i,1)) >= 0) {
DateTemp = DateTemp + DateValue.substr(i,1);
}
}
DateValue = DateTemp;
/* Validation of month*/
if ((month < 1) || (month > 12)) {
err = 21;
}
/* Validation of day*/
if (day < 1) {
err = 22;
}
/* Validation leap-year / february / day */
if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) {
leap = 1;
}
if ((month == 2) && (leap == 1) && (day > 29)) {
err = 23;
}
if ((month == 2) && (leap != 1) && (day > 28)) {
err = 24;
}
/* Validation of other months */
if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12"))) {
err = 25;
}
if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) {
err = 26;
}
/* if 00 ist entered, no error, deleting the entry */
if ((day == 0) && (month == 0) && (year == 00)) {
err = 0; day = ""; month = ""; year = ""; seperator = "";
}
if (err != 0)
{
alert("Data Inválida!");
DateField.focus();
}
return (err == 0);
}

JS MSCRM 4.0 - Inserir / Formatar objetos dinamicamente na página do CRM.

with(crmForm.all.new_labelicms)
{
style.border = 0;
style.color = '#6699cc';
style.fonteSize = '7px';
style.fontWeight = 'bold';
style.overflow = 'hidden';
Disabled = true;
DataValue = 'Obs % ICMS: No caso de venda direta...'
}

/* Insert Adjacent Elements */
var server = window.location.host;
var oImg = document.createElement("<" + "img src='http://" + server + "/_imgs/ico/16_alert.gif'" + " />");
var oHr = document.createElement("<" + "HR class='ms-crm-MenuList-Spacer'" + ">");
var oSpn = document.createElement("<" + "span" + ">");
oSpn.innerText = ' Observações';
oSpn.style.fontWeight = 'bold';
crmForm.all.mit_labelicms.insertAdjacentElement("BeforeBegin",oImg);
crmForm.all.mit_labelicms.insertAdjacentElement("BeforeBegin",oSpn);
crmForm.all.mit_labelicms.insertAdjacentElement("BeforeBegin",oHr);

JS MSCRM 4.0 - AJAX no CRM - Chamada assíncrona em um Web Services Customizado.

function FillUOMProduct()
{
var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
var server = window.location.host;
var params = "?productID=" + crmForm.all.productid.DataValue[0].id;
params += "&fields=productnumber,defaultuomid";
var url="http://"+ server+"/WebServicesCRM/Product.asmx/GetProductById"+params;
xmlHttpRequest.open("GET", url, true);
xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttpRequest.setRequestHeader ("SOAPAction", "http://tempuri.org/GetProductById");
xmlHttpRequest.onreadystatechange = HandleStateChangeProduct;
xmlHttpRequest.send();
}

function HandleStateChangeProduct()
{
if (xmlHttpRequest.readyState == 4)
{
var doc = new ActiveXObject('Microsoft.XMLDOM');
var result = xmlHttpRequest.responseXML.xml;
doc.loadXML(result);
}
}

quarta-feira, 19 de novembro de 2008

>> CRM 4.0; IE6; KB953838; Error!!

Após efetuar um Security Update (KB953838) do Windows, teremos um repetitivo "File Download for Blank.aspx" no CRM 4.0.



Soluções:

1 - Instalar o IE7, ou:
2 - Desinstalar o KB953838, ou:
3 - Efetuar o download da Blank.aspx (qq diretório); right-click no arquivo -> Abrir como -> Escolher Programa -> selecionar IE, marcando o checkbox para sempre usar este tipo de programa;

>> Unable to Load Client Print Control - CRM 4.0

Recentemente, no cliente que estou atuando (com o Microsoft Dynamics CRM 4.0) houve uma reclamação de um erro ao tentar imprimir um relatório desenvolvido no Reporting Services.



Pesquisando sobre o assunto e a mensagem de erro descobri a causa, um HotFix de Segurança da Microsoft (KB956391).

Para solucionar o problema, vai ser necessário atualizações de Service Packs, do Report Viewer e do Sql Server (2005 / 2008).

Segue links para Download dos pacotes:

Microsoft Report Viewer Redistributable 2005 Service Pack 1
http://www.microsoft.com/downloads/details.aspx?FamilyID=82833f27-081d-4b72-83ef-2836360a904d&DisplayLang=en

Security Update for SQL Server 2005 Service Pack 3
http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=ae7387c3-348c-4faa-8ae5-949fdfbe59c4

______________________________________________________________________

Microsoft Report Viewer Redistributable 2008 Service Pack 1
http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=bb196d5d-76c2-4a0e-9458-267d22b6aac6

Security Update for SQL Server 2008 Service Pack 1
http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=66ab3dbb-bf3e-4f46-9559-ccc6a4f9dc19


P.S.: Se o servidor do [Reporting Services] não for o mesmo do [Sql Server], existe a necessidade da instalação do [Microsoft Dynamics CRM Data Connector for Reporting Services] no servidor do Sql Server, para que a autenticação funcione corretamente na execução de relatórios pelo CRM.

terça-feira, 18 de novembro de 2008

>> ResizeControls - aspx

Gostaria de deixar os objetos de uma aspx sempre com a altura da janela do browser?

Adicione o código abaixo no html de sua página:

P.S.: Execute a função resizeControls() do método onresize do BODY da página.

>> Busca do ID de um Web Site no IIS

Segue código Template para encontrar o ID de um determinado projeto Web no IIS:

<< C# - VS.NET 2005 - Console Application >>

using System.DirectoryServices;
using System;

public class IISAdmin
{
public static void GetWebsiteID(string websiteName)
{
DirectoryEntry w3svc = new DirectoryEntry("IIS://localhost/w3svc");

foreach(DirectoryEntry de in w3svc.Children)
{
if(de.SchemaClassName == "IIsWebServer" && de.Properties["ServerComment"][0].ToString() == websiteName)
{
Console.Write(de.Name);
}

}

}
public static void Main()
{
GetWebsiteID("Default Web Site");
}

}

>> .NET 2.0 - Chamada Web Services - Sem "Add Web References"

Segue exemplo de código para chamada a Web Services sem a necessidade de adição da referência web no projeto.

Basta passar para a função "CallWebServices" a URL, o nome da função e os parâmetros do Web Services.

Exemplo de uso da função:

using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Text;

List<'Hashtable> oParams = new List<'Hashtable>();
Hashtable ht1 = new Hashtable();
ht1.Add("paramName", "productid");
ht1.Add("paramValue", "413D080B-09A7-DB11-89C7-0016356BE094");
oParams.Add(ht1);

string xml = CallWebServices("http://localhost/MyWS/product.asmx", "GetProductPriceList", oParams);

public static string CallWebServices(string url, string functionName, List<'Hashtable> oParams)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.Headers.Add("SOAPAction", "\"http://tempuri.org/" + functionName + "\"");
request.Method = "POST";
request.ContentType = "text/xml; charset=utf-8";
request.Accept = "text/xml";
request.Timeout = 10000;
Stream requestStream = request.GetRequestStream();
string soapEnvelope = "";
soapEnvelope += " soapEnvelope += " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"";
soapEnvelope += " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"";
soapEnvelope += " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
soapEnvelope += " ";
soapEnvelope += " <" + functionName + " xmlns=\"http://tempuri.org/\">";
if (oParams.Count > 0)
{
Boolean hashListOk = (oParams[0].Contains("paramName") && oParams[0].Contains("paramValue"));
if (!hashListOk) return string.Empty;
foreach (Hashtable ht in oParams)
{
soapEnvelope += "<" + ht["paramName"].ToString() + ">" + ht["paramValue"].ToString() + "";
}
}
soapEnvelope += " ";
soapEnvelope += "
";
soapEnvelope += " ";
// Convert the string into a byte array.
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] ByteArray = encoder.GetBytes(soapEnvelope);
// Write data to the stream.
requestStream.Write(ByteArray, 0, ByteArray.Length);
requestStream.Flush();
requestStream.Close();
StreamReader esr = null;
string result = string.Empty;
try
{
esr = new StreamReader(request.GetResponse().GetResponseStream());
result = esr.ReadToEnd();
}
catch (System.Web.Services.Protocols.SoapException ex)
{
string x = ex.Detail.InnerText;
}
catch (Exception ex)
{
string x = ex.Message;
}
return result;
}

>> Artigos - ASP.NET 1.1

Olá pessoal,

Gostaria de compartilhar com vocês algumas dicas e códigos para facilitar no entendimento e desenvolvimento na plataforma .NET, mais especificamente no ASP.NET 1.1 (em breve também para as versões 2.0 e 3.5) .

Abaixo segue links de artigos que publiquei no site do msdn para desenvolvedores, o SharePedia (http://www.msdnbrasil.com.br/Sharepedia/).

P.S.: Para baixar os artigos, é necessária uma conta no Passport.NET ou Windows Live da Microsoft.

- Navegando entre Forms - http://www.msdnbrasil.com.br/secure/sharepedia/download.aspx?id=52345

- Mantendo informações de estado em uma aplicação Web - http://www.msdnbrasil.com.br/secure/sharepedia/download.aspx?id=52270

- Entendendo Transações - http://www.msdnbrasil.com.br/secure/sharepedia/download.aspx?id=52644

- Autenticação e autorização de usuários - segurança na sua aplicação Web - PARTE I - http://www.msdnbrasil.com.br/secure/sharepedia/download.aspx?id=52199

- Autenticação e autorização de usuários - segurança na sua aplicação Web - PARTE II - http://www.msdnbrasil.com.br/secure/sharepedia/download.aspx?id=52200

- Autenticação e autorização de usuários - segurança na sua aplicação Web - PARTE III - http://www.msdnbrasil.com.br/secure/sharepedia/download.aspx?id=52201

- WebApp - Trabalhando com objetos – Parte I - http://www.msdnbrasil.com.br/secure/sharepedia/download.aspx?id=52266

- WebApp - Trabalhando com objetos – Parte II - http://www.msdnbrasil.com.br/secure/sharepedia/download.aspx?id=52267

- Tratamento de erros/exceptions - ASP.NET - http://www.msdnbrasil.com.br/secure/sharepedia/download.aspx?id=52034