I am trying to make a program where permit's needs to be deleted from the user account. API's are used to pull up the user account and the permits. After the permits and restrictions are removed an event is created to confirm the deletion. Right now it's not giving me any output what so ever.
String User;
String License;
List<String> Permit;
public RemovePermit(String User, String license, List<String> Permit)
{
this.User = user;
this.License = license;
this.Permit = Permit;
}
public void Run()
{
List<PPermitGroups> permitGroupAdd = new List<PPermitGroups>();
using (var apiUser = new ApiUser())
{
var user = apiGetPerson(User);
var userPermit = apiGetPermitGroup(user.ID);
String license = License;
var deletePermitResult = userPermit.Where(x => Permit.Any(l => x.PermitGroup.Equals(l)|(!String.IsNullOrEmpty(x.Company)&& x.Company.Equals(l))));
foreach (PPermitGroups p in deletePermitResult)
{
apiDeletePermitAndRestrictions(p);
if(p.PermitGroupType == PPermitGroupsPermitGroupTypeEnum.ApplicationPermit)
if (p.LicenseType.Equals("Not Fixed") || p.LicenseType.Equals("Fixed"))
if (p.PermitGroup.StartsWith("Framework") || p.PermitGroup.StartsWith("Release"))
{
var temp = new UserEvent
EventType= " Delete"
License= ""
Permit = ""
}
api.CreateEvent(temp)
Related
i am currently making a application for my a level computing coursework. for my coursework i am required to make a login and registration system which requires me to store the user details in a text file this is only for my coursework so security isent important. my registration and login system works fine but i am also required to have a change account details screen in which the user can change their username and password.
my problem is that my code that i have currently changes the password for every user with the same password ie if 2 users have password123 as a password both their passwordds gets changed to the new password
private void btnUpdatePassword_Click(object sender, EventArgs e)
{
string oldusername = txtBoxOldUsername.Text;
string newusername = txtBoxNewUsername.Text;
string oldpassword = txtBoxOldPassword.Text;
string newpassword = txtBoxNewPassword.Text;
string text = File.ReadAllText("users.txt");
text = text.Replace(oldpassword, newpassword).Replace(oldusername, newusername);
File.WriteAllText("users.txt", text);
}
my problem is that i dont know how to change the password for only the correct user. it would be great if anyone could help thanks. also i HAVE to use a text file to do this meaning i cant use jason on xml etc
this is what my text file looks like
first user ~username~password
second user ~username123~password
third user ~username1234~password
and this is the code i use to write to the text file
FileStream fileStream = new FileStream("users.txt", FileMode.Append, FileAccess.Write);
StreamWriter streamWriter = new StreamWriter(fileStream);
try
{
streamWriter.WriteLine(fullname + "~" + username + "~" + password + "~" + lastlogin);
MessageBox.Show("User registered successfully", "Registration Successful");
this.Hide();
var homeForm = new HomeForm();
homeForm.Closed += (s, args) => this.Close();
homeForm.Show();
}
catch (Exception)
{
MessageBox.Show("Error registering the user", "Please try again");
}
finally
{
streamWriter.Close();
fileStream.Close();
}
Here is an idea on how to implement it. My first suggestion is to add a comma deliminator to your text file so your values in users.txt will be in the following form
second user~username123~password,
third user~username1234~password,
first user~username~smelly,
Import all the users from users.txt at once and split them by our deliminator ','
var users = File.ReadAllText(#"C:\users.txt").Split(',').ToList().Where(x=> !String.IsNullOrWhiteSpace(x));
Note this clause .Where(x=> !String.IsNullOrWhiteSpace(x) will be needed because when I rewrite the file , for simplicity sake I add a comma to each entry. As last entry will have a comma we end up with an extra empty object. This clause will rectify it.
Create a class which will contains all the user properties:
private class User
{
public string Name { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string PrepareForFile()
{
return Name + "~" + UserName + "~" + Password + ",";
}
}
Loop through all the retrieved users information from file and build a list of user:
List<User> myUsers = new List<User>();
foreach (var user in users)
{
var information = user.Split('~');
User temp = new User();
temp.Name = information[0].Trim();
temp.UserName = information[1].Trim();
temp.Password = information[2].Trim();
myUsers.Add(temp);
}
Now you have a manageable structure and you can perform all the desired operations. Once finished use the method PrepareForFile() to create a string like second user~username123~password to be written into file.
Putting it all together(this is a console app):
static class Program
{
private class User
{
public string Name { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string PrepareForFile()
{
return Name + "~" + UserName + "~" + Password + ",";
}
}
static void Main(string[] args)
{
var users = File.ReadAllText(#"C:\users.txt").Split(',').ToList().Where(x=> !String.IsNullOrWhiteSpace(x));
List<User> myUsers = new List<User>();
foreach (var user in users)
{
var information = user.Split('~');
User temp = new User();
temp.Name = information[0].Trim();
temp.UserName = information[1].Trim();
temp.Password = information[2].Trim();
myUsers.Add(temp);
}
var selectedUser = myUsers.Where(x => x.UserName == "username").SingleOrDefault();
myUsers.Remove(selectedUser);
selectedUser.Password = "Leo";
myUsers.Add(selectedUser);
List<string> formatForFile = new List<string>();
foreach(var item in myUsers)
{
formatForFile.Add(item.PrepareForFile());
}
File.WriteAllLines(#"C:\users.txt", formatForFile.ToArray());
}
}
Changing username1234 password from "password" to "AlexLeo":
Before
After
You can store the username with the password when saving the password and delete the username when it is extracted from the password and add the username when adding the password.
for example:
private void btnUpdatePassword_Click(object sender, EventArgs e)
{
string oldusername = txtBoxOldUsername.Text;
string newusername = txtBoxNewUsername.Text;
string oldpassword = txtBoxOldPassword.Text;
string newpassword = txtBoxNewPassword.Text;
string text = File.ReadAllText("users.txt");
text = text.Replace(oldpassword + oldusername, newpassword + newusername).Replace(oldusername, newusername);
File.WriteAllText("users.txt", text);
}
Based on your updated OP
string str = System.IO.File.ReadAllText(fileName);
var users = str.Split(new []{Environment.NewLine},StringSplitOptions.RemoveEmptyEntries)
.Select(x=>
{
var strArray = x.Split(new []{"~"},StringSplitOptions.RemoveEmptyEntries);
return new
{
FirstName = strArray[0],
User = strArray[1],
Password = strArray[2]
};
}
);
var usernameToUpdate = "username123";
var newPassword = "Thisisnewpassword";
var updatedList = users.Select(x => x.User.Equals(usernameToUpdate) ?
$"{x.FirstName} ~{x.User}~{newPassword}"
: $"{x.FirstName} ~{x.User}~{x.Password}").ToList();
var newFileData = String.Join(Environment.NewLine,
updatedList);
File.WriteAllText(fileName, newFileData);
I have an API that has devices firing data to it at the same time or within a few milliseconds. What I am finding is that the data is getting mixed up. The data is sent every five minutes (on the clock 05, 10, 15 etc.) I have an execution filter that traps the URL data coming in so I always have a real source, then it goes to the endpoint and then onto processing. For example, there will a be random five minute period missing. When I debug step by step with the missing URL from the execution filter it works fine. By that I mean I take the URL and debug, then it inserts.
In summary, I have device id 1 and device id 2.I will get missing intervals even though, I can see the data has hit the execution filter.
I am assuming that the API is not handling these as separate transactions, but somehow mixing them up together, hence the data missing and the serial numbers appearing in the wrong place, such that data from id 1 is appearing in id 2 vice versa etc.
API End Point:
public class SomeController : ApiController
{
[HttpGet]
[ExecutionFilter]
public async Task<HttpResponseMessage> Get([FromUri] FixedDataModel fdm)
{
var reply = new HttpResponseMessage();
string url = HttpUtility.UrlDecode(HttpContext.Current.Request.QueryString.ToString());
if (url.Contains("timestamp"))
{
reply = TimeSyncValidation.TimeSync;
return reply;
}
else if (!url.Contains("timestamp"))
{
reply = await Task.Run(() => DeviceClass.DeviceApiAsync(fdm, url));
}
return reply;
}
}
Processing class:
namespace API.Services
{
public class DeviceClass
{
private static string serialNumber;
private static byte chk;
private static string channelName, channelReadingNumber, channelValue, queryString, readingDate;
private static int colonPosition, chanCountFrom, equalsPosition;
private static bool checkSumCorrect;
public static HttpResponseMessage DeviceApiAsync(FixedDataModel fdm, string urlQqueryString)
{
Guid guid = Guid.NewGuid();
//ExecutionTrackerHandler.Guid = guid;
//Remove question mark
var q = urlQqueryString;
queryString = q.Substring(0);
var items = HttpUtility.ParseQueryString(queryString);
serialNumber = items["se"];
//Store raw uri for fault finding
var rawUri = new List<RawUriModel>
{
new RawUriModel
{
UniqueId = guid,
RawUri = q,
TimeStamp = DateTime.Now
}
};
//Checksum validation
chk = Convert.ToByte(fdm.chk);
checkSumCorrect = CheckSumValidator.XorCheckSum(queryString, chk);
if (!checkSumCorrect)
{
return ValidationResponseMessage.ResponseHeaders("Checksum");
}
//Create list of items that exist in URL
var urldata = new UrlDataList
{
UrlData = queryString.Split('&').ToList(),
};
var data = new List<UriDataModel>();
//Split the URL string into its parts
foreach (var item in urldata.UrlData)
{
colonPosition = item.IndexOf(":");
chanCountFrom = colonPosition + 1;
equalsPosition = item.LastIndexOf("=");
if (colonPosition == -1)
{
channelName = item.Substring(0, equalsPosition);
channelReadingNumber = "";
channelValue = item.Substring(item.LastIndexOf("=") + 1);
}
else
{
channelName = item.Substring(0, colonPosition);
channelReadingNumber = item.Substring(chanCountFrom, equalsPosition - chanCountFrom);
channelValue = item.Substring(item.LastIndexOf("=") + 1);
if (channelName == "atime" || channelName == "adate")
{
readingDate = DateValidator.CreateDate(channelValue);
}
};
bool nullFlag = false;
if (channelValue == null)
nullFlag = true;
bool missingFlag = false;
if (channelValue == "x") {
missingFlag = true;
channelValue = "0";
}
//Add data to model ready for DB insert.
data.Add(new UriDataModel
{
uid = guid,
SerialNumber = serialNumber,
ChannelName = channelName,
ChannelReadingNumber = channelReadingNumber,
ChannelValue = channelValue.Replace(",", "."),
ReadingDate = readingDate,
TimeStamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm"),
Processed = false,
NullFlag = nullFlag,
MissingFlag = missingFlag
});
};
//Validate dates
var allDates = (from x in data where x.ChannelName.Contains("atime") || x.ChannelName.Contains("adate") select x.ChannelValue).ToList();
bool dateValidation = DateValidator.IsValid(allDates);
if (!dateValidation)
{
return ValidationResponseMessage.ResponseHeaders("Date");
};
//Validate values
var channels = Enum.GetNames(typeof(Channels)).ToList();
List<string> allChannelValues = data.Where(d => channels.Contains(d.ChannelName)).Select(d => d.ChannelValue).ToList();
bool valueValidation = ValueValidator.IsValid(allChannelValues);
if (!valueValidation)
{
return ValidationResponseMessage.ResponseHeaders("Values");
};
//Insert live data
var insertData = DataInsert<UriDataModel>.InsertData(data, "Staging.UriData");
if (!insertData)
{
return ValidationResponseMessage.ResponseHeaders("Sql");
}
var content = "\r\nSUCCESS\r\n";
var reply = new HttpResponseMessage(System.Net.HttpStatusCode.OK)
{
Content = new StringContent(content)
};
return reply;
}
}
}
TIA
You are using global variables and static method to process your data.
Change your method to non-static.
Each DeviceClass worker must update only its own isolated data then push that off back to controller.
In my C# application I use 2 connection strings (application_cs, users_cs). To change these connection strings I use:
private static void SetProviderConnectionString(string connectionString)
{
var connectionStringFieldM =
Membership.Provider.GetType().GetField("_sqlConnectionString",
BindingFlags.Instance | BindingFlags.NonPublic);
var connectionStringFieldR = Roles.Provider.GetType().GetField("_sqlConnectionString",
BindingFlags.Instance | BindingFlags.NonPublic);
var connectionStringFieldP = ProfileManager.Provider.GetType().GetField("_sqlConnectionString",
BindingFlags.Instance | BindingFlags.NonPublic);
connectionStringFieldM.SetValue(Membership.Provider, connectionString);
connectionStringFieldR.SetValue(Roles.Provider, connectionString);
connectionStringFieldP.SetValue(ProfileManager.Provider, connectionString);
}
public static void SetProviderUsers()
{
SetProviderConnectionString(ConfigurationManager.ConnectionStrings["users_cs"].ConnectionString);
}
public static void SetProviderApp()
{
SetProviderConnectionString(ConfigurationManager.ConnectionStrings["application_cs"].ConnectionString);
}
So in my code whenever I want to add a user I do this:
public int CreateUser(int stid, int cid, int usrId, string email, string tel, string mob, string username,
bool create, bool prime)
{
int result = 0;
Guid userid = new Guid();
DALUsers.UserDBDataContext dc = new DALUsers.UserDBDataContext();
DAL.AppDataContext d = new DAL.AppDataContext();
BLL.Security.SetProviderUsers();
if (create) //create the user first
{
string question = "1";
string answer = "1";
bool isAproved = true;
string password = System.Web.Security.Membership.GeneratePassword(8, 2);
MembershipCreateStatus cs = new MembershipCreateStatus();
MembershipUser newUser = Membership.CreateUser(username, password, email, question, answer, isAproved, out cs);
Membership.UpdateUser(newUser);
Roles.AddUserToRole(username, "User_x");
if (cs == MembershipCreateStatus.Success)
{
result = 1;
}
else
X.MessageBox.Info("Error", "Cannot create user due to :" + cs.ToString(), UI.Danger).Show();
}
//at this point we have the user created either way.
// return userid;
var id = (from i in dc.aspnet_Users where i.UserName.CompareTo(username) == 0 select i.UserId);
if (id.Count() == 1)
{
userid = id.First();
bool contin = true;
var fulname = (from i in dc.Clients where i.id == usrId select i).First();
if (String.IsNullOrEmpty(fulname.Mobile)) fulname.Mobile = mob;
fulname.Email = email;
fulname.ModifiedBy = HttpContext.Current.User.Identity.Name;
fulname.ModifiedDate = DateTime.Now;
dc.SubmitChanges();
DateTime dt = DateTime.Now;
DALUsers.CIUser usr = new DALUsers.CIUser();
var existing = (from i in dc.CIUsers where i.UserName.CompareTo(username) == 0 && i.cid == cid select i);
if (existing.Count() > 0)
{
X.MessageBox.Info("Warning", "UserName already exists . Please try another!", UI.Warning).Show();
contin = false;
}
else
{
dc.CIUsers.InsertOnSubmit(usr);
dc.SubmitChanges();
}
if (contin)
{
DALUsers.CIUser usrNew = new DALUsers.CIUser();
var approved = (from k in dc.aspnet_Memberships //if user is not approved
where k.UserId == userid
select k).FirstOrDefault();
if (approved.IsApproved == false)
{
approved.IsApproved = true;
}
ProfileBase profile = ProfileBase.Create(username);
profile.SetPropertyValue("Mobile", mob);
profile.SetPropertyValue("Email", email);
profile.Save();
usrNew.UserId = usrId;
usrNew.cid = cid;
usrNew.FullName = fulname.LastName + " " + fulname.FirstName;
usrNew.Role = "User_x";
usrNew.SignRights = prime;
usrNew.IsPrime = prime;
usrNew.stid = stid;
usrNew.UserName = username;
usrNew.UserId = userid;
usrNew.CreatedDate = DateTime.Now;
usrNew.CreatedBy = HttpContext.Current.User.Identity.Name;
dc.CIUsers.InsertOnSubmit(usrNew);
dc.SubmitChanges();
result = 1;
X.MessageBox.Info("Success", "The user has been successfully added", UI.Success).Show();
}
}
else
X.MessageBox.Info("Error", "Could not find the user", UI.Danger).Show();
BLL.Security.SetProviderApp();
return result;
}
EDIT
I just saw that in my code there is this line:
DALUsers.aspnet_User user = new DALUsers.aspnet_User();
But the variable user is not used anywhere else in the code. Probably it has been left there... And its the only variable named user in my code. Is that causing the issue? But then why only on the production server?
EDIT
The weird part is that when I run my application from visual studio locally it works as a charm. But when I am adding a user in the application running on the production server when I am trying to add the second user it fails and I receive this error:
Value cannot be null. Parameter name: user
And if I try to login to my application after that it fails. I have to restart my website from iis to be able to login again.
Any ideas?
Well I cant find the error in your code but if you say that this error occurs only in server and that you are sure that your files are synched between server and your local machine, then probably the error lies in your web.config. Take a look
For a specific VM, I want to be able to retrieve the public IP address.
I know how to get all public IP addresses for a resource group, I also know how to get a nic-id for a specific VM - but I can't figure out how to connect the two.
This is what I have:
var resourceGroupName = "My-Resource-Group";
var vmName = "MyVM";
var subscriptionId = "bzz-bzz-bzz-bzz-bzz-bzz";
var tenantId = "bar-bar-bar-bar-bar-bar";
string clientId = "foo-foo-foo-foo-foo-foo";
string clientSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
var token = GetAccessTokenAsync(tenantId, clientId, clientSecret);
var credential = new TokenCredentials(token.Result.AccessToken);
var computeManagementClient = new ComputeManagementClient(credential) { SubscriptionId = subscriptionId };
var vmResult = await computeManagementClient.VirtualMachines.GetAsync(resourceGroupName, vmName, InstanceViewTypes.InstanceView);
//Get the NIC ID for the VM:
foreach (NetworkInterfaceReference nic in vmResult.NetworkProfile.NetworkInterfaces)
{
Console.WriteLine(" networkInterface id: " + nic.Id);
}
this gives me something like this:
/subscriptions/[guid]/resourceGroups/My-Resource-Group/providers/Microsoft.Network/networkInterfaces/myvm123
To get all public IPs for the resource group, I can do this:
using (var client = new NetworkManagementClient(credential))
{
client.SubscriptionId = subscriptionId;
foreach (var publicIpAddress in client.PublicIPAddresses.ListAll())
{
Console.WriteLine(publicIpAddress.IpAddress);
}
}
...But inspecting the properties of the nic-id and the public ip object, there are no obvious ways to get from one to the other.
Question:
How do I get from the nic-id string, to the actual public IP address for that VM/nic?
Helper function:
private static async Task<AuthenticationResult> GetAccessTokenAsync(string tenantId, string clientId, string clientSecret)
{
var cc = new ClientCredential(clientId, clientSecret);
var context = new AuthenticationContext($"https://login.windows.net/{tenantId}");
var token = context.AcquireToken("https://management.azure.com/", cc);
if (token == null)
{
throw new InvalidOperationException("Could not get the token");
}
return token;
}
I found a workaround. Not pretty, but it works.
It assumes you already have a Microsoft.Azure.Management.Compute.Models.VirtualMachine object from something like this:
VirtualMachine vmResult = await computeManagementClient.VirtualMachines.GetAsync(resourceGroupName, vmName, InstanceViewTypes.InstanceView);
Then you can take the first NIC, get the last part of that as an ID:
var firstNic = vmResult.NetworkProfile.NetworkInterfaces.First();
var nicNameParts = firstNic.Id.Split('/');
string networkIntefaceName = nicNameParts.Last();
using (var client = new NetworkManagementClient(credential))
{
client.SubscriptionId = subscriptionId;
string publicNicId = string.Empty;
//Query ALL Networkinterfaces in the client, and find the one with the matching NIC-name
var nic = client.NetworkInterfaces.ListAll().FirstOrDefault(x => x.Name == networkIntefaceName);
if (nic != null)
{
//If we find that, we can now use that to find the ID of the PublicIPAddress for said NIC
publicNicId = nic.IpConfigurations[0].PublicIPAddress.Id;
//...And when we have that, we can now query all public IP addresses for that specific public Nic ID
var publicIp = client.PublicIPAddresses.ListAll().FirstOrDefault(x => x.Id == publicNicId);
if (publicIp != null)
{
vmInfo.PublicIP = publicIp.IpAddress;
Console.WriteLine(" public ip: " + publicIp.IpAddress);
}
else
{
Console.WriteLine(" public ip: unknown");
}
}
}
Yes, it is not super elegant, it can be optimized etc - but it works, so that's a start. :)
I have two sub-sites in my sharepoint site,SampleSite1 and SampleSite2 under Parentsite called MainSite.
http://xyz.sharepoint.com/sites/MainSite/ - SiteUrl
http://xyz.sharepoint.com/sites/MainSite/SampleSite1 - Subsite1's Url
http://xyz.sharepoint.com/sites/MainSite/SampleSite2 - Subsite2's Url
Each of the Sites have two groups superUser and NormalUser respectively.
The credential uses SiteUrl of MainSite.
SecureString password = new SecureString();
string pwd = "Pass123";
string UserName = "abc#xyz.com";
password = convertToSecureString(pwd);
ClientContext clientContext = new ClientContext("http://xyz.sharepoint.com/sites/MainSite/");
clientContext.Credentials = new SharePointOnlineCredentials(UserName, password);
Incase of adding user to subsite's groups like NormalUser,Can we use the same sharepoint context with above siteUrl to access and perform operations(add/remove user) in groups present under subsites?
If Yes,how can we do it?I already have built code to add or remove user from a sharepoint site group based on some requirement.
public void AddUserToDMSite(string useremail, string securityGroupName)
{
GroupCollection collGroup = SPContext.Web.SiteGroups;
Group oGroup1 = collGroup.GetByName("UserList");
Group oGroup2 = collGroup.GetByName(securityGroupName);
UserCollection oUserCollection1 = oGroup1.Users;
UserCollection oUserCollection2 = oGroup2.Users;
SPContext.Load(oUserCollection1);
SPContext.Load(oUserCollection2);
SPContext.ExecuteQuery();
var uname = oGroup1.Users.GetByEmail(useremail);
var userCheck = oUserCollection2.Where(u => u.Email == useremail).FirstOrDefault();
if (userCheck == null)
{
Microsoft.SharePoint.Client.User oUser2 = oGroup2.Users.AddUser(uname);
}
SPContext.ExecuteQuery();
}
For subsites you can proceed as follows:
Web oWebsite = clientContext.Web;
clientContext.Load(oWebsite, website => website.Webs);
clientContext.ExecuteQuery();
foreach (Web orWebsite in oWebsite.Webs)
{
AddUserToDMSite(useremail, securityGroupName, orWebSite)
}
and change AddUserToDMSite to work with either sites and subsites as:
public void AddUserToDMSite(string useremail, string securityGroupName, Web aWeb)
{
GroupCollection collGroup = aWeb.SiteGroups;
Group oGroup1 = collGroup.GetByName("UserList");
Group oGroup2 = collGroup.GetByName(securityGroupName);
UserCollection oUserCollection1 = oGroup1.Users;
UserCollection oUserCollection2 = oGroup2.Users;
SPContext.Load(oUserCollection1);
SPContext.Load(oUserCollection2);
SPContext.ExecuteQuery();
var uname = oGroup1.Users.GetByEmail(useremail);
var userCheck = oUserCollection2.Where(u => u.Email == useremail).FirstOrDefault();
if (userCheck == null)
{
Microsoft.SharePoint.Client.User oUser2 = oGroup2.Users.AddUser(uname);
}
SPContext.ExecuteQuery();
}