JavaScript and Microsoft Dynamics CRM

I was thinking that it would have been nice if some expert would have written some article or post about how to use JavaScript within CRM.

And today only i came to know about such an article , it is written by none other than MichaelHohne, the CRM guru, the creator of stunnware site( the most helpful site for Microsoft CRM Developer)

For different things we can do by making use of JavaScript in Microsoft Dynamics CRM,

Plzzzz check and bookmark this url

http://www.stunnware.com/crm2/topic.aspx?id=JS13

Bye

Operation failed due to a SQL integrity violation

Hi,

Today i was suppose to write a callout which would be sending email to owner’s manager for our opportunity entity.

I thought before trying out with an callout(which is really hard to debug) i should try it first in a windows application. Finally after some time i was able to get it working.

So than i decided to put the same code in the callout as well. But to my surprise i found that the same code was not working in the callout.

This was the error i was getting as

ex.detail.innerxml // for (SoapException ex)

<error>
<code>0x80040237</code>
<description>Operation failed due to a SQL integrity violation.</description>
<type>Platform</type>
</error>

After searching on the internet for the same i was able to find the cause for the error in my code

For my windows application this piece of code was sufficient

CrmService service=new CrmService();
service.Credentials=System.Net.CredentialCache.DefaultCredentials;
service.Url=”http://d-2927:5555/mscrmservices/2006/crmservice.asmx&#8221;;

But when it came to callout it had to be

CrmService service=new CrmService();
service.Credentials=System.Net.CredentialCache.DefaultCredentials;
service.Url=”http://d-2927:5555/mscrmservices/2006/crmservice.asmx&#8221;;
service.CallerIdValue = new CallerId();
service.CallerIdValue.CallerGuid =userContext.UserId;

This helped me to solve the error.

Check this link as well

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1768766&SiteID=1

Bye

Creating a simple Hello World ASP.NET AJAX web page.

Hi,

Here we will create a simple ASP.Net Ajax webpage having a button and textbox control in it.
On the click of button we will fill the textbox with “Hello world” string returned from the server without refreshing our webpage.

1) Create a new ASP.NET Ajax web site(Visual Studio 2005)or ASP.NET web site (version 3.5) if we are using Orcas(Visual studio 2008)

2) Add a ScriptManager control in the page( if it isn’t there)

3) Add button and textbox server side control.

<asp:TextBox ID=”TextBox1″ runat=”server” />

<asp:Button ID=”Button1″ runat=”server” Text=”Button” />

4) Add this event Handler for button click event

protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.Text=”Hello World”;
}

4) Now to make our page AJAX enabled the only thing we need to add is

<asp:UpdatePanel id=up1 runat=server>
<ContentTemplate>

<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>
<asp:Button ID=”Button1″ runat=”server” onclick=”Button1_Click” Text=”Button” />

</ContentTemplate>
</asp:UpdatePanel>

Just wrap our server side controls inside update panel control’s content template.

5) That’s it. Now run the application and click on the button the textbox should get filled with Hello World string without any refresh of the page.

Right now what we saw was a server-centric approach using updatePanel control.

We can do the same thing using client-centric approach using ASP.NET AJAX client library. Check this post

https://nishantrana.wordpress.com/2007/11/06/creating-and-calling-aspnet-ajax-web-service/

Bye.

 

Creating and Calling ASP.NET AJAX Web Service

Hi,

First we will create a new ASP.NET Ajax web site(Visual Studio 2005)
or ASP.NET web site (version 3.5) if we are using Orcas(Visual studio 2008)

Through Add New Item, add a new web service WebService.asmx in the website.

1) Add this in webservice.cs

using System.Web.Script.Services;


2) Add a ScriptService attribute to our webservice class

[ScriptService]
[WebService(Namespace = “http://tempuri.org/&#8221;)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

3) We’ll use the default Hello World web service. So just save the web service and view it in browser to test it.

Now change the url of the webservice in browser and append “/js” to it
i.e.
Change
http://d-0824/AjaxinAction/WebService.asmx
to
http://d-0824/AjaxinAction/WebService.asmx/js

Press enter it will ask you to save the file,
just save and open it in notepad

We will see something like this

var WebService=function() {
WebService.initializeBase(this);
this._timeout = 0;
this._userContext = null;
this._succeeded = null;
this._failed = null;
}
WebService.prototype={
_get_path:function() {
…………………………
……………………….

This is a javascript proxy class which the our client side ajax library will use to make call to our web service.

4) Add a script manager control to our default.aspx page ( if not already there), and add the reference to our web service

<asp:ScriptManager ID=”ScriptManager1″ runat=”server”>
<Services>
<asp:ServiceReference Path=”WebService.asmx” />
</Services>
</asp:ScriptManager>

5) Now add a simple html text control on the default.aspx page. We will be calling our web service and fill the text box value returned from the webservce (“Hello World”).

<input id=”Text1″ type=”text” />

6) Put this script on your default.aspx page

<script type=”text/javascript”>

function pageLoad()
{
WebService.HelloWorld(onSuccess);
}

function onSuccess(result)
{
$get(“Text1”).value=result;
}

</script>

7) Now just view the page in browser we should see the textbox filled with “Hello World” string returned from our web service.

8) Or if we want to call it in the click of the button. add a html button control.

<input id=”Button1″ type=”button” value=”button” />

9) Replace the above script with this one

<script type=”text/javascript”>
var myButton=null;
function pageLoad(sender,e)
{
myButton=$get(“Button1″);
$addHandler(myButton,”click”,btn_click);
}

function btn_click(sender,e)
{
WebService.HelloWorld(onSuccess);
}

function onSuccess(result)
{
$get(“Text1”).value=result;
}
</script>

In the above example we saw a client centric approach, the same thing can be done very easily by making use  of server centric approach in ASP.NET AJAX framework.

https://nishantrana.wordpress.com/2007/11/06/creating-a-simple-hello-world-aspnet-ajax-web-page/

Bye

 

Creating Word document using C#

Create a new windows application project and add a button to it.

On click of that button, we will create a new document(word) and write a simple Hello World text in it.

To create a word document using C# we need to first reference the following DLL(com)

DLL

After adding reference, add this directive

using Microsoft.Office.Interop.Word;

Put this code on button click

    private void button1_Click(object sender, EventArgs e)

        {

            object missing = System.Reflection.Missing.Value;

            object Visible=true;

            object start1 = 0;

            object end1 = 0;

 

            ApplicationClass WordApp = new ApplicationClass();

            Document adoc = WordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);

            Range rng = adoc.Range(ref start1, ref missing);

 

            try

            {              

                rng.Font.Name = “Georgia”;

                rng.InsertAfter(“Hello World!”);

                object filename = @”D:\MyWord.doc”;

                adoc.SaveAs(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing,

                ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);

                WordApp.Visible = true;

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }        

        }

The easiest way to write code for office interoperability is to make use of VBA code.

Say you want to insert a picture in a word document what you can do is

open the word document – Go to Tools ->Macro-> Record New Macro

Now click on insert menu and insert the picture. Stop the recording, again go to Macro -Macros-> Select your Macro and click on edit

You will find the vba code over there

Sub Macro1()

Selection.InlineShapes.AddPicture FileName:= _
“C:\Documents and Settings\nishantr1\My Documents\My Pictures\untitled.bmp” _
, LinkToFile:=False, SaveWithDocument:=True
End Sub

Now to write the same code in c# you will do something like this

Range rngPic = adoc.Tables[1].Range;

rngPic.InlineShapes.AddPicture(@”C:\anne_hathaway.jpg”, ref missing, ref missing, ref missing);

Bye

Saving and Retrieving richtextbox control’s content (.rtf file) in database

Let’s start with a very simple application.

Form

Drop OpenFileDialog control in the application.

When user click on Pick File button using OpenFileDialog he will select a rtf file to display in richtextbox control.

The content of richtextbox control will be saved in the sql server table.

This is how our table looks like.

Table

File content is the image data type column where we will store our rtf content.

<!–[if gte vml 1]> <![endif]–>

Put the following code in Pick file button click.

if(openFileDialog1.ShowDialog() == DialogResult.OK)

{

try

{

rtfContent.LoadFile(openFileDialog1.FileName);

}

catch(Exception ex)

{

MessageBox.Show(ex.Message);

}

}

Put the following code in Save Button Click

SqlConnection conn=new SqlConnection(“Data Source=D-0824;Initial Catalog=WordInterOp; uid=sa;pwd=sa;”);

SqlCommand cmd=new SqlCommand();

cmd.CommandText = “Insert into RtfStore (fileName,fileContent) values ( @fname,@fcontent)”;

cmd.Connection=conn;

SqlParameter fileName=new SqlParameter(“@fname”,openFileDialog1.SafeFileName);

rtfContent.SaveFile(@”c:\temp.rtf”, RichTextBoxStreamType.RichText);

FileStream stream = new FileStream(@”c:\temp.rtf”, FileMode.Open, FileAccess.Read);

int size = Convert.ToInt32(stream.Length);

Byte[] rtf = new Byte[size];

stream.Read(rtf, 0, size);

SqlParameter fileContent=new SqlParameter();

fileContent.ParameterName=”@fcontent”;

fileContent.SqlDbType=SqlDbType.Image;

fileContent.Size=rtf.Length;

fileContent.Value=rtf;

cmd.Parameters.Add(fileName);

cmd.Parameters.Add(fileContent);

conn.Open();

int success=cmd.ExecuteNonQuery();

if(success==1)

{

MessageBox.Show(“Entered data successfully”);

}

openFileDialog1.SafeFileName- To get the name of file instead of the complete path.

rtfContent.SaveFile- Saving the content of the control in a rtf file.

RichTextBoxStreamType.RichText– This tells that we are saving richtext having some formatting and not just plain text.

Finally through filestream we are reading that file and saving it’s content in our sqlserver table.

Similary to read the rtf content from the database and display it in Richtextbox control, this is what we need to do

// cmd.commandText=”select fileContent from RtfStore where filename=’xyz’ “;

SqlDataReader dr =  cmd.ExecuteReader();

if (dr.Read())

{

Byte[] rtf = new Byte[Convert.ToInt32((dr.GetBytes(0, 0,

null, 0, Int32.MaxValue)))];

long bytesReceived = dr.GetBytes(0, 0, rtf, 0, rtf.Length);

ASCIIEncoding encoding = new ASCIIEncoding();

rtfContent.Rtf = encoding.GetString(rtf, 0, Convert.ToInt32(bytesReceived));

}

Bye