Why does the arrow function (line 35) return undefined? - arrow-functions

Why does the function (line 30) return expected values ("my name is Pumpkin Latte and I cost $5") but the arrow function (line 35) return undefined for this.name and this.price ("my name is Codepen and I cost undefined")?
https://codepen.io/mikntj/pen/xxrOEdE?editors=0011
function Latte (name) {
this.name = name
this.price = "$5"
}
function Cappucino (name) {
this.name = name
this.price = "$6"
}
function CoffeeFactory (name, price) {
this.create = (name, price) => {
switch(price) {
case 1:
return new Latte(name);
break;
case 2:
return new Cappucino(name);
break;
}
}
}
// function say ()
// {
// console.log("my name is " + this.name + " and I cost " +this.price)
// }
const say = () => {
console.log("my name is " + this.name + " and I cost " +this.price)
}
const coffeeFactory = new CoffeeFactory()
const coffees = []
coffees.push(coffeeFactory.create("Pumpkin Latte", 1))
coffees.push(coffeeFactory.create("Double Cappucino", 2))
coffees.forEach( cof => {
say.call(cof)
})

Related

Custom GL Lines Plug-in creates error on paid in full invoices

I created a script that re-books certain transactions depending on the account they were booked to. The script is running fine on all invoices and creating the expected outcome except when an invoice has the status "paid in full". The error states Cannot use 0 as input to setDebitAmount(). Amount to debit must be positive.
Already tried the script on the same invoice with different statuses - same outcome.
Why does the invoice status make a difference here?
/**
* Custom GL lines Plug-In Implementation for rebooking Invoices (articles and discounts)
* Configuration of Plug-In Implementation:
* Transaction Type: Invoice
* Subsidiaries: MTE
* #param {*} transactionRecord
* #param {*} standardLines
* #param {*} customLines
*/
function customizeGlImpact(
transactionRecord,
standardLines,
customLines
) {
function sign(x) {
// If x is NaN, the result is NaN.
// If x is -0, the result is -0.
// If x is +0, the result is +0.
// If x is negative and not -0, the result is -1.
// If x is positive and not +0, the result is +1.
return ((x > 0) - (x < 0)) || +x;
}
if (standardLines.getCount() > 0) {
var tranid = transactionRecord.getFieldValue("tranid");
var customername = transactionRecord.getFieldValue("entityname");
for (var i = 0; i < standardLines.getCount(); i++) {
// get information for GL standard line
var currLineStandard = standardLines.getLine(i);
var taxCodeId = currLineStandard.getTaxItemId();
var accountID = currLineStandard.getAccountId();
nlapiLogExecution("debug", "Line: " + i, JSON.stringify({ "taxCodeId": taxCodeId, "accountID": accountID }));
if (taxCodeId === null || accountID === null) {// specific lines don't have accountID
continue;
}
var correctAccountId = targetAccountSearch(accountID, taxCodeId);
nlapiLogExecution("debug", "Line: " + i, JSON.stringify({ "correctAccountId": correctAccountId }));
if (correctAccountId === -1) {
continue;
}
if (correctAccountId !== accountID) {
var salestaxitem = nlapiLoadRecord("salestaxitem", taxCodeId);
var newLine = customLines.addNewLine();
if (currLineStandard.creditAmount === "0") {
if (sign(currLineStandard.debitAmount) === 1) {
newLine.setCreditAmount(currLineStandard.debitAmount);
} else {
newLine.setDebitAmount(currLineStandard.debitAmount);
}
} else {
if (sign(currLineStandard.creditAmount) === 1) {
newLine.setDebitAmount(currLineStandard.creditAmount);
} else {
newLine.setCreditAmount(currLineStandard.creditAmount);
}
}
newLine.setAccountId(accountID);
newLine.setLocationId(currLineStandard.getLocationId());
newLine.setDepartmentId(currLineStandard.getDepartmentId());
newLine.setClassId(currLineStandard.getClassId());
newLine.setEntityId(currLineStandard.getEntityId());
newLine.setMemo((
"Umbuchung " +
salestaxitem.getFieldValue("itemid") +
" - " +
tranid +
" - " +
customername +
(currLineStandard.getMemo() !== null ? " - " + currLineStandard.getMemo() : "")).substring(0, 100)
);
var newLine = customLines.addNewLine();
if (currLineStandard.creditAmount === "0") {
if (sign(currLineStandard.debitAmount) === 1) {
newLine.setDebitAmount(currLineStandard.debitAmount);
} else {
newLine.setCreditAmount(currLineStandard.debitAmount);
}
} else {
if (sign(currLineStandard.creditAmount) === 1) {
newLine.setCreditAmount(currLineStandard.creditAmount);
} else {
newLine.setDebitAmount(currLineStandard.creditAmount);
}
}
newLine.setAccountId(correctAccountId);
newLine.setLocationId(currLineStandard.getLocationId());
newLine.setDepartmentId(currLineStandard.getDepartmentId());
newLine.setClassId(currLineStandard.getClassId());
newLine.setEntityId(currLineStandard.getEntityId());
newLine.setMemo((
"Umbuchung " +
salestaxitem.getFieldValue("itemid") +
" - " +
tranid +
" - " +
customername +
(currLineStandard.getMemo() !== null ? " - " + currLineStandard.getMemo() : "")).substring(0, 100)
);
}
}
}
}
/**
*
* #param {*} custrecord_pg_source_account
* #param {*} custrecord_pg_lookup_tax_code
* #returns
*/
function targetAccountSearch(
custrecord_pg_source_account,
custrecord_pg_lookup_tax_code
) {
// saved search for mapping
var accountRebookingSearch = nlapiCreateSearch(
"customrecord_pg_account_rebooking",
[
nlobjSearchFilter(
"custrecord_pg_source_account",
null,
"is",
custrecord_pg_source_account
),
nlobjSearchFilter(
"custrecord_pg_lookup_tax_code",
null,
"is",
custrecord_pg_lookup_tax_code
),
nlobjSearchFilter(
"isinactive",
null,
"is",
"F"
)
],
[
new nlobjSearchColumn('custrecord_pg_source_account'),
new nlobjSearchColumn('custrecord_pg_lookup_tax_code'),
new nlobjSearchColumn('custrecord_pg_target_account')
]
);
// run search
var accountRebookingSearchResults = accountRebookingSearch
.runSearch()
.getResults(0, 2);
accountRebookingSearchResults = JSON.parse(
JSON.stringify(accountRebookingSearchResults)
);
nlapiLogExecution("debug", "accountRebookingSearchResults", JSON.stringify({ "accountRebookingSearchResults": accountRebookingSearchResults }));
if (accountRebookingSearchResults.length === 0) {
return -1; // no mapping found
}
if (accountRebookingSearchResults.length > 1) {
throw "more than one mapping found";
}
var accountRebookingSearchResult = accountRebookingSearchResults[0];
return parseInt(accountRebookingSearchResult.columns.custrecord_pg_target_account.internalid);
}
Apparently, the standardlines contains datalines with credit amoung && debit amount == 0. Why that is, I don't know - maybe someone knows and leaves a comment about that. So all I needed was a check for both values.

this doesn't work for me SESSION_STORAGE:

I am trying to create a new session to have the session in a database, Postgres. I am trying to use this code, but nothing works, and it is frustrating.
I'm almost sure that I need to send a second argument, but I don't know what it will be!.
my code:
Shopify.Context.initialize({
API_KEY: process.env.SHOPIFY_API_KEY,
API_SECRET_KEY: process.env.SHOPIFY_API_SECRET,
SCOPES: process.env.SCOPES.split(","),
HOST_NAME: process.env.HOST.replace(/https:\/\//, ""),
API_VERSION: ApiVersion.April22,
IS_EMBEDDED_APP: true,
// This should be replaced with your preferred storage strategy
SESSION_STORAGE: new Shopify.Session.PostgreSQLSessionStorage(
new URL(process.env.DATABASE_URL)
),
});
error:
┃ file:///Users/blablabla/Documents/Apps/cli_shopify_mayo2022/cli-19may/server/middleware/verify-request.js:25
┃ if (session?.isActive()) {
┃ ^
┃
┃ TypeError: session?.isActive is not a function
┃ at file:///Users/diegotorres/Documents/Apps/cli_shopify_mayo2022/cli-19may/server/middleware/verify-request.js:25:18
┃ at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
┃
┃ Node.js v18.0.0
┃ [nodemon] app crashed - waiting for file changes before starting...
postgres file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PostgreSQLSessionStorage = void 0;
var tslib_1 = require("tslib");
var pg_1 = tslib_1.__importDefault(require("pg"));
var session_utils_1 = require("../session-utils");
var defaultPostgreSQLSessionStorageOptions = {
sessionTableName: 'shopify_sessions',
port: 3211,
};
var PostgreSQLSessionStorage = /** #class */ (function () {
function PostgreSQLSessionStorage(dbUrl, opts) {
if (opts === void 0) { opts = {}; }
this.dbUrl = dbUrl;
if (typeof this.dbUrl === 'string') {
this.dbUrl = new URL(this.dbUrl);
}
this.options = tslib_1.__assign(tslib_1.__assign({}, defaultPostgreSQLSessionStorageOptions), opts);
this.ready = this.init();
}
PostgreSQLSessionStorage.withCredentials = function (host, dbName, username, password, opts) {
return new PostgreSQLSessionStorage(new URL("postgres://".concat(encodeURIComponent(username), ":").concat(encodeURIComponent(password), "#").concat(host, "/").concat(encodeURIComponent(dbName))), opts);
};
PostgreSQLSessionStorage.prototype.storeSession = function (session) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var entries, query;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.ready];
case 1:
_a.sent();
entries = (0, session_utils_1.sessionEntries)(session);
query = "\n INSERT INTO ".concat(this.options.sessionTableName, "\n (").concat(entries.map(function (_a) {
var _b = tslib_1.__read(_a, 1), key = _b[0];
return key;
}).join(', '), ")\n VALUES (").concat(entries.map(function (_, i) { return "$".concat(i + 1); }).join(', '), ")\n ON CONFLICT (id) DO UPDATE SET ").concat(entries
.map(function (_a) {
var _b = tslib_1.__read(_a, 1), key = _b[0];
return "".concat(key, " = Excluded.").concat(key);
})
.join(', '), ";\n ");
return [4 /*yield*/, this.query(query, entries.map(function (_a) {
var _b = tslib_1.__read(_a, 2), _key = _b[0], value = _b[1];
return value;
}))];
case 2:
_a.sent();
return [2 /*return*/, true];
}
});
});
};
PostgreSQLSessionStorage.prototype.loadSession = function (id) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var query, rows, rawResult;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.ready];
case 1:
_a.sent();
query = "\n SELECT * FROM ".concat(this.options.sessionTableName, "\n WHERE id = $1;\n ");
return [4 /*yield*/, this.query(query, [id])];
case 2:
rows = _a.sent();
if (!Array.isArray(rows) || (rows === null || rows === void 0 ? void 0 : rows.length) !== 1)
return [2 /*return*/, undefined];
rawResult = rows[0];
return [2 /*return*/, (0, session_utils_1.sessionFromEntries)(Object.entries(rawResult))];
}
});
});
};
PostgreSQLSessionStorage.prototype.deleteSession = function (id) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var query;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.ready];
case 1:
_a.sent();
query = "\n DELETE FROM ".concat(this.options.sessionTableName, "\n WHERE id = $1;\n ");
return [4 /*yield*/, this.query(query, [id])];
case 2:
_a.sent();
return [2 /*return*/, true];
}
});
});
};
PostgreSQLSessionStorage.prototype.disconnect = function () {
return this.client.end();
};
PostgreSQLSessionStorage.prototype.init = function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
this.client = new pg_1.default.Client({ connectionString: this.dbUrl.toString() });
return [4 /*yield*/, this.connectClient()];
case 1:
_a.sent();
return [4 /*yield*/, this.createTable()];
case 2:
_a.sent();
return [2 /*return*/];
}
});
});
};
PostgreSQLSessionStorage.prototype.connectClient = function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.client.connect()];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
PostgreSQLSessionStorage.prototype.hasSessionTable = function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var query, _a, rows;
return tslib_1.__generator(this, function (_b) {
switch (_b.label) {
case 0:
query = "\n SELECT * FROM pg_catalog.pg_tables WHERE tablename = $1\n ";
return [4 /*yield*/, this.query(query, [this.options.sessionTableName])];
case 1:
_a = tslib_1.__read.apply(void 0, [_b.sent(), 1]), rows = _a[0];
return [2 /*return*/, Array.isArray(rows) && rows.length === 1];
}
});
});
};
PostgreSQLSessionStorage.prototype.createTable = function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var hasSessionTable, query;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.hasSessionTable()];
case 1:
hasSessionTable = _a.sent();
if (!!hasSessionTable) return [3 /*break*/, 3];
query = "\n CREATE TABLE ".concat(this.options.sessionTableName, " (\n id varchar(255) NOT NULL PRIMARY KEY,\n shop varchar(255) NOT NULL,\n state varchar(255) NOT NULL,\n isOnline boolean NOT NULL,\n scope varchar(255),\n accessToken varchar(255)\n )\n ");
return [4 /*yield*/, this.query(query)];
case 2:
_a.sent();
_a.label = 3;
case 3: return [2 /*return*/];
}
});
});
};
PostgreSQLSessionStorage.prototype.query = function (sql, params) {
if (params === void 0) { params = []; }
return tslib_1.__awaiter(this, void 0, void 0, function () {
var result;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.client.query(sql, params)];
case 1:
result = _a.sent();
return [2 /*return*/, result.rows];
}
});
});
};
return PostgreSQLSessionStorage;
}());
exports.PostgreSQLSessionStorage = PostgreSQLSessionStorage;
so, investigating a bit I found the following file which is where the app breaks
import { Shopify } from "#shopify/shopify-api";
const TEST_GRAPHQL_QUERY = `
{
shop {
name
}
}`;
export default function verifyRequest(app, { returnHeader = true } = {}) {
return async (req, res, next) => {
const session = await Shopify.Utils.loadCurrentSession(
req,
res,
app.get("use-online-tokens")
);
let shop = req.query.shop;
if (session && shop && session.shop !== shop) {
// The current request is for a different shop. Redirect gracefully.
return res.redirect(`/auth?shop=${shop}`);
}
if (session?.isActive()) {
try {
// make a request to make sure oauth has succeeded, retry otherwise
const client = new Shopify.Clients.Graphql(
session.shop,
session.accessToken
);
await client.query({ data: TEST_GRAPHQL_QUERY });
return next();
} catch (e) {
if (
e instanceof Shopify.Errors.HttpResponseError &&
e.response.code === 401
) {
// We only want to catch 401s here, anything else should bubble up
} else {
throw e;
}
}
}
if (returnHeader) {
if (!shop) {
if (session) {
shop = session.shop;
} else if (Shopify.Context.IS_EMBEDDED_APP) {
const authHeader = req.headers.authorization;
const matches = authHeader?.match(/Bearer (.*)/);
if (matches) {
const payload = Shopify.Utils.decodeSessionToken(matches[1]);
shop = payload.dest.replace("https://", "");
}
}
}
if (!shop || shop === "") {
return res
.status(400)
.send(
`Could not find a shop to authenticate with. Make sure you are making your XHR request with App Bridge's authenticatedFetch method.`
);
}
res.status(403);
res.header("X-Shopify-API-Request-Failure-Reauthorize", "1");
res.header(
"X-Shopify-API-Request-Failure-Reauthorize-Url",
`/auth?shop=${shop}`
);
res.end();
} else {
res.redirect(`/auth?shop=${shop}`);
}
};
}
You should use cloneSession from Session
Here is full code from my working project and custom implimentation of postgresql session
// tslint:disable-next-line:no-submodule-imports
import { Session } from '#shopify/shopify-api/dist/auth/session/index.js';
import pg from 'pg';
// tslint:disable-next-line:interface-name
interface SessionInterface {
readonly id: string;
shop: string;
state: string;
isOnline: boolean;
scope?: string;
expires?: Date;
accessToken?: string;
onlineAccessInfo?: any;
isActive(): boolean;
}
// tslint:disable-next-line:interface-name
interface SessionStorage {
/**
* Creates or updates the given session in storage.
*
* #param session Session to store
*/
storeSession(session: SessionInterface): Promise<boolean>;
/**
* Loads a session from storage.
*
* #param id Id of the session to load
*/
loadSession(id: string): Promise<SessionInterface | undefined>;
/**
* Deletes a session from storage.
*
* #param id Id of the session to delete
*/
deleteSession(id: string): Promise<boolean>;
}
function fromEntries<T>(entries: Array<[keyof T, T[keyof T]]>): T {
return entries.reduce(
(acc, [key, value]) => ({ ...acc, [key]: value }),
<T>{}
);
}
function sessionFromEntries(
entries: Array<[string, string | number]>,
): SessionInterface {
const obj = fromEntries(
entries
// tslint:disable-next-line:variable-name
.filter(([_key, value]) => value !== null)
.map(([key, value]) => {
switch (key.toLowerCase()) {
case 'isonline':
return ['isOnline', value];
case 'accesstoken':
return ['accessToken', value];
default:
return [key.toLowerCase(), value];
}
}),
) as any;
if (typeof obj.isOnline === 'string') {
obj.isOnline = obj.isOnline.toString().toLowerCase() === 'true';
} else if (typeof obj.isOnline === 'number') {
obj.isOnline = Boolean(obj.isOnline);
}
if (obj.scope) { obj.scope = obj.scope.toString(); }
return obj;
}
const includedKeys = [
'id',
'shop',
'state',
'isOnline',
'scope',
'accessToken',
];
function sessionEntries(
session: SessionInterface,
): Array<[string, string | number]> {
return Object.entries(session).filter(([key]) => includedKeys.includes(key));
}
// tslint:disable-next-line:interface-name
interface PostgreSQLSessionStorageOptions {
sessionTableName: string;
port: number;
}
const defaultPostgreSQLSessionStorageOptions: PostgreSQLSessionStorageOptions =
{
sessionTableName: 'shopify_sessions',
port: 3211,
};
export class PostgreSQLSessionStorage implements SessionStorage {
public static withCredentials(
host: string,
dbName: string,
username: string,
password: string,
opts: Partial<PostgreSQLSessionStorageOptions>,
) {
return new PostgreSQLSessionStorage(
new URL(
`postgres://${encodeURIComponent(username)}:${encodeURIComponent(
password,
)}#${host}/${encodeURIComponent(dbName)}`,
),
opts,
);
}
public readonly ready: Promise<void>;
private options: PostgreSQLSessionStorageOptions;
private client: pg.Client;
constructor(
private dbUrl: URL,
opts: Partial<PostgreSQLSessionStorageOptions> = {},
) {
if (typeof this.dbUrl === 'string') {
this.dbUrl = new URL(this.dbUrl);
}
this.options = {...defaultPostgreSQLSessionStorageOptions, ...opts};
this.ready = this.init();
}
public async storeSession(session: SessionInterface): Promise<boolean> {
await this.ready;
const entries = sessionEntries(session);
const query = `
INSERT INTO ${this.options.sessionTableName}
(${entries.map(([key]) => key).join(', ')})
VALUES (${entries.map((_, i) => `$${i + 1}`).join(', ')})
ON CONFLICT (id) DO UPDATE SET ${entries
.map(([key]) => `${key} = Excluded.${key}`)
.join(', ')};
`;
await this.query(
query,
// tslint:disable-next-line:variable-name
entries.map(([_key, value]) => value),
);
return true;
}
public async loadSession(id: string): Promise<Session | undefined> {
await this.ready;
const query = `
SELECT * FROM ${this.options.sessionTableName}
WHERE id = $1;
`;
const rows = await this.query(query, [id]);
if (!Array.isArray(rows) || rows?.length !== 1) { return undefined; }
const rawResult = rows[0] as any;
const sessionData = sessionFromEntries(Object.entries(rawResult));
return Session.cloneSession(sessionData, sessionData.id);
}
public async deleteSession(id: string): Promise<boolean> {
await this.ready;
const query = `
DELETE FROM ${this.options.sessionTableName}
WHERE id = $1;
`;
await this.query(query, [id]);
return true;
}
public disconnect(): Promise<void> {
return this.client.end();
}
private async init() {
this.client = new pg.Client({connectionString: this.dbUrl.toString(), ssl: true});
await this.connectClient();
await this.createTable();
}
private async connectClient(): Promise<void> {
await this.client.connect();
}
private async hasSessionTable(): Promise<boolean> {
const query = `
SELECT * FROM pg_catalog.pg_tables WHERE tablename = $1
`;
const [rows] = await this.query(query, [this.options.sessionTableName]);
return Array.isArray(rows) && rows.length === 1;
}
private async createTable() {
const hasSessionTable = await this.hasSessionTable();
if (!hasSessionTable) {
const query = `
CREATE TABLE IF NOT EXISTS ${this.options.sessionTableName} (
id varchar(255) NOT NULL PRIMARY KEY,
shop varchar(255) NOT NULL,
state varchar(255) NOT NULL,
isOnline boolean NOT NULL,
scope varchar(255),
accessToken varchar(255)
)
`;
await this.query(query);
}
}
private async query(sql: string, params: any[] = []): Promise<any> {
const result = await this.client.query(sql, params);
return result.rows;
}
}

Protractor - How to resolve the promise to get number output

I have the following method in my helper class. I need the method to return the rowNum of Number type. But I always get a Promise when i call the method. I want to see the number when I call the method.
getRowNum(table, colNum, searchText) {
let rowNum = -1;
return table.all(by.css("tbody tr td:nth-child(" + colNum + ")")).map(function (element) {
return element.getText();
}).then(function (textArray) {
for (var i in textArray) {
if (textArray[i].trim().indexOf(searchText) != -1) {
console.log(i);
console.log(textArray[i]);
rowNum = i + 1;
}
}
return rowNum;
});
});
//I'm using it in my other js file like this
let rowNum = helper.getRowNum($("div.sponsor-table table"), 2, "some text");
Have you tried this?
getRowNum = (table, colNum, searchText) => {
let rowNum = -1;
let text;
table.all(by.css("tbody tr td:nth-child(" + colNum + ")")).map(function (element) {
return text = element.getText();
})
.then(function () {
for (var i in text) {
if (text[i].trim().indexOf(searchText) != -1) {
console.log(i);
console.log(text[i]);
rowNum = i + 1;
break;
}
}
return rowNum;
});
};
Let me know if it works

what's the problem when integrating roxyfileman with tinymce in ABP

I want to use tinyMCE in ABP CoreMVC project,so I read the [http://www.iaspnetcore.com/Blog/BlogPost/5bd70fb5b169590f280f64dd/integrating-roxy-fileman-with-tinymce-in-aspnet-core], and add RoxyFilemanController.cs
in a normal netcore mvc project,and copy the tinymce and fileman directory to the www/lib directory,it works fine.but when I copy the same code to my ABP CoreMVC project,It not work. the controller code is:
[Produces("application/json")]
public class RoxyFilemanController : Controller
{
private string _systemRootPath;
private string _tempPath;
private string _filesRootPath;
private string _filesRootVirtual;
private Dictionary<string, string> _settings;
private Dictionary<string, string> _lang = null;
public RoxyFilemanController(IHostingEnvironment env)
{
// Setup CMS paths to suit your environment (we usually inject settings for these)
_systemRootPath = env.ContentRootPath;
_tempPath = _systemRootPath + "\\wwwroot\\CMS\\Temp";
_filesRootPath = "/wwwroot/CMS/Content";
_filesRootVirtual = "/CMS/Content";
// Load Fileman settings
LoadSettings();
}
private void LoadSettings()
{
_settings = JsonConvert.DeserializeObject<Dictionary<string, string>>(System.IO.File.ReadAllText(_systemRootPath + "/wwwroot/lib/fileman/conf.json"));
string langFile = _systemRootPath + "/wwwroot/lib/fileman/lang/" + GetSetting("LANG") + ".json";
if (!System.IO.File.Exists(langFile)) langFile = _systemRootPath + "/wwwroot/lib/fileman/lang/en.json";
_lang = JsonConvert.DeserializeObject<Dictionary<string, string>>(System.IO.File.ReadAllText(langFile));
}
// GET api/RoxyFileman - test entry point//]
[AllowAnonymous, Produces("text/plain"), ActionName("")]
public string Get() { return "RoxyFileman - access to API requires Authorisation"; }
#region API Actions
[HttpGet]
public IActionResult DIRLIST(string type)
{
try
{
DirectoryInfo d = new DirectoryInfo(GetFilesRoot());
if (!d.Exists) throw new Exception("Invalid files root directory. Check your configuration.");
ArrayList dirs = ListDirs(d.FullName);
dirs.Insert(0, d.FullName);
string localPath = _systemRootPath;
string result = "";
for (int i = 0; i < dirs.Count; i++)
{
string dir = (string)dirs[i];
result += (result != "" ? "," : "") + "{\"p\":\"" + MakeVirtualPath(dir.Replace(localPath, "").Replace("\\", "/")) + "\",\"f\":\"" + GetFiles(dir, type).Count.ToString() + "\",\"d\":\"" + Directory.GetDirectories(dir).Length.ToString() + "\"}";
}
return Content("[" + result + "]", "application/json");
}
catch (Exception ex) { return Content(GetErrorRes(ex.Message)); }
}
public IActionResult FILESLIST(string d, string type)
{
try
{
d = MakePhysicalPath(d);
CheckPath(d);
string fullPath = FixPath(d);
List<string> files = GetFiles(fullPath, type);
string result = "";
for (int i = 0; i < files.Count; i++)
{
FileInfo f = new FileInfo(files[i]);
int w = 0, h = 0;
// NO SUPPORT IN ASP.NET CORE! Per haps see https://github.com/CoreCompat/CoreCompat
//if (GetFileType(f.Extension) == "image")
//{
// try
// {
// //FileStream fs = new FileStream(f.FullName, FileMode.Open, FileAccess.Read);
// //Image img = Image.FromStream(fs);
// //w = img.Width;
// //h = img.Height;
// //fs.Close();
// //fs.Dispose();
// //img.Dispose();
// }
// catch (Exception ex) { throw ex; }
//}
result += (result != "" ? "," : "") +
"{" +
"\"p\":\"" + MakeVirtualPath(d) + "/" + f.Name + "\"" +
",\"t\":\"" + Math.Ceiling(LinuxTimestamp(f.LastWriteTime)).ToString() + "\"" +
",\"s\":\"" + f.Length.ToString() + "\"" +
",\"w\":\"" + w.ToString() + "\"" +
",\"h\":\"" + h.ToString() + "\"" +
"}";
}
return Content("[" + result + "]");
}
catch (Exception ex) { return Content(GetErrorRes(ex.Message)); }
}
public IActionResult COPYDIR(string d, string n)
{
try
{
d = MakePhysicalPath(d);
n = MakePhysicalPath(n);
CheckPath(d);
CheckPath(n);
DirectoryInfo dir = new DirectoryInfo(FixPath(d));
DirectoryInfo newDir = new DirectoryInfo(FixPath(n + "/" + dir.Name));
if (!dir.Exists) throw new Exception(LangRes("E_CopyDirInvalidPath"));
else if (newDir.Exists) throw new Exception(LangRes("E_DirAlreadyExists"));
else CopyDir(dir.FullName, newDir.FullName);
return Content(GetSuccessRes());
}
catch (Exception ex) { return Content(GetErrorRes(ex.Message)); }
}
public IActionResult COPYFILE(string f, string n)
{
try
{
f = MakePhysicalPath(f);
CheckPath(f);
FileInfo file = new FileInfo(FixPath(f));
n = FixPath(n);
if (!file.Exists) throw new Exception(LangRes("E_CopyFileInvalisPath"));
else
{
try
{
System.IO.File.Copy(file.FullName, Path.Combine(n, MakeUniqueFilename(n, file.Name)));
return Content(GetSuccessRes());
}
catch (Exception) { throw new Exception(LangRes("E_CopyFile")); }
}
}
catch (Exception ex) { return Content(GetErrorRes(ex.Message)); }
}
public IActionResult CREATEDIR(string d, string n)
{
try
{
d = MakePhysicalPath(d);
CheckPath(d);
d = FixPath(d);
if (!Directory.Exists(d)) throw new Exception(LangRes("E_CreateDirInvalidPath"));
else
{
try
{
d = Path.Combine(d, n);
if (!Directory.Exists(d)) Directory.CreateDirectory(d);
return Content(GetSuccessRes());
}
catch (Exception) { throw new Exception(LangRes("E_CreateDirFailed")); }
}
}
catch (Exception ex) { return Content(GetErrorRes(ex.Message)); }
}
public IActionResult DELETEDIR(string d)
{
try
{
d = MakePhysicalPath(d);
CheckPath(d);
d = FixPath(d);
if (!Directory.Exists(d)) throw new Exception(LangRes("E_DeleteDirInvalidPath"));
else if (d == GetFilesRoot()) throw new Exception(LangRes("E_CannotDeleteRoot"));
else if (Directory.GetDirectories(d).Length > 0 || Directory.GetFiles(d).Length > 0) throw new Exception(LangRes("E_DeleteNonEmpty"));
else
{
try
{
Directory.Delete(d);
return Content(GetSuccessRes());
}
catch (Exception) { throw new Exception(LangRes("E_CannotDeleteDir")); }
}
}
catch (Exception ex) { return Content(GetErrorRes(ex.Message)); }
}
public IActionResult DELETEFILE(string f)
{
try
{
f = MakePhysicalPath(f);
CheckPath(f);
f = FixPath(f);
if (!System.IO.File.Exists(f)) throw new Exception(LangRes("E_DeleteFileInvalidPath"));
else
{
try
{
System.IO.File.Delete(f);
return Content(GetSuccessRes());
}
catch (Exception) { throw new Exception(LangRes("E_DeletеFile")); }
}
}
catch (Exception ex) { return Content(GetErrorRes(ex.Message)); }
}
public ActionResult DOWNLOAD(string f)
{
try
{
f = MakePhysicalPath(f);
CheckPath(f);
FileInfo file = new FileInfo(FixPath(f));
if (file.Exists)
{
string contentType;
new FileExtensionContentTypeProvider().TryGetContentType(file.FullName, out contentType);
return PhysicalFile(file.FullName, contentType ?? "application/octet-stream", file.Name);
}
else return NotFound();
}
catch (Exception ex) { return Json(GetErrorRes(ex.Message)); }
}
public ActionResult DOWNLOADDIR(string d)
{
try
{
d = MakePhysicalPath(d);
d = FixPath(d);
if (!Directory.Exists(d)) throw new Exception(LangRes("E_CreateArchive"));
string dirName = new FileInfo(d).Name;
string tmpZip = _tempPath + "/" + dirName + ".zip";
if (System.IO.File.Exists(tmpZip)) System.IO.File.Delete(tmpZip);
ZipFile.CreateFromDirectory(d, tmpZip, CompressionLevel.Fastest, true);
return PhysicalFile(tmpZip, "application/zip", dirName + ".zip");
}
catch (Exception ex) { return Json(GetErrorRes(ex.Message)); }
}
public IActionResult MOVEDIR(string d, string n)
{
try
{
d = MakePhysicalPath(d);
n = MakePhysicalPath(n);
CheckPath(d);
CheckPath(n);
DirectoryInfo source = new DirectoryInfo(FixPath(d));
DirectoryInfo dest = new DirectoryInfo(FixPath(Path.Combine(n, source.Name)));
if (dest.FullName.IndexOf(source.FullName) == 0) throw new Exception(LangRes("E_CannotMoveDirToChild"));
else if (!source.Exists) throw new Exception(LangRes("E_MoveDirInvalisPath"));
else if (dest.Exists) throw new Exception(LangRes("E_DirAlreadyExists"));
else
{
try
{
source.MoveTo(dest.FullName);
return Content(GetSuccessRes());
}
catch (Exception) { throw new Exception(LangRes("E_MoveDir") + " \"" + d + "\""); }
}
}
catch (Exception ex) { return Content(GetErrorRes(ex.Message)); }
}
public IActionResult MOVEFILE(string f, string n)
{
try
{
f = MakePhysicalPath(f);
n = MakePhysicalPath(n);
CheckPath(f);
CheckPath(n);
FileInfo source = new FileInfo(FixPath(f));
FileInfo dest = new FileInfo(FixPath(n));
if (!source.Exists) throw new Exception(LangRes("E_MoveFileInvalisPath"));
else if (dest.Exists) throw new Exception(LangRes("E_MoveFileAlreadyExists"));
else if (!CanHandleFile(dest.Name)) throw new Exception(LangRes("E_FileExtensionForbidden"));
else
{
try
{
source.MoveTo(dest.FullName);
return Content(GetSuccessRes());
}
catch (Exception) { throw new Exception(LangRes("E_MoveFile") + " \"" + f + "\""); }
}
}
catch (Exception ex) { return Content(GetErrorRes(ex.Message)); }
}
public IActionResult RENAMEDIR(string d, string n)
{
try
{
d = MakePhysicalPath(d);
CheckPath(d);
DirectoryInfo source = new DirectoryInfo(FixPath(d));
DirectoryInfo dest = new DirectoryInfo(Path.Combine(source.Parent.FullName, n));
if (source.FullName == GetFilesRoot()) throw new Exception(LangRes("E_CannotRenameRoot"));
else if (!source.Exists) throw new Exception(LangRes("E_RenameDirInvalidPath"));
else if (dest.Exists) throw new Exception(LangRes("E_DirAlreadyExists"));
else
{
try
{
source.MoveTo(dest.FullName);
return Content(GetSuccessRes());
}
catch (Exception) { throw new Exception(LangRes("E_RenameDir") + " \"" + d + "\""); }
}
}
catch (Exception ex) { return Content(GetErrorRes(ex.Message)); }
}
public IActionResult RENAMEFILE(string f, string n)
{
try
{
f = MakePhysicalPath(f);
CheckPath(f);
FileInfo source = new FileInfo(FixPath(f));
FileInfo dest = new FileInfo(Path.Combine(source.Directory.FullName, n));
if (!source.Exists) throw new Exception(LangRes("E_RenameFileInvalidPath"));
else if (!CanHandleFile(n)) throw new Exception(LangRes("E_FileExtensionForbidden"));
else
{
try
{
source.MoveTo(dest.FullName);
return Content(GetSuccessRes());
}
catch (Exception ex) { throw new Exception(ex.Message + "; " + LangRes("E_RenameFile") + " \"" + f + "\""); }
}
}
catch (Exception ex) { return Content(GetErrorRes(ex.Message)); }
}
[HttpPost, Produces("text/plain")]
public string UPLOAD(string d)
{
try
{
d = MakePhysicalPath(d);
CheckPath(d);
d = FixPath(d);
string res = GetSuccessRes();
bool hasErrors = false;
try
{
foreach (var file in HttpContext.Request.Form.Files)
{
if (CanHandleFile(file.FileName))
{
FileInfo f = new FileInfo(file.FileName);
string filename = MakeUniqueFilename(d, f.Name);
string dest = Path.Combine(d, filename);
using (var saveFile = new FileStream(dest, FileMode.Create)) file.CopyTo(saveFile);
//if (GetFileType(new FileInfo(filename).Extension) == "image")
//{
// int w = 0;
// int h = 0;
// int.TryParse(GetSetting("MAX_IMAGE_WIDTH"), out w);
// int.TryParse(GetSetting("MAX_IMAGE_HEIGHT"), out h);
// ImageResize(dest, dest, w, h);
//}
}
else
{
hasErrors = true;
res = GetSuccessRes(LangRes("E_UploadNotAll"));
}
}
}
catch (Exception ex) { res = GetErrorRes(ex.Message); }
if (IsAjaxUpload())
{
if (hasErrors) res = GetErrorRes(LangRes("E_UploadNotAll"));
return res;
}
else return "<script>parent.fileUploaded(" + res + ");</script>";
}
catch (Exception ex)
{
if (!IsAjaxUpload()) return "<script>parent.fileUploaded(" + GetErrorRes(LangRes("E_UploadNoFiles")) + ");</script>";
else return GetErrorRes(ex.Message);
}
}
/*
public string GENERATETHUMB(string type)
{
try
{
//int w = 140, h = 0;
//int.TryParse(_context.Request["width"].Replace("px", ""), out w);
//int.TryParse(_context.Request["height"].Replace("px", ""), out h);
//ShowThumbnail(_context.Request["f"], w, h);
}
catch (Exception ex) { return GetErrorRes(ex.Message); }
}
*/
#endregion
#region Utilities
private string MakeVirtualPath(string path)
{
return !path.StartsWith(_filesRootPath) ? path : _filesRootVirtual + path.Substring(_filesRootPath.Length);
}
private string MakePhysicalPath(string path)
{
return !path.StartsWith(_filesRootVirtual) ? path : _filesRootPath + path.Substring(_filesRootVirtual.Length);
}
private string GetFilesRoot()
{
string ret = _filesRootPath;
if (GetSetting("SESSION_PATH_KEY") != "" && HttpContext.Session.GetString(GetSetting("SESSION_PATH_KEY")) != null) ret = HttpContext.Session.GetString(GetSetting("SESSION_PATH_KEY"));
ret = FixPath(ret);
return ret;
}
private ArrayList ListDirs(string path)
{
string[] dirs = Directory.GetDirectories(path);
ArrayList ret = new ArrayList();
foreach (string dir in dirs)
{
ret.Add(dir);
ret.AddRange(ListDirs(dir));
}
return ret;
}
private List<string> GetFiles(string path, string type)
{
List<string> ret = new List<string>();
if (type == "#" || type == null) type = "";
string[] files = Directory.GetFiles(path);
foreach (string f in files) { if ((GetFileType(new FileInfo(f).Extension) == type) || (type == "")) ret.Add(f); }
return ret;
}
private string GetFileType(string ext)
{
string ret = "file";
ext = ext.ToLower();
if (ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".gif") ret = "image";
else if (ext == ".swf" || ext == ".flv") ret = "flash";
return ret;
}
private void CheckPath(string path)
{
if (FixPath(path).IndexOf(GetFilesRoot()) != 0) throw new Exception("Access to " + path + " is denied");
}
private string FixPath(string path)
{
path = path.TrimStart('~');
if (!path.StartsWith("/")) path = "/" + path;
return _systemRootPath + path;
}
private double LinuxTimestamp(DateTime d)
{
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0).ToLocalTime();
TimeSpan timeSpan = (d.ToLocalTime() - epoch);
return timeSpan.TotalSeconds;
}
private string GetSetting(string name)
{
string ret = "";
if (_settings.ContainsKey(name)) ret = _settings[name];
return ret;
}
private string GetErrorRes(string msg) { return GetResultStr("error", msg); }
private string GetResultStr(string type, string msg)
{
return "{\"res\":\"" + type + "\",\"msg\":\"" + msg.Replace("\"", "\\\"") + "\"}";
}
private string LangRes(string name) { return _lang.ContainsKey(name) ? _lang[name] : name; }
private string GetSuccessRes(string msg) { return GetResultStr("ok", msg); }
private string GetSuccessRes() { return GetSuccessRes(""); }
private void CopyDir(string path, string dest)
{
if (!Directory.Exists(dest)) Directory.CreateDirectory(dest);
foreach (string f in Directory.GetFiles(path))
{
FileInfo file = new FileInfo(f);
if (!System.IO.File.Exists(Path.Combine(dest, file.Name))) System.IO.File.Copy(f, Path.Combine(dest, file.Name));
}
foreach (string d in Directory.GetDirectories(path)) CopyDir(d, Path.Combine(dest, new DirectoryInfo(d).Name));
}
private string MakeUniqueFilename(string dir, string filename)
{
string ret = filename;
int i = 0;
while (System.IO.File.Exists(Path.Combine(dir, ret)))
{
i++;
ret = Path.GetFileNameWithoutExtension(filename) + " - Copy " + i.ToString() + Path.GetExtension(filename);
}
return ret;
}
private bool CanHandleFile(string filename)
{
bool ret = false;
FileInfo file = new FileInfo(filename);
string ext = file.Extension.Replace(".", "").ToLower();
string setting = GetSetting("FORBIDDEN_UPLOADS").Trim().ToLower();
if (setting != "")
{
ArrayList tmp = new ArrayList();
tmp.AddRange(Regex.Split(setting, "\\s+"));
if (!tmp.Contains(ext)) ret = true;
}
setting = GetSetting("ALLOWED_UPLOADS").Trim().ToLower();
if (setting != "")
{
ArrayList tmp = new ArrayList();
tmp.AddRange(Regex.Split(setting, "\\s+"));
if (!tmp.Contains(ext)) ret = false;
}
return ret;
}
private bool IsAjaxUpload()
{
return (!string.IsNullOrEmpty(HttpContext.Request.Query["method"]) && HttpContext.Request.Query["method"].ToString() == "ajax");
}
#endregion
/*
public bool ThumbnailCallback()
{
return false;
}
protected void ShowThumbnail(string path, int width, int height)
{
CheckPath(path);
FileStream fs = new FileStream(FixPath(path), FileMode.Open, FileAccess.Read);
Bitmap img = new Bitmap(Bitmap.FromStream(fs));
fs.Close();
fs.Dispose();
int cropWidth = img.Width, cropHeight = img.Height;
int cropX = 0, cropY = 0;
double imgRatio = (double)img.Width / (double)img.Height;
if(height == 0)
height = Convert.ToInt32(Math.Floor((double)width / imgRatio));
if (width > img.Width)
width = img.Width;
if (height > img.Height)
height = img.Height;
double cropRatio = (double)width / (double)height;
cropWidth = Convert.ToInt32(Math.Floor((double)img.Height * cropRatio));
cropHeight = Convert.ToInt32(Math.Floor((double)cropWidth / cropRatio));
if (cropWidth > img.Width)
{
cropWidth = img.Width;
cropHeight = Convert.ToInt32(Math.Floor((double)cropWidth / cropRatio));
}
if (cropHeight > img.Height)
{
cropHeight = img.Height;
cropWidth = Convert.ToInt32(Math.Floor((double)cropHeight * cropRatio));
}
if(cropWidth < img.Width){
cropX = Convert.ToInt32(Math.Floor((double)(img.Width - cropWidth) / 2));
}
if(cropHeight < img.Height){
cropY = Convert.ToInt32(Math.Floor((double)(img.Height - cropHeight) / 2));
}
Rectangle area = new Rectangle(cropX, cropY, cropWidth, cropHeight);
Bitmap cropImg = img.Clone(area, System.Drawing.Imaging.PixelFormat.DontCare);
img.Dispose();
Image.GetThumbnailImageAbort imgCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
_r.AddHeader("Content-Type", "image/png");
cropImg.GetThumbnailImage(width, height, imgCallback, IntPtr.Zero).Save(_r.OutputStream, ImageFormat.Png);
_r.OutputStream.Close();
cropImg.Dispose();
}
private ImageFormat GetImageFormat(string filename){
ImageFormat ret = ImageFormat.Jpeg;
switch(new FileInfo(filename).Extension.ToLower()){
case ".png": ret = ImageFormat.Png; break;
case ".gif": ret = ImageFormat.Gif; break;
}
return ret;
}
protected void ImageResize(string path, string dest, int width, int height)
{
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
Image img = Image.FromStream(fs);
fs.Close();
fs.Dispose();
float ratio = (float)img.Width / (float)img.Height;
if ((img.Width <= width && img.Height <= height) || (width == 0 && height == 0))
return;
int newWidth = width;
int newHeight = Convert.ToInt16(Math.Floor((float)newWidth / ratio));
if ((height > 0 && newHeight > height) || (width == 0))
{
newHeight = height;
newWidth = Convert.ToInt16(Math.Floor((float)newHeight * ratio));
}
Bitmap newImg = new Bitmap(newWidth, newHeight);
Graphics g = Graphics.FromImage((Image)newImg);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(img, 0, 0, newWidth, newHeight);
img.Dispose();
g.Dispose();
if(dest != ""){
newImg.Save(dest, GetImageFormat(dest));
}
newImg.Dispose();
}
public bool IsReusable {
get {
return false;
}
}
*/
}
In ABP CoreMVC,I change the About/index.html as follow:
#using testRoxyMan.Web.Startup
<script src="~/lib/tinymce/tinymce.min.js"></script>
<script type="text/javascript">
function RoxyFileBrowser(field_name, url, type, win) {
var roxyFileman = '/lib/fileman/index.html';
if (roxyFileman.indexOf("?") < 0) {
roxyFileman += "?type=" + type;
}
else {
roxyFileman += "&type=" + type;
}
roxyFileman += '&input=' + field_name + '&value=' + win.document.getElementById(field_name).value;
if (tinyMCE.activeEditor.settings.language) {
roxyFileman += '&langCode=' + tinyMCE.activeEditor.settings.language;
}
tinyMCE.activeEditor.windowManager.open({
file: roxyFileman,
title: 'Roxy Fileman',
width: 850,
height: 650,
resizable: "yes",
plugins: "media",
inline: "yes",
close_previous: "no"
}, { window: win, input: field_name });
return false;
}
tinymce.init({
selector: 'textarea', // change this value according to your HTML
theme: 'modern',
height: 200,
width: '100%',
plugins: [
"advlist autolink autoresize directionality lists link image charmap preview anchor",
"searchreplace visualblocks code fullscreen textcolor",
"insertdatetime media table contextmenu "
],
toolbar: 'ltr rtl | insertfile undo redo | styleselect | fontselect | fontsizeselect | bold italic | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
file_browser_callback: RoxyFileBrowser
});
</script>
<div class="row clearfix">
<textarea></textarea>
</div>
but when I click the addImg btn,It not work,
the wrong msg is:
An unhandled exception occurred while processing the request.
ComponentNotFoundException: No component for supporting the service testRoxyMan.Web.Mvc.Controllers.RoxyFilemanController was found
Castle.MicroKernel.DefaultKernel.Castle.MicroKernel.IKernelInternal.Resolve(Type service, IDictionary arguments, IReleasePolicy policy, bool ignoreParentContext)
so ,what's problem? Thanks a lot
Try to inherit AbpController
public class RoxyFilemanController : AbpController

Add a user to a group programatically

Is it possible to add a user to a group via REST/sdk?
Scenario: We want to add all our users to a mandatory group on a regularly basis.
Thanks!Max
you can get group ids from share point list like this
function GetMandatoryGroups() {
var context;
var factory;
var appContextSite;
var oList;
var collListItem;
context = new SP.ClientContext(appweburl);
factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
context.set_webRequestExecutorFactory(factory);
appContextSite = new SP.AppContextSite(context, hostweburl);
this.web = appContextSite.get_web();
oList = this.web.get_lists().getByTitle('MandatoryGroups');
context.load(oList);
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><RowLimit>100</RowLimit></View>');
collListItem = oList.getItems(camlQuery);
context.load(collListItem, 'Include(Title,Id)');
context.executeQueryAsync(
Function.createDelegate(this, successHandler),
Function.createDelegate(this, errorHandler)
);
function successHandler() {
MandatoryGroups = new Array();
var listItemInfo = '';
var listitemenumerator = collListItem.getEnumerator();
while (listitemenumerator.moveNext()) {
var olistitem = listitemenumerator.get_current();
//listItemInfo += '<li>ID:' + olistitem.get_id().toString() + ' GroupID: ' + olistitem.get_item('Title') + '</li>';
MandatoryGroups.push(olistitem.get_item('Title'));
}
AutoJoinGroups();
// document.getElementById("message").innerHTML = 'Lists found' + oList.get_title() + ':<ul>' + listItemInfo + '</ul>';
}
function errorHandler(sender, args) {
document.getElementById("message").innerText =
"Could not complete cross-domain call: " + args.get_message();
}
}
you can join users to the mendatory groups like this (after user logs in )
function AutoJoinGroups() {
yam.platform.request({
// yam.request({
url: "groups.json?mine=1",
method: "GET",
data: {},
success: function (group) {
//for ($i = 0; $i < MandatoryGroups.length; $i++) {
// if (!ArrayContains(MandatoryGroups[$i].toString(), group)) {
// joinGroupAsync(MandatoryGroups[$i].toString());
// setTimeout('', 10000);
// // setTimeout(joinGroupAsync(MandatoryGroups[$i].toString()),5000);
// }
//}
var i = 0;
function AsyncAutoJoinLoop() {
if (i < MandatoryGroups.length) {
if (!ArrayContains(MandatoryGroups[i].toString(), group)) {
setTimeout(function () {
joinGroupAsync(MandatoryGroups[i].toString());
i++;
if (i < MandatoryGroups.length) {
AsyncAutoJoinLoop();
}
}, 3000)
}
}
}
AsyncAutoJoinLoop();
// getMyGroups();
},
error: function (group) {
console.error("There was an error with the request.");
}
});
}
function joinGroupAsync(id) {
yam.platform.request({
// yam.request({
url: "group_memberships.json?group_id=" + id,
method: "POST",
data: {},
success: function (group) {
},
error: function (group) {
console.error("There was an error with the request.");
}
});
}
you can add group to the sharepoint list like this.
function InsertMandatoryItem() {
var context;
var factory;
var appContextSite;
var oListItem;
context = new SP.ClientContext(appweburl);
factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
context.set_webRequestExecutorFactory(factory);
appContextSite = new SP.AppContextSite(context, hostweburl);
this.web = appContextSite.get_web();
var oList = this.web.get_lists().getByTitle('MandatoryGroups');
var itemCreateInfo = new SP.ListItemCreationInformation();
oListItem = oList.addItem(itemCreateInfo);
oListItem.set_item('Title', InsertGroupId);
oListItem.update();
context.load(oListItem);
context.executeQueryAsync(
Function.createDelegate(this, onQuerySucceeded),
Function.createDelegate(this, onQueryFailed)
);
function onQuerySucceeded() {
//alert('Item created: ' + oListItem.get_id());
// getMyGroups();
// AutoJoinGroups();
$.getScript(scriptbase + 'SP.RequestExecutor.js', GetMandatoryGroups);
}
function onQueryFailed(sender, args) {
$.getScript(scriptbase + 'SP.RequestExecutor.js', GetMandatoryGroups);
alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());
}
}
You can remove remove group from sharepoint list like this
function RemoveMandatoryGroup() {
var context;
var factory;
var appContextSite;
var collListItem;
var itemId;
context = new SP.ClientContext(appweburl);
factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
context.set_webRequestExecutorFactory(factory);
appContextSite = new SP.AppContextSite(context, hostweburl);
this.web = appContextSite.get_web();
var oList = this.web.get_lists().getByTitle('MandatoryGroups');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + RemoveGroupId.toString() + "</Value></Eq></Where></Query></View>");
collListItem = oList.getItems(camlQuery);
context.load(collListItem, 'Include(Title,Id)');
// this.oListItem.deleteObject();
context.executeQueryAsync(
Function.createDelegate(this, onQuerySucceeded),
Function.createDelegate(this, onQueryFailed)
);
function onQuerySucceeded() {
var oListItem;
var listitemenumerator = collListItem.getEnumerator();
while (listitemenumerator.moveNext()) {
var itemtoDelete = listitemenumerator.get_current();
////listItemInfo += '<li>ID:' + olistitem.get_id().toString() + ' GroupID: ' + olistitem.get_item('Title') + '</li>';
//MandatoryGroups.push(olistitem.get_item('Title'));
itemId = itemtoDelete.get_id();
}
oListItem = oList.getItemById(itemId);
oListItem.deleteObject();
context.executeQueryAsync(Function.createDelegate(this, onQueryDeleteSucceeded), Function.createDelegate(this, onQueryDeleteFailed));
//alert('Item created: ' + oListItem.get_id());
function onQueryDeleteSucceeded() {
//alert('Request failed. ' + args.get_message() +
// '\n' + args.get_stackTrace());
getMyGroups();
$.getScript(scriptbase + 'SP.RequestExecutor.js', GetMandatoryGroups);
}
function onQueryDeleteFailed() {
alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());
}
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());
}
}
No, there isn't. This is by design. Yammer likes to entice with the carrot, not by the stick. What we've done is create communications to ask people to join a specific group.
The api does allow the ability for the currently logged to be joined to a specific group. E.g. Put a link on a SharePoint site that says "Join the Yammer group", and have the action join that user to the group. You can see the details for how to do that here:
https://developer.yammer.com/restapi/#rest-groups
ya, in costume app yo can autojoin that user when he logs in..Same thing i ma doing.