I am surely missing something small here. I am trying to open multiple resx files, load them into a dictionary, then cross reference a translation file. The problem is that when I open up the resx file with resxResourceReader, it reads in all the the form setup data as well. I.E. container information, control names, etc.
Now I noticed in the resx file that the entries I want have "xml:space" along with them. What is the correct way to only get the strings I want, and leave all the other stuff behind?
Thanks!
foreach (String s in sourceLocations)
{
Dictionary<string, string> sourceTemp = new Dictionary<string, string>();
Dictionary<string, object> Temp = new Dictionary<string, object>();
using (ResXResourceReader rsxr = new ResXResourceReader(s))
{
foreach (DictionaryEntry entry in rsxr)
{
string[] parts = s.Split('\\');
if (!entry.Key.ToString().Contains(">>"))
{
sourceTemp.Add(parts[parts.Count() - 1] + "_" + entry.Key.ToString(), entry.Value.ToString());
}
}
sources.Add(sourceTemp);
}
}
For anyone who runs into this later, this ended up working :
foreach (String s in sourceLocations)
{
Dictionary<string, string> sourceTemp = new Dictionary<string, string>();
Dictionary<string, object> Temp = new Dictionary<string, object>();
using (ResXResourceReader rsxr = new ResXResourceReader(s))
{
rsxr.UseResXDataNodes = true;
foreach (DictionaryEntry entry in rsxr)
{
string[] parts = s.Split('\\');
if ((!entry.Key.ToString().Contains(">>")))
{
if (isNodeString((ResXDataNode)entry.Value))
sourceTemp.Add(parts[parts.Count() - 1] + "_" + entry.Key.ToString(), getNodeValue((ResXDataNode)entry.Value));
}
}
sources.Add(sourceTemp);
}
}
private string getNodeValue(ResXDataNode node)
{
if (node.FileRef == null)
{
return node.GetValue((ITypeResolutionService)null).ToString();
}
else return String.Empty;
}
private bool isNodeString(ResXDataNode node)
{
string result = node.GetValueTypeName((ITypeResolutionService)null);
if (result.Contains("System.String")) return true;
else return false;
}
Related
The best I found was that available solutions at stack do not have answer for nested json object, they only address liner json values. But I have data to send is like
{ ob: { a: "78", b: { a: "gffg", h: {m:67, j:"fff"} } } }
If I want to do it in php i would just do
$json = $_POST['ob'];
$obj = json_decode($json);
But In c# I can'not do that. So I would appreciate any built-in method if available and I would love to be helped to fix my following code
I want to make a nested dictionary (I would prefer JOBject though). For ease of showing output I have serialized the result,
What result I have achieved yet from following code is
{"a":"78","ob":{},"ob.b":{"a":"gffg"},"ob.b.h":{"m":"67","j":"fff"}} but desired result is like sent data { "ob": { "a": "78", "b": { "a": "gffg", "h": {m:67, "j":"fff"} } } } Code is
string getJsonStringFromQueryString()
{
Dictionary<string, object> dic = new Dictionary<string, object>();
var nvc = Request.QueryString;
foreach (string key in nvc.Keys)
{
string[] values = nvc.GetValues(key);
string tempKey = key;
tempKey = tempKey.Replace("[", ".").Replace("]", "");
if (values.Length == 1)
dic.Add(tempKey, values[0]);
else
dic.Add(tempKey, values);
}
//It is giving me
{[ob.a, 78]}
{[ob.b.a, gffg]}
{[ob.b.h.m, 67]}
{[ob.b.h.j, fff]}
var result = makeNestedObject(dic);
var json = new JavaScriptSerializer().Serialize(result);
return json;
}
I am trying to add the leaf keys and their values as it is and all other keys as dictionary
Dictionary<string, object> makeNestedObject(Dictionary<string, object> qsDictionar)
{
Dictionary<string, object> result = new Dictionary<string, object>();
foreach (string key in qsDictionar.Keys)
{
string temp = "";
if (key.Contains("."))
{
string[] ar = key.Split('.');
if (ar.Length > 2)
{
for (int i = 0; i < ar.Length - 1; i++)
{
temp = ar[0];
for (int j = 1; j <= i; j++)
{
temp += "." + ar[j];
}
//above is getting the previous key i want to use as dictionary, leaving the leaf key.
try
{
Dictionary<string, object> forTry = (Dictionary<string, object>)result[temp];
}
catch
{
result.Add(temp, new Dictionary<string, object>());
}
}
((Dictionary<string, object>)result[temp]).Add(ar[ar.Length - 1], qsDictionar[key]);
}
else
result.Add(ar[1], qsDictionar[key]);
}
}
return result;
}
Following method gives you complete solution for any json object.
string getJsonStringFromQueryString()
{
Dictionary<string, object> dic = new Dictionary<string, object>();
var nvc = Request.QueryString;
foreach (string key in nvc.Keys)
{
string[] values = nvc.GetValues(key);
string tempKey = key;
tempKey = tempKey.Replace("[", ".").Replace("]", "");
if (values.Length == 1)
dic.Add(tempKey, values[0]);
else
dic.Add(tempKey, values);
}
string vald = Request.QueryString["ob"];
var result = makeNestedObject(dic);
var json = new JavaScriptSerializer().Serialize(result);
return json;
}
Dictionary<string, object> makeNestedObject(Dictionary<string, object> qsDictionar)
{
Dictionary<string, object> result = new Dictionary<string, object>();
foreach (string key in qsDictionar.Keys)
{
if (key.Contains("."))
{
List<string> keysList = key.Split('.').ToList();
Dictionary<string, object> lastAddedDictionary = result;
while (keysList.Count > 1)
{
if (!lastAddedDictionary.ContainsKey(keysList[0]))
{
Dictionary<string, object> temp = new Dictionary<string, object>();
lastAddedDictionary[keysList[0]] = temp;
lastAddedDictionary = temp;
}
else
lastAddedDictionary = (Dictionary<string, object>)lastAddedDictionary[keysList[0]];
keysList.RemoveAt(0);
}
lastAddedDictionary[keysList[0]] = qsDictionar[key];
}
else
{
result.Add(key, qsDictionar[key]);
}
}
return result;
}
I'm actually trying to check if a string is equal to any of the key's in my Dictionary object.
Here is what I have done so far:
using (var oStreamReader = new StreamReader(path))
{
Dictionary<String, String> typeNames = new Dictionary<string, string>();
typeNames.Add("Kind","nvarchar(1000)");
typeNames.Add("Name","nvarchar(1000)");
DataTable oDataTable = new DataTable();
var headLine = oStreamReader.ReadLine().Trim().Replace("\"", "");
var columnNames = headLine.Split(new[] { ';' });
String[] oStreamDataValues;
/*
*create DataTable header with specific datatypes and names
*/
int countCol = 0;
foreach (string readColumn in columnNames)
{
if ((readColumn.ToString().Replace("\"", "").CompareTo(typeNames) == true))
{
// this comparison doesn't work
}
}
}
I am not quite sure what exactly you are trying to achieve. If you have a C# dictonary you can use linq to check for values that match the required value, e.g.
string valueToCompare = "Value to match";
Dictionary<string, string> dict = new Dictionary<string, string>
{
{"Key 1", "A value"},
{"Key 2", "Another value"}
};
bool found= dict.Values
.Any(value
=>
value.Equals(valueToCompare,
StringComparison.CurrentCultureIgnoreCase)
);
Since you want check if exist an entry in your Dictionary that as the same key of one of the values in your columnNames object I suggest you to use ContainsKey method
Dictionary<string, string> d = new Dictionary<string, string>();
string keyvalue;
if (d.ContainsKey("value to find"))
{
if (d.TryGetValue("value to find", out keyvalue))
{
//// here keyvalue variable has the value
}
else
{
///value is null or throws exception
}
}
else
{
////key no exists
}
I have solved this (by inspiration of Paul Houlston and Thomas Lielacher)
string headLine = oStreamReader.ReadLine().Trim().Replace("\"", "");
string columnNames = headLine.Split(new[] { ';' });
foreach (string readColumn in columnNames)
{
if (typeNames.Keys.Contains(readColumn, StringComparer.CurrentCultureIgnoreCase) == true)
{
DataColumn oDataColumn = new DataColumn(readColumn,typeof(System.String));
oDataTable.Columns.Add(oDataColumn);
}
}
I have a question regarding bookmarks in PDF.
I'm importing list of parameters from file and want to compare them with extracted bookmarks. I'm having troubles looping through list of imported parameters and my extracted bookmarks.
Can someone take a look at this piece of code and help me out a bit?
Thanks!
public static void CompareBookmarks(string MyPDf, List<string> MyTitles)
{
PdfReader reader = new PdfReader(MyPdf);
IList<Dictionary<string, object>> bookmarks = SimpleBookmark.GetBookmark(reader);
foreach (Dictionary<string, object> itemBookmark in bookmarks)
{
foreach (KeyValuePair<string, object> item in itemBookmark)
{
foreach (var title in MyTitles)
{
if (item.Value == str.ToString())
{
Console.WriteLine("Found");
}
else
{
Console.WriteLine("Not found");
}
}
}
}
Problem is, as I can see now, that each item in bookmark have 3 key/pair values(title, page number.). So the issue is- how can I compare only first value- Title with my string?
I see no reason to enumerate all items in the bookmark since you are only interested in the title. So without testing, I would expect something like this:
foreach (Dictionary<string, object> bookmark in bookmarks)
{
foreach (var title in MyTitles)
{
if (bookmark["Title"].ToString() == title)
{
// found
}
}
}
public static void CompareBookmarks(string MyPDf, List<string> MyTitles)
{
PdfReader reader = new PdfReader(MyPdf);
IList<Dictionary<string, object>> bookmarks = SimpleBookmark.GetBookmark(reader);
foreach (Dictionary<string, object> itemBookmark in bookmarks)
{
KeyValuePair<string, object> firstPairOfDictionary = item.FirstOrDefault();
foreach (var title in myTitles)
{
if (firstPairOfDictionary.Value != title.ToString())
{
Console.WriteLine("Did not found");
continue;
}
break;
}
}
The solution was to get first object in KeyValuePair.
I made a mistake and iterate through all objects in each bookmark.
I want to get some params from Request
I need from Request.Params all params with text contains "txt" I have more type of text structure:
"ctl00$cphMain$repDelTypes$ctl00$ucDel$txtPhone"
"ctl00$cphMain$repDelTypes$ctl00$ucDel$txtPhone2"
"ctl00$cphMain$repDelTypes$ctl00$ucDel$txtPhone3"
"ctl00$cphMain$repDelTypes$ctl00$ucDel$txtAdr1"
"ctl00$cphMain$repDelTypes$ctl00$ucDel$txtAdr2"
"ctl00$cphMain$repDelTypes$ctl00$ucDel$txtAdr3"
how Get value all text after "txt"
var dictionary = new Dictionary<string, string>();
foreach (var key in Request.Params.AllKeys)
{
if (key.ToString().Contains("txt"))
{
// add to dictionary name and value
// dictionary.Add("name", "val");
}
}
You can do this:
var dictionary = new Dictionary<string, string>();
foreach (var key in Request.Params.AllKeys)
{
if (key.ToString().Contains("txt"))
{
int index = Request.Params[key].LastIndexOf("txt");
Dictionary.Add(key, Request.Params[key].SubString(index));
}
}
Are you asking how to add to the dictionary?
var dictionary = new Dictionary<string, string>();
foreach (var key in Request.Params.AllKeys)
{
if (key.ToString().Contains("txt"))
{
//get the text after "txt"
var index = Request.Params[key].LastIndexOf("txt");
var val = Request.Params[key].SubString(index);
Dictionary.Add(key, val);
}
}
var dictionary = new Dictionary<string, string>();
foreach (var key in Request.Params.AllKeys)
{
if (key.ToString().Contains("txt"))
{
// add to dictionary name and value
dictionary.Add(key.Split(new string[]{"txt"}, StringSplitOptions.None)[1], Request.Params[key]);
}
}
I'm having trouble pulling individual address components from google map's api results.
Here are the results received from this url:
http://maps.googleapis.com/maps/api/geocode/json?address=jobing.com+glendale+arizona&sensor=false
This url is in the "uri" variable. Here's the code I'm using to try and retrieve the address_component by type. Take into consideration that I'm a bit new at c#.
String Output = client.DownloadString(uri);
Dictionary<String, Object> RinkData = JsonConvert.DeserializeObject<Dictionary<String, Object>>(Output);
Dictionary<String, Object> RinkDataResults = (Dictionary<String, Object>) RinkData["results"];
if (RinkDataResults.ContainsKey("formatted_address"))
{
Route = GetAddressComponentByType(RinkDataResults["address_components"], "route");
}
And here is the function I'm using "GetAddressComponentByType"
protected String GetAddressComponentByType(Object AddressComponents, String AddressType)
{
Boolean MatchFound = false;
String MatchingLongName = "";
Dictionary<String, Object> AddressComponentsDict = (Dictionary<String, Object>)AddressComponents;
foreach (KeyValuePair<String, Object> ac in AddressComponentsDict)
{
Dictionary<String, Object> acDict = (Dictionary<String, Object>) ac.Value;
ArrayList acTypes = (ArrayList) acDict["types"];
foreach (String acType in acTypes)
{
if (acType == AddressType)
{
MatchFound = true;
break;
}
}
if (MatchFound)
{
MatchingLongName = (String) acDict["long_name"];
}
}
return MatchingLongName;
}
The problem is, it doesn't even get to my component retrieval function. It bombs converting RinkData["results"] to a Dictionary saying it's an invalid conversion.
Does anyone see what I'm doing wrong? Or maybe someone has a custom object I can read google maps geocode results into that works?
Ah, nevermind. I can extract address components easily if I start with this object
dynamic googleResults = new Uri(uri).GetDynamicJsonObject();
foreach (var result in googleResults.results)
{
foreach (var addressComp in result.address_components)
{
Literal1.Text += "<br />" + addressComp.long_name;
}
}
It's an extension class for JSON.NET found here. From L.B.'s answer to this question.