certain user(s) can only use a command - c#

Essentially this program allows a user to use a command !weaponrequest, it then saves their request into a list, with !nextweapon you can see what the next weapon in the list is, this allows a streamer to take weapon requests in a game with a fully automated system.
Anyway moving onto my problem, I need a way to make it so that a certain user(s) can only use a command. I know that I am going to need a list to store the users in. I will write them in manually so I don't need any kind of system for that. All I am wondering is using an IF statement how would I check to see if the user is in this list and then make it so that only that user(s) can activate that command and receive a response.
case "nextweapon":
{
if (new FileInfo("MyFile.txt").Length == 0)
{
irc.sendChatMessage("There are no weapons in the list!");
break;
}
string Lines = File.ReadLines("MyFile.txt").Take(1).First();
//irc.sendChatMessage(Lines);
List<string> WeaponList = File.ReadAllLines("MyFile.txt").ToList();
string FirstItem = WeaponList[0];
WeaponList.RemoveAt(0);
File.WriteAllLines("MyFile.txt", WeaponList.ToArray());
irc.sendChatMessage(Lines);
break;
}
This is the command that I want to only be used by a certain user(s).

Add your special users from a source (in-code, text, database, etc.) into a List<string> variable using the List<string>.Add(strUserName) function.
List<string> lstCertainUsers = new List<string>();
/*
* ToDo: Add users from source (in-code, text, database, etc.) into lstCertainUsers
*/
Then, get the list of users and check if it contains the certain user.
// Check if user has access to special commands
if (lstCertainUsers.Contains(strUserName))
{
/* nextweapon code here */
}

if ((username == "") || (username == "") || (username == ""))
{
}
This is how I solved the issue, it's not the most efficient way but there are only limited users that I needed so making a list was not necessary.
Obviously you need to replace the names with your own names you want to be able to use the command. For example:
(username == "RandomStranger")
{
}

You'd read the file into a buffer, split it line-by-line, loop through those lines and break the loop if and when their username is found. I'm not used to C# but the following pseudocode should highlight my idea:
username = /* the current user's username */;
userfile = readfile('users.txt');
userlist = split(userfile, "\n");
is_valid = false;
for user in userlist
if user equals username
command_is_valid = true;
break;
if command_is_valid:
// your code
else
// do nothing
I'm sure there's a better way to do it because, as I say, I'm not used to C#. On another note, MyFile.txt probably isn't the best name for your flat-file database. Hope this helps!

Related

How to point to the correct Store in Outlook automation by C#?

I have a lot of VBA automation that interlinks an Outlook and Word solution; it is fine, but time is inexorable... so, I'm start to decorating and extending that old solution, wraping it with C#/VS2017.
Through a conventional Winform I can choose my patients, and from this action I do a lot of actions, including open the correct Outlook contact; that's the problem, because I can't get the correct Store; the patients.pst, depending on the machine, may be the 1st, 2nd, 3rd...
In VBA I do this:
WhichStoreNameToPointAt="patients"
Set myNamespace = myolApp.GetNamespace("MAPI")
For i = 1 To myNamespace.Stores.Count Step 1
If myNamespace.Stores.item(i).DisplayName = WhichStoreNameToPointAt Then
intOutlookItemStore = i
End if
End If
Set myFolderPatients = myNamespace.Stores.item(intOutlookItemStore).GetDefaultFolder(olFolderContacts)
And it always functions like a charm.
In C# I tried a lot of variations, and could not point to the correct store:
public void OpenPatientContact(string patientName)
{
Outlook.Store whichStore = null;
Outlook.NameSpace nameSpace = OlkApp.Session;
int i = 1;
foreach (Outlook.Folder folder in nameSpace.Folders)
{
bool p = false;
if (whichStoreNameToPointAt == folder.Name)
{
p = true;
whichStore = folder.Store;
//Correct Store selected; I can tell because of this watch:
//whichStore.displayname == whichStoreNameToPointAt
}
i++;
if (p)
break;
}
var contactItemsOlk = whichStore.Session.GetDefaultFolder
(Outlook.OlDefaultFolders.olFolderContacts).Items;
// The problem is below; always the first Store
Outlook.ContactItem contact = (Outlook.ContactItem)contactItemsOlk
.Find(string.Format("[FullName]='{0}'", patientName)); //[1];
if (contact != null)
{
contact.Display(true);
}
else
{
MessageBox.Show("The contact information was not found.");
}
}
Unfortunately, it keeps pointing ever to the same first Store, the one that has no patients...
If I change the Store order I can get past this and test other stuff, but of course it is not the right way.
Any other heads/eyes to see the light?
TIA
While seated writing the question, looking at a yellow rubber duck - and a lot of other stuff that belongs to my 1 yo daughter ;), I realized that whichStore.Session.GetDefaultFolder is a little strange in this context. I only changed this
var contactItemsOlk = whichStore.Session.GetDefaultFolder
(Outlook.OlDefaultFolders.olFolderContacts).Items;
To that:
var contactItemsOlk = whichStore.GetDefaultFolder
(Outlook.OlDefaultFolders.olFolderContacts).Items;
Voilá! Magic happens with C# too!
Session returns the default NameSpace object for the current session.
PS: yellow rubber duck; guys of The Pragmatic Programmer really knows some secrets and tricks ;)
Thanks Thomas and Hunt!

Visual Studio Debugger Extension get user settings

I'm writing a visual studio extension based on the Concord Samples Hello World project. The goal is to let the user filter out stack frames by setting a list of search strings. If any of the search strings are in a stack frame, it is omitted.
I've got the filter working for a hardcoded list. That needs to be in a non-package-based dll project in order for the debugger to pick it up. And I have a vsix project that references that dll with an OptionPageGrid to accept the list of strings. But I can't for the life of me find a way to connect them.
On the debugger side, my code looks something like this:
DkmStackWalkFrame[] IDkmCallStackFilter.FilterNextFrame(DkmStackContext stackContext, DkmStackWalkFrame input)
{
if (input == null) // null input frame indicates the end of the call stack. This sample does nothing on end-of-stack.
return null;
if (input.InstructionAddress == null) // error case
return new[] { input };
DkmWorkList workList = DkmWorkList.Create(null);
DkmLanguage language = input.Process.EngineSettings.GetLanguage(new DkmCompilerId());
DkmInspectionContext inspection = DkmInspectionContext.Create(stackContext.InspectionSession, input.RuntimeInstance, input.Thread, 1000,
DkmEvaluationFlags.None, DkmFuncEvalFlags.None, 10, language, null);
string frameName = "";
inspection.GetFrameName(workList, input, DkmVariableInfoFlags.None, result => GotFrameName(result, out frameName));
workList.Execute();
CallstackCollapserDataItem dataItem = CallstackCollapserDataItem.GetInstance(stackContext);
bool omitFrame = false;
foreach (string filterString in dataItem.FilterStrings)
{
if (frameName.Contains(filterString))
{
omitFrame = true;
}
}
The CallstackCollapserDataItem is where I theoretically need to retrieve the strings from user settings. But I don't have access to any services/packages in order to e.g. ask for WritableSettingsStore, like in You've Been Haacked's Example. Nor can I get my OptionPageGrid, like in the MSDN Options Example.
The other thing I tried was based on this StackOverflow question. I overrode the LoadSettingsFromStorage function of my OptionPageGrid and attempted to set a static variable on a public class in the dll project. But if that code existed in the LoadSettingsFromStorage function at all, the settings failed to load without even entering the function. Which felt like voodoo to me. Comment out the line that sets the variable, the breakpoint hits normally, the settings load normally. Restore it, and the function isn't even entered.
I'm at a loss. I really just want to pass a string into my Concord extension, and I really don't care how.
Ok, apparently all I needed to do was post the question here for me to figure out the last little pieces. In my CallstackCollapserDataItem : DkmDataItem class, I added the following code:
private CallstackCollapserDataItem()
{
string registryRoot = DkmGlobalSettings.RegistryRoot;
string propertyPath = "vsix\\CallstackCollapserOptionPageGrid";
string fullKey = "HKEY_CURRENT_USER\\" + registryRoot + "\\ApplicationPrivateSettings\\" + propertyPath;
string savedStringSetting = (string)Registry.GetValue(fullKey, "SearchStrings", "");
string semicolonSeparatedStrings = "";
// The setting resembles "1*System String*Foo;Bar"
if (savedStringSetting != null && savedStringSetting.Length > 0 && savedStringSetting.Split('*').Length == 3)
{
semicolonSeparatedStrings = savedStringSetting.Split('*')[2];
}
}
vsix is the assembly in which CallstackCollapserOptionPageGrid is a DialogPage, and SearchStrings is its public property that's saved out of the options menu.

Selenium entering invalid text (Half text) in text box

While running multiple test cases, selenium is entering invalid text as shown in the attachment.
Below are the two Examples showing the error:
Instead of entering AutomationTest123_6035633258972, it just enters 6035633258972. .
Instead of Entering AutomationTest123_636010703068635512, it just
enters utomationTest123_636010703068635512. .
Code
//StaticVariable is class which has static values
var username = StaticVariable.username;
var password = StaticVariable.password;
driver.FindElement(By.Id("username")).SendKeys(username); //putting wrong values
driver.FindElement(By.Id("password")).SendKeys(password); //putting wrong values
driver.FindElement(By.Id("login")).Click();
Can anyone help me on this? Any help would appreciated.
first of all make sure that
var username = StaticVariable.username;
is assigning the right value.
use a
print
to check what the value of username after assign.
than try by using the below code:
driver.FindElement(By.Id("username")).click()
driver.FindElement(By.Id("username")).clear()
driver.FindElement(By.Id("username")).SendKeys(username);
There can be a couple of reasons I've seen that this can be an issue. I'd first try to clear out the text input first and make sure it has focus.
var username = StaticVariable.username;
var password = StaticVariable.password;
// Fill out user name
var userElem = driver.findElement(By.id("username"));
userElem.click();
userElem.clear();
userElem.sendKeys(userName);
// Fill out password
var passElem = driver.findElement(By.id("password"));
passElem.click();
passElem.clear();
passElem.sendKeys(password);
// Click login button
driver.findElement(By.id("login"))
.click();
If, however, that doesn't fix it, I've had situations where splitting the string up and sending keys a few at a time has worked. That does have a performance penalty so I wouldn't do it unless you really really need to.
public void fooTest() {
// Do stuff to get to the correct page, etc
var username = StaticVariable.username;
var password = StaticVariable.password;
// Fill out user name
var userElem = driver.findElement(By.id("username"));
sendKeys(userElem, userName);
// Fill out password
var passElem = driver.findElement(By.id("password"));
sendKeys(passElem, password);
// Click login button
driver.findElement(By.id("login"))
.click();
// do assertions, etc
}
private void sendKeys(WebElement elem, String keys) {
elem.click();
elem.clear();
for (int i = 0; i < keys.length(); i) {
elem.sendKeys(keys.charAt(i));
}
}
Note : sorry for any syntax / c# errors, I've barely used the language ... I'm much more familiar with Java ;-)
Use the clear method then type the text: driver.findElement(By.cssSelector("").clear();
It may help.
Rather than using 'var' , you might want to try putting in the specific type , such as 'string'. The problem has to be in what is being passed to .SendKeys() or how it is being received by the function.
string username = StaticVariable.username;
string password = StaticVariable.password;

Can not find data from the dbcontext with linq

I am trying to develop a "password reset" functionality. To achieve this, I am generating a guid when a user requests a password reset and send this as an email, with a link to the password reset page, that has the guid as a query string.
The code I have written is below:
Request.QueryString[BusinessLayerConstants.resetPasswordQueryString]) ? Request.QueryString[BusinessLayerConstants.resetPasswordQueryString] : String.Empty;
passwordCode = System.Web.HttpUtility.UrlDecode(passwordCode);
using (DBEntities entities = new DBEntities())
{
User = entities.AspNetUsers.FirstOrDefault(u => u.PasswordReset == passwordCode);
if (User != null)
{
//TODO
}
}
The problem is, linq always returns null. If I run a SQL command in the database with the same guid, I am able to see the data. And the passwordCode variable is getting the right value as well. I have even checked if the passwordCode has some hidden characters because it is coming from the query string; but it is also fine.
I am also using this exact same logic for activation as well. I am passing a guid as a query string, and for activation, I am able to find the data with the following code:
AspNetUser user = entities.AspNetUsers.FirstOrDefault(u => u.ActivationCode == activationCode);
It is not working for the password, I have also tried using .Equals() and .Contains() with no luck.
If anyone has any idea what might be wrong, I would appreciate any help. Thanks.
EDIT:
PasswordReset is just some GUID I generate to pass as a querystring.
Everything is fine when I do this:
But in the code, the code I have written returns null:
Remember that C# is case sensitive you should do like:
Request.QueryString[BusinessLayerConstants.resetPasswordQueryString]) ? Request.QueryString[BusinessLayerConstants.resetPasswordQueryString] : String.Empty;
passwordCode = System.Web.HttpUtility.UrlDecode(passwordCode);
using (DBEntities entities = new DBEntities())
{
User = entities.AspNetUsers.FirstOrDefault(u => u.PasswordReset.ToLower() == passwordCode.ToLower());
if (User != null)
{
//TODO
}
}

Sitecore workflow approval/rejection emails

We are working on implementing some custom code on a workflow in a Sitecore 6.2 site. Our workflow currently looks something like the following:
Our goal is simple: email the submitter whether their content revision was approved or rejected in the "Awaiting Approval" step along with the comments that the reviewer made. To accomplish this we are adding an action under the "Approve" and "Reject" steps like so:
We are having two big issues in trying to write this code
There doesn't seem to be any easy way to determine which Command was chosen (the workaround would be to pass an argument in the action step but I'd much rather detect which was chosen)
I can't seem to get the comments within this workflow state (I can get them is the next state though)
For further context, here is the code that I have so far:
var contentItem = args.DataItem;
var contentDatabase = contentItem.Database;
var contentWorkflow = contentDatabase.WorkflowProvider.GetWorkflow(contentItem);
var contentHistory = contentWorkflow.GetHistory(contentItem);
//Get the workflow history so that we can email the last person in that chain.
if (contentHistory.Length > 0)
{
//contentWorkflow.GetCommands
var status = contentWorkflow.GetState(contentHistory[contentHistory.Length - 1].NewState);
//submitting user (string)
string lastUser = contentHistory[contentHistory.Length - 1].User;
//approve/reject comments
var message = contentHistory[contentHistory.Length - 1].Text;
//sitecore user (so we can get email address)
var submittingUser = sc.Security.Accounts.User.FromName(lastUser, false);
}
I ended up with the following code. I still see no good way to differentiate between commands but have instead implemented two separate classes (one for approve, one for reject):
public void Process(WorkflowPipelineArgs args)
{
//all variables get initialized
string contentPath = args.DataItem.Paths.ContentPath;
var contentItem = args.DataItem;
var contentWorkflow = contentItem.Database.WorkflowProvider.GetWorkflow(contentItem);
var contentHistory = contentWorkflow.GetHistory(contentItem);
var status = "Approved";
var subject = "Item approved in workflow: ";
var message = "The above item was approved in workflow.";
var comments = args.Comments;
//Get the workflow history so that we can email the last person in that chain.
if (contentHistory.Length > 0)
{
//submitting user (string)
string lastUser = contentHistory[contentHistory.Length - 1].User;
var submittingUser = Sitecore.Security.Accounts.User.FromName(lastUser, false);
//send email however you like (we use postmark, for example)
//submittingUser.Profile.Email
}
}
I have answered a very similar question.
Basically you need to get the Mail Workflow Action and then you need to further extend it to use the original's submitter's email.
Easiest way to get the command item itself is ProcessorItem.InnerItem.Parent
This will give you the GUID for commands like submit, reject etc.
args.CommandItem.ID
This will give you the GUID for states like Draft, approved etc.
args.CommandItem.ParentID

Categories