I have an array of strings that contains usernames that I'd like to extract and add it to a list. So for example, I have this string => "UserName: JohnSmith" and I want to extract JohnSmith. The below is the code I'm attempting to get working:
var documentSource = content.Replace("\n" , "").Trim();
string[] contents = documentSource.Split(',');
List<Model> modelList = new List<Model>();
Model model = new Model();
foreach (var item in contents)
{
//this is where I'd like to locate the username or usernames
if(item.Any())
{
model.userName = //username only;
modelList.Add(model);
}
}
return modelList;
This is the kind of problem that can be easily solved with regular expressions:
using System.Text.RegularExpressions;
// ...
var regex = new Regex("UserName: ([^,]*)");
// ..
foreach(var item in contents)
{
var match = regex.Match(item);
if(match.Success)
{
modelList.Add(
new Model
{
userName = match.Groups[1].Value
}
);
}
}
In it's simplest form, since you know that each username start after "UserName: " part that is fixed, it would be something like this:
var documentSource = content.Replace("\n" , "").Trim();
string[] contents = documentSource.Split(',', StringSplitOptions.RemoveEmptyEntries);
var modelList = new List<Model>();
foreach (var item in contents)
{
var username = item.Substring("UserName: ".Length).Trim();
if (!string.IsNullOrEmpty(username))
{
Model model = new Model();
model.userName = username;
modelList.Add(model);
}
}
return modelList;
Since you know that you have one : inside of the username string and the second part of the : is your actual username that you want, so, you can split the string in two parts and get the second one. Something like below:
foreach (var item in contents)
{
var username = item.Split(':').Last()?.Trim();
if(!string.IsNullOrEmpty(username))
{
modelList.Add(new Model{ userName = username });
}
}
Related
I have this Action method which act as an API end point inside our ASP.NET MVC-5, where it search for a username and return the username Phone number and Department from Active Directory (we are serializing the object using Newtonsoft.net):-
public ActionResult UsersInfo2()
{
DomainContext result = new DomainContext();
try
{
// create LDAP connection object
DirectoryEntry myLdapConnection = createDirectoryEntry();
string ADServerName = System.Web.Configuration.WebConfigurationManager.AppSettings["ADServerName"];
string ADusername = System.Web.Configuration.WebConfigurationManager.AppSettings["ADUserName"];
string ADpassword = System.Web.Configuration.WebConfigurationManager.AppSettings["ADPassword"];
using (var context = new DirectoryEntry("LDAP://mydomain.com:389/DC=mydomain,DC=com", ADusername, ADpassword))
using (var search = new DirectorySearcher(context))
{
// create search object which operates on LDAP connection object
// and set search object to only find the user specified
// DirectorySearcher search = new DirectorySearcher(myLdapConnection);
// search.PropertiesToLoad.Add("telephoneNumber");
search.Filter = "(&(objectClass=user)(sAMAccountName=test.test))";
SearchResult r = search.FindOne();
ResultPropertyCollection fields = r.Properties;
foreach (String ldapField in fields.PropertyNames)
{
// cycle through objects in each field e.g. group membership
// (for many fields there will only be one object such as name)
string temp;
// foreach (Object myCollection in fields[ldapField])
// {
// temp = String.Format("{0,-20} : {1}",
// ldapField, myCollection.ToString());
if (ldapField.ToLower() == "telephonenumber")
{
foreach (Object myCollection in fields[ldapField])
{
result.Telephone = myCollection.ToString();
}
}
else if (ldapField.ToLower() == "department")
{
foreach (Object myCollection in fields[ldapField])
{
result.Department = myCollection.ToString();
}
}
// }
}
string output = JsonConvert.SerializeObject(result);
return Json(output,JsonRequestBehavior.AllowGet);
}
}
catch (Exception e)
{
Console.WriteLine("Exception caught:\n\n" + e.ToString());
}
return View(result);
}
now the return JSON will be as follow:-
"\"DisplayName\":null,\"Telephone\":\"123123\",\"Department\":\"IT\",\"Name\":null,\"SamAccountName\":null,\"DistinguishedName\":null,\"UserPrincipalName\":null}"
but in our case we need to return a status code beside the return json data. for example inccase there is an exception we need to return an error code,also if we are able to get the user's info we need to pass succes code 200, and so on.. so how we can achieve this?
you can try something like this
var statusCode=200;
string output = JsonConvert.SerializeObject( new { result = result, StatusCode = statusCode);
but nobody usually do this. When users call API they can check status code that HTTP Client returns, using code like this
var response = await client.GetAsync(api);
//or
var response = await client.PutAsJsonAsync(api, data);
var statusCode = response.StatusCode.ToString();
//or usually
if (response.IsSuccessStatusCode) {...}
else {...}
I am trying to get a list of item ids with the code below, not a list of items, but I am not getting any Ids although the response message has Count set to the expected number of items. Could you please let me know if it is possible to get item ids only without item contents and how? Thanks.
string query = "select r.Id from root r where r.itemType = #itemType";
QueryDefinition queryDefinition = new QueryDefinition(query);
queryDefinition.WithParameter("#itemType", ItemType.Banana);
using (var feedIterator = container.GetItemQueryStreamIterator(queryDefinition))
{
while (feedIterator.HasMoreResults)
{
using (ResponseMessage responseMessage = await feedIterator.ReadNextAsync())
{
using (StreamReader streamReader = new StreamReader(responseMessage.Content))
{
using (JsonTextReader jsonTextReader = new JsonTextReader(streamReader))
{
JsonSerializer jsonSerializer = new JsonSerializer();
JObject content = jsonSerializer.Deserialize<JObject>(jsonTextReader);
if (content.ContainsKey("Documents"))
{
foreach (var doc in content["Documents"])
{
// why doc is empty?
}
}
}
}
}
}
}
To just get the ids back without each one being it's own document, change your query to select value(r.Id) from root r where r.itemType = #itemType
I get this error when running this code. I have looked for solution though I don't like the idea of using MARS as people have suggested as it may contain a lot of data, is there any other option here? Also can I edit a variable in a database without rewriting all of them as I do here, will this save server power or make no difference?
There is already an open DataReader associated with this Command which must be closed first.
public ActionResult CheckLinks(Link model)
{
var userId = User.Identity.GetUserId();
var UserTableID = db.UserTables.Where(c => c.ApplicationUserId == userId).First().ID;
foreach (var item in db.Links.Where(p => p.UserTable.ID == UserTableID))
{
string pageContent = null;
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(item.Obdomain);
HttpWebResponse myres = (HttpWebResponse)myReq.GetResponse();
using (StreamReader sr = new StreamReader(myres.GetResponseStream()))
{
pageContent = sr.ReadToEnd();
}
string live = "";
if (pageContent.Contains(item.Obpage))
{
live = "Yes";
}
else { live = "No"; }
var link = new Link { Obdomain = item.Obdomain, ClientID = item.ClientID, Obpage = item.Obpage, BuildDate = item.BuildDate, Anchor = item.Anchor, IdentifierID = item.IdentifierID, live = (Link.Live)Enum.Parse(typeof(Link.Live), live), UserTableID = item.UserTableID };
db.Entry(link).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("Index");
}
Entity Framework allows only one active command per context at a time. You should add .ToList() at the end of the following statement:
db.Links.Where(p => p.UserTable.ID == UserTableID).ToList();
So your code could look like this:
var items = db.Links.Where(p => p.UserTable.ID == UserTableID).ToList();
foreach (var item in items)
LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.
public ActionResult PopulateFromDB(string sidx, string sord, int page, int rows)
{
var context = new NerdDinnerEntities();
var jsonData = new
{
total = 1,
page = page,
sord =sord,
records = context.Authors.Count(),
rows = (from n in context.Authors
select new
{ AuthorId = n.AuthorId ,
cell = new string[] { n.AuthorId.ToString(), n.Name.ToString(), n.Location.ToString() }
}).ToList()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
I am writting ToList or Toarray is it not working the error comes :
public ActionResult PopulateFromDB(string sidx, string sord, int page, int rows)
{
var context = new NerdDinnerEntities();
var jsonData = new
{
total = 1,
page = page,
sord =sord,
records = context.Authors.Count(),
rows = (from n in context.Authors
select new
{ AuthorId = n.AuthorId ,
cell = new string[] { n.AuthorId.ToString(), n.Name.ToString(), n.Location.ToString() }
}).ToList()
};
return Json(jsonData,JsonRequestBehavior.AllowGet);
}
From your code I assume your adding a custom property cell for display/storage purposes on the client-side. I would avoid this as your essentially coupling your API call to one particular client. I would suggest you simply return the data required & deal with it at the client-side specifically e.g.
Server
...
select new
{
Id = n.AuthorId,
Name = n.Name,
Location = n.Location
}).ToList();
...
Client
var response = ...
foreach (var author in response)
{
var cell = new string[] { author.Id.ToString(), author.Name, author.Location };
// do something with cell
}
You should try SqlFunctions.StringConvert to convert this, There is no overload for int so you should cast your number to a double or a decimal.
public ActionResult PopulateFromDB(string sidx, string sord, int page, int rows)
{
var context = new NerdDinnerEntities();
var jsonData = new
{
total = 1,
page = page,
sord =sord,
records = context.Authors.Count(),
rows = (from n in context.Authors
select new
{ AuthorId = n.AuthorId ,
cell = new string[] { SqlFunctions.StringConvert((double)n.AuthorId), n.Name, n.Location }
}).ToList()
};
return Json(jsonData,JsonRequestBehavior.AllowGet);
}
You are not using LinqToSql Classes, if you were using that your code should work, but as you mention that you are using LinqToEntity then You should use SqlFunctions.StringConvert to convert to string.
I am trying to retrieve all the email gruops and their mail address from company's AD system. I've got about 1800 groups but I've found there are about 20 gourps which I cannot get their properties. I tried in my outlook and got properties like mail address correctly. But I cannot get them by code, someone please help. Thanks. Below is my code snippet:
static void TestGroupEmails()
{
ICollection<DirectoryEntry> groups = GetGroups();
Console.WriteLine(groups.Count + "groups");
List<String> noNameGroups = new List<String>();
foreach (DirectoryEntry de in groups)
{
String name = de.Properties["sAMAccountName"].Value as String;
String email = de.Properties["mail"].Value as String;
if (String.IsNullOrEmpty(email))
noNameGroups.Add(name);
}
StreamWriter writer = new StreamWriter(#"C:\ad\group mails.txt");
noNameGroups.Sort();
foreach (String name in noNameGroups)
{
writer.WriteLine(name);
}
writer.Close();
Console.ReadLine();
}
public static List<DirectoryEntry> GetGroups()
{
String filter = #"(&(objectCategory=group))";
List<DirectoryEntry> groups = new List<DirectoryEntry>();
using (DirectoryEntry root = new DirectoryEntry(Constants.ADConnPrefix))
{
using (DirectorySearcher searcher = new DirectorySearcher(filter, null))
{
searcher.PageSize = 10000;
searcher.ReferralChasing = ReferralChasingOption.All;
searcher.SearchScope = SearchScope.Subtree;
searcher.SearchRoot = root;
root.Username = Constants.UserName;
root.Password = Constants.Password;
using (SearchResultCollection searchResult = searcher.FindAll())
{
foreach (SearchResult sr in searchResult)
{
DirectoryEntry de = sr.GetDirectoryEntry();
groups.Add(de);
}
}
}
}
return groups;
}
public static SearchResult GetGroupInfo(String groupName)
{
String normalName = Utility.RemoveLoginNamePrefix(groupName);
String filterFormat = "(&(objectCategory=group)(sAMAccountName={0}))";
using (SearchResultCollection searchResult = Search(ADConnPrefix, null, filterFormat, normalName))
{
int count = searchResult.Count;
SearchResult sr = searchResult[0];
return sr;
}
}
Are you certain the groups in question actually have email addresses? It is possible for groups in AD to not have them.
If you modify your search filter to (&(objectCategory=group)(mail=*)) it will filter out any groups that don't have email addresses.