Mostrando postagens com marcador C#. Mostrar todas as postagens
Mostrando postagens com marcador C#. Mostrar todas as postagens

quinta-feira, 3 de outubro de 2013

Obter Valor de OptionSet

0 comentários
Neste exemplo, temos o código do OptionSet, e queremos retornar a descrição(Label).

1:      public int ObterValordeOptionSet(string entidade, string campo, string opcao)  
2:      {  
3:        int retorno = 0;  
4:        RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest  
5:        {  
6:          EntityLogicalName = entidade,  
7:          LogicalName = campo,  
8:          RetrieveAsIfPublished = true  
9:        };  
10:        RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)orgContext.Execute(attributeRequest);  
11:        EnumAttributeMetadata attributeMetadata = (EnumAttributeMetadata)attributeResponse.AttributeMetadata;  
12:        foreach (OptionMetadata om in attributeMetadata.OptionSet.Options)  
13:        {  
14:          if (om.Label.UserLocalizedLabel.Label == opcao)  
15:          {  
16:            retorno = (int)om.Value;  
17:          }  
18:        }  
19:        return retorno;  
20:      }  
 

Leia Mais >>

Get value from OptionSet

0 comentários
In this example, we have the OptionSet Code and want to return the description (Label).

1:      public int ObterValordeOptionSet(string entidade, string campo, string opcao)  
2:      {  
3:        int retorno = 0;  
4:        RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest  
5:        {  
6:          EntityLogicalName = entidade,  
7:          LogicalName = campo,  
8:          RetrieveAsIfPublished = true  
9:        };  
10:        RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)orgContext.Execute(attributeRequest);  
11:        EnumAttributeMetadata attributeMetadata = (EnumAttributeMetadata)attributeResponse.AttributeMetadata;  
12:        foreach (OptionMetadata om in attributeMetadata.OptionSet.Options)  
13:        {  
14:          if (om.Label.UserLocalizedLabel.Label == opcao)  
15:          {  
16:            retorno = (int)om.Value;  
17:          }  
18:        }  
19:        return retorno;  
20:      }  
 

Leia Mais >>

terça-feira, 17 de setembro de 2013

Você deveria especificar um parente Contato ou Conta - FautException

0 comentários
Ao tentar gravar uma ocorrência/incidente, apresenta um exception com a mensagem "Você deveria especificar um parente Contato ou Conta".











Para resolver basta atribuir o valor do atributo customerid conforme exemplo abaixo:

   1:  Entity ocorrencia = new Entity("incident");
   2:  ocorrencia["title"] = txtDescricao.Text.Split('\n')[0];
   3:   
   4:  if (cliente.LogicalName.Contains("account"))
   5:     ocorrencia["accountid"] = cliente;
   6:  else if (cliente.LogicalName.Contains("contact"))
   7:     ocorrencia["contactid"] = cliente;
   8:   
   9:  ocorrencia["customerid"] = cliente;

Leia Mais >>

You should specify a parent contact or account - FaultException

0 comentários
When trying to record an occurrence / incident, an exception with the message "You should specify a parent contact or account."












To solve simply assign the value of the atribute customerid example below:

   1:  Entity ocorrencia = new Entity("incident");
   2:  ocorrencia["title"] = txtDescricao.Text.Split('\n')[0];
   3:   
   4:  if (cliente.LogicalName.Contains("account"))
   5:     ocorrencia["accountid"] = cliente;
   6:  else if (cliente.LogicalName.Contains("contact"))
   7:     ocorrencia["contactid"] = cliente;
   8:   
   9:  ocorrencia["customerid"] = cliente;

Leia Mais >>

quinta-feira, 12 de setembro de 2013

Criar Ocorrências no C#

0 comentários

Neste post mostro como criar ocorrências no C#

   1:  Entity ocorrencia = new Entity("incident");
   2:  ocorrencia["title"] = txtDescricao.Text.Split('\n')[0];
   3:   
   4:  if (cliente.LogicalName.Contains("account"))
   5:     ocorrencia["accountid"] = cliente;
   6:  else if (cliente.LogicalName.Contains("contact"))
   7:     ocorrencia["contactid"] = cliente;
   8:   
   9:  ocorrencia["customerid"] = cliente;
  10:  ocorrencia["subjectid"] = assunto;
  11:   
  12:  int tipoassunto = LocalizarOpcao("incident", "casetypecode", ddlSetor.SelectedItem.Text);
  13:   
  14:  ocorrencia["casetypecode"] = new OptionSetValue(tipoassunto);
  15:  ocorrencia["caseorigincode"] = new OptionSetValue(3);
  16:  ocorrencia["ahi_fila"] = fila;
  17:   
  18:  config = serverConnect.GetServerConfiguration();
  19:  ServerConnection.GetOrganizationProxy(config).EnableProxyTypes();
  20:  IOrganizationService service = ServerConnection.GetOrganizationProxy(config);
  21:   
  22:  _idocorrencia = service.Create(ocorrencia);

Leia Mais >>

Create Incidents in C #

0 comentários

In this post I show how to create incidents in C#

   1:  Entity ocorrencia = new Entity("incident");
   2:  ocorrencia["title"] = txtDescricao.Text.Split('\n')[0];
   3:   
   4:  if (cliente.LogicalName.Contains("account"))
   5:     ocorrencia["accountid"] = cliente;
   6:  else if (cliente.LogicalName.Contains("contact"))
   7:     ocorrencia["contactid"] = cliente;
   8:   
   9:  ocorrencia["customerid"] = cliente;
  10:  ocorrencia["subjectid"] = assunto;
  11:   
  12:  int tipoassunto = LocalizarOpcao("incident", "casetypecode", ddlSetor.SelectedItem.Text);
  13:   
  14:  ocorrencia["casetypecode"] = new OptionSetValue(tipoassunto);
  15:  ocorrencia["caseorigincode"] = new OptionSetValue(3);
  16:  ocorrencia["ahi_fila"] = fila;
  17:   
  18:  config = serverConnect.GetServerConfiguration();
  19:  ServerConnection.GetOrganizationProxy(config).EnableProxyTypes();
  20:  IOrganizationService service = ServerConnection.GetOrganizationProxy(config);
  21:   
  22:  _idocorrencia = service.Create(ocorrencia);

Leia Mais >>

segunda-feira, 21 de novembro de 2011

Customization using Visual Studio 2010 (C #) - Plug-In

0 comentários
Customization using Visual Studio 2010 (C #) - Plug-In

In the post 07. Customization using Visual Studio 2010 (C #) and 08. Customization using Visual Studio 2010 (C #) - Download the SDK, we began the study of customization using VS 2010. Today we will develop the plug-in to record the data from Dynamics CRM to ERP customer.
Launch Visual Studio 2010 and open a new project by adding a class library.

Name the CadCliente, and select the location where you saved the files in your project and click OK.
We need to sign the bill as follows:
Click right-click properties, and click Open.
Check Sign the Assembly and click in Signing and New

In the field (key file name), tell CadCliente and click OK




 
Add a new item in the project of type Class with the name of PluginCliente.cs


And insert the following code:

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System.Data.SqlClient;

namespace CadCliente
{
public class PluginCliente : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
// Pega contexto em execução
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

if (context.MessageName.ToUpper() == "CREATE")
{
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
// Captura a entidade
Entity targetEntity = (Entity)context.InputParameters["Target"];

if (targetEntity.LogicalName.ToUpper() == "ACCOUNT")
{
// Captura o serviço
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

// String de conexão SQL do banco de dados ERP
string conexao = "Data Source=WIN-4EF7UMIGTTO;Initial Catalog=ERP;Integrated Security=SSPI";

string sql = "Insert into ERP_Cliente (codcliente,nome,endereco,bairro,cidade,estado,cep,telefone) values (@codcliente, @nome, @endereco, @bairro, @cidade, @estado, @cep, @telefone)";
SqlConnection con = new SqlConnection(conexao);
SqlCommand comando = new SqlCommand(sql, con);

comando.Parameters.Add(new SqlParameter("@codcliente", targetEntity["jd_codigo"].ToString()));
comando.Parameters.Add(new SqlParameter("@nome", targetEntity["name"].ToString()));
comando.Parameters.Add(new SqlParameter("@endereco", targetEntity["address1_name"].ToString()));
comando.Parameters.Add(new SqlParameter("@bairro", targetEntity["address1_line1"].ToString()));
comando.Parameters.Add(new SqlParameter("@cidade", targetEntity["address1_city"].ToString()));
comando.Parameters.Add(new SqlParameter("@estado", targetEntity["address1_stateorprovince"].ToString()));
comando.Parameters.Add(new SqlParameter("@cep", targetEntity["address1_postalcode"].ToString()));
comando.Parameters.Add(new SqlParameter("@telefone", targetEntity["telephone1"].ToString()));

try
{
con.Open();
comando.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
return;
}
}
else
{
return;
}
}
else
{
return;
}
}
else if (context.MessageName.ToUpper() == "UPDATE")
{
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
// Captura a entidade.
Entity targetEntity = (Entity)context.InputParameters["Target"];

if (targetEntity.LogicalName.ToUpper() == "ACCOUNT")
{
// Captura o serviço
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

// Id do registro atual
Guid id = (Guid)targetEntity["accountid"];

// captura dados da entidade
Entity entidade = service.Retrieve("account", id, new ColumnSet(true));

// String de conexão SQL do banco de dados ERP
// WIN-4EF7UMIGTTO = Nome da máquina/servidor pode ser substituido por "." (ponto).

string conexao = "Data Source=WIN-4EF7UMIGTTO;Initial Catalog=ERP;Integrated Security=SSPI";
string sql = @"Update ERP_Cliente Set nome = @nome , endereco = @endereco, bairro = @bairro,cidade = @cidade, estado = @estado, cep = @cep,
telefone = @telefone Where codcliente = @codcliente" ;

SqlConnection con = new SqlConnection(conexao);
SqlCommand comando = new SqlCommand(sql, con);

comando.Parameters.Add(new SqlParameter("@codcliente", entidade["jd_codigo"].ToString()));
comando.Parameters.Add(new SqlParameter("@nome", entidade["name"].ToString()));
comando.Parameters.Add(new SqlParameter("@endereco", entidade["address1_name"].ToString()));
comando.Parameters.Add(new SqlParameter("@bairro", entidade["address1_line1"].ToString()));
comando.Parameters.Add(new SqlParameter("@cidade", entidade["address1_city"].ToString()));
comando.Parameters.Add(new SqlParameter("@estado", entidade["address1_stateorprovince"].ToString()));
comando.Parameters.Add(new SqlParameter("@cep", entidade["address1_postalcode"].ToString()));
comando.Parameters.Add(new SqlParameter("@telefone", entidade["telephone1"].ToString()));

try
{
con.Open();
comando.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
return;
}
}
}
}
}
}
}


Build and take out all the errors that may have appeared.
In the next posting we will register the plugin, and how to debug.








Leia Mais >>

Customização usando Visual Studio 2010 (C #) - Plug-In

0 comentários
Customização usando Visual Studio 2010 (C #) - Plug-In

No post 07. Customização usando Visual Studio 2010 (C#) e 08. Customização usando Visual Studio 2010 (C#) - Download SDK, iniciamos o estudo de customização usando o VS 2010. Hoje iremos desenvolver o plug-in para cadastrar os dados do Dynamics CRM para o ERP do cliente.
Inicie o Visual Studio 2010,  e abra um novo projeto adicionando um class library.

Dê o nome de CadCliente, e selecione o local onde será gravado os arquivos do seu projeto e clique em OK.
Precisamos assinar o projeto da seguinte forma:

Cique com botão direito do mouse em properties, e clique com Open.

Check Sign the Assembly and clique em Signing e em New

No campo (key file name), informe CadCliente e clique em Ok




Adicione no projeto um novo item do tipo Class com o nome de PluginCliente.cs


E insira o seguinte código:

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System.Data.SqlClient;

namespace CadCliente
{
    public class PluginCliente : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            // Pega contexto em execução
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            if (context.MessageName.ToUpper() == "CREATE")
            {
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    // Captura a entidade
                    Entity targetEntity = (Entity)context.InputParameters["Target"];

                    if (targetEntity.LogicalName.ToUpper() == "ACCOUNT")
                    {
                        // Captura o serviço
                        IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                        IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                        // String de conexão SQL do banco de dados ERP
                        string conexao = "Data Source=WIN-4EF7UMIGTTO;Initial Catalog=ERP;Integrated Security=SSPI";

                        string sql = "Insert into ERP_Cliente (codcliente,nome,endereco,bairro,cidade,estado,cep,telefone) values (@codcliente, @nome, @endereco, @bairro, @cidade, @estado, @cep, @telefone)";
                        SqlConnection con = new SqlConnection(conexao);
                        SqlCommand comando = new SqlCommand(sql, con);

                        comando.Parameters.Add(new SqlParameter("@codcliente", targetEntity["jd_codigo"].ToString()));
                        comando.Parameters.Add(new SqlParameter("@nome", targetEntity["name"].ToString()));
                        comando.Parameters.Add(new SqlParameter("@endereco", targetEntity["address1_name"].ToString()));
                        comando.Parameters.Add(new SqlParameter("@bairro", targetEntity["address1_line1"].ToString()));
                        comando.Parameters.Add(new SqlParameter("@cidade", targetEntity["address1_city"].ToString()));
                        comando.Parameters.Add(new SqlParameter("@estado", targetEntity["address1_stateorprovince"].ToString()));
                        comando.Parameters.Add(new SqlParameter("@cep", targetEntity["address1_postalcode"].ToString()));
                        comando.Parameters.Add(new SqlParameter("@telefone", targetEntity["telephone1"].ToString()));

                        try
                        {
                            con.Open();
                            comando.ExecuteNonQuery();
                            con.Close();
                        }
                        catch (Exception ex)
                        {
                            return;
                        }
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    return;
                }
            }
            else if (context.MessageName.ToUpper() == "UPDATE")
            {
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    // Captura a entidade.
                    Entity targetEntity = (Entity)context.InputParameters["Target"];

                    if (targetEntity.LogicalName.ToUpper() == "ACCOUNT")
                    {
                        // Captura o serviço
                        IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                        IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                        // Id do registro atual
                        Guid id = (Guid)targetEntity["accountid"];

                        // captura dados da entidade
                        Entity entidade = service.Retrieve("account", id, new ColumnSet(true));

                        // String de conexão SQL do banco de dados ERP
                        // WIN-4EF7UMIGTTO = Nome da máquina/servidor pode ser substituido por "." (ponto).

                        string conexao = "Data Source=WIN-4EF7UMIGTTO;Initial Catalog=ERP;Integrated Security=SSPI";
                        string sql = @"Update ERP_Cliente Set nome = @nome , endereco = @endereco, bairro = @bairro,cidade = @cidade, estado = @estado, cep = @cep,
                                                              telefone = @telefone Where codcliente = @codcliente" ;

                        SqlConnection con = new SqlConnection(conexao);
                        SqlCommand comando = new SqlCommand(sql, con);

                        comando.Parameters.Add(new SqlParameter("@codcliente", entidade["jd_codigo"].ToString()));
                        comando.Parameters.Add(new SqlParameter("@nome", entidade["name"].ToString()));
                        comando.Parameters.Add(new SqlParameter("@endereco", entidade["address1_name"].ToString()));
                        comando.Parameters.Add(new SqlParameter("@bairro", entidade["address1_line1"].ToString()));
                        comando.Parameters.Add(new SqlParameter("@cidade", entidade["address1_city"].ToString()));
                        comando.Parameters.Add(new SqlParameter("@estado", entidade["address1_stateorprovince"].ToString()));
                        comando.Parameters.Add(new SqlParameter("@cep", entidade["address1_postalcode"].ToString()));
                        comando.Parameters.Add(new SqlParameter("@telefone", entidade["telephone1"].ToString()));

                        try
                        {
                            con.Open();
                            comando.ExecuteNonQuery();
                            con.Close();
                        }
                        catch (Exception ex)
                        {
                            return;
                        }
                    }
                }
            }
        }
    }
}


Compile e tire todos os erros que podem ter aparecido.
Nas próximas postagem iremos registrar o plugin, e como debugar.













Leia Mais >>

terça-feira, 15 de novembro de 2011

Customization using Visual Studio 2010 (C #) - Download the SDK

0 comentários
Customization using Visual Studio 2010 (C #) - Download the SDK
Before starting the development of the plugin mentioned in post 07. Customization using Visual Studio 2010 (C #), we must download the Microsoft Dynamics CRM 2011 SDKand install on the machine, preferably where you installed the Microsoft Dynamics CRM 2011.
The Software Development Kit (SDK) contains information for developers writing server side code, custom business logic, integration modules, workflow, and plug-ins. It provides an architectural overview of Microsoft Dynamics CRM entity model, security model, and Web services code example and guidance is provided to guide you through the new features. It also contains information for developers customizing the Web client or Microsoft Dynamics CRM for Microsoft Office Outlook, including scripting, integration of custom Web pages, and a lot of sample code.

Besides the documentation, including tools for development.

Related Post:
07. Customization using Visual Studio 2010 (C #)




Leia Mais >>

Customização usando Visual Studio 2010 (C#) - Download SDK

0 comentários
Customização usando Visual Studio 2010 (C#) - Download SDK

Antes de iniciarmos o desenvolvimento do Plugin citado no post 07. Customização usando Visual Studio 2010 (C#), devemos fazer o download do Microsoft Dynamics CRM 2011 SDK, e instalar na máquina, preferencialmente onde está instalado o Microsoft Dynamics CRM 2011.

O Software Development Kit (SDK) contém informações para desenvolvedores escrever código do lado do servidor, lógica de negócios personalizada, módulos de integraçãofluxo de trabalho, e plug-ins. Ele fornece uma visão geral da arquitetura do Microsoft Dynamics CRM, modelo de entidade, modelo de segurança, e serviços Web. Código de exemplo e são fornecidas orientações para guiá-lo através dos novos recursos. Ele também contém informações para desenvolvedores personalizar o cliente Web ou o Microsoft Dynamics CRM para Microsoft Office Outlook, incluindo scripting, integração de páginas Web personalizados, e um monte de código de exemplo.

Além da documentação, inclui ferramentas necessárias para o desenvolvimento.
Post Relacionado:
07. Customização usando Visual Studio 2010 (C#)

Leia Mais >>

sábado, 12 de novembro de 2011

Customization using Visual Studio 2010 (C #)

0 comentários
Customization using Visual Studio 2010 (C #)

Hello,


     My previous posts were doing customizations using javascript, and how to find a few blogs .Net (C #), following my posts will have examples of how to customize the Dynamics CRM using Visual Studio 2010 (C #).
    Suppose that our customer asked to write a customer (Account), the same is recorded in the database already exists in the customer's ERP. For this solution we will develop a plugin.
     
     To start it, have on their machines:
         - SQL Server
         - Dynamics CRM 2011
         - Visual Studio 2010

      To simulate the database client, we create a database in SQL as follows:    
         - Create a database with the name ERP

          .






         - In the ERP database, create the Customer table, with the following structure










       In the next post we will develop the Plugin, see you soon.

Leia Mais >>

Customização usando Visual Studio 2010 (C#)

0 comentários
Customização usando Visual Studio 2010 (C#)

Olá,
    Meus posts anteriores foram customizações usando o javascript, e como encontramos poucos blogs em .Net (C#), meus posts seguintes terão exemplos de como customizar o Dynamics CRM, utilizando o Visual Studio 2010 (C#).

     Suponhamos que o nosso cliente solicitou que ao gravar um cliente (Account), o mesmo seja gravado no banco de dados já existente no ERP do cliente. Para esta solução iremos desenvolver um Plugin.

     Para comerçamos, tenham em suas máquinas:
        - SQL Server
        - Dynamics CRM 2011
        - Visual Studio 2010

     Para simular o banco de dados do cliente, iremos criar um banco no SQL conforme abaixo:
        - Crie um banco de dados com o nome ERP.










        - No banco de dados ERP, crie a tabela Cliente, com a seguinte estrutura









      No próximo post iremos desenvolver o Plugin, até breve.

Leia Mais >>

sábado, 5 de novembro de 2011

IdentityModel (Windows Identity Foundation)

0 comentários
IdentityModel (Windows Identity Foundation)

Sometimes when we're deploying custom applications on the server where you installed the Dynamics CRM, SharePoint, or even, we encounter the following message.



When this happens, you need to manually install WIF (Windows Identity Foundation), the WIF is not included. NET Framework.
You can download and install the appropriate WIF Windows Identity Foundation.

Leia Mais >>

IdentityModel (Windows Identity Foundation)

0 comentários
IdentityModel (Windows Identity Foundation)

As vezes quando estamos implantando aplicações personalizadas em servidores onde está instalado o Dynamics CRM, ou até mesmo o SharePoint, nos deparamos com a seguinte mensagem.



Quando isto acontecer, você precisa instalar manualmente WIF (Windows Identity Foundation), o WIF não está incluído no .Net FrameWork.
Você pode baixar e instalar o WIF apropriado Windows Identity Foundation.

Leia Mais >>

Arquivo do blog

Números de Visitas

  

TOPO