Azure API Management Policies - Using conditional statements - For Payloads - azure

I am using C# syntax to transform payload body Using conditional statements to transform body, I want to transform one key of the payload body using conditional statement if possible.
More explanation of the scenario is shown in code below. I tried to implement what I am trying to achieve but I get a error.
Not sure if its just my syntax, or putting the logic there would make sense or not.
If this is the payload:
{
"dependentee_name": "Steve",
"dependentee_last_name": "Rogers",
"dependentee_comment": "This is test",
"dependentee_relationship_primary": "Parent",
"dependentee_relationship_secondary": "null",
"insurer_name": "Steve",
"insurer_last_name": "Rogers",
"insurer_comment": "This is test",
"extra_info": "This is comments"
}
As shown in the payload has a key dependentee_relationship_primary which has value Parent, so the expected transformed body would be as follows:
{
"dependentee_info": {
"name": "Steve",
"last_name": "Rogers"
},
"insurer_info": {
"i_name": "Tony",
"i_last_name": "Stark"
},
"extra_info": "This is comments",
"relationship_type": "Parent"
}
If this is the payload:
{
"dependentee_name": "Steve",
"dependentee_last_name": "Rogers",
"dependentee_comment": "This is test",
"dependentee_relationship_primary": "null",
"dependentee_relationship_secondary": "Uncle",
"insurer_name": "Steve",
"insurer_last_name": "Rogers",
"insurer_comment": "This is test",
"extra_info": "This is comments"
}
As shown in the payload has a key dependentee_relationship_secondary which has value Uncle, so the expected transformed body would be as follows:
{
"dependentee_info": {
"name": "Steve",
"last_name": "Rogers"
},
"insurer_info": {
"i_name": "Tony",
"i_last_name": "Stark"
},
"extra_info": "This is comments",
"relationship_type": "Uncle"
}
I have attempted the code so far, but I run into an error
<policies>
<inbound>
<base />
<return-response>
<set-status code="200" reason="ok" />
<set-header name="Content-Type" exists-action="override">
<value>application/json</value>
</set-header>
<set-body>#{
var body = context.Request.Body.As<JObject>(true);
var transformedBody = new JObject();
transformedBody["extra_info"] = body["extra_info"];
var dependentee= new JObject();
dependetee["name"] = body["dependtee_name"];
dependentee["lastName"] = body["depdentee_last_name"];
transformedBody["dependtee_info"] = dependentee;
var insurer_info = new JObject();
dependetee["i_name"] = body["insurer_name"];
dependentee["i_last_name"] = body["insurer_last_name"];
transformedBody["insurer_info"] = insurer_info;
if (body["dependentee_relationship_primary"] !=null)
{
transformedBody["relationship_type"] = body["dependentee_relationship_primary"];
}
else if (body["dependentee_relationship_secondary"] !=null) {
transformedBody["relationship_type"] = body["adultrelationship"];
}
return transformedBody.ToString();
}</set-body>
</return-response>
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
</outbound>
<on-error>
<base />
</on-error>
</policies>

First of all, it's a good idea to fix the long-existing typo issues like dependetee which I fixed for you already in:
Azure API Management (Policies)
You have to check if
the body has a child dependentee_relationship_primary
the property dependentee_relationship_primary is not null
the property dependentee_relationship_primary is not an empty string
if (body.ContainsKey("dependentee_relationship_primary") && body["dependentee_relationship_primary"].Type != JTokenType.Null && !string.IsNullOrEmpty(body["dependentee_relationship_primary"].Value<string>()))
{
transformedBody["relationship_type"] = body["dependentee_relationship_primary"];
}
The complete policy:
<policies>
<inbound>
<base />
<return-response>
<set-status code="200" reason="ok" />
<set-header name="Content-Type" exists-action="override">
<value>application/json</value>
</set-header>
<set-body>#{
var body = context.Request.Body.As<JObject>(true);
var transformedBody = new JObject();
transformedBody["extra_info"] = body["extra_info"];
var dependentee= new JObject();
dependentee["name"] = body["dependtee_name"];
dependentee["lastName"] = body["depdentee_last_name"];
transformedBody["dependtee_info"] = dependentee;
var insurer_info = new JObject();
insurer_info["i_name"] = body["insurer_name"];
insurer_info["i_last_name"] = body["insurer_last_name"];
transformedBody["insurer_info"] = insurer_info;
if (body.ContainsKey("dependentee_relationship_primary") && body["dependentee_relationship_primary"].Type != JTokenType.Null && !string.IsNullOrEmpty(body["dependentee_relationship_primary"].Value<string>()))
{
transformedBody["relationship_type"] = body["dependentee_relationship_primary"];
}
else if (body.ContainsKey("dependentee_relationship_secondary") && body["dependentee_relationship_secondary"].Type != JTokenType.Null && !string.IsNullOrEmpty(body["dependentee_relationship_secondary"].Value<string>()))
{
transformedBody["relationship_type"] = body["adultrelationship"];
}
return transformedBody.ToString();
}</set-body>
</return-response>
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
</outbound>
<on-error>
<base />
</on-error>
</policies>
Result:
BTW:
Your condition does not make sense:
There's no adultrelationship defined.

Related

Azure APIM Policies Transforming Body of Payload

I am still currently exploring in APIM. I have a payload in payload #1, which I want to transform into another payload # 2(expected).
How would I edit my policy to construct this pay load?
Payload 1
{
"dependtee_name": "Steve",
"depdentee_last_name": "Rogers",
"dependtee_comment" : "This is test",
"file": "file.txt",
"file_type": "text file",
"insurer_name": "Steve",
"insurer_last_name": "Rogers",
"insurer_comment" : "This is test",
"extra_info": "This is comments"
}
Payload 2 - Expected
{
"dependtee_info": {
"name": "Steve",
"last_name": "Rogers"
},
"file_details": {
"all_file": [ "file.txt", "null" ],
"fileFormat": "text file"
},
"insurer_info": {
"i_name": "Tony",
"i_last_name": "Stark"
},
"extra_info": "This is comments"
}
Current Code
<policies>
<inbound>
<base />
<return-response>
<set-status code="200" reason="ok" />
<set-header name="Content-Type" exists-action="override">
<value>application/json</value>
</set-header>
<set-body>#{
var body = context.Request.Body.As<JObject>(true);
var transformedBody = new JObject();
transformedBody["extra_info"] = body["extra_info"];
var dependentee= new JObject();
dependetee["name"] = body["dependtee_name"];
dependentee["lastName"] = body["depdentee_last_name"];
transformedBody["dependtee_info"] = dependentee;
var file_details = new JObject();
dependentee["all_file"] = body["file"];
dependentee["fileFormat"] = body["file_type"];
transformedBody["file_details"] = file_details;
var insurer_info = new JObject();
dependetee["i_name"] = body["insurer_name"];
dependentee["i_last_name"] = body["insurer_last_name"];
transformedBody["insurer_info"] = insurer_info;
return transformedBody.ToString();
}</set-body>
</return-response>
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
</outbound>
<on-error>
<base />
</on-error>
</policies>
Looking to change the body specifically for the file.
I want to know how I can add those square brackets in my expected payload.
Payload 2 should have more than one value for key "all_file", but I want to be able to get it from Payload 1.
Thank you for your help
You have to create a JArray and Add the strings and assign the JArray to the parent object:
var file_details = new JObject();
var all_File = new JArray();
all_File.Add(body["extra_info"]);
all_File.Add("null"); // does not makes sense to a null string
file_details["all_file"] = all_File;
file_details["fileFormat"] = body["file_type"];
transformedBody["file_details"] = file_details;
I do not understand the purpose of "null" in Payload 2 - Expected:
"all_file": [ "file.txt", "null" ],
Where does it comes from? And why is it a string "null" and not null?
Here's complete fixed policy:
<policies>
<inbound>
<base />
<return-response>
<set-status code="200" reason="ok" />
<set-header name="Content-Type" exists-action="override">
<value>application/json</value>
</set-header>
<set-body>#{
var body = context.Request.Body.As<JObject>(true);
var transformedBody = new JObject();
transformedBody["extra_info"] = body["extra_info"];
var dependentee= new JObject();
dependentee["name"] = body["dependtee_name"];
dependentee["lastName"] = body["depdentee_last_name"];
transformedBody["dependtee_info"] = dependentee;
var file_details = new JObject();
var all_File = new JArray();
all_File.Add(body["extra_info"]);
all_File.Add("null"); // does not makes sense to use a null string
file_details["all_file"] = all_File;
file_details["fileFormat"] = body["file_type"];
transformedBody["file_details"] = file_details;
var insurer_info = new JObject();
insurer_info["i_name"] = body["insurer_name"];
insurer_info["i_last_name"] = body["insurer_last_name"];
transformedBody["insurer_info"] = insurer_info;
return transformedBody.ToString();
}</set-body>
</return-response>
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
</outbound>
<on-error>
<base />
</on-error>
</policies>
Result:

Azure API Management Policies - Using conditional statements to transform body

I am using C# syntax to transform payload body Using conditional statements to transform body, I want to transform one key of the payload body using conditional statement if possible. More explanation of the scenario is shown in code below.
I tried to implement what I am trying to achieve but I get a error. Not sure if its just my syntax, or putting the logic there would make sense or not.
If this is the payload:
{
"dependentee_name": "Steve",
"dependentee_last_name": "Rogers",
"dependentee_comment" : "This is test",
"dependentee_relationship_primary" : "Parent",
"dependentee_relationship_secondary" : "null",
"insurer_name": "Steve",
"insurer_last_name": "Rogers",
"insurer_comment" : "This is test",
"extra_info": "This is comments"
}
As shown in the payload has a key dependentee_relationship_primary which has value Parent, so the expected transformed body would be as follows:
{
"dependentee_info": {
"name": "Steve",
"last_name": "Rogers"
},
"insurer_info": {
"i_name": "Tony",
"i_last_name": "Stark"
},
"extra_info" : "This is comments",
"relationship_type" : "Parent"
}
If this is the payload:
{
"dependentee_name": "Steve",
"dependentee_last_name": "Rogers",
"dependentee_comment" : "This is test",
"dependentee_relationship_primary" : "null",
"dependentee_relationship_secondary" : "Uncle",
"insurer_name": "Steve",
"insurer_last_name": "Rogers",
"insurer_comment" : "This is test",
"extra_info": "This is comments"
}
As shown in the payload has a key dependentee_relationship_secondaru which has value Uncle, so the expected transformed body would be as follows:
{
"dependentee_info": {
"name": "Steve",
"last_name": "Rogers"
},
"insurer_info": {
"i_name": "Tony",
"i_last_name": "Stark"
},
"extra_info" : "This is comments",
"relationship_type" : "Uncle"
}
I have attempted the code so far, but I run into an error
<policies>
<inbound>
<base />
<return-response>
<set-status code="200" reason="ok" />
<set-header name="Content-Type" exists-action="override">
<value>application/json</value>
</set-header>
<set-body>#{
var body = context.Request.Body.As<JObject>(true);
var transformedBody = new JObject();
transformedBody["extra_info"] = body["extra_info"];
var dependentee= new JObject();
dependetee["name"] = body["dependtee_name"];
dependentee["lastName"] = body["depdentee_last_name"];
transformedBody["dependtee_info"] = dependentee;
var insurer_info = new JObject();
dependetee["i_name"] = body["insurer_name"];
dependentee["i_last_name"] = body["insurer_last_name"];
transformedBody["insurer_info"] = insurer_info;
if (body["dependentee_relationship_primary"] !=null)
{
transformedBody["relationship_type"] = body["dependentee_relationship_primary"];
}
else if (body["dependentee_relationship_secondary"] !=null) {
transformedBody["relationship_type"] = body["adultrelationship"];
}
return transformedBody.ToString();
}</set-body>
</return-response>
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
</outbound>
<on-error>
<base />
</on-error>
</policies>
Duplicate of Azure API Management Policies - Using conditional statements - For Payloads
First of all, it's a good idea to fix the long-existing typo issues like dependetee which I fixed for you already in:
Azure API Management (Policies)
You have to check if
the body has a child dependentee_relationship_primary
the property dependentee_relationship_primary is not null
the property dependentee_relationship_primary is not an empty string
if (body.ContainsKey("dependentee_relationship_primary") && body["dependentee_relationship_primary"].Type != JTokenType.Null && !string.IsNullOrEmpty(body["dependentee_relationship_primary"].Value<string>()))
{
transformedBody["relationship_type"] = body["dependentee_relationship_primary"];
}
The complete policy:
<policies>
<inbound>
<base />
<return-response>
<set-status code="200" reason="ok" />
<set-header name="Content-Type" exists-action="override">
<value>application/json</value>
</set-header>
<set-body>#{
var body = context.Request.Body.As<JObject>(true);
var transformedBody = new JObject();
transformedBody["extra_info"] = body["extra_info"];
var dependentee= new JObject();
dependentee["name"] = body["dependtee_name"];
dependentee["lastName"] = body["depdentee_last_name"];
transformedBody["dependtee_info"] = dependentee;
var insurer_info = new JObject();
insurer_info["i_name"] = body["insurer_name"];
insurer_info["i_last_name"] = body["insurer_last_name"];
transformedBody["insurer_info"] = insurer_info;
if (body.ContainsKey("dependentee_relationship_primary") && body["dependentee_relationship_primary"].Type != JTokenType.Null && !string.IsNullOrEmpty(body["dependentee_relationship_primary"].Value<string>()))
{
transformedBody["relationship_type"] = body["dependentee_relationship_primary"];
}
else if (body.ContainsKey("dependentee_relationship_secondary") && body["dependentee_relationship_secondary"].Type != JTokenType.Null && !string.IsNullOrEmpty(body["dependentee_relationship_secondary"].Value<string>()))
{
transformedBody["relationship_type"] = body["adultrelationship"];
}
return transformedBody.ToString();
}</set-body>
</return-response>
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
</outbound>
<on-error>
<base />
</on-error>
</policies>
Result:
BTW:
Your condition does not make sense:
There's no adultrelationship defined.

treemodel + skype-bots Cannot read property 'model' of undefined

I'm working on skype bot app. I have issue with read the node from tree-model.
Tree-model example follow the children node but my node has diff tab to read by system.
XML example-
<?xml version="1.0" encoding="UTF-8" ?>
<rootmenu id="1" title="menu" description="What scenario would you like to run?">
<MenuOption id="1.1" title="Company Data" response="You entered company data" description="What action would you like to perform">
<HierarchyMenuItem id="1.1.1.1" title="Select new data " response="You entered select new filter">
<action>Filter</action>
</HierarchyMenuItem>
<HierarchyMenuItem id="1.1.1.2" title="Navigate node" response="You entered select node">
<action description="Current Filter is ">Hierarchy</action>
<HierarchyLevel level="1" name="One" navigateHierarchy="true">
<action>RootAction</action>
<Option title="Select a Country">
<OptionChoices id="1" title="One1" refNode="ForOne1" />
<OptionChoices id="2" title="One2" refNode="ForOne2" />
<OptionChoices id="3" title="One3" refNode="ForOne3" />
<OptionChoices id="4" title="One4" refNode="ForOne4" />
</Option>
</HierarchyLevel>
</HierarchyMenuItem>
</MenuOption>
<MenuOption id="1.2" title="Adhoc Data">
<Option>
<OptionChoices id="1" title="Ad1" refNode="ForAdOne1" />
<OptionChoices id="2" title="Ad2" refNode="ForAdOne2" />
<OptionChoices id="3" title="Ad3" refNode="ForAdOne3" />
<OptionChoices id="4" title="Ad4" refNode="ForAdOne4" />
</Option>
</MenuOption>
<MenuOption id="1.3" title="(quit)">
</MenuOption>
</rootmenu>
Read the xml from server-
function getXMLData(callback) {
var request = require('request');
var DOMParser = require('xmldom').DOMParser;
var simpleconvertxml = require('simpleconvert-xml');
request('http://demo.in/RefactoredXML.xml', function (error, response, body) {
if (!error && response.statusCode == 200) {
var xmlnode = new DOMParser().parseFromString([body].join('\n'), 'text/xml');
var myNumber = simpleconvertxml.getXMLAsObj(xmlnode);
treeRoot = tree.parse(myNumber.rootmenu);
callback(treeRoot);
}
})
}
My first bot call
bot.dialog('/menu', [
function (session, args) {
getXMLData(function (treeRoot) {
//session.send('node place:'+treeRoot.model.title);
var firstChild = [];
for (var i = 0; i < treeRoot.model.MenuOption.length; i++) {
if(treeRoot.model.MenuOption[i].title !='' && treeRoot.model.MenuOption[i].title != undefined && treeRoot.model.MenuOption[i].title != null) {
firstChild.push(treeRoot.model.MenuOption[i].title);
}
}
if(firstChild.length > 0) {
builder.Prompts.choice(session, treeRoot.model.description,firstChild );
// it shows builder.Prompts.choice(session, "What scenario would you like to run? ", "company data|adhoc data|(quit)");
} else {
session.send('Something went wrong. You can use the back or top command.');
}
});
},
function (session, results) {
if (results.response && results.response.entity != '(quit)') {
session.userData.profile.treeSelectdNodeTitle = results.response.entity;
getXMLData(function (treeRoot) {
for (var i = 0; i < treeRoot.model.MenuOption.length; i++) {
if(treeRoot.model.MenuOption[i].title == session.userData.profile.treeSelectdNodeTitle) {
session.userData.profile.treeSelectdNodeId = treeRoot.model.MenuOption[i].id;
session.userData.profile.treeSelectdResponse = treeRoot.model.MenuOption[i].response;
}
}
session.send('resp ' + session.userData.profile.treeSelectdResponse);
if(treeRoot.hasChildren()) {
session.send('in the children');
session.beginDialog('/get Tree Node');
} else {
session.send('in the title');
session.beginDialog('/'+ treeRoot.model.title);
}
});
} else {
// Exit the menu
session.endDialog();
}
},
function (session, results) {
// The menu runs a loop until the user chooses to (quit).
session.replaceDialog('/menu');
}
]).reloadAction('reloadMenu', null, {matches: /^menu|show menu|top|top menu/i});
Menu dialog call should display 1.company data 2. adhoc data 3. (quit) but its showing only 1.company data 2.adhoc data and Issue in the menu is if user select the 1 option as Company Data it will not goes to treeRoot.hasChildren() condition.
bot.dialog('/get Tree Node', [
function(session,agrs) {
getTreeNode(session);
}
]);
function getTreeNode(session) {
session.send("in tree "+ session.userData.profile.treeSelectdNodeId);
getXMLData(function(treeRoot) {
var nextLevel = treeRoot.first(function (node) {
return node.model.id === session.userData.profile.treeSelectdNodeId;
});
session.send('selected title '+ nextLevel.model.HierarchyMenuItem[0].title);
/* var secondListChild = [];
for(var i = 0; i < nextLevel.model.HierarchyMenuItem.length; i++) {
if(nextLevel.model.HierarchyMenuItem[i].title !='' && nextLevel.model.HierarchyMenuItem[i].title != undefined && nextLevel.model.HierarchyMenuItem[i].title != null) {
secondListChild.push(nextLevel.model.HierarchyMenuItem[i].title);
}
}
if(secondListChild.length > 0) {
builder.Prompts.choice(session, nextLevel.model.description,secondListChild);
} else {
session.send('Something went wrong. You can use the back or top command.');
} */
});
}
issue with the getTreeNode is
session.send('selected title '+ nextLevel.model.HierarchyMenuItem[0].title);
^
TypeError: Cannot read property 'model' of undefined
Got Solution....
I have change the XML parse NPM and its working for me..
var parse = require('xml-parser');
var inspect = require('util').inspect;
function getXMLData(callback) {
var request = require('request');
request('http://ztdemo.headfitted.in/RefactoredXML.xml', function (error, response, body) {
if (!error && response.statusCode == 200) {
var obj = parse(body);
//console.log(inspect(obj, { colors: true, depth: Infinity }));
//callback(treeRoot);
treeRoot = tree.parse(obj.root);
callback(treeRoot);
}
})
}

How to call SP.UI.Status in visual webpart

I have a scenario where i need to display an Alert banner with the title column in my list.
Below is the code which iam trying to use . But it is not displaying correctly. Can any one let me know Errorl
<script type="text/ecmascript" language="ecmascript">
var strStatusID;
function showInfo(strMessage) {
alert("Code sucess");
strStatusID = SP.UI.Status.addStatus(strMessage, true);
alert(strMessage.toString());
SP.UI.Status.setStatusPriColor(strStatusID, "yellow");
}
</script>
<asp:Panel ID="Panel1" runat="server">
<asp:Label ID="lblScripter" runat="server" Visible="false"></asp:Label>
</asp:Panel>
public void LoadGrid()
{
//System.Diagnostics.Debugger.Break();
var oSPWeb = SPContext.Current.Web;
SPList oSpList = oSPWeb.Lists["AlertList"];
SPQuery oQuery = new SPQuery();
oQuery.Query = #"<Where><Neq><FieldRef Name='NoOfDays' /><Value Type='Calculated'>0:00</Value></Neq></Where>";
SPListItemCollection _AlertListCollection = oSpList.GetItems(oQuery);
DataTable Table_Calendar = _AlertListCollection.GetDataTable();
if (Table_Calendar != null)
{
foreach (SPListItem item in _AlertListCollection)
{
MessageShow = item["Title"].ToString();
}
// strStatusID = SP.UI.Status.addStatus(strMessage, true);
lblScripter.Text = "<Script language='javascript;>showInfo('" + MessageShow + "');</script>";
}
else
{
lblScripter.Visible = false;
}
}
<asp:Timer runat="server" ID="UpdateTimer" Interval="6000" OnTick="UpdateTimer_Tick" />
<asp:UpdatePanel runat="server" ID="TimedPanel" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="UpdateTimer" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label runat="server" ID="DateStampLabel" />
<asp:Label ID="lblScripter" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
protected void UpdateTimer_Tick(object sender, EventArgs e)
{
System.Diagnostics.Debugger.Break();
DateStampLabel.Text = DateTime.Now.ToString();
DateTime Currenttime = DateTime.Parse(DateStampLabel.Text.ToString());
var oSPWeb = SPContext.Current.Web;
SPList oSpList = oSPWeb.Lists["Alertlist"];
SPQuery oQuery = new SPQuery();
oQuery.Query = #"<Where><Neq><FieldRef Name='NoOfDays' /><Value Type='Calculated'>0:00</Value></Neq></Where>";
SPListItemCollection _AlertListCollection = oSpList.GetItems(oQuery);
DataTable Table_Calendar = _AlertListCollection.GetDataTable();
if (Table_Calendar != null)
{
foreach (SPListItem item in _AlertListCollection)
{
MessageShow = item["Title"].ToString();
Enddate = DateTime.Parse(item["EndDate"].ToString());
}
lblScripter.Text = #"<script type=""text/javascript"">SP.SOD.executeOrDelayUntilScriptLoaded(function() {showInfo('" + MessageShow + "');}, 'sp.js');</script>";
if (Currenttime >= Enddate)
{
lblScripter.Text = "hi after date tim refreshed";
lblScripter.Text = #"<script type=""text/javascript"">SP.SOD.executeOrDelayUntilScriptLoaded(function() {removeAllInfos();}, 'sp.js');</script>";
}
}
//else
//{
// lblScripter.Visible = false;
//}
}
Try to set :
lblScripter.Text = #"<script type=""text/javascript"">SP.SOD.executeOrDelayUntilScriptLoaded(function() {showInfo('" + MessageShow + "');}, 'sp.js');</script>"
Most likely this will solve your problem of calling the SP.UI.Status javascript functions before they have been loaded.
I Have solved this PFB code in order to acheive this. Thanks to my friend Hameed who has helped me to acheive the same
<script type="text/ecmascript" language="ecmascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(RegisterMethods);
function RegisterMethods() {
showInfo();
RemoveLastStatus();
}
function showInfo() {
var strMessage = document.getElementById('<%= Message.ClientID %>').value;
var strstatus = document.getElementById('<%= StartStatus.ClientID %>').value;
if (strMessage != null) {
if (strstatus != "false") {
var strStatusID;
strStatusID = SP.UI.Status.addStatus(strMessage);
SP.UI.Status.setStatusPriColor(strStatusID, "red");
document.getElementById('<%= StartStatus.ClientID %>').value = "false";
document.getElementById('<%= StatusId.ClientID %>').value = strStatusID;
}
}
}
function RemoveLastStatus() {
var statusId = document.getElementById('<%= StatusId.ClientID %>').value;
var stopStatus = document.getElementById('<%= StopStatus.ClientID %>').value;
if (statusId != null) {
if (stopStatus == "true") {
SP.UI.Status.removeStatus(statusId);
statusId = '';
}
}
}
</script>
<asp:Timer runat="server" ID="UpdateTimer" Interval="5000" OnTick="UpdateTimer_Tick" />
<asp:UpdatePanel runat="server" ID="TimedPanel" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="UpdateTimer" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label runat="server" ID="DateStampLabel" />
<asp:Label ID="lblScripter" runat="server" Visible="True"></asp:Label>
<asp:HiddenField ID="StartStatus" runat="server" />
<asp:HiddenField ID="StopStatus" runat="server" />
<asp:HiddenField ID="Message" runat="server" />
<asp:HiddenField ID="StatusId" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
CODEBEHIND.cs
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections.Generic;
using System.Web;
using System.Drawing;
using System.Globalization;
using System.Data;
using System.Linq;
using Microsoft.SharePoint.Utilities;
namespace ITBANNER
{
public partial class ITOpsBannerUserControl : UserControl
{
String MessageShow = string.Empty;
DateTime Enddate, starttime;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DateStampLabel.Text = DateTime.Now.ToString();
DateTime Currenttime = DateTime.Parse(DateStampLabel.Text.ToString());
var oSPWeb = SPContext.Current.Web;
SPList oSpList = oSPWeb.Lists["AlertList"];
SPListItemCollection items = oSpList.Items;
SPListItem item;
for (int i = 0; i < items.Count; i++)
{
item = items[i];
Console.WriteLine("Index = {0} ID = {1}", i, item.ID);
}
SPListItem item = oSpList.GetItemById(3);
Message.Value = item["Title"].ToString();
starttime = DateTime.Parse(item["StartDate"].ToString());
if (Currenttime >= starttime)
{
StartStatus.Value = "true";
StopStatus.Value = "false";
}
}
}
protected void UpdateTimer_Tick(object sender, EventArgs e)
{
DateStampLabel.Text = DateTime.Now.ToString();
DateTime Currenttime = DateTime.Parse(DateStampLabel.Text.ToString());
var oSPWeb = SPContext.Current.Web;
SPList oSpList = oSPWeb.Lists["AlertList"];
SPListItem item = oSpList.GetItemById(3);
Enddate = DateTime.Parse(item["EndDate"].ToString());
if (Currenttime >= Enddate)
{
StopStatus.Value = "true";
}
}
//public void HideStatusBar()
//{
// string script = "document.onreadystatechange=fnRemoveAllStatus; function fnRemoveAllStatus(){removeAllStatus(true)};";
// this.Page.ClientScript.RegisterClientScriptBlock(typeof(Type), "statusBarRemover", script, true);
//}
}
}

Need to get a field editable depending on a field content in EXT.NET. Get this.field.msgTarget is null or not an object error

I try to use your example to dynamically add/remove editor and get this error:
this.field.msgTarget is null or not an object error. I'm new to the ext.net - could somebody help me?
Thanks,
Jenny
this is my code:
EditExample.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="EditExample.aspx.cs" Inherits="myApp.EditExample" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%# Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
var setEditor = function (e) {
var column = e.grid.getColumnModel().columns[e.column],
ed = column.getCellEditor(e.row);
if (ed && (e.value != null || e.value != '')) {
ed.destroy();
}
else {
column.setEditor(new Ext.form.TextField());
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<ext:ResourceManager runat="server" />
<ext:Store ID="extStore" runat="server" >
<Reader>
<ext:JsonReader>
<Fields>
<ext:RecordField Name = "Name" />
<ext:RecordField Name = "Code" ></ext:RecordField>
<ext:RecordField Name = "Description" ></ext:RecordField>
</Fields>
</ext:JsonReader>
</Reader>
</ext:Store>
<div>
<ext:GridPanel ID="extGrd" runat="server" StripeRows="true" TrackMouseOver="true"
StoreID="extStore" Cls="x-grid-custom"
Height="250px" Layout="fit">
<ColumnModel ID="cmFC" runat="server">
<Columns>
<ext:Column ColumnID="Name" DataIndex="Name" Header="Name">
</ext:Column>
<ext:Column ColumnID="Code" DataIndex="Code" Header="Code">
</ext:Column>
<ext:Column ColumnID="Description" DataIndex="Description" Header="Description" Editable ="true" >
<Editor>
<ext:TextField ID="TextField1" runat="server"></ext:TextField>
</Editor>
</ext:Column>
</Columns>
</ColumnModel>
<Listeners>
<BeforeEdit Fn="setEditor" />
<Render Handler="this.getColumnModel().setEditable(0, true);" />
</Listeners>
<SelectionModel>
<ext:RowSelectionModel ID="RowSelectionModel1" runat="server" SingleSelect="true" MoveEditorOnEnter="true"/>
</SelectionModel>
<LoadMask ShowMask="true" />
</ext:GridPanel>
</div>
</form>
</body>
</html>
EditExample.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace myApp
{
public class info
{
public string Name { get; set; }
public string Code { get; set; }
public string Description { get; set; }
}
public partial class EditExample : System.Web.UI.Page
{
protected void Page_Load( object sender, EventArgs e )
{
List<info> thisInfo = new List<info>();
thisInfo.Add( new info { Code = "1", Description = "one", Name = "one Name" } );
thisInfo.Add( new info { Code = "2", Description = "two", Name = "two Names" } );
thisInfo.Add( new info { Code = "3", Description = "three", Name = "three Names" } );
thisInfo.Add( new info { Code = "4", Description = "four", Name = "four Names" } );
thisInfo.Add( new info { Code = "5", Description = "five", Name = "five Names" } );
thisInfo.Add( new info { Code = "6", Description = "six", Name = "six Names" } );
this.extStore.DataSource = thisInfo;
this.extStore.DataBind();
}
}
EDIT:
I tried to make the field disabled and readonly.
It made the field appear disabled (greyed out), but readable.
var setEditor = function (e)
{
var column = e.grid.getColumnModel().columns[e.column],
ed = column.getCellEditor(e.row);
if (ed)
{
if (e.value != null && e.value != '')
{
ed.readOnly = true; ed.setDisabled(true);
}
else
{
ed.readOnly = false; ed.setDisabled(false);
}
}
}
You can just return false to before event.
var setEditor = function (e) {
var column = e.grid.getColumnModel().columns[e.column],
ed = column.getCellEditor(e.row);
if (ed && (e.value != '')) {
return false;
}
}

Resources