Unauthorized exception with SPSecurity.RunWithElevatedPrivileges? - sharepoint

I'm checking, if a given user is part of a group by this code below. I'm getting
unauthorized exception
(0x80070005)
and I do not understand why? I'm using SPSecurity.RunWithElevatedPrivileges, so why it is giving me this exception!? Anybody a hint for me? Thanks in advance!
public bool IsUserInGroup(SPWeb web, string groupName, string user)
{
try
{
bool returnValue = false;
SPSecurity.RunWithElevatedPrivileges(() =>
{
if (web.Groups.OfType<SPGroup>().Where(g => g.Name == groupName).Count() > 0)
{
SPGroup spGroup = web.Groups[groupName];
if (spGroup.Users.OfType<SPUser>().Where(u => u.LoginName.Equals(user)).Count() > 0)
{
returnValue = true;
}
else
{
returnValue = false;
}
}
else
{
returnValue = false;
}
});
return returnValue;
}
catch (Exception exp)
{
Classes.Logs.Error.Log_Error("IsUserInGroup", "DocumentCenterItem.cs", exp.Message, DateTime.Now);
return false;
}
}

You need to create a new instance of SP Web inside elevated privileges. In your current implementation, you are reusing the web object which runs in current user context.
So, try and modify the below code as per your requirement :
public bool IsUserInGroup(SPWeb web, string groupName, string user)
{
try
{
bool returnValue = false;
SPSecurity.RunWithElevatedPrivileges(() =>
{
using(SPSite site = new SPSite(web.Site.ID))
{
using(SPWeb elevatedWeb = site.OpenWeb(web.ID))
{
if (elevatedWeb.Groups.OfType<SPGroup>().Where(g => g.Name == groupName).Count() > 0)
{
SPGroup spGroup = elevatedWeb.Groups[groupName];
if (spGroup.Users.OfType<SPUser>().Where(u => u.LoginName.Equals(user)).Count() > 0)
{
returnValue = true;
}
else
{
returnValue = false;
}
}
else
{
returnValue = false;
}
}
}
});
return returnValue;
}
catch (Exception exp)
{
Classes.Logs.Error.Log_Error("IsUserInGroup", "DocumentCenterItem.cs", exp.Message, DateTime.Now);
return false;
}
}

Related

i want to pass header in login API using unity web request

public class Login : MonoBehaviour
{
[SerializeField] private string authenticationEndpoint = "http://146.190.226.27/api/login";
[SerializeField] private TMP_InputField usernameInputField;
[SerializeField] private TMP_InputField passwordInputField;
[SerializeField] private TextMeshProUGUI alertText;
[SerializeField] private Button loginButton;
public void OnLoginClick()
{
alertText.text = "Signing In...";
loginButton.interactable = false;
StartCoroutine(TryLogin());
}
private IEnumerator TryLogin()
{
string email = usernameInputField.text;
string password = passwordInputField.text;
if(email.Length < 15 || email.Length > 24)
{
alertText.text = "Invalid Username";
loginButton.interactable = true;
yield break;
}
if(password.Length < 3 || password.Length > 24)
{
alertText.text = "Invalid Password";
loginButton.interactable = true;
yield break;
}
else
{
alertText.text = "Locale is Required";
//Debug.Log("Locale is Required");
loginButton.interactable = true;
}
WWWForm form = new WWWForm();
form.AddField("email", email);
form.AddField("password", password);
UnityWebRequest request = UnityWebRequest.Post(authenticationEndpoint,form);
var handler = request.SendWebRequest();
float startTime = 0.0f;
while (!handler.isDone)
{
startTime += Time.deltaTime;
if(startTime > 10.0f)
{
break;
}
yield return null;
}
if(request.result == UnityWebRequest.Result.Success)
{
if (request.downloadHandler.text != "Invalid Credentials")
{
alertText.text = "Welcome";
loginButton.interactable = false;
}
else
{
alertText.text = "Invalid Credentials";
loginButton.interactable = true;
}
}
//Debug.Log($"{username}:{password}");
yield return null;
}
}
here is my code i have no idea how to call header or pass in unity here is API in json format
{
"msg": "Locale is required",
"data": {}
}

Check if string is a valid double value in Swift

In Swift, how can one check if a string is a valid double value? I have been using the following extension from this question (but as a float) but if the value cannot be converted, it simply returns "0":
extension String {
var doubleValue:Double? {
return (self as NSString).doubleValue
}
}
Ideally, I would like it to return nil so it can be caught in an if-let, like so:
if let i = str.doubleValue {
object.price = i
} else {
// Tell user the value is invalid
}
edit/update: Xcode 11 or later • Swift 5.1 or later
You can use Double initializer init?<S>(_ text: S) where S : StringProtocol to create an instance property on StringProtocol and use it to check if a String or Substring is a valid Double:
extension StringProtocol {
var double: Double? { Double(self) }
var float: Float? { Float(self) }
var integer: Int? { Int(self) }
}
Testing
let str = "2.9"
if let value = str.double {
print(value) // "2.9\n"
} else {
print("invalid input")
}
str.prefix(1).integer // 2
str.suffix(1).integer // 9
It is indeed more efficient not to create a number formatter every time we do a conversion:
extension String {
struct NumFormatter {
static let instance = NumberFormatter()
}
var doubleValue: Double? {
return NumFormatter.instance.number(from: self)?.doubleValue
}
var integerValue: Int? {
return NumFormatter.instance.number(from: self)?.intValue
}
}
Why not let it return false? Or true of course.
extension String {
func isInt() -> Bool {
if let intValue = Int(self) {
return true
}
return false
}
func isFloat() -> Bool {
if let floatValue = Float(self) {
return true
}
return false
}
func isDouble() -> Bool {
if let doubleValue = Double(self) {
return true
}
return false
}
func numberOfCharacters() -> Int {
return self.characters.count
}
}
Or even better, as suggested by #LeoDabus:
extension String {
var isInteger: Bool { return Int(self) != nil }
var isFloat: Bool { return Float(self) != nil }
var isDouble: Bool { return Double(self) != nil }
}
Here is my function:
func je_numerik(text:Character)->Bool //en znak
{
if((text=="0")||(text=="1")||(text=="2")||(text=="3")||(text=="4")||(text=="5")||(text=="6")||(text=="7")||(text=="8")||(text=="9")){
return true
}
else
{
return false
}
}
func je_stevilka(text: String)->Bool
{
var pika:Character
pika="."
var je_stevilka=true
//var znaki = Character(text)
var znaki=Array(text)
var stevilo_znakov=znaki.count
if(stevilo_znakov==0)
{
je_stevilka=false
}
else
{
if(stevilo_znakov==1)
{
if(je_numerik(znaki[0]))
{
je_stevilka=true
}
else
{
je_stevilka=false
}
}
else
{
if((je_numerik(znaki[0])) && (!((znaki[0]=="0")&&((znaki[1]=="0"))))&&(!((znaki[0]=="0")&&((je_numerik(znaki[1]))))))
{
var je_pika=false
for var i = 0; i < stevilo_znakov; i++
{
if(je_numerik(znaki[i])||(znaki[i]==pika))
{
if(znaki[i]==pika)
{
if(je_pika)
{
je_stevilka=false
}
else
{
je_pika=true
if(stevilo_znakov==(i+1))
{
je_stevilka=false
}
}
}
}
else
{
je_stevilka=false
}
}
}
else
{
je_stevilka=false
}
}
}
return je_stevilka
}
Just call it like this:
var check_if_is_number=je_stevilka(numberText)

is it possible to use MS Excel for all CRUD operations on OData source?

I have the following OData Controller, which provides for all common CRUD operations:
public class ProductsController : ODataController
{
ApplicationDbContext db = new ApplicationDbContext();
private bool ProductExists(int key)
{
return db.Products.Any(p => p.Id == key);
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
[EnableQuery]
public IQueryable<Product> Get()
{
return db.Products;
}
[EnableQuery]
public SingleResult<Product> Get([FromODataUri] int key)
{
IQueryable<Product> result = db.Products.Where(p => p.Id == key);
return SingleResult.Create(result);
}
public async Task<IHttpActionResult> Post(Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Products.Add(product);
await db.SaveChangesAsync();
return Created(product);
}
public async Task<IHttpActionResult> Patch([FromODataUri] int key, Delta<Product> product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var entity = await db.Products.FindAsync(key);
if (entity == null)
{
return NotFound();
}
product.Patch(entity);
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(key))
{
return NotFound();
}
else
{
throw;
}
}
return Updated(entity);
}
public async Task<IHttpActionResult> Put([FromODataUri] int key, Product update)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (key != update.Id)
{
return BadRequest();
}
db.Entry(update).State = EntityState.Modified;
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(key))
{
return NotFound();
}
else
{
throw;
}
}
return Updated(update);
}
public async Task<IHttpActionResult> Delete([FromODataUri] int key)
{
var product = await db.Products.FindAsync(key);
if (product == null)
{
return NotFound();
}
db.Products.Remove(product);
await db.SaveChangesAsync();
return StatusCode(HttpStatusCode.NoContent);
}
}
Is it possible to use MS Excel's OData client capabilities to use Excel as a data management tool to perform addition, deletion, complete and partial updates of the data exposed via my controller?

Database in J2ME

I am new in J2ME.
In my Application, I want to add the Multiple Records in the Record Store and also want to access it.
How can I add the multiple Records in the Record Store and how can I access it?
Here is my library code for RMS, just study it, it is very easy to implement, all the methods like insert,updated, delete is there.
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreFullException;
import javax.microedition.rms.RecordStoreNotOpenException;
import com.project.gui.components.CustomAlert;
import com.project.gui.midlet.MyMidlet;
public class RMSStore
{
private RecordStore rs = null;
public void openRecordStore(String str)
{
try
{
if(rs == null)
{
rs = RecordStore.openRecordStore(str, true);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void closeRecordStore()
{
try
{
if(rs!=null)
{
rs.closeRecordStore();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void deleteRecordStore(String storenName)
{
try
{
RecordStore.deleteRecordStore(storenName);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void deleteRMS(String storenName)
{
int count = 0;
try
{
RecordStore newRS = RecordStore.openRecordStore(storenName, true);
count = newRS.getNumRecords();
newRS.closeRecordStore();
}
catch ( Exception e )
{
System.out.println ( "Error while Opening " + e.toString() );
}
if ( count > 0 )
{
try
{
RecordStore.deleteRecordStore(storenName);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
public static String[] listAllRecordStore ()
{
return RecordStore.listRecordStores();
}
public boolean SearchRecord(String Rec)
{
String [] data = getRecordData();
for ( int i = 0 ; i < data.length ; i++ )
{
if ( Rec.toString().trim().equals(data[i].toString().trim()) )
{
data = null; // System.gc();
return true;
}
}
data = null; // System.gc();
return false;
}
public boolean SearchRecord(String Rec, int pos )
{
String [] data = getRecordData();
Rec = Rec.substring(0,pos);
for ( int i = 0 ; i < data.length ; i++ )
{
data[i] = data[i].substring(0, pos );
if ( Rec.toString().trim().equals(data[i].toString().trim()) )
{
data = null; // System.gc();
return true;
}
}
data = null; // System.gc();
return false;
}
public int getCurrentRecordID ( RMSStore rmsTable, String Rec )
{
RecordEnumeration re = null;
try
{
re = rmsTable.getRecordEnumData();
while ( re.hasNextElement() )
{
int id = re.nextRecordId();
String record = rmsTable.getRecordFromId(id);
if ( record.indexOf(Rec) != -1 )
{
return id;
}
}
}
catch ( Exception e ) { System.out.println ( "getCurrentRecordID Error:" + e.toString() ); }
return -1;
}
public int writeRecord(String str)
{
int id = 0;
try
{
id = rs.addRecord(str.getBytes(), 0, str.getBytes().length);
}
catch (RecordStoreFullException e)
{
CustomAlert memoryFullAlert = new CustomAlert("");
memoryFullAlert.setString("Memory Full");
MyMidlet.getDisplay().setCurrent(memoryFullAlert);
}
catch (Exception e)
{
e.printStackTrace();
}
return id;
}
public int writeByteRecord(byte[] data)
{
int id = -1;
try
{
id = rs.addRecord(data, 0, data.length);
}
catch (RecordStoreFullException e)
{
e.printStackTrace();
CustomAlert memoryFullAlert = new CustomAlert("");
memoryFullAlert.setString("Memory Full");
MyMidlet.getDisplay().setCurrent(memoryFullAlert);
}
catch (Exception e)
{
e.printStackTrace();
}
return id;
}
public int getRecordCount()
{
try
{
return rs.getNumRecords();
}
catch (Exception e)
{
e.printStackTrace();
}
return 0;
}
public byte[] getRecordDataFromId(int id)
{
byte[] data = null;
try
{
data = rs.getRecord(id);
}
catch (Exception e)
{
e.printStackTrace();
}
return data;
}
public String getRecordFromId(int id)
{
return new String(getRecordDataFromId(id));
}
public byte[] getRecordByteFromId(int id)
{
return getRecordDataFromId(id);
}
public void deleteRecord(int id)
{
try
{
rs.deleteRecord(id);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public boolean checkRecordExists(String compare)
{
for(int i = 0; i < getRecordCount(); i++)
{
if(compare.equals(getRecordFromId(i + 1)))
{
return true;
}
}
return false;
}
public int getMaxRMSSize()
{
int size = 0;
try
{
size = rs.getSizeAvailable() + rs.getSize();
}
catch (RecordStoreNotOpenException e)
{
e.printStackTrace();
}
return size;
}
public void setRecordById(String str, int id)
{
try
{
rs.setRecord(id, str.getBytes(), 0, str.getBytes().length);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public int getNextRecordId()
{
int id = 0;
try
{
id = rs.getNextRecordID();
}
catch (Exception e)
{
e.printStackTrace();
}
return id;
}
public RecordEnumeration getRecordEnumData ()
{
try
{
return rs.enumerateRecords(null, null, false);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
public String [] getRecordData()
{
String[] str = null;
int counter = 0;
try
{
RecordEnumeration enumeration = rs.enumerateRecords(null, null, false);
str = new String[rs.getNumRecords()];
while(enumeration.hasNextElement())
{
try
{
str[counter] = (new String(enumeration.nextRecord()));
counter ++;
}
catch (Exception e)
{
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
}
RMS is a record based data storage mechanism, so you can store multiple records very easily, see following blog to see how RMS works.
http://www.ibm.com/developerworks/library/wi-rms/

Login page in Ajax popup box on home page load Magento

How can we display login page in Ajax popup box on homepage load in Magento that to popup box need to come only one time until browser is closed and i also need to place FB connect to same popup box .can any reply me soon please
Hi you can use any lightbox plugin to display the code, and to show login in popup you can override the customer AccountController.php like this
protected $_validActions = array('create','login','logoutSuccess','forgotpassword','forgotpasswordpost','confirm','confirmation','resetpassword','resetpasswordpost');
protected $_customActions = array('signupformpopup','ajaxLogin','ajaxCreate');
public function preDispatch()
{
// a brute-force protection here would be nice
$action = $this->getRequest()->getActionName();
if (preg_match('/^('.$this->_getCustomActions().')/i', $action))
{
$this->getRequest()->setActionName($this->_validActions[1]);
}
parent::preDispatch();
if ($action != $this->getRequest()->getActionName())
{
$this->getRequest()->setActionName($action);
}
if (!$this->getRequest()->isDispatched()) {
return;
}
if (!preg_match('/^('.$this->_getValidActions().')/i', $action)) {
if (!$this->_getSession()->authenticate($this)) {
$this->setFlag('', 'no-dispatch', true);
}
} else {
$this->_getSession()->setNoReferer(true);
}
}
protected function _getValidActions()
{
return implode("|", array_merge($this->_validActions, $this->_customActions));
}
protected function _getCustomActions()
{
return implode("|", $this->_customActions);
}
/**
* Login post action
*/
public function ajaxLoginAction() {
if ($this->_getSession()->isLoggedIn()) {
$this->_redirect('*/*/');
return;
}
$session = $this->_getSession();
$result=array();
if ($this->getRequest()->isPost()) {
$login = $this->getRequest()->getPost('login');
if (!empty($login['username']) && !empty($login['password'])) {
try {
$session->login($login['username'], $login['password']);
if ($session->getCustomer()->getIsJustConfirmed()) {
$this->_welcomeCustomer($session->getCustomer(), true);
}
$result['success'] = true;
$result['redirecturl'] = Mage::getUrl('customer/account/edit');
} catch (Mage_Core_Exception $e) {
switch ($e->getCode()) {
case Mage_Customer_Model_Customer::EXCEPTION_EMAIL_NOT_CONFIRMED:
/*$message = Mage::helper('customer')->__('This account is not confirmed. Click here to resend confirmation email.', Mage::helper('customer')->getEmailConfirmationUrl($login['username']));*/
$result['success'] = false;
$result['message'] = Mage::helper('customer')->__('This account is not confirmed.');
break;
case Mage_Customer_Model_Customer::EXCEPTION_INVALID_EMAIL_OR_PASSWORD:
$message = $e->getMessage();
$result['success'] = false;
$result['message'] = Mage::helper('customer')->__($message);
break;
default:
$message = $e->getMessage();
$result['success'] = false;
$result['message'] = Mage::helper('customer')->__($message);
}
//$session->addError($message);
$session->setUsername($login['username']);
} catch (Exception $e) {
// Mage::logException($e); // PA DSS violation: this exception log can disclose customer password
}
} else {
//$session->addError($this->__('Login and password are required.'));
$result['success'] = false;
$result['message'] = Mage::helper('customer')->__('Login and password are required.');
}
}
$this->getResponse()->setBody(Zend_Json::encode($result));
//$this->_loginPostRedirect();
}
/**
* Login post action
*/
public function ajaxCreateAction()
{
$session = $this->_getSession();
if ($session->isLoggedIn()) {
$this->_redirect('*/*/');
return;
}
$session->setEscapeMessages(true); // prevent XSS injection in user input
if ($this->getRequest()->isPost()) {
$errors = array();
if (!$customer = Mage::registry('current_customer')) {
$customer = Mage::getModel('customer/customer')->setId(null);
}
/* #var $customerForm Mage_Customer_Model_Form */
$customerForm = Mage::getModel('customer/form');
$customerForm->setFormCode('customer_account_create')
->setEntity($customer);
$customerData = $customerForm->extractData($this->getRequest());
if ($this->getRequest()->getParam('is_subscribed', false)) {
$customer->setIsSubscribed(1);
}
/**
* Initialize customer group id
*/
$customer->getGroupId();
if ($this->getRequest()->getPost('create_address')) {
/* #var $address Mage_Customer_Model_Address */
$address = Mage::getModel('customer/address');
/* #var $addressForm Mage_Customer_Model_Form */
$addressForm = Mage::getModel('customer/form');
$addressForm->setFormCode('customer_register_address')
->setEntity($address);
$addressData = $addressForm->extractData($this->getRequest(), 'address', false);
$addressErrors = $addressForm->validateData($addressData);
if ($addressErrors === true) {
$address->setId(null)
->setIsDefaultBilling($this->getRequest()->getParam('default_billing', false))
->setIsDefaultShipping($this->getRequest()->getParam('default_shipping', false));
$addressForm->compactData($addressData);
$customer->addAddress($address);
$addressErrors = $address->validate();
if (is_array($addressErrors)) {
$errors = array_merge($errors, $addressErrors);
}
} else {
$errors = array_merge($errors, $addressErrors);
}
}
try {
$customerErrors = $customerForm->validateData($customerData);
if ($customerErrors !== true) {
$errors = array_merge($customerErrors, $errors);
} else {
$customerForm->compactData($customerData);
$customer->setPassword($this->getRequest()->getPost('password'));
$customer->setConfirmation($this->getRequest()->getPost('confirmation'));
$customerErrors = $customer->validate();
if (is_array($customerErrors)) {
$errors = array_merge($customerErrors, $errors);
}
}
$validationResult = count($errors) == 0;
$result = array();
if (true === $validationResult) {
$customer->save();
if ($customer->isConfirmationRequired()) {
$customer->sendNewAccountEmail('confirmation', $session->getBeforeAuthUrl());
// $session->addSuccess($this->__('Account confirmation is required. Please, check your email for the confirmation link. To resend the confirmation email please click here.', Mage::helper('customer')->getEmailConfirmationUrl($customer->getEmail())));
//$this->_redirectSuccess(Mage::getUrl('*/*/index', array('_secure'=>true)));
//return;
$result['success'] = true;
$result['message'] = $this->__('Account confirmation is required. Please, check your email for the confirmation link. To resend the confirmation email please click here.', Mage::helper('customer')->getEmailConfirmationUrl($customer->getEmail()));
} else {
$session->setCustomerAsLoggedIn($customer);
$url = $this->_welcomeCustomer($customer);
//$this->_redirectSuccess($url);
//return;
$result['success'] = true;
$result['message'] = $this->__('You are successfully registered');
}
} else {
$session->setCustomerFormData($this->getRequest()->getPost());
if (is_array($errors)) {
$result['success'] = false;
foreach ($errors as $errorMessage) {
//$session->addError($errorMessage);
$result['message'] .= $errorMessage;
}
} else {
//$session->addError($this->__('Invalid customer data'));
$result['success'] = false;
$result['message'] = $this->__('Invalid customer data');
}
}
} catch (Mage_Core_Exception $e) {
$session->setCustomerFormData($this->getRequest()->getPost());
if ($e->getCode() === Mage_Customer_Model_Customer::EXCEPTION_EMAIL_EXISTS) {
$url = Mage::getUrl('customer/account/forgotpassword');
$result['success'] = false;
$result['message'] = $this->__('There is already an account with this email address. If you are sure that it is your email address.');
} else {
$result['success'] = false;
$result['message'] = $e->getMessage();
}
//$session->addError($message);
} catch (Exception $e) {
// $session->setCustomerFormData($this->getRequest()->getPost())
// ->addException($e, $this->__('Cannot save the customer.'));
$result['success'] = false;
$result['message'] = $this->__('Cannot save the customer.');
}
}
//$this->_redirectError(Mage::getUrl('*/*/create', array('_secure' => true)));
$this->getResponse()->setBody(Zend_Json::encode($result));
}
}

Resources