i have got the below code to check whether the login user access to menu item
but if first item fails the if condition it is redirecting to error page, but i need to check second item from that string array with if condition even the first item fails the if condition ...
please find the below given code for test..
var count = 0;
string[] strPageId = PageId.Split(';');
foreach (string menuPageId in strPageId)
{
if (objDALookup.IsPageVisible(PageType,Int32.Parse(menuPageId), role, AcctId) == false)
{
Session["ErrorInfo"] = "Access denied, please contact system administrator.";
new Lib.Utils.Log().logInfo("FORCE_ACCESS", strUser + " tried to access PageId:" + PageId + " PageType:" + PageType);
Response.Redirect(ConfigurationManager.AppSettings["ACCESS_DENIED_URL"], true);
}
else
{
count++;
if (count == strPageId.Length) break;
}
}
You can make condition something like this by figuring out condition in loop and executing the action outside loop once it is decided.
bool access = false;
foreach (string menuPageId in strPageId)
{
if (objDALookup.IsPageVisible(PageType,Int32.Parse(menuPageId), role, AcctId) == true)
{
access = true;
break;
}
}
if(!access)
{
Session["ErrorInfo"] = "Access denied, please contact system administrator.";
new Lib.Utils.Log().logInfo("FORCE_ACCESS", strUser + " tried to access PageId:" + PageId + " PageType:" + PageType);
Response.Redirect(ConfigurationManager.AppSettings["ACCESS_DENIED_URL"], true);
}
OR
You can use linq
bool access = strPageId.Any(s=> objDALookup.IsPageVisible(PageType,Int32.Parse(menuPageId), role, AcctId) == true);
if(!access)
{
}
Related
I'm trying to extract the values of a SharePoint list to use with Revit to update the status parameters of some elements and after many tries I can connect and get the values if I know the keys for the dictionary inside every ListItem, but there are many problems with this approach.
The first one is the need to know the keys, sometimes the key is changed because of encoding, It would be more productive for me to get all the list values at one time. I tried to use a GetDataTable like some tutorials, but it appears that this don't work with the client.
The second is sometimes I can't get the value of the List but a description of the value, like "Microsoft.SharePoint.Client.FieldLookupValue".
Can someone help me with this issue? Bellow is the code I'm using.
using Microsoft.SharePoint.Client;
using System;
using System.Security;
namespace ConsoleTESTES
{
class Program
{
static void Main(string[] args)
{
string username = "USERNAME";
string siteURL = "SITEURL";
SecureString password = GetPassword();
GetAllWebProperties(siteURL, username, password);
}
public static void GetAllWebProperties(string siteURL, string username, SecureString password)
{
using (var context = new ClientContext(siteURL))
{
context.Credentials = new SharePointOnlineCredentials(username, password);
Web web = context.Web;
context.Load(web);
context.ExecuteQuery();
Console.WriteLine("Title: " + web.Title + "; URL: " + web.Url);
// Assume the web has a list named "Announcements".
//List lista = context.Web.Lists.GetByTitle("Lista teste");
List lista = context.Web.Lists.GetByTitle("LIST");
// This creates a CamlQuery that has a RowLimit of 100, and also specifies Scope="RecursiveAll"
// so that it grabs all list items, regardless of the folder they are in.
CamlQuery query = CamlQuery.CreateAllItemsQuery();
ListItemCollection items = lista.GetItems(query);
// Retrieve all items in the ListItemCollection from List.GetItems(Query).
context.Load(items);
context.ExecuteQuery();
//GET VALUES FROM LISTITEM
foreach (ListItem listItem in items)
{
Console.WriteLine(listItem["Setor"] + " " + "|" + " "
+ listItem["LocalServico"] + " " + "|" + " "
+ listItem["Equipe"] + " " + "|" + " "
+ listItem["Confeccao"]);
}
Console.ReadLine();
}
}
public static SecureString GetPassword()
{
ConsoleKeyInfo info;
SecureString securePassword = new SecureString();
do
{
info = Console.ReadKey();
if (info.Key != ConsoleKey.Enter)
{
securePassword.AppendChar(info.KeyChar);
}
}
while (info.Key != ConsoleKey.Enter);
return securePassword;
}
}
}
You could get the values from the fields collection, but be warned that some special types of fields might require special treatment for the values and that you might not need to get all the values from the server (you can probably reduce your payload):
var items = lista.GetItems(query);
var fields = list.Fields;
var fieldsToIgnore = new[] { "ContentType", "Attachments" };
context.Load(items);
context.Load(fields);
context.ExecuteQuery();
foreach (ListItem listItem in items)
{
foreach (Field field in fields)
{
if (!fieldsToIgnore.Contains(fld.InternalName))
Console.WriteLine(item[field.InternalName]);
}
}
There are some fields that might not be loaded by default of that you might not need, so I have included the fieldsToIgnore to make your test easier.
After some search I found this solution to my FieldLookUpTable, to avoid errors if the item is null I added a if statement, but I could access the value with (listItem["Setor"] as FieldLookupValue).LookupValue. Here my messy code to check if is a LookupValue and get the value. Now I need to implement Pedro's solution to get all the values without the need to write everyone.
String setor = "";
String localServico = "";
String confeccao = "";
if (listItem["Setor"] != null && listItem["Setor"].ToString() == "Microsoft.SharePoint.Client.FieldLookupValue")
{
setor = (listItem["Setor"] as FieldLookupValue).LookupValue;
}
else if (listItem["Setor"] != null && listItem["Setor"].ToString() != "Microsoft.SharePoint.Client.FieldLookupValue")
{
setor = listItem["Setor"].ToString();
}
if (listItem["LocalServico"] != null && listItem["LocalServico"].ToString() == "Microsoft.SharePoint.Client.FieldLookupValue")
{
localServico = (listItem["LocalServico"] as FieldLookupValue).LookupValue;
}
else if (listItem["LocalServico"] != null && listItem["LocalServico"].ToString() != "Microsoft.SharePoint.Client.FieldLookupValue")
{
localServico = listItem["LocalServico"].ToString();
}
if (listItem["Confeccao"] != null && listItem["Confeccao"].ToString() == "Microsoft.SharePoint.Client.FieldLookupValue")
{
confeccao = (listItem["Confeccao"] as FieldLookupValue).LookupValue;
}
else if (listItem["Confeccao"] != null && listItem["Confeccao"].ToString() != "Microsoft.SharePoint.Client.FieldLookupValue")
{
confeccao = listItem["Confeccao"].ToString();
}
Console.WriteLine(setor + " " + "|" + " "
+ localServico + " " + "|" + " "
+ confeccao);
I am unable to fix this issue and can't seem to figure out what I have done wrong.
This is the else part to my code.
else {
string prevFundedList = firstFundList;
foreach (object[] item in tempRsList)
{
if(prevfundedList != fundedList && item[12].ToString() == "PinYear")
{
oExcelApp.Cells[rowNum, 1] = "SFY " + year.ToString() + " Planning List - Bypass Systems";
oExcelApp.Cells[rowNum, 1].Font.Bold = true;
rowNum = rowNum + 1;
}
prevFundedList = item[12].ToString();
}
} // end of else
Error says
"The name 'prevfundedList' does not exist in the current contex"
Variable names in c# are case-sensitive.
You're declaration is prevFundedList but you use it in the if statement as prevfundedList.
I have attached my code below. I am trying to get the message box to go away after one pop up until another action within the application triggers it.
using (VIModel vi = new VIModel())
{
var VideoFiles = vi.VI_VIDEO_FILES.Where(a => a.SEGMENT_ID == segmentId);
foreach (var vf in VideoFiles)
{
string location = vf.URL;
location = location.Replace('/', '\\');
string[] smain = location.Split('\\');
string unamemain = smain.Last().ToString();
string fileToCopySource = Path.Combine(inputDirectory, location);
string fileToCopyDestination = Path.Combine(outputDirectory, unamemain);
foreach (char c in fileToCopySource)
{
if (fileToCopySource.Contains(c))
{
// notify user that the inputDirectory isn't valid
MessageBox.Show("FOO");
}
}
if (!File.Exists(fileToCopySource))
{
// notify user that file doesn't exist
MessageBox.Show("FOO");
}
//File.Copy(inputDirectory + location, outputDirectory + unamemain, true);
File.Copy(fileToCopySource, fileToCopyDestination, true);
lbConsole.Items.Add("Moved " + location + " from: " + inputDirectory + " to " + fileToCopyDestination);
}
}
Your code is alerting multiple times -- once for every "alertable" condition it finds, i.e. input directory not valid. What you need to do is record the fact that anything caused the condition that will need to be alerted, and then alert only once, outside of the loop:
bool needAlert = false;
foreach (char c in fileToCopySource)
{
if (fileToCopySource.Contains(c))
{
needAlert = true;
break; // no more looping needed.
}
}
if(needAlert) MessageBox.Show("FOO"); // notify user that the inputDirectory isn't valid
Hi I would like to avoid printing certain rows (valid accounts) in my foreach loop (in GetSAM)as opposed to printing everything.
When I try to do so by commenting away the line (in valSAM) that prints the valid accounts, the will be a blank in the area where a valid account once was. I understand that this is because the foreach loops through all the variables in the database.
How am I able to remove the gaps between the output?
GetSAM:
//Get SAMAccount
private static string GetSAM(string ldapAddress, string serviceAccountUserName, string serviceAccountPassword)
{
string ldapPath = "LDAP://" + ldapAddress;
string ldapFilter = "(&(objectclass=user)(objectcategory=person))";
DirectoryEntry directoryEntry = new DirectoryEntry(ldapPath, serviceAccountUserName, serviceAccountPassword);
string readOutput;
List<string> list = new List<string>();
List<int> invalid = new List<int>();
using (DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry))
{
string samAccountName;
directorySearcher.Filter = ldapFilter;
directorySearcher.SearchScope = SearchScope.Subtree;
directorySearcher.PageSize = 1000;
using (SearchResultCollection searchResultCollection = directorySearcher.FindAll())
{
**foreach (SearchResult result in searchResultCollection)
{
samAccountName = result.Properties["sAMAccountName"][0].ToString();
if (valSAM(samAccountName, ldapAddress, serviceAccountUserName, serviceAccountPassword)!= true)
{
invalid.Add('1');
}
list.Add(samAccountName);
} //end of foreach**
// Count all accounts
int totalAccounts = list.Count;
// Count all invalid accounts
int invalidAccounts = invalid.Count;
Console.WriteLine("Found " + invalidAccounts + " invalid accounts out of " + totalAccounts + " user accounts.\nQuery in " + ldapAddress + " has finished.\n");
Console.WriteLine("Press [enter] to continue.\n");
readOutput = Console.ReadLine();
}//SearchResultCollection will be disposed here
}
return readOutput;
}
valSAM:
//Validate SAMAccount
private static bool valSAM(string samAccountName, string ldapAddress, string serviceAccountUserName, string serviceAccountPassword)
{
string ldapPath = "LDAP://" + ldapAddress;
DirectoryEntry directoryEntry = new DirectoryEntry(ldapPath, serviceAccountUserName, serviceAccountPassword);
StringBuilder builder = new StringBuilder();
bool accountValidation = false;
//create instance fo the directory searcher
DirectorySearcher desearch = new DirectorySearcher(directoryEntry);
//set the search filter
desearch.Filter = "(&(sAMAccountName=" + samAccountName + ")(objectcategory=user))";
//find the first instance
SearchResult results = desearch.FindOne();
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, ldapAddress))
{
//if users are present in database
if (results != null)
{
//Check if account is activated
bool isAccountActived = IsActive(results.GetDirectoryEntry());
//Check if account is expired or locked
bool isAccountLocked = IsAccountLockOrExpired(results.GetDirectoryEntry());
accountValidation = ((isAccountActived != true) || (isAccountLocked));
//account is invalid
if (accountValidation)
{
builder.Append("User account " + samAccountName + " is invalid. ");
if ((isAccountActived != true) && (isAccountLocked))
{
builder.Append("Account is inactive and locked or expired.").Append('\n'); ;
} else if (isAccountActived != true)
{
builder.Append("Account is inactive.").Append('\n'); ;
}
else if (isAccountLocked)
{
builder.Append("Account is locked or has expired.").Append('\n'); ;
}
else
{
builder.Append("Unknown reason for status. Contact admin for help.").Append('\n'); ;
}
accountValidation = false;
}
//account is valid
if ((isAccountActived) && (isAccountLocked != true))
{
**//builder.Append("User account " + samAccountName + " is valid.").Append('\n');
accountValidation = true;
}
}
else Console.WriteLine("Nothing found.");
Console.WriteLine(builder);
}//end of using
return accountValidation;
}
You probably want to only write if builder has something otherwise it will print an empty line. Namely, change
Console.WriteLine(builder);
to
if (builder.Length > 0)
{
Console.WriteLine(builder);
}
or just
Console.Write(builder);
if you're going to handle all of the new lines in the builder itself. If you're going to do that, use StringBuilder.AppendLine() instead of hardcoding the '\n' like that.
StringBuilder.AppendLine https://msdn.microsoft.com/en-us/library/system.text.stringbuilder.appendline(v=vs.110).aspx
when i try to run the code below, I am getting
"Value cannot be null. Parameter name: type"
error at runtime.
How to handle this exception and why my objectName is null here? I am expecting objectName to hold the value of local user account on my computer.
namespace Users
{
class EnableDisableUsers
{
public static void Main(string[] args)
{
Console.WriteLine("Enter user account to be enabled or disabled");
var user = Console.ReadLine();
Console.WriteLine("Enter E to enable and D to disable the user account");
string enableStr = Console.ReadLine();
bool enable;
var computer = ".";
if (enableStr.Equals("E") || enableStr.Equals("e"))
{
enable = true;
var objectName = "WinNT://" + computer + "/" + user + ",user";
dynamic objUser = Activator.CreateInstance(Type.GetTypeFromProgID(objectName));
objUser.AccountDisabled = false;
objUser.SetInfo();
Console.WriteLine(user + " Enabled = " + result.ToString());
Console.ReadLine();
}
else if (enableStr.Equals("D") || enableStr.Equals("d"))
{
enable = false;
var objectName = "WinNT://" + computer + "/" + user + ",user";
dynamic objUser = Activator.CreateInstance(Type.GetTypeFromProgID(objectName));
objUser.AccountDisabled = true;
objUser.SetInfo();
Console.WriteLine(user + " Enabled = " + result.ToString());
Console.ReadLine();
}
else
{
Console.WriteLine("Operation for " + user + " failed ");
}
}
}
}
Any help will be useful.
How to handle this exception and why my objectName is null here?
objectName is not going to be null. The more likely scenario is that Type.GetTypeFromProgID(objectName) is returning null, because that prog-id doesn't exist, or the account doesn't have access.
Check what Type.GetTypeFromProgID(objectName) returns, and act accordingly. Make sure it is actually a prog-id, and that you are using that API correctly. For example:
var type = Type.GetTypeFromProgID(objectName);
if(type == null) throw new InvalidOperationException(
"Invalid prog-id: " + objectName);
dynamic objUser = Activator.CreateInstance(type);
Edit: Note that Activator.CreateInstance etc is not the same as VBScript's GetObject. To access that, reference Microsoft.VisualBasic.dll, and use:
dynamic obj = Microsoft.VisualBasic.Interaction.GetObject(objectName);