This logic checks accessGroup and if accessGroup is equal to "Admin" then it only checks if result.Admin or baccess is true but if accessGroup is anything else it will need to check two other objects result.Admin == true || result.PowerUser.
Is there any other way to do this if condition?
if (accessGroup == "Admin")
{
if (baccess == true || result.Admin == true)
{
var FileInfo = GetFile(fileManagerGuidId);
if (FileInfo != null)
{
FileManagerLog _filemanagerLog = new FileManagerLog();
_filemanagerLog.CustomerId =Request.Cookies["customerid"] != null ? Convert.ToInt32(Request.Cookies["customerid"].Value) : 0;
_filemanagerLog.FileManagerGuid = new Guid(fileManagerGuidId);
SaveFileManagerLog(_filemanagerLog);
byte[] fileBytes = FileInfo.FileData;
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, FileInfo.FileName);
}
else
{
return null;
}
}
}
else
{
if (baccess == true || result.Admin == true || result.PowerUser)
{
var FileInfo = GetFile(fileManagerGuidId);
if (FileInfo != null)
{
FileManagerLog _filemanagerLog = new FileManagerLog();
_filemanagerLog.CustomerId =Request.Cookies["customerid"] != null ? Convert.ToInt32(Request.Cookies["customerid"].Value) : 0;
_filemanagerLog.FileManagerGuid = new Guid(fileManagerGuidId);
SaveFileManagerLog(_filemanagerLog);
byte[] fileBytes = FileInfo.FileData;
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, FileInfo.FileName);
}
else
{
return null;
}
}
}
Using Enum flags is really great in ur case,
create an enum with
admin = 1
poweruser = 2
normaluser = 4
and check on the result you have
"== true" is useless, writing the boolean itself is enough
if (baccess|| result.Admin || result.PowerUser)
second solution :
if powerUse is only for normal user, you can use Or state
Boolean allowed = false;
if (baccess || result.Admin)
{
if (accessGroup == "Admin")
{
allowed = true;
}
else
{
allowed =result.PowerUser
}
}
if(allowed)
{
var FileInfo = GetFile(fileManagerGuidId);
if (FileInfo == null)
{
FileManagerLog _filemanagerLog = new FileManagerLog();
_filemanagerLog.CustomerId =Request.Cookies["customerid"] != null ? Convert.ToInt32(Request.Cookies["customerid"].Value) : 0;
_filemanagerLog.FileManagerGuid = new Guid(fileManagerGuidId);
SaveFileManagerLog(_filemanagerLog);
byte[] fileBytes = FileInfo.FileData;
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, FileInfo.FileName);
}
else
{
return null;
}
}
There are lots of ways to do this some better than others
however looking at the logic i think you can drop most of it
as you are ORing all the fields then
if they have bacess the code runs regardless of anything else
if they
have result.Admin the code runs regardless of anything else
if they
have accessGroup == "Admin" the code runs regardless of anything else
if they have result.PowerUser the code runs regardless of anything
else
the only way this code wont run is if !baccess & !result.Admin & !result.PowerUser & accessGroup != "Admin"
so this is exactly the same
if (baccess || result.Admin || (accessGroup != "Admin" && Result.PowerUser))
{
var FileInfo = GetFile(fileManagerGuidId);
if (FileInfo != null)
{
FileManagerLog _filemanagerLog = new FileManagerLog();
_filemanagerLog.CustomerId =Request.Cookies["customerid"] != null ? Convert.ToInt32(Request.Cookies["customerid"].Value) : 0;
_filemanagerLog.FileManagerGuid = new Guid(fileManagerGuidId);
SaveFileManagerLog(_filemanagerLog);
byte[] fileBytes = FileInfo.FileData;
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, FileInfo.FileName);
}
else
{
return null;
}
}
though i suspect you actually wanting to AND (&&) the fields together
which would look like
if (baccess && (result.Admin || (accessGroup != "Admin" && result.PowerUser))
ie if they have access and are an admin or a poweruser
Related
I have a way here how I check multiple variables for null, and fill them with the correct data according to the nullness. However, this way is very messy and I am now wondering if there is a better way to do this.
`
try
{
user = new ADUser();
nextEntry = ldapSearch.Next();
var attName = nextEntry.getAttribute("name");
var attMail = nextEntry.getAttribute("mail");
var attTelephone = nextEntry.getAttribute("telephoneNumber");
if(attName == null || attMail == null || attTelephone == null)
{
if( attName == null)
{
user.name = "";
}
else
{
user.name = attName.StringValue;
}
if(attMail == null)
{
user.mail = "";
}
else
{
user.mail = attMail.StringValue;
}
if(attTelephone == null)
{
user.telephone = "";
}
else
{
user.telephone = attTelephone.StringValue;
}
}
else
{
user.name = attName.StringValue;
user.mail = attMail.StringValue;
user.telephone = attTelephone.StringValue;
}
model.ADUserList.Add(user);
}
catch
{
continue;
}
`
I have tried it my way, but I think it can be done cleaner.
yes, you can achive the same result without any 'if-else':
user.name = attName?.StringValue ?? "";
user.mail = attMail?.StringValue ?? "";
user.telephone = attTelephone?.StringValue ?? "";
you can also write an extension method to return the empty string:
public static class StringExtensions
{
public static string EmptyIfNull(this string str)
{
return str ?? String.Empty;
}
}
and then use it like this:
user.name = attName?.StringValue.EmptyIfNull();
user.mail = attMail?.StringValue.EmptyIfNull();
user.telephone = attTelephone?.StringValue.EmptyIfNull();
While submitting a form, in one of the fields i am inserting vulnerable characters like =cmd|'/C calc'!A0. So in security terms it is termed as CSV-injection in export functionality
I have written code like this for above error. but its not working
[WebMethod]
public static string SaveRecord(RRSOCSaving RRSOCSaving, string Indication)
{
string strReturnId = "";
string strAppURL = ConfigurationManager.AppSettings["AppUrl"].ToString();
string strmail_Content = "";
CommonDB commonObj = new CommonDB();
try
{
// Cross site scripting issue code tag..!!
if (commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_CODE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.CITY)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_SITENAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_SITENAME_LANDL_1)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_SITENAME_LANDL_2)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_ASST_MANAGER_NAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_ASST_MANAGER_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_MANAGER_NAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.MANAGER_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.EMP_NEAREST_STORE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.EMP_NEAREST_STORE_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.SUPERVISOR_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.SECURITY_SUP_NAME_STORE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.SECURITY_SUP_MOBNO_STORE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.ALPM_ALPO_NAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.ALPM_ALPO_MOBNO))
{
strReturnId = "Something went wrong due to malicious script attack..!!!";
}
else
{
if (RRSOCSaving.ROLE_ASSIGNED == "SLP State Head")
{
bool blnState1 = Array.Exists(RRSOCSaving.ASSIGNED_STATE.ToString().ToUpper().Split(','), element => element == (RRSOCSaving.STATE).ToString().ToUpper());
if (blnState1)
{
strmail_Content = Get_Email_Content(RRSOCSaving.STORE_CODE, RRSOCSaving.UserName, Indication, RRSOCSaving.STATE, RRSOCSaving.SITE_STORE_FORMAT, RRSOCSaving.STORE_SITENAME);
// SendEmail(RRSOCSaving.UserName, RRSOCSaving.STORE_CODE, RRSOCSaving.SLP_EMAILID, ConfigurationManager.AppSettings["NHQEmail"].ToString(), strmail_Content, Indication);
strReturnId = CommonDB.INSERT_INTO_RRSOC_INFO(RRSOCSaving, Indication);
}
else
{
strReturnId = "User can add data for " + RRSOCSaving.ASSIGNED_STATE + " only";
}
}
else if (RRSOCSaving.ROLE_ASSIGNED == "NHQ Admin")
{
strmail_Content = Get_Email_Content(RRSOCSaving.STORE_CODE, RRSOCSaving.UserName, Indication, RRSOCSaving.STATE, RRSOCSaving.SITE_STORE_FORMAT, RRSOCSaving.STORE_SITENAME);
// SendEmail(RRSOCSaving.UserName, RRSOCSaving.STORE_CODE, RRSOCSaving.SLP_EMAILID, ConfigurationManager.AppSettings["NHQEmail"].ToString(), strmail_Content, Indication);
strReturnId = CommonDB.INSERT_INTO_RRSOC_INFO(RRSOCSaving, Indication);
//strReturnId = "Record Saved Succesfully";
}
}
// strReturnId = CommonDB.INSERT_INTO_RRSOC_INFO(RRSOCSaving);
}
catch (Exception)
{
throw;
}
return strReturnId;
}
public bool HackerTextExistOrNot(string Text)
{
bool flgValid = false;
Regex htmltags = new Regex(#"<.*?>");
Match chkMatch = htmltags.Match(Text);
if (chkMatch.Success)
{
flgValid = true;
}
return flgValid;
}
Please suggest how to stop this error.
Your HackerTextExistOrNot method is checking for the existance of html tags.
You should however check if the text is starting with one of the formular triggering characters.
To protect yourself against the injection attack ensure that none of the given text begins with any of the following characters:
Equals to ("=")
Plus ("+")
Minus ("-")
At ("#")
So you can check like this:
var attackChars = new char[]{'=','+','-','#'};
if(attackChars.Contains(text[0])
{
}
I am trying to fetch all account entity fields from an organization.(https://democrm365.crm4.dynamics.com).
Also, I created some custom fields in account and added into form. After that when I run the following code I am getting all fields related to account.
IOrganizationService service = (IOrganizationService)serviceProxy;
RetrieveEntityRequest request = new RetrieveEntityRequest()
{
EntityFilters = EntityFilters.Attributes,
RetrieveAsIfPublished = false,
LogicalName = "account"
};
RetrieveEntityResponse res = (RetrieveEntityResponse)service.Execute(request);
EntityMetadata currentEntity = res.EntityMetadata;
foreach (AttributeMetadata attribute in currentEntity.Attributes)
{
if (attribute.DisplayName.UserLocalizedLabel != null && attribute.AttributeType != null && attribute.LogicalName != "" && attribute.AttributeType != null && attribute.IsValidForRead.Value == true)
{
if (_allowedFieldTypes.Contains(attribute.AttributeType.ToString().ToLower()))
{
EntityField ef = new EntityField();
ef.AttributeType = attribute.AttributeType.ToString() ?? "";
ef.DisplayName = attribute.DisplayName.UserLocalizedLabel.Label;
ef.IsCustomField = attribute.IsCustomAttribute ?? false;
ef.IsAllowUpdate = attribute.IsValidForUpdate ?? false;
ef.LogicalName = attribute.LogicalName;
if (attribute.AttributeType.ToString().ToLower() == "picklist")
{
PicklistAttributeMetadata pm = (PicklistAttributeMetadata)attribute;
foreach (OptionMetadata x in pm.OptionSet.Options)
{
ef.Items.Add(x.Label.UserLocalizedLabel.Label);
}
}
else if (attribute.AttributeType.ToString().ToLower() == "virtual")
{
if (attribute.AttributeTypeName.Value == "MultiSelectPicklistType")
{
MultiSelectPicklistAttributeMetadata pm = (MultiSelectPicklistAttributeMetadata)attribute;
foreach (OptionMetadata x in pm.OptionSet.Options)
{
ef.Items.Add(x.Label.UserLocalizedLabel.Label);
}
}
}
if (Add)
{
fieldLst.Add(ef);
}
}
}
}
Again, I tested the same code on different organization (https://zoho5.crm.dynamics.com) with all above mentioned steps, then
below code is not working.
if (attribute.DisplayName.UserLocalizedLabel != null && attribute.AttributeType != null && attribute.LogicalName != "" && attribute.AttributeType != null && attribute.IsValidForRead.Value == true)
attribute.DisplayName.UserLocalizedLabel is null for all fields like (Account Name, Account No. Etc)
After some test runs, I removed the custom fields from account form and publish form. Then the above code is working fine.
Try this. You may have to get the label from LocalizedLabels when UserLocalizedLabel is null.
foreach (AttributeMetadata attribute in currentEntity.Attributes)
{
if (attribute.AttributeType != null && attribute.LogicalName != "" && attribute.AttributeType != null && attribute.IsValidForRead.Value == true)
{
string attributeName = attribute.LogicalName;
if (attribute.DisplayName.UserLocalizedLabel != null)
{
attributeName = attribute.DisplayName.UserLocalizedLabel.Label;
}
if (attributeName == attribute.LogicalName && attribute.DisplayName.LocalizedLabels.Count > 0)
{
attributeName = attribute.DisplayName.LocalizedLabels[0].Label;
}
}
}
I have a signup page that have many filed. Many of them should filled by user.
I use RequiredFieldValidator and RegularExpressionValidator for validate in client side.
Should I validate them in server side? How?
I wrote this code. I use many if and else if. Is this correct?
CaptchaControl1.ValidateCaptcha(txtSecureImg.Text);
if (CaptchaControl1.UserValidated)
{
if (txtFName.Text != string.Empty && txtLName.Text != string.Empty && txtUserName.Text != string.Empty && txtEmail.Text != string.Empty && txtPass.Text != string.Empty && txtCPass.Text != string.Empty && txtSecureImg.Text != string.Empty)
{
if (RegEx.EmailValidate(txtEmail.Text) == 1 && RegEx.PasswordValidate(txtPass.Text) == 1 && RegEx.UserName(txtUserName.Text) == 1)
{
try
{
// insert in database
}
catch (Exception)
{
lblMsg.Text = "Error";
}
}
else if(RegEx.EmailValidate(txtEmail.Text) == 0)
{
EmailRegularExpression.Visible = true;
}
else if(RegEx.PasswordValidate(txtPass.Text) == 0)
{
passRegularExpression.Visible = true;
}
else if(RegEx.UserName(txtUserName.Text) == 0)
{
UnameRegularExpression.Visible = true;
}
}
else if(txtFName.Text == string.Empty)
{
RequiredFieldValidator1.Visible = true;
}
// continue like above for another filed
}
else
{
lblMsg.Text = "Please insert Secure Image";
}
And :
public static int EmailValidate(string Mail)
{
int i = 0;
Regex regExEmail = new Regex(#"\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*");
if (regExEmail.IsMatch(Mail))
i = 1;
return i;
}
I'm assuming this is Web Forms...
The validation is run automatically. You can just use the Page.IsValid property: msdn
You'll still need to manually check the captcha field though.
CaptchaControl1.ValidateCaptcha(txtSecureImg.Text);
if (CaptchaControl1.UserValidated && Page.IsValid)
{
// Insert in db.
}
Since you use those validators, then you don't need to validate form in server side again like your codes.
But you should call Page.Validate()and then check page with Page.IsValid method.
from here
example
If the filename contains # - download from skydrive fails. More precisely - length of result always 0. Other files are loaded without any problems;
Thanks
start downloading:
if (!loading) {
if (!Storage.Exists(item.Name)
|| MessageBox.Show(AppResources.alreadyExists, AppResources.confirmation, MessageBoxButton.OKCancel) == MessageBoxResult.OK) {
loading = true;
App.loadInfo.Name = item.Name;
App.loadInfo.Info = AppResources.loadingStart;
PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disa bled;
client.DownloadAsync(item.Id + CONTENT, item);
}
}
download completed:
void client_DownloadCompleted(object sender, LiveDownloadCompletedEventArgs e) {
PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Enabled;
try {
FileItem item = e.UserState as FileItem;
if (e.Error == null
&& !e.Cancelled
&& e.UserState != null
&& item.Size == e.Result.Length.ToString()) //LENGTH = 0 { Storage.SaveFile(item.Name, e.Result);
App.loadInfo.Info = AppResources.loadingComplete;
new GetIcon(item._name);
}
else {
if (item != null) App.loadInfo.Name = item.Name;
App.loadInfo.Info = AppResources.loadingError;
}
}
finally { App.loadInfo.Progress = 0; loading = false; MakeUi(); }
}
LiveDownloadProgressChangedEventArgs does not arise
If this is genuinely the case, can you not just strip the fragments from the URI before you make the request?
Live Connect & Live SDK Known Issues