Convert a ActiveXObject to a Fetch object - crm

I'm working with CRM Dynamics. There is a JavaScript that uses ActiveXObject to resolve a request but I need to convert that to a Fetch Request.
The old code is this:
function fnSetStateActiveQuoteRequest() {
var xml = "" +
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
GenerateAuthenticationHeader() +
" <soap:Body>" +
" <Execute xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
" <Request xsi:type=\"SetStateQuoteRequest\">" +
" <EntityId>" + Xrm.Page.data.entity.getId() + "</EntityId>" +
" <QuoteState>Active</QuoteState>" +
" <QuoteStatus>2</QuoteStatus>" +
" </Request>" +
" </Execute>" +
" </soap:Body>" +
"</soap:Envelope>" +
"";
var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Execute");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);
and I'm trying to convert that with:
var _oService;
var _sOrgName = "myOrg";
var _sServerUrl = Xrm.Page.context.getServerUrl();
function fnSetStateActiveQuoteRequest(){
var sFetch = '<fetch mapping="logical">';
sFetch+= '<entity name='+Xrm.Page.data.entity.getId()'>';
sFetch+= '</filter>';
sFetch+= '</entity>';
sFetch+= '</fetch>';
_oService = new FetchUtil(_sOrgName, _sServerUrl);
var oEntity = _oService.Fetch(sFetch, myCallBack);
}
But I have no idea how to declare the Request> and the QuoteState>

The problem you're having is the first XML you are looking at is the serialized version of an execute request. Fetch is more of a Query Language so you write it slightly differently.
The easiest way to figure out what the fetch xml needs to look like is open up an advanced find and perform the search manually. The Advanced Find gives you a "Download Fetch XML" button to save you the hassle of writing all the fetch!
So, the old query looked like it was trying to return all records of entity "X" where it was Active and had a status reason of 2. If I write something similar in advanced find (let's say I'm looking for opportunities) my query might look like this:
<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='opportunity'>
<attribute name='name' />
<attribute name='customerid' />
<attribute name='estimatedvalue' />
<attribute name='opportunityid' />
<order attribute='name' descending='false' />
<filter type='and'>
<condition attribute='statecode' operator='eq' value='0' />
<condition attribute='statuscode' operator='eq' value='2' />
</filter>
</entity>
</fetch>
That was pretty much a copy and paste from the Download Fetch XML of an advanced find.

Related

Why the where clause is not working on sharepointsearch?

StringBuilder xmlString = new StringBuilder(
"<QueryPacket xmlns='urn:Microsoft.Search.Query'>"
+ "<Query><SupportedFormats><Format revision='1'> urn:Microsoft.Search.Response.Document:Document"
+ "</Format></SupportedFormats><Context>"
+ " <QueryText language='en-US' type='FQL'>");
// this adds the search free form text
xmlString.Append("Earth");
query.Append(
"</QueryText></Context>"
+ "<Properties>"
+ "<Property name='Name'/>"
+ "<Property name='Department' />"
+ "<Property name='Property1' />"
+ "<Property name='Property2' />"
+ "<Property name='Property3' />"
+ "<Property name='Property4' />"
+ "<Property name='Property5' />"
+ "</Properties>"
+ "<Where>"
+ "<IsNotNull><FieldRef Name='Name'></FieldRef></IsNotNull>"
+ "<And><IsNotNull><FieldRef Name='Property1'></FieldRef></IsNotNull></And>"
+ "</Where>"
+ "</Query></QueryPacket>"
);
QueryServiceSoapClient.QueryEx(query)
I am getting data with the null/empty value on Name and Property1 column.
Why where is not working?
It looks like your where clause is not properly formatted as #Damith suggested. Why dont you build your query using FAST Search for Sharepoint MOSS 2010 Query Tool. Its really quick and efficient way to work on this kind of tasks.
+ "<And><IsNotNull><FieldRef Name='Property1'></FieldRef>"+"</IsNotNull>And>"
In this line after IsNotNull you missing </ so the line should be
+ "<And><IsNotNull><FieldRef Name='Property1'></FieldRef>"+"</IsNotNull></And>"
Your issue is that you've got the <and> clause sitting in the wrong place.
It should look like this:
<Where>
<And>
<IsNotNull>
<FieldRef Name='Name'>
</FieldRef>
</IsNotNull>
<IsNotNull>
<FieldRef Name='Property1'></FieldRef>
</IsNotNull>
</And>
</Where>
It's a weird place to have to put the and clause, I know, but that's how CAML works. I strongly recommend using a program such as CAMLQueryHelper if you're going to use CAML instead of Linq.

remove xmlns="something" from xml document using linq to xml

I'm parsing an xml file.
the first line of xml looks like;
<DataSetMenu xmlns="http://tempuri.org/DataSetMenu.xsd">
I'm using below code to parse the xml.
string filename = Request.QueryString["file"].ToString();
XElement xdocument = XElement.Load(Server.MapPath("xml\\" + filename));
xdocument.Attribute("xmlns").Remove();
IEnumerable<XElement> MenuGroups = xdocument.Elements();
sb.Append("<link href='StyleSheet.css' rel='stylesheet' type='text/css' />");
foreach (var xel in MenuGroups)
{
if (xel.Elements("MenuCatName").Any())
{
Int32 MenuCatID = Convert.ToInt32(xel.Element("MenuCatID").Value);
string MenuCatName = xel.Element("MenuCatName").Value;
sb.Append("<div class='CategoryDiv'><h1 class='category'>" + MenuCatName + " </h1>");
GetGroupItems(xdocument, MenuCatID);
}
}
But when ever xml file's first node contains :
xmlns="http://tempuri.org/DataSetMenu.xsd"
It doesn't work at all. when i try to access xml's data it gives me error, Object reference not set to an instance of an object
XML FILE
<DataSetMenu xmlns="http://tempuri.org/DataSetMenu.xsd">
<MenuCategories>
<MenuCatID>10108</MenuCatID>
<MenuCatName>SPEICALS</MenuCatName>
<BusinessEntityID>20137</BusinessEntityID>
<DisplayIndex>10107</DisplayIndex>
<MenuCatDesc />
<Visible>true</Visible>
<ImagePath />
</MenuCategories>
<MenuCategories>
<MenuCatID>10109</MenuCatID>
<MenuCatName>GENERAL MENU</MenuCatName>
<BusinessEntityID>20137</BusinessEntityID>
<DisplayIndex>10108</DisplayIndex>
< MenuCatDesc />
<Visible>true</Visible>
<ImagePath />
</MenuCategories>
<MenuGroups>
<MenuGroupID>110079</MenuGroupID>
<MenuCatID>10108</MenuCatID>
<MenuGroupName>SPECIAL OFFERS</MenuGroupName>
<MenuGroupDesc />
<Visible>true</Visible>
<DisplayIndex>0</DisplayIndex>
<MenuTypeID>1</MenuTypeID>
<ImagePath />
<ServiceTimeEnforced>false</ServiceTimeEnforced>
<ServiceStartTime>1900-01-01T11:00:00-06:00</ServiceStartTime>
<ServiceEndTime>1900-01-01T15:00:00-06:00</ServiceEndTime>
<Monday>true</Monday>
<Tuesday>true</Tuesday>
<Wednesday>true</Wednesday>
<Thursday>true</Thursday>
<Friday>true</Friday>
<Saturday>true</Saturday>
<Sunday>true</Sunday>
</MenuGroups>
</DataSetMenu>
Give me a solution so that it works fine. Or any way to remove this attribute.
Thanks.
Now It's now working here
private void GetGroupItems(XElement xdocument, Int32 MenuCatID)
{
var MenuGroup = from nm in xdocument.Elements("MenuGroups")
where (int)nm.Element("MenuCatID") == MenuCatID
select nm;
foreach (XElement GroupName in MenuGroup)
{
Int32 MenuGroupID = Convert.ToInt32(GroupName.Element("MenuGroupID").Value);
string MenuGroupName = GroupName.Element("MenuGroupName").Value;
sb.Append("<div class='IType'>" + MenuGroupName + " </div>");
sb.Append("<table class='restaurantlist'><tbody><tr><td class='righttd'>");
GetMenuItems(MenuGroupID, xdocument);
sb.Append("</td></tr></tbody></table>");
sb.Append("<div class='restaurantlistdiv'><div style='clear: both;'></div>");
}
}
please tell me, how should i modify this?
You have to specify namespace when you're querying your XML.
Create XNamespace instance:
var ns = XNamespace.Get("http://tempuri.org/DataSetMenu.xsd");
Then use XNamespace + String operator implementation:
public static XName operator +(
XNamespace ns,
string localName
)
within Elements() method call, like that:
IEnumerable<XElement> MenuGroups = xdocument.Elements();
sb.Append("<link href='StyleSheet.css' rel='stylesheet' type='text/css' />");
foreach (var xel in MenuGroups)
{
if (xel.Elements(ns + "MenuCatName").Any())
{
Int32 MenuCatID = Convert.ToInt32(xel.Element(ns + "MenuCatID").Value);
string MenuCatName = xel.Element(ns + "MenuCatName").Value;
sb.Append("<div class='CategoryDiv'><h1 class='category'>" + MenuCatName + " </h1>");
GetGroupItems(xdocument, MenuCatID);
}
}
The key thing to remember here is that you are not working with an attribute, but the namespace declaration. That's why you can't just remove the attribute. See if the suggestions at C#: How to remove namespace information from XML elements help.

How do I load content into Request.Files collection for latter retrieval on server side?

I'm using a multi-upload input control and it is not server sided i.e pure HTML not asp: tagged.
Now the issue is on the server side I'm trying to access the Request object's Files collection hoping that after an upload, the input control will put the files into this collection in question.
I even imported some scripts in javascript to make it work but whenever I step through the code behind, the Request.Files property, which should contain the browsed and chosen files, is always empty. What should I do? Ooooops! sorry i didnt show some code:
var x = this.Page.FindControl("FileUpload1");
lbuploadmessage.Text = x.GetType().ToString();
HttpFileCollection hfc = Request.Files;
List<L2SQLData.PatientFile> list = new List<L2SQLData.PatientFile>();
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0 && hpf.ContentLength < 1024000)
{
string filename = Path.GetFileName(hpf.FileName);
string ext = Path.GetExtension(hpf.FileName);
var guidname = Guid.NewGuid().ToString();
//FileUpload1.SaveAs(Server.MapPath("~/Uploads/DocClerkings/") + guidname + ext);
hpf.SaveAs(Server.MapPath("~/Uploads/DocClerkings/") + guidname + ext );
lbuploadmessage.Text = "Upload status:" + hpf.FileName + " successfully uploaded!";
As you can see I named the control-"FileUpload1" but at runtime (Debug) the object x is null and Request.Files collection that's supposed to contain the browsed files is empty too. The multi - upload control looks like this:
<input id = "FileUpload1" type="file" class="multi"/>
with two scripts i added as follows:
<script src="jquery-latest.js" type="text/javascript" language="javascript"></script>
<script src="jquery.MultiFile.js" type="text/javascript" language="javascript"></script>
So what did I leave out?
Cheers
To make it work you need to change it
<asp:FileUpload ID="FileUpload1" runat="server" class="multi" />
That plugin is unobstrusive and knows from class="multi" that you want it to do something...
For a complete walkthrough on how to make it work see http://www.dotnetcurry.com/ShowArticle.aspx?ID=317 and http://www.codeproject.com/KB/aspnet/multiple_file_upload.aspx
Remark: your usage is not working because this plugin does NOT upload anything, it is "only" for providing some nice additions on the client side - from http://www.fyneworks.com/jquery/multiple-file-upload/#tab-Uploading
Can this plugin upload files?
No, this jQuery plugin does not upload files
I finally found the missing link at http://docs.jquery.com/Tutorials:Multiple_File_Upload_Magic
var fileMax = 3;
$("input[#type=file]").change(function(){
doIt(this, fileMax);
});
These lines are all in the designer mark up. Of course the server code still remains the same as detailed in Yahia's solution above-reason why I accepted it :D. Here it is- in the upload button place this:
HttpFileCollection hfc = Request.Files;
List<L2SQLData.PatientFile> list = new List<L2SQLData.PatientFile>();
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0 && hpf.ContentLength < 1024000)
{
string filename = Path.GetFileName(hpf.FileName);
string ext = Path.GetExtension(hpf.FileName);
var guidname = Guid.NewGuid().ToString();
hpf.SaveAs(Server.MapPath("~/Uploads/DocClerkings/") + guidname + ext );
lbuploadmessage.Text = "Upload status:" + hpf.FileName + " successfully uploaded!";
Thanks for the assistance Yahia and everyone. You guys on Stack Overfolow are the best!

Passing XML string to a FusionWidget in Flex

If I set my HLED Widget's FCDataURL to some a valid XML the LED shows up fine but now I want to change the HLED's value programatically. For this purpose, I have made a string named xmlData, containing data from an XML file as shown below:
String for XML:
private var xmlData:String="<?xml version='1.0' encoding='UTF-8'?>" +
"<chart chartBottomMargin='5' lowerLimit='0' upperLimit='100' lowerLimitDisplay='Low' " +
"upperLimitDisplay='High' numberSuffix='' showTickMarks='1' tickValueDistance='0' " +
"majorTMNumber='5' majorTMHeight='4' minorTMNumber='0' showTickValues='1' decimalPrecision='0'" +
" ledGap='1' ledSize='1' ledBoxBgColor='FFFFFF' ledBorderColor='666666' borderThickness='0' " +
"chartRightMargin='20' background='0' bgColor='FFFFFF' showBorder='0'>" +
"<colorRange>" +
" <color minValue='0' maxValue='30' code='00FF00'/>" +
" <color minValue='30' maxValue='50' code='FFFF00'/>" +
" <color minValue='50' maxValue='100' code='FF0000'/>" +
"</colorRange>" +
"<value>66/value>" +
"</chart>";
Then, I tried to set the widget's FCDataXML to my string and rendered the widget.
Setting Widget's data and rendering
threatLevelWidget.FCDataXML=xmlData;
threatLevelWidget.FCRender();
Widget...
<components:FusionWidgets id="threatLevelWidget" FCChartType="HLED" x="10" y="-20" width="510" height="100"/>
I was hoping to see the chart load up with value = 66 but all I get is "Error in loading data". :-/
Any idea what's going wrong!
Please use :
threatLevelWidget.FCSetDataXML(xmlData);
Do NOT use : threatLevelWidget.FCRender(); if using FCSetDataXML() function.

Using HTML formatting to output variables in Flex/MXML

I'm trying to output a sentence containing 4 variables, with their values emboldened using the following code:
<mx:Text width="100%" y="307">
<mx:htmlText>
<![CDATA[Showing data from <b>{labelStartTime.text} {labelStartDate.text}</b> to <b>{labelEndTime.text} {labelEndDate.text}</b>]]>
</mx:htmlText>
</mx:Text>
However, this just outputs the variable names, rather than their values. I'm sure I'm missing something simple, but I'd appreciate any pointers.
Cheers.
I know of a workaround:
Actionscript:
private var variable:String = "Variable String";
private var str:String = "<i><b>" + Variable + "</b></i>";
Mxml:
<Text htmlText="{str}" />
I don't think it's possible to add bindings directly in a CDATA section like that, you do have a couple of options though :
Use a function, taking advantage of BindingUtils.bindSetter :
import mx.binding.utils.BindingUtils;
//called on creationComplete
private function init():void
{
BindingUtils.bindSetter(setHtmlText, labelStartTime, "text");
BindingUtils.bindSetter(setHtmlText, labelStartDate, "text");
BindingUtils.bindSetter(setHtmlText, labelEndTime, "text");
BindingUtils.bindSetter(setHtmlText, labelEndDate, "text");
}
private function setHtmlText(val:String):void
{
myText.htmlText = "Showing data from <b>" +
labelStartTime.text + " " +
labelStartDate.text + "</b> to <b>" +
labelEndTime.text + " " +
labelEndDate.text + "</b>";
}
Or simply encode the tags and insert them directly into the attribute :
<mx:Text id="myText" width="100%" y="307"
htmlText="Showing data from <b>{labelStartTime.text} {labelStartDate.text}</b> to <b>{labelEndTime.text} {labelEndDate.text}</b>"/>
This isn't really recommended as it makes the markup incredibly difficult to read, but you might get away with it for something small like this.

Resources