Calling Server Side Scripting from JavaScript Not Working in Asp.Net - javascript

I want to call Server Side function using JavaScript . I m using PageMethod.
But Code is not working. Please tell Error in code Block.
I m using two JavaScript function onLoad. AJAX Script Manager PageMethod is also set to true.
My Server Side Function in not taking any value as input nor returning any value.
function GetData() {
PageMethods.GetData(OnSuccess);
}
function OnSuccess(response, userContext, methodName) {
alert(response);
}
function GetOS() {
console.log("rom");
$('input[type="checkbox"]').on('change', function (e) {
var data = {},
fdata = [],
loc = $('<a>', { href: window.location })[0];
$('input[type="checkbox"]').each(function (i) {
if (this.checked) {
if (!data.hasOwnProperty(this.name)) {
data[this.name] = [];
}
data[this.name].push(this.value);
}
});
var key = Object.keys(data)[0];
var fdata = key + "=" + data[key].join(',');
$.post('/ajax-post-url/', fdata);
if (history.pushState) {
history.pushState(null, null, loc.pathname + '?' + fdata);
}
});
}
window.addEventListener("load", GetOS, false);
window.addEventListener("load", GetData, false);
[System.Web.Services.WebMethod]
public void GetData()
{
if(Request.QueryString.ToString() != "")
{
System.Data.DataTable DT = new System.Data.DataTable();
DT = BLL.GetProjectByLike(Request.QueryString["PSC"].ToString());
if (DT.Rows.Count > 0)
{
Repeater1.DataSource = DT;
Repeater1.DataBind();
}
}
else
{
System.Data.DataTable DT = new System.Data.DataTable();
DT = BLL.AdminSeeProjectIns();
if (DT.Rows.Count > 0)
{
Repeater1.DataSource = DT;
Repeater1.DataBind();
}
}
}

Related

How to modify anchor tags in botframework Web chat

We've just started using the bot-framework. For client side we are using the cdn and not react. We have certain links that bot responds with. And we would like to append a url parameter to each link and open the link in the same window. So far this is what my code looks like. Is there a better way to achieve this using the botframework. I know there is cardActionMiddleware which has openUrl cardAction, but we don't have any cards and I am not sure on how to implement that.
var webchatMount = document.getElementById('webchatMount');
function loadChatbot() {
var xhr = new XMLHttpRequest();
xhr.open('GET', "https://webchat.botframework.com/api/tokens", true);
xhr.setRequestHeader('Authorization', 'BotConnector ' + '<secret>');
xhr.send();
xhr.onreadystatechange = function (e) {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
var store = window.WebChat.createStore({}, function ({ dispatch }) {
return function (next) {
return function (action) {
if (action.type === 'DIRECT_LINE/INCOMING_ACTIVITY') {
var event = new Event('webchatincomingactivity');
event.data = action.payload.activity;
window.dispatchEvent(event);
}
return next(action);
}
}
});
window.WebChat.renderWebChat(
{
directLine: window.WebChat.createDirectLine({ token: response }),
store: store,
},
webchatMount
);
document.querySelector('.webchat__send-box-text-box__input').focus();
window.addEventListener('webchatincomingactivity', ({ data }) => {
setTimeout(function () {
var links = document.querySelectorAll('#webchatMount a');
if (links.length >= 1) {
for (var i = 0; i <= links.length; i++) {
if (links[i] == undefined)
break;
var compare = new RegExp('maindomain');
var href = links[i].getAttribute('href');
var st = getParameterByName('st', href);
if (links[i].hasAttribute('target')) {
links[i].removeAttribute('target');
}
if (compare.test(href)) {
// internal link
// check if it has st=INTRA
if (st) {
console.log(' it has a value');
} else {
links[i].setAttribute('href', insertParam('st', 'INTRA', href));
}
} else {
// external link, do nothing
}
}
}
}, 1000);
});
}
}
}
and here are getParameterByName and insertParam functions.
function getParameterByName(name, url) {
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
function insertParam(key, value, url) {
key = encodeURIComponent(key);
value = encodeURIComponent(value);
// kvp looks like ['key1=value1', 'key2=value2', ...]
var kvp = url.split('&');
var i=0;
for(; i<kvp.length; i++){
if (kvp[i].startsWith(key + '=')) {
var pair = kvp[i].split('=');
pair[1] = value;
kvp[i] = pair.join('=');
break;
}
}
if(i >= kvp.length){
kvp[kvp.length] = [key,value].join('=');
}
return kvp.join('&');
}
I am new to botframework webchat so I don't know it very well. I know that the secret should not be used like that, but for know we are testing and would like to get it to work. Any help would be appericiated
Thanks.

html table no longer supported

As others before I used yql to get data from a website. The website is in xml format.
I am doing this to build a web data connector in Tableau to connect to xmldata and I got my code from here: https://github.com/tableau/webdataconnector/blob/v1.1.0/Examples/xmlConnector.html
As recommended on here: YQL: html table is no longer supported I tried htmlstring and added the reference to the community environment.
// try to use yql as a proxy
function _yqlProxyAjaxRequest2(url, successCallback){
var yqlQueryBase = "http://query.yahooapis.com/v1/public/yql?q=";
var query = "select * from htmlstring where url='" + url + "'";
var restOfQueryString = "&format=xml" ;
var yqlUrl = yqlQueryBase + encodeURIComponent(query) + restOfQueryString + "&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
_ajaxRequestHelper(url, successCallback, yqlUrl, _giveUpOnUrl9);
}
function _giveUpOnUrl9(url, successCallback) {
tableau.abortWithError("Could not load url: " + url);
}
However, I still got the message: Html table no longer supported.
As I don't know much about yql, I tried to work with xmlHttpRequestinstead, but Tableau ended up processing the request for ages and nothing happened.
Here my attempt to find another solution and avoid the yql thingy:
function _retrieveXmlData(retrieveDataCallback) {
if (!window.cachedTableData) {
var conData = JSON.parse(tableau.connectionData);
var xmlString = conData.xmlString;
if (conData.xmlUrl) {
var successCallback = function(data) {
window.cachedTableData = _xmlToTable(data);
retrieveDataCallback(window.cachedTableData);
};
//INSTEAD OF THIS:
//_basicAjaxRequest1(conData.xmlUrl, successCallback);
//USE NOT YQL BUT XMLHTTPREQUEST:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open('GET', 'https://www.w3schools.com/xml/cd_catalog.xml', true);
xhttp.send();
return;
}
try {
var xmlDoc = $.parseXML(conData.xmlString);
window.cachedTableData = _xmlToTable(xmlDoc);
}
catch (e) {
tableau.abortWithError("unable to parse xml data");
return;
}
}
retrieveDataCallback(window.cachedTableData);
}
Does anyone have an idea how to get YQL work or comment on my approach trying to avoid it?
Thank you very much!
For reference, if there is any Tableau user that wants to test it on Tableau, here is my full code:
<html>
<head>
<title>XML Connector</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script src="https://connectors.tableau.com/libs/tableauwdc-1.1.1.js" type="text/javascript"></script>
<script type="text/javascript">
(function() {
var myConnector = tableau.makeConnector();
myConnector.init = function () {
tableau.connectionName = 'XML data';
tableau.initCallback();
};
myConnector.getColumnHeaders = function() {
_retrieveXmlData(function (tableData) {
var headers = tableData.headers;
var fieldNames = [];
var fieldTypes = [];
for (var fieldName in headers) {
if (headers.hasOwnProperty(fieldName)) {
fieldNames.push(fieldName);
fieldTypes.push(headers[fieldName]);
}
}
tableau.headersCallback(fieldNames, fieldTypes); // tell tableau about the fields and their types
});
}
myConnector.getTableData = function (lastRecordToken) {
_retrieveXmlData(function (tableData) {
var rowData = tableData.rowData;
tableau.dataCallback(rowData, rowData.length.toString(), false);
});
};
tableau.registerConnector(myConnector);
})();
function _retrieveXmlData(retrieveDataCallback) {
if (!window.cachedTableData) {
var conData = JSON.parse(tableau.connectionData);
var xmlString = conData.xmlString;
if (conData.xmlUrl) {
var successCallback = function(data) {
window.cachedTableData = _xmlToTable(data);
retrieveDataCallback(window.cachedTableData);
};
//_basicAjaxRequest1(conData.xmlUrl, successCallback);
//here try another approach not using yql but xmlHttpRequest?
//try xml dom to get url (xml http request)
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open('GET', 'https://www.w3schools.com/xml/cd_catalog.xml', true);
xhttp.send();
return;
}
try {
var xmlDoc = $.parseXML(conData.xmlString);
window.cachedTableData = _xmlToTable(xmlDoc);
}
catch (e) {
tableau.abortWithError("unable to parse xml data");
return;
}
}
retrieveDataCallback(window.cachedTableData);
}
function myFunction(xml) {
var xmlDoc = xml.responseXML;
window.cachedTableData = _xmlToTable(xmlDoc);
}
// There are a lot of ways to handle URLS. Sometimes we'll need workarounds for CORS. These
// methods chain together a series of attempts to get the data at the given url
function _ajaxRequestHelper(url, successCallback, conUrl, nextFunction,
specialSuccessCallback){
specialSuccessCallback = specialSuccessCallback || successCallback;
var xhr = $.ajax({
url: conUrl,
dataType: 'xml',
success: specialSuccessCallback,
error: function()
{
nextFunction(url, successCallback);
}
});
}
// try the straightforward request
function _basicAjaxRequest1(url, successCallback){
_ajaxRequestHelper(url, successCallback, url, _yqlProxyAjaxRequest2);
}
// try to use yql as a proxy
function _yqlProxyAjaxRequest2(url, successCallback){
var yqlQueryBase = "http://query.yahooapis.com/v1/public/yql?q=";
var query = "select * from htmlstring where url='" + url + "'";
var restOfQueryString = "&format=xml" ;
var yqlUrl = yqlQueryBase + encodeURIComponent(query) + restOfQueryString + "&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
_ajaxRequestHelper(url, successCallback, yqlUrl, _giveUpOnUrl9);
}
function _giveUpOnUrl9(url, successCallback) {
tableau.abortWithError("Could not load url: " + url);
}
// Takes a hierarchical xml document and tries to turn it into a table
// Returns an object with headers and the row level data
function _xmlToTable(xmlDocument) {
var rowData = _flattenData(xmlDocument);
var headers = _extractHeaders(rowData);
return {"headers":headers, "rowData":rowData};
}
// Given an object:
// - finds the longest array in the xml
// - flattens each element in that array so it is a single element with many properties
// If there is no array that is a descendent of the original object, this wraps
function _flattenData(xmlDocument) {
// first find the longest array
var longestArray = _findLongestArray(xmlDocument, xmlDocument);
if (!longestArray || longestArray.length == 0) {
// if no array found, just wrap the entire object blob in an array
longestArray = [objectBlob];
}
toRet = [];
for (var ii = 0; ii < longestArray.childNodes.length; ++ii) {
toRet[ii] = _flattenObject(longestArray.childNodes[ii]);
}
return toRet;
}
// Given an element with hierarchical properties, flattens it so all the properties
// sit on the base element.
function _flattenObject(xmlElt) {
var toRet = {};
if (xmlElt.attributes) {
for (var attributeNum = 0; attributeNum < xmlElt.attributes.length; ++attributeNum) {
var attribute = xmlElt.attributes[attributeNum];
toRet[attribute.nodeName] = attribute.nodeValue;
}
}
var children = xmlElt.childNodes;
if (!children || !children.length) {
if (xmlElt.textContent) {
toRet.text = xmlElt.textContent.trim();
}
} else {
for (var childNum = 0; childNum < children.length; ++childNum) {
var child = xmlElt.childNodes[childNum];
var childName = child.nodeName;
var subObj = _flattenObject(child);
for (var k in subObj) {
if (subObj.hasOwnProperty(k)) {
toRet[childName + '_' + k] = subObj[k];
}
}
}
}
return toRet;
}
// Finds the longest array that is a descendent of the given object
function _findLongestArray(xmlElement, bestSoFar) {
var children = xmlElement.childNodes;
if (children && children.length) {
if (children.length > bestSoFar.childNodes.length) {
bestSoFar = xmlElement;
}
for (var childNum in children) {
var subBest = _findLongestArray(children[childNum], bestSoFar);
if (subBest.childNodes.length > bestSoFar.childNodes.length) {
bestSoFar = subBest;
}
}
}
return bestSoFar;
}
// Given an array of js objects, returns a map from data column name to data type
function _extractHeaders(rowData) {
var toRet = {};
for (var row = 0; row < rowData.length; ++row) {
var rowLine = rowData[row];
for (var key in rowLine) {
if (rowLine.hasOwnProperty(key)) {
if (!(key in toRet)) {
toRet[key] = _determineType(rowLine[key]);
}
}
}
}
return toRet;
}
// Given a primitive, tries to make a guess at the data type of the input
function _determineType(primitive) {
// possible types: 'float', 'date', 'datetime', 'bool', 'string', 'int'
if (parseInt(primitive) == primitive) return 'int';
if (parseFloat(primitive) == primitive) return 'float';
if (isFinite(new Date(primitive).getTime())) return 'datetime';
return 'string';
}
function _submitXMLToTableau(xmlString, xmlUrl) {
var conData = {"xmlString" : xmlString, "xmlUrl": xmlUrl};
tableau.connectionData = JSON.stringify(conData);
tableau.submit();
}
function _buildConnectionUrl(url) {
// var yqlQueryBase = "http://query.yahooapis.com/v1/public/yql?q=";
// var query = "select * from html where url='" + url + "'";
// var restOfQueryString = "&format=xml";
// var yqlUrl = yqlQueryBase + encodeURIComponent(query) + restOfQueryString;
// return yqlUrl;
return url;
}
$(document).ready(function(){
var cancel = function (e) {
e.stopPropagation();
e.preventDefault();
}
$("#inputForm").submit(function(e) { // This event fires when a button is clicked
// Since we use a form for input, make sure to stop the default form behavior
cancel(e);
var xmlString = $('textarea[name=xmlText]')[0].value.trim();
var xmlUrl = $('input[name=xmlUrl]')[0].value.trim();
_submitXMLToTableau(xmlString, xmlUrl);
});
var ddHandler = $("#dragandrophandler");
ddHandler.on('dragenter', function (e)
{
cancel(e);
$(this).css('border', '2px solid #0B85A1');
}).on('dragover', cancel)
.on('drop', function (e)
{
$(this).css('border', '2px dashed #0B85A1');
e.preventDefault();
var files = e.originalEvent.dataTransfer.files;
var file = files[0];
var reader = new FileReader();
reader.onload = function(e) { _submitXMLToTableau(reader.result); };
reader.readAsText(file);
});
$(document).on('dragenter', cancel)
.on('drop', cancel)
.on('dragover', function (e)
{
cancel(e);
ddHandler.css('border', '2px dashed #0B85A1');
});
});
</script>
<style>
#dragandrophandler {
border:1px dashed #999;
width:300px;
color:#333;
text-align:left;vertical-align:middle;
padding:10px 10px 10 10px;
margin:10px;
font-size:150%;
}
</style>
</head>
<body>
<form id="inputForm" action="">
Enter a URL for XML data:
<input type="text" name="xmlUrl" size="50" />
<br>
<div id="dragandrophandler">Or Drag & Drop Files Here</div>
<br>
Or paste XML data below
<br>
<textarea name="xmlText" rows="10" cols="70"/></textarea>
<input type="submit" value="Submit">
</form>

How to Send Input File Over JS Ajax Send and Get Path From File

I am currently using the following JS Code to do my Ajax calls:
var ajax = {};
ajax.x = function () {
if (typeof XMLHttpRequest !== 'undefined') {
return new XMLHttpRequest();
}
var versions = [
"MSXML2.XmlHttp.6.0",
"MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"
];
var xhr;
for (var i = 0; i < versions.length; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
} catch (e) {
}
}
return xhr;
};
ajax.send = function (url, callback, method, data, async) {
if (async === undefined) {
async = true;
}
var x = ajax.x();
x.open(method, url, async);
x.onreadystatechange = function () {
if (x.readyState == 4) {
callback(x.responseText)
}
};
if (method == 'POST') {
x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
}
x.send(data)
};
ajax.get = function (url, data, callback, async) {
var query = [];
for (var key in data) {
query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
ajax.send(url + (query.length ? '?' + query.join('&') : ''), callback, 'GET', null, async)
};
ajax.post = function (url, data, callback, async) {
var query = [];
for (var key in data) {
query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
ajax.send(url, callback, 'POST', query.join('&'), async)
};
And I currently have this little snippet that calls my controller's action and send the input file to the controller:
function UpdateChapterText() {
try {
document.getElementById("chapterTextInput").value = "";
} catch (e) { }
ajax.post('/Create/ImportFromFile', document.getElementById("chapterFile"), function (data, e) {
document.getElementById("chapterTextInput").value = data;
});
}
The element with "chapterFile" as the ID is the input element with type="file". Here is my controller:
[HttpPost]
public ActionResult ImportFromFile(HttpPostedFileBase chapterFile)
{
string path = Path.GetFileName(chapterFile.FileName);
}
However, after debugging, it looks like the HttpPostedFileBase chapterFile always remains null. Am I sending over the element wrong entirely?
Thanks.

CEFSharp RegisterExtension not working

I had an screen scraper app that used CEFSharp that was working fine until I updated CEFSharp to the latest version. It appears that the way I was registering javascript extension functions no longer works. Here is my startup code:
[STAThread]
public static void Main()
{
try
{
CefSettings settings = new CefSettings();
settings.RegisterExtension(new CefExtension("showModalDialog", Resources.showModalDialog));
//Perform dependency check to make sure all relevant resources are in our output directory.
Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);
ProcessCommandLine();
var browser = new BrowserForm("https://www.google.com");
Application.Run(browser);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
If I comment out the settings.RegisterExtension line, it runs fine. It used to work. Here is the code for my extension:
(function () {
absolutePath = function (href) {
var link = document.createElement("a");
link.href = href;
return (link.protocol + "//" + link.host + link.pathname + link.search + link.hash);
}
showModalDialog = function (url, arg, opt) {
url = url || ''; //URL of a dialog
arg = arg || null; //arguments to a dialog
opt = opt || 'dialogWidth:300px;dialogHeight:200px'; //options: dialogTop;dialogLeft;dialogWidth;dialogHeight or CSS styles
var caller = showModalDialog.caller.toString();
var dialog = document.body.appendChild(document.createElement('dialog'));
dialog.setAttribute('style', opt.replace(/dialog/gi, ''));
dialog.innerHTML = '×<iframe id="dialog-body" name="dialog-body" src="' + absolutePath(url) + '" style="border: 0; width: 100%; height: 100%;"></iframe>';
//document.getElementById('dialog-body').contentWindow.dialogArguments = arg;
document.getElementById('dialog-close').addEventListener('click', function (e) {
e.preventDefault();
dialog.close();
});
document.getElementById('dialog-body').addEventListener('load', function (e) {
this.style.height = this.contentWindow.document.body.scrollHeight + 'px';
this.style.width = this.contentWindow.document.body.scrollWidth + 'px';
this.contentWindow.close = function () {
dialog.close();
};
this.contentWindow.dialogArguments = arg;
this.window = this.contentWindow;
});
dialog.showModal();
//if using yield
if (caller.indexOf('yield') >= 0) {
return new Promise(function (resolve, reject) {
dialog.addEventListener('close', function () {
var returnValue = document.getElementById('dialog- body').contentWindow.returnValue;
document.body.removeChild(dialog);
resolve(returnValue);
});
});
}
//if using eval
var isNext = false;
var nextStmts = caller.split('\n').filter(function (stmt) {
if (isNext || stmt.indexOf('showModalDialog(') >= 0)
return isNext = true;
return false;
});
dialog.addEventListener('close', function () {
var returnValue = document.getElementById('dialog-body').contentWindow.returnValue;
document.body.removeChild(dialog);
//nextStmts[0] = nextStmts[0].replace(/(window\.)?showModalDialog\(.*\)/g, JSON.stringify(returnValue));
//eval('{\n' + nextStmts.join('\n'));
});
throw 'Execution stopped until showModalDialog is closed';
};
})();
Did something change about the syntax of extensions?
https://bugs.chromium.org/p/chromium/issues/detail?id=665391
It's a Chrome thing and it doesn't look like they are going to fix it.

Read-Only Button for List Item in Sharepoint

I've got the following Sharepoint problem: I've created a Ribbon Button, which says "Read Only". When I am on a list, and check some items, I want to set those items to read only.
The ribbon button works great and when I am doing an alert or something, I get an answer. So this cannot be the problem. I did the following:
var listitem;
var roleAssgn;
var Assgn;
var selectedItems;
function readonly() {
selectedItems = SP.ListOperation.Selection.getSelectedItems();
var currentListGuid = SP.ListOperation.Selection.getSelectedList();
var context = SP.ClientContext.get_current();
var currentWeb = context.get_web();
var currentList = currentWeb.get_lists().getById(currentListGuid);
for (k in selectedItems) {
listitem = currentList.getItemById(selectedItems[k].id);
context.load(listitem, 'RoleAssignments');
context.executeQueryAsync(Function.createDelegate(this, this.readonlyPerItem), Function.createDelegate(this, this.failed));
}
}
function readonlyPerItem(sender, args) {
var k;
var Assgn;
var r;
context = SP.ClientContext.get_current();
roleAssgn = listitem.get_roleAssignments();
for(r in roleAssgn){
Assgn = roleAssgn[r];
alert("1");
context.load(Assgn, 'RoleDefinitionBindings');
alert("2");
context.executeQueryAsync(Function.createDelegate(this, this.readonlyPerRoleA), Function.createDelegate(this, this.failed));
}
}
function readonlyPerRoleA(sender, args) {
var bindings = Assgn.get_roleDefinitionBindings();
var member = Assgn.get_member();
}
function failed(sender, args) {
alert("FAIL");
}
This works great until it gets to the alerts. Alert-1 is working, but not Alert-2. The Debugger says: The object does not support the property "get_$h".
And that happens in the sp_runtime.js with:
SP.DataRetrievalWithExpressionString.$1Q_0(a.get_$h(),d)
I dont really see a problem. Is this a bug or is it just not possible?
Ok, I used another way to do this and wanted to let you know, how it worked for me. I used a JS in the Ribbon Menu to call another website, which is just an empty site. I added the parameters (listguid, siteurl and the itemid's comma-seperated).
Then that site just prints an "True" or "False". This response will be caught by my Ribbon JS and show some message if it worked or not. This is my Ribbon JS:
<CustomAction
Id="ReadOnlyButton"
RegistrationId="101"
RegistrationType="List"
Location="CommandUI.Ribbon"
Sequence="15"
Rights="ManageLists"
Title="Set Readonly">
<CommandUIExtension>
<CommandUIDefinitions>
<CommandUIDefinition
Location="Ribbon.Documents.Manage.Controls._children">
<Button
Id="Ribbon.Documents.ReadOnly"
Command="ReadOnly"
Sequence="15"
Image16by16="/_layouts/1031/images/formatmap16x16.png"
Image16by16Left="-80"
Image16by16Top="-128"
Image32by32="/_layouts/1031/images/formatmap32x32.png"
Image32by32Left="-160"
Image32by32Top="-256"
Description="Read Only"
LabelText="Read Only"
TemplateAlias="o1"/>
</CommandUIDefinition>
</CommandUIDefinitions>
<CommandUIHandlers>
<CommandUIHandler
Command="ReadOnly"
CommandAction="javascript:
var nid;
function getItemIds()
{
var itemIds = '';
var items = SP.ListOperation.Selection.getSelectedItems();
var item;
for(var i in items)
{
item = items[i];
if(itemIds != '')
{
itemIds = itemIds + ',';
}
itemIds = itemIds + item.id;
}
return itemIds;
}
function handleReadyStateChange()
{
if (client.readyState == 4)
{
if (client.status == 200)
{
SP.UI.Notify.removeNotification(nid);
if(client.responseText == 'True') {
nid = SP.UI.Status.addStatus('The Rights has been set successfully', '', true);
SP.UI.Status.setStatusPriColor(nid, 'green');
} else {
nid = SP.UI.Status.addStatus('Error while setting Rights', '', true);
SP.UI.Status.setStatusPriColor(nid, 'red');
}
window.setTimeout('SP.UI.Status.removeStatus(\'' + nid + '\')', 5000);
}
}
}
function invokeReadOnly()
{
var itemLength = 0;
var params = 'itemids=' + getItemIds();
for (var i=0;i<params.length;i++) { if (',' == params.substr(i,1)) { itemLength++; } }
if(itemLength > 0) {
nid = SP.UI.Notify.addNotification('Rights set for ' + (itemLength +1) + ' elements...', true);
} else {
nid = SP.UI.Notify.addNotification('Set Rights...', true);
}
var site='{SiteUrl}';
var url = site + '/_layouts/ReadOnly.aspx?listId={ListId}';
client = null;
client = new XMLHttpRequest();
client.onreadystatechange = handleReadyStateChange;
client.open('POST', url, true);
client.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
client.setRequestHeader('Content-length', params.length);
client.send(params);
}
invokeReadOnly();"
EnabledScript="javascript:
function enableReadOnly()
{
var items = SP.ListOperation.Selection.getSelectedItems();
return (items.length > 0);
}
enableReadOnly();"/>
</CommandUIHandlers>
</CommandUIExtension>
</CustomAction>
And this is my site behind it (ReadOnly.aspx):
protected void Page_Load(object sender, EventArgs e)
{
string itemidsAll = Page.Request["itemids"];
string listId = Page.Request["listId"];
bool set = true;
if (!String.IsNullOrEmpty(itemidsAll))
{
string[] itemIds = itemidsAll.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
int item = 0;
SPSite _site = null;
SPListItem spitem = null;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
_site = new SPSite(SPContext.Current.Site.ID);
});
using (SPWeb web = _site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPList doclib = SPContext.Current.Web.Lists.GetList(new Guid(listId), false);
foreach (string itemId in itemIds)
{
if (Int32.TryParse(itemId, out item))
{
spitem = doclib.GetItemById(item);
set &= SetItem(spitem, SPContext.Current, ref _site);
}
}
web.AllowUnsafeUpdates = false;
}
_site.Dispose();
}
Response.Clear();
Response.Write(set.ToString());
Response.End();
}
The SetItem-Method is for setting the Rights. You can use your own stuff there :)

Categories

Resources