Friday, April 22, 2011

Writing Leads from your corporate web site to on-premise Microsoft Dynamics CRM 2011 using XRM, LINQ to CRM, C#, and Web Services

Scenario

I was asked by our sales team to modify their web form so it wouldn’t just send emails but also write a new Lead to our Dynamics CRM 2011 system.

l4fpv030

>

aocqtheo
Email

+

yzjjyw0f

CRM

Solution

LINQ to CRM Generation

I used Hosk’s method to generate and use the LINQ to CRM classes for our specific server.

 

C# Function to Write Lead to CRM
public void AddLead(string subject, string contactFullName,
string companyName, Guid ownerId, LeadSourceWebSiteName leadSourceWebSiteName,
Uri organizationUri, string runAsUser, string runAsPassword, string runAsDomain, string emailAddress,
string phone, string message)
{
try
{
var credentials = new ClientCredentials();
credentials.Windows.ClientCredential = new System.Net.NetworkCredential(runAsUser, runAsPassword, runAsDomain); ;
var serviceProxy = new OrganizationServiceProxy(organizationUri, null, credentials, null);
serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
var oc = new ErServiceContext(serviceProxy);
var newLead = new Lead()
{
Subject = subject,
LastName = contactFullName,
CompanyName = companyName,
OwnerId = new EntityReference(SystemUser.EntityLogicalName, ownerId),
LeadSourceCode = new OptionSetValue(8),
new_LeadSourceWebSiteName = leadSourceWebSiteName.ToString(),
EMailAddress1 = emailAddress,
Telephone1 = phone,
Description = string.Format("Message from web lead on {0}: {1}", DateTime.Now, message)
};
//serviceProxy.Create(newLead);
oc.AddObject(newLead);
oc.SaveChanges();
}
catch (Exception ex)
{
throw ex;
}
}

Calling it from the Web Form
protected void SendLeadToCrm(string subject, string name, string company, string email, string phone, string message)
{
try
{
//Colyer
var ownerId = new Guid("AB56EF33-4913-DE11-9EE8-00156D0A7301"); //You have to get this from the server
var serviceUrl = new Uri("http://server/company/xrmservices/2011/Organization.svc");
var serviceAccountUser = "serviceAccount";
var serviceAccountPassword = "password";
var crm = new CrmServiceClient();
crm.AddLead("Web Lead", name, company, ownerId, LeadSourceWebSiteName.extendedresults,
serviceUrl, serviceAccountUser, serviceAccountPassword, "yourdomain", email, phone, message);
}
catch (Exception ex)
{
//
}
}

Conclusions


This was a fun but long and drawn out project.  I got to learn a lot about CRM 2011 and how it works with C#.  It is way better than CRM 4.0 and the LINQ to CRM stuff is pretty slick.


I hope you find the above useful.  There are a lot of “hidden tricks” in the code above but I think it’ll get you pointed in the right direction if you dissect it.


Happy programming!

Wednesday, April 06, 2011

Query String Parameters as a Table for Debugging in Fiddler

cwcyjycs

I frequently run into this problem of wanting to know what’s in the query string for debugging web apps.  Here’s where to get it in Fiddler.  Pretty handy!!!

Inspectors > WebForms > QueryString

Monday, March 21, 2011

Updating Read-Only Dynamics CRM 2011 Fields (Pipeline Phase and Probability) from a Sales Stage Dropdown

We’re setting up Dynamics CRM 2011 at my workplace and I had to figure out how to set up our pipeline. Here’s my solution:

fffcpplt

I created a Sales Stage field that updates the Pipeline Phase and Probability fields on change. I followed Ayaz Ahmad’s solution for hooking up a javascript function to my Opportunity form and then wrote the following function (after some iteration).

function new_SalesStage_OnChange()
{
var new_salesstageAttr = Xrm.Page.getAttribute("new_salesstage");
var stepnameAttr = Xrm.Page.getAttribute("stepname");
var closeprobabilityAttr = Xrm.Page.getAttribute("closeprobability");

closeprobabilityAttr.setSubmitMode("always");
stepnameAttr.setSubmitMode("always");

if (new_salesstageAttr.getSelectedOption() == null)
{
stepnameAttr.setValue("");
closeprobabilityAttr.setValue(null);
}
else
{
var ssVal = new_salesstageAttr.getSelectedOption().text;
var pl = ssVal.lastIndexOf('%');
var probability = parseInt(ssVal.substring(pl-2, pl));

stepnameAttr.setValue(ssVal);
closeprobabilityAttr.setValue(probability);
}
}

The biggest tricks were:



  • Using LOWER CASE names for my field names.  This breaks if I use getAttribute(“new_SalesStage”), which is it’s real name.  Booo, Microsoft!!!
  • Handling the null value.
  • Using the setSubmitMode(“always”) call to make sure the readonly fields were beiing saved.

This solution should have been quicker but I learned a lot on it.

  

Friday, March 04, 2011

This means war! Forcing collaboration

Whether you’re trying to convince Moammar Gadhafi to stand down or trying to work with coworkers, you are at war.  I don’t mean this in a bad/negative way, I mean it in a real(istic) way.  People are competitive and out for their own.  They may be your coworkers and friends but in my experience, it’s still competitive; it’s still a battle and a daily challenge.

To me, the elements of collaboration are as follows: the people, roles, relationships, events, actions, and artifacts/documents/messages have to be defined and shared effectively for a given relationship to be successful and beneficial. 

Sure we can operate under other pretenses: avoidance, control, dictatorship, and subversion but our goal should always be collaboration and partnership.  We may grow tired and give up on certain objectives, but we have to keep going on, keep forming the relationship and agreement.

In work and business I think this is far easier (and more necessary) than in personal relationships.  But you have to define these things. 

I’m dealing with one of our senior executives at work no, trying to form a clear and beneficial relationship between the sales/account management/business development functions and the project management/planning/delivery function.  This distinction/division is relatively new (probably better stated as IMMATURE) within our company, so there is a lot to do.  First we have to figure out each others’ incentives and interests and then we can figure out a working relationship / process / protocol that works and benefits the organization.

These things take time but if you stay after it you (and the other party) will win.

Thursday, March 03, 2011

Identify those who you will let manage and influence you wisely

This should be simple.  You should choose your boss and your bosses.  They should all be allowed to manage you.  Don’t fight it.  Some may be clueless idiots, but others may be extremely talented and really able to help you out.

When it comes to finding the right people for you to work with daily and repeatedly (your best friends within a project or organization), choose wisely.  Know your criteria.  Do you want them to be your friend?  Do you want them to be smarter than you?  Dumber?  Superior?  More junior?  More senior?

Whichever way you go, choose your work-friends and partners wisely.  Getting this wrong will really suck.  You can choose who these followers are and do it wisely.

Wednesday, March 02, 2011

Fluent API Navigation–What’s the member returning?

Getting up and down an object map isn’t easy, especially when you don’t understand the API.  Some APIs allow “chaining” where I can write something like Coffee.MakeCup().CupSize(‘Large’). 

What this example implies is that each child member/method call returns itself or the base.  Determining if something is returning itself or the base is a pretty big distinction / way of thinking.

This can be applied to people: does this guy really believe what he’s saying or is he just a talking head?  People that “return the base” are not representing themselves.  People who return themselves are real and authentic. 

I’m not saying that one is better than the other but there are situations and needs for both.  This is a fundamental design decision.

Friday, January 28, 2011

Rely on others and remove impediments

I’ve written before about the Theory of Wringable Necks.  Some people want to put things on people and delegate and not have to care about things.  This is perhaps good management but probably not good leadership.  Leaders are aware that they are the ones who are ultimately responsible and accountable for everything even when things have been delegated.  Life is a team and they’re a key member.1aynqlh0

I have a project manager who asked me to do something and I’m doing it..but slowly.  It’s taking me a long time to learn a new set of technologies and the result is tricky.  If I get it wrong, I break something.  The project manager has not provided me any input or guidance and is expecting me to get the job done.  He just stopped by to ask if I was done and the answer was, “I’m still trying to work out that one last kink.”  He offered no suggestions and simply looked disappointed. 

If you’re going to delegate a task, be prepared to involve others to get the job done.  Never assume that the person that you chose is the right person for the job or that you have the right to wring their neck if things don’t go so well.  Remove impediments for people, find support, and recognize that you (as the PM) are the one responsible for the speed and quality by which something is delivered.

Wednesday, January 26, 2011

The beauty of Inversion of Control

public CoeController() : this(IoC.Resolve<IRepository<Coe>>(), IoC.Resolve<IAuthenticationService>()) 
{ }

A controller that can look up what its dependencies are.


Seems neat.  Still thinking about it.

Inversion of Control, Dependency Injection. Awesome!

This stuff seems so cool and important for being able to test your code.  I just watched this very excellent video from James Kovaks on IoC and DI in C#.  He makes it very simple to use and understand the concepts of why and how to do this.  Great job on this.

Tuesday, January 18, 2011

Knowledge “streams” vs. knowledge as a globe, query, function, service

I think these are two pretty big distinctions in how we think about knowledge and information. 

When knowledge is a “stream” (a book, a web page that you read from beginning to end, a blog post with comments), we consume it in a specific form and have certain expectations.  For example, we don’t think that we can “query” a book unless we have read it.  If the book has a Table of Contents or good Index, then we can access its information.

 

These “query methods” / shortcuts like Indices, Tables of Contents, and Search Engines are short-hand forms of accessing knowledge.  Since humans generally want to “move forward”, they store knowledge in (sometimes disconnected) streams rather than taking the time to update the index.  We build computer systems, search engines and other technologies to “mine” our knowledge, but we’ll probably never be able to keep up with the steams of information that are being produced (both on- and off-paper).

Monday, January 17, 2011

Looking for a UI control that will allow me to do bulk adding with edit and delete

I’m working on a couple of projects now that have the need for quick-edit lists.  (Lists of free-form things like Actions, Reasons, etc.).  I want the user to be able to quickly add a lot of these items, almost in a brainstorming type way.  Editing and deleting the items should also be easy. 

Here’s a quick mock-up of what I’m trying to accomplish:

eejn0snh

I see an article and video on the web from Elijah Manor (a .NET MVP) about hooking up a control called jqGrid (download page is here) that works with .NET MVC.

It looks like it could be a lot of work to use that.  I may roll my own method but I’m not yet sure.  TBD tomorrow…

Sunday, January 16, 2011

CTP5 [DataAnnotations]

DataAnnotations are sweet! 

The MSDN announcement to CTP5 has a listing of the Data Annotations provided.  Here they are formatted for your enjoyment:

  • Key
  • StringLength
  • MaxLength
  • ConcurrencyCheck
  • Required
  • Timestamp
  • ComplexType
  • Column    - Placed on a property to specify the column name, ordinal & data type
  • Table - Placed on a class to specify the table name and schema
  • InverseProperty - Placed on a navigation property to specify the property that represents the other end of a relationship
  • ForeignKey - Placed on a navigation property to specify the property that represents the foreign key of the relationship
  • DatabaseGenerated - Placed on a property to specify how the database generates a value for the property (Identity, Computed or None)
  • NotMapped - Placed on a property or class to exclude it from the database

Many-to-Many table mapping in EF CTP5

Was just reading that the method of many-to-many mapping is different in CTP5.  Here’s the method:

public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Store> SoldAt { get; set; }
}

public class Store
{
public int Id { get; set; }
public string StoreName { get; set; }
public ICollection<Product> Products { get; set; }
}

public class MyContext : DbContext
{
public DbSet<Product> Products { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{

modelBuilder.Entity<Product>()
.HasMany(p => p.SoldAt)
.WithMany(s => s.Products)
.Map(mc => {
mc.ToTable("ProductsAtStores");
mc.MapLeftKey(p => p.Id, "ProductId");
mc.MapRightKey(s => s.Id, "StoreId");
});
}

Saturday, January 15, 2011

My volunteer experience today

I had a fun day at Seattle GiveCamp today.  I worked with a couple of guys from MokaSocial to create a mobile app for a conference.  It’s going to be available on iPhone, Android, Blackberry, and Windows Phone.  It is a “skin” for a WordPress site and detects the user’s phone.

4q0prk4e

Friday, January 14, 2011

Scrummerfall

rzliwivdDo blended / hybrid models work?  For some.

You can be a waterfall project manager and set commitments with the customer that way.  You can get commitments from developers that they’ll hit targets but they might not.  By doing Agile, you handle risk on a daily scale and can track things in real time.

They’re not mutually exclusive, I think they support each other.  One helps plan long-term and set expectations with the customer and the other helps get work done in the short term and manage risk and communications.

They work together and together they can make you successful.

s1xynzrd

I can paste code to my blog now!

Probably not exciting for you, but it is for me!  Check it out:

C# block:

namespace TestProject1
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void SystemTracksWorkflow()
{
var c = new CoeController();
c.Create(4);

c.DoAction(c.CoeId, ActionName.OpenCoeSystem.ToString(), "system", "marla", "stuff");
//Assert.AreEqual("Open", coe.Status);

c.DoAction(c.CoeId, ActionName.AssignCoe.ToString(), "marla", "eric", "Please look at this, it looks really messed up.");
//Assert.AreEqual("Assigned", coe.Status);

SQL block:

CREATE TABLE [dbo].[Coe](
[Id] [int] IDENTITY(1,1) NOT NULL,
[ClassId] [int] NOT NULL,
[Created] [datetime] NOT NULL,
[StatusId] [int] NOT NULL,
CONSTRAINT [PK_Coe] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

XML block:

<configuration>
<connectionStrings>
<add name="COEConnectionString" connectionString="Data Source=.;Initial Catalog=COE;Integrated Security=True;Pooling=False"
providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>

I spent a very long time yesterday trying to make this work.  I have a Blogger (BlogSpot) account and I want to use Live Write.r  I gave up yesterday after many trials but had to make it happen today.  I did.


Here are the instructions from MLA Wire about getting this working in Blogger and the instructions from Yordan Pavlov about getting SyntaxHighlighter marked up within LiveWriter.  I know Scott Handselman had a post about this a long time ago and I remember reading it and being excited but I never got it going.  But I have it going now! 


At least my posts will be more colorful and interesting now.  I’m still looking for a good Live Writer plug-in for pasting images.


  lckq1dqk


I pasted this one in with the Clipboard Live plug-in…not sure if it did anything good.

Thursday, December 23, 2010

One many, many one

As a project manager on a single project, I will not go as far as writing the code. It is too much to manage the project and to be on the hook for producing the product, you have to separate these concerns! I must manage the project only and employ others to do the main work.

When someone else is the project manager on a project, I am happy to plug in and write code / do work / take direction. Great.

In my opinion, in organizations, people need to own things and they cannot own both the project/business side AND the code/delivery side AT THE SAME TIME (for a single project/account).

I do think it is possible, however, to be both a project manager/owner on one project while simultaneously developing code on ANOTHER project as a team-member (non-manager). I think this is an ideal situation to me, where I can do both. I get to play with technology and be a developer/producer, and also be a manager. I can improve skills at both at once. No need to pick, it's not one-sided!

How low will you go?

In project management—I think—you can go all the way down to the level where you're doing all the work and writing all the code. But can you really "manage" the project if you're in it? Probably not.

A coworker is making me think about how low I will go on this. Will I write code? Will I talk to the dev team about the solution? Will I design the solution? Maybe as long as I REFUSE to write code, I'll be fine. That is high enough level and I can insure that others and not me write the code and produce the project. I have to stay high-level and be a manager, not a doer.

The sexy parts of project management


It's not the work, it's the people, results, client, technologies, and knowledge.

Much project management today is focused on the BORING (and hard) part of project management: the work. The work is fine, it's hard, it's there, it's complicated, but it really doesn't matter if you can't market your WORK PRODUCT. Your work product is your results; what you accomplished, what you produced, what you changed, learned, did. It's the end and the journey.

My proposal is for a new view of project management that is MARKETING focused. I want to think about and share the SEXY parts of project management like the people and how smart they are, the client and how cool it is, the industry and how interesting it is, the technologies and how cutting-edge/cool they are, and the results and how awesome and game-changing they are.

There's a way to do this and I want to start the wheels in motion on it ASAP.

Make the budget last

Many things in business are fixed-bid, not time- and materials-based. Sure, it's lovely when you're in a situation that you can charge the client for all reasonable time, but this isn't usually the case.

Right now, I'm working on a fixed 80-hour budget that will have to carry me into Jan 7. I've spent almost all of the hours so far, as this is my only project and I'm pretty much full time on it. But what's reasonable to bill?

I have to think about what I have to complete (a statement of work and technical spec and a couple of days of meetings with the client) and how much time that will take (~20 hours). So I think I'm only going to bill for 20 hours this week so I can bill for 20 the following week to fill the budget. This makes sense to me but is kind of "weird math".