Issues in Finding Windows Activation through SoftwareProductLicensing Class - c#-4.0

I am using the below code to determine the activation of the Widnows7. I am getting 7 instances/product. I am not clear which product refers to original Windows 7.
I am unable to find documentation on to check which instance to determine whether Windows is activated or not
//use a SelectQuery to tell what we're searching in
SelectQuery searchQuery = new SelectQuery("SELECT * FROM SoftwareLicensingProduct");
//set the search up
ManagementObjectSearcher searcherObj = new ManagementObjectSearcher(scope, searchQuery);
//get the results into a collection
using (ManagementObjectCollection obj = searcherObj.Get())
{
foreach (ManagementObject m in obj)
{
if (Convert.ToInt32(m["GracePeriodRemaining"].ToString()) == 0)
{
MessageBox.Show("Windows is active");
break;
}
else
{
MessageBox.Show(" Windows is not active");
break;
}
}
//now loop through the collection looking for
//an activation status
}

When you use the SoftwareLicensingProduct WMI class, more than an instance is returned due to the Volume Licensing feature introduced in Windows Vista, so to return only the instance of you Windows version you must filter the WQL sentence using the PartialProductKey, ApplicationId and LicenseIsAddon properties.
Try this sample
using System;
using System.Collections.Generic;
using System.Management;
using System.Text;
namespace GetWMI_Info
{
class Program
{
static void Main(string[] args)
{
try
{
string ComputerName = "localhost";
ManagementScope Scope;
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);
Scope.Connect();
ObjectQuery Query = new ObjectQuery("SELECT * FROM SoftwareLicensingProduct Where PartialProductKey <> null AND ApplicationId='55c92734-d682-4d71-983e-d6ec3f16059f' AND LicenseIsAddon=False");
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);
foreach (ManagementObject WmiObject in Searcher.Get())
{
Console.WriteLine("{0,-35} {1,-40}", "Name", (String)WmiObject["Name"]);
Console.WriteLine("{0,-35} {1,-40}", "GracePeriodRemaining", (UInt32) WmiObject["GracePeriodRemaining"]);// Uint32
switch ((UInt32)WmiObject["LicenseStatus"])
{
case 0: Console.WriteLine("{0,-35} {1,-40}", "LicenseStatus", "Unlicensed");
break;
case 1: Console.WriteLine("{0,-35} {1,-40}", "LicenseStatus", "Licensed");
break;
case 2: Console.WriteLine("{0,-35} {1,-40}", "LicenseStatus", "Out-Of-Box Grace Period");
break;
case 3: Console.WriteLine("{0,-35} {1,-40}", "LicenseStatus", "Out-Of-Tolerance Grace Period");
break;
case 4: Console.WriteLine("{0,-35} {1,-40}", "LicenseStatus", "on-Genuine Grace Period");
break;
case 5: Console.WriteLine("{0,-35} {1,-40}", "LicenseStatus", "Notification");
break;
}
}
}
catch (Exception e)
{
Console.WriteLine(String.Format("Exception {0} Trace {1}",e.Message,e.StackTrace));
}
Console.WriteLine("Press Enter to exit");
Console.Read();
}
}
}
Another option is use the SLIsGenuineLocal function.
Try the answer to this question Determine Genuine Windows Installation in C# for a C# sample.

Windows® 7, VOLUME_KMSCLIENT channel refers to the actual product. this can found in description property
string ComputerName = "localhost";
ManagementScope Scope;
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);
Scope.Connect();
SelectQuery searchQuery = new SelectQuery("SELECT * FROM SoftwareLicensingProduct");
//set the search up
ManagementObjectSearcher searcherObj = new ManagementObjectSearcher(Scope, searchQuery);
//get the results into a collection
using (ManagementObjectCollection obj = searcherObj.Get())
{
foreach (ManagementObject m in obj)
{
String s = m["Description"].ToString();
if ((m["Description"].ToString()) .Contains("VOLUME_KMSCLIENT channel"))
{
if (m["LicenseStatus"].ToString() == "1")
{
var gracePeriod = Convert.ToInt32(m["GracePeriodRemaining"]) / (60 * 24);
MessageBox.Show("Not Licensed " + " Grace Period Remaining--" + gracePeriod.ToString() + "days");
}
else
{
var gracePeriod = Convert.ToInt32(m["GracePeriodRemaining"]) / (60 * 24);
MessageBox.Show("Not Licensed " + " Grace Period Remaining--" + gracePeriod.ToString() + "days");
}
}
}
}

Related

No such property: getToHour for class: OutagePolicyScript

I 've continously getting error:
2019-05-06 14:37:40,128 [EPI-TaskExecutor-1] ERROR
ScriptExecutionExceptionHandler.handleScriptError(31) - Script with id
[3e2fd082-62f3-46a2-8fca-71b1f9cef028] and label [Outage definition
script] reports an error: : No such property: getToHour for class:
OutagePolicyScript.
Outages.xml file is OK, and is placed together with outage.dtd file in correct location.
import java.util.List;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import com.hp.opr.api.scripting.Event;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.lang3.ArrayUtils;
class OutagePolicyScript
{
Object syncObject = new Object();
final static String fileName = "/opt/HP/BSM/Temp/outages.xml"; // for Windows it will be: "d:/HPBSM/Temp/outages.xml";
final static Log s_log = LogFactory.getLog("com.hp.opr.epi.OutagePolicyScript");
List<OutageDefinition> outageDefinitions = new ArrayList<OutageDefinition>();
Thread loadXMLThread;
final boolean isSuppressEventsOrClose = true;
def init()
{
LoadOutagesFromXML r1 = new LoadOutagesFromXML();
loadXMLThread = new Thread(r1);
loadXMLThread.start();
s_log.debug("init finished");
}
def destroy()
{
s_log.debug("going to stop thread....");
loadXMLThread.interrupt();
}
def process(List<Event> events)
{
synchronized(syncObject) {
try
{
events.each {Event event ->
handleEventSuppressionIfNeeded(event, "EST");
//event.setTitle("Modified by CA/EPI: " + event.getTitle());
// always include following check for each event
if(Thread.interrupted())
throw new InterruptedException()
}
}
catch(InterruptedException e)
{
s_log.error("process of events interrupted", e);
}
}
}
private void handleEventSuppressionIfNeeded(Event event, String timezoneId)
{
// Calculate if event was received during the accepted time window.
Date timeRecieved = event.getTimeReceived();
Calendar cal = Calendar.getInstance();
TimeZone tz = TimeZone.getTimeZone(timezoneId);
if (tz != null)
cal = Calendar.getInstance(tz);
cal.setTime(timeRecieved);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int dow = cal.get(Calendar.DAY_OF_WEEK);
//event.addCustomAttribute("hour", Integer.toString(hour));
//event.addCustomAttribute("minute", Integer.toString(minute));
//event.addCustomAttribute("day of week", Integer.toString(dow));
// go over all the outage definitions, and compare event attributes to the rule
outageDefinitions.each {OutageDefinition outage ->
if (outage.getIsActive()) {
s_log.debug("Checking active rule: " + outage.getDescription());
// check if the event's day of week is one of the outage definition days. in case the rule cross day, reduce 1 for day of week
if (ArrayUtils.contains(outage.getDays(), dow) || (outage.getCrossDay() && ArrayUtils.contains(outage.getDays(), (dow == 1) ? 7 : dow-1 ))) {
// check if event hour and minute are inside rule's from/to
// convert all configurations to minutes
// if the rule cross a day, then add to "to" 24 hours in order to compare from <= event_time < to
// if the rule cross a day AND event hour < "from" then it means the event is in the next day and need to add 24 hours too
int eventTimeInMin = ((hour < outage.getFromHour() && outage.getCrossDay()) ? hour + 24 : hour) * 60 + minute;
int fromInMin = outage.getFromHour() * 60 + outage.getFromMinute();
int toInMin = (outage.getCrossDay() ? outage.getToHour() + 24 : outage.getToHour) * 60 + outage.getToMinute();
if (eventTimeInMin >= fromInMin && eventTimeInMin < toInMin) {
s_log.debug("event time is within this outage rule, proceed to compare event's attributes");
boolean foundMatch = true;
Set<String> attributeNames = outage.getAttributesList().keySet();
attributeNames.each {String name ->
boolean attMatchResult;
// at the moment, all comparisons are using "EQ"
switch (name) {
case "title" : attMatchResult = compareEventAttributeToOutageRuleForcontains("title", event.getTitle(), outage.getAttributesList().get(name)); break;
case "application" : attMatchResult = compareEventAttributeToOutageRule("application", event.getApplication(), outage.getAttributesList().get(name)); break;
case "object" : attMatchResult = compareEventAttributeToOutageRule("object", event.getObject(), outage.getAttributesList().get(name)); break;
case "category" : attMatchResult = compareEventAttributeToOutageRule("category", event.getCategory(), outage.getAttributesList().get(name)); break;
case "subcategory" : attMatchResult = compareEventAttributeToOutageRule("subcategory", event.getSubCategory(), outage.getAttributesList().get(name)); break;
case "nodeHint" : attMatchResult = compareEventAttributeToOutageRuleForcontains("nodeHint", event.getNodeHints().getHint(), outage.getAttributesList().get(name)); break;
default : s_log.error("attribute name [" + name + "] from outages.xml is not supported");
}
s_log.debug("result for attribute [" + name + "] is: " + attMatchResult);
foundMatch &= attMatchResult;
}
s_log.debug("result after processing all attributes in the rule is: " + foundMatch);
if (foundMatch) {
if (isSuppressEventsOrClose)
event.addCustomAttribute("SuppressDueToOutageRule", outage.getDescription());
else
event.setState(LifecycleState.CLOSED);
}
}
else {
s_log.debug("Current rule doesnt match for the event's time, this rule will be skipped");
}
}
else {
s_log.debug("Current rule doesnt match for the event's day, this rule will be skipped");
}
}
}
}
private boolean compareEventAttributeToOutageRule(String eventAttName, String eventAttValue, Set<String> ruleValues)
{
if (ruleValues.contains(eventAttValue)) {
s_log.debug("found match on attribute [" + eventAttName + "], attribute value=" + eventAttValue);
return true;
}
// else, no match
s_log.debug("no match for attribute " + eventAttName);
return false;
}
private boolean compareEventAttributeToOutageRuleForcontains(String eventAttName, String eventAttValue, Set<String> ruleValues)
{
Iterator<String> itr = ruleValues.iterator();
while (itr.hasNext()) {
if (eventAttValue.indexOf(itr.next()) != -1) { // check if the event attribute contains the rule's value
s_log.debug("found match on attribute [" + eventAttName + "], attribute value=" + eventAttValue);
return true;
}
}
// else, no match
s_log.debug("no match for attribute " + eventAttName);
return false;
}
class LoadOutagesFromXML implements Runnable
{
long lastModifiedTime = -1;
public void run()
{
while (!Thread.interrupted()) {
s_log.debug("in running.... current time: " + new Date());
// lock the sync object
synchronized(syncObject) {
long before = System.currentTimeMillis();
readOutageFile();
long after = System.currentTimeMillis();
s_log.debug("Loading outages definitions from XML took [" + (after - before) + "] ms.");
}
Thread.sleep(60000); // 60 seconds
}
s_log.debug("thread interrupted....");
}
private void readOutageFile()
{
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
File f = new File(fileName);
if (f.lastModified() == lastModifiedTime) {
// the file wasnt changed, no need to reload file
s_log.debug("file LastModifiedTime didn't change, no need to reload configuration");
return;
}
// otherwise, clear previous results and reload XML file
outageDefinitions.clear();
s_log.debug("going to load outage.xml");
Document doc = db.parse(f);
NodeList outages = doc.getElementsByTagName("outage");
for (int i=0 ; i<outages.getLength() ; ++i) {
s_log.debug("handle outage: " + Integer.toString(i));
// going to handle specific outage definition
Element aOutage = (Element)outages.item(i);
Element aTimeWindow = (Element)(aOutage.getElementsByTagName("timeWindow").item(0));
outageDefinitions.add(new OutageDefinition(aOutage.getAttribute("description"),
aOutage.getAttribute("isEnabled"),
aTimeWindow.getElementsByTagName("days").item(0).getTextContent(),
parseIntFromStr(aTimeWindow.getElementsByTagName("from").item(0).getTextContent(), true),
parseIntFromStr(aTimeWindow.getElementsByTagName("from").item(0).getTextContent(), false),
parseIntFromStr(aTimeWindow.getElementsByTagName("to").item(0).getTextContent(), true),
parseIntFromStr(aTimeWindow.getElementsByTagName("to").item(0).getTextContent(), false),
parseAttributesFromXML((Element)aOutage.getElementsByTagName("eventsFilter").item(0))));
}
lastModifiedTime = f.lastModified();
s_log.debug("Going to keep lastModifiedTime as " + lastModifiedTime);
}
catch (Exception e) {
s_log.error("caught exception during parsing of outage.xml", e);
lastModifiedTime = -1;
}
}
private int parseIntFromStr(String str, boolean isHour)
{
String[] array = str.trim().split(":");
if (array.length != 2) {
s_log.debug("Bad time format, expect HH:MM format but recieved: " + str);
return -1;
}
if (isHour)
return Integer.parseInt(array[0]);
else
return Integer.parseInt(array[1]);
}
private Map<String, Set<String>> parseAttributesFromXML(Element eventsFilter)
{
Map<String, Set<String>> result = new HashMap<String, Set<String>>();
NodeList eventAttributes = eventsFilter.getElementsByTagName("eventAttribute");
for (int i=0 ; i<eventAttributes.getLength() ; ++i) {
NodeList attributeValues = eventAttributes.item(i).getElementsByTagName("value");
Set<String> values = new HashSet<String>(attributeValues.getLength());
for (int j=0 ; j<attributeValues.getLength() ; j++) {
values.add(attributeValues.item(j).getTextContent());
}
result.put(eventAttributes.item(i).getAttribute("name"), values);
}
return result;
}
}
class OutageDefinition
{
String description;
boolean isActive;
int[] days;
int fromHour;
int fromMinute;
int toHour;
int toMinute;
boolean crossDay;
Map<String, Set<String>> attributesList;
public OutageDefinition(String desc, String active, String outageDays, int oFromHour, int oFromMinute, int oToHour, int oToMinute, Map<String, Set<String>> oAttributes) {
this.description = desc;
this.isActive = Boolean.parseBoolean(active);
this.fromHour = oFromHour;
this.fromMinute = oFromMinute;
this.toHour = oToHour;
this.toMinute = oToMinute;
this.attributesList = oAttributes;
this.crossDay = false;
// check if time cross a day
if (this.fromHour > this.toHour) {
s_log.debug("in rule [" + this.description + "] found time condition that crosses midnight, adjust toHour accordingly");
this.crossDay = true;
}
this.days = getDaysFromString(outageDays);
}
private int[] getDaysFromString(String str)
{
String[] days = str.trim().split(",");
int[] result = new int[days.length];
for (int i=0 ; i<days.length ; ++i) {
switch (days[i]) {
case "Sunday" : result[i] = 1; break;
case "Monday" : result[i] = 2; break;
case "Tuesday" : result[i] = 3; break;
case "Wednesday" : result[i] = 4; break;
case "Thursday" : result[i] = 5; break;
case "Friday" : result[i] = 6; break;
case "Saturday" : result[i] = 7; break;
default : result[i] = -1; break;
}
}
return result;
}
public String getDescription() {
return description;
}
public boolean getIsActive() {
return isActive;
}
public int[] getDays() {
return days;
}
public int getFromHour() {
return fromHour;
}
public int getFromMinute() {
return fromMinute;
}
public int getToHour() {
return toHour;
}
public int getToMinute() {
return toMinute;
}
public Map<String, Set<String>> getAttributesList() {
return attributesList;
}
public boolean getCrossDay() {
return crossDay;
}
}
}
Look closely at this line. You must either call a method (outage.getToHour()) or access a property (outage.getToHour), but here you do both things. Choose what is correct
int toInMin = (outage.getCrossDay() ? outage.getToHour() + 24 : outage.getToHour) * 60 + outage.getToMinute();

The remote server returned an error: (401) Unauthorized - CSOM - OAuth - after specific time

I am trying to get permissions assigned to each document from the document library using csom in console application. Console app is running fine for almost one hour and post that I get error : "The remote server returned an error: (401) Unauthorized."
I registered an app in SharePoint and I'm using Client ID & Client Secret Key to generate Client Context. Here is the code to get the client context
public static ClientContext getClientContext()
{
ClientContext ctx = null;
try
{
ctx = new AuthenticationManager().GetAppOnlyAuthenticatedContext(SiteUrl, ClientId, ClientSecret);
ctx.RequestTimeout = 6000000;
ctx.ExecutingWebRequest += delegate (object sender, WebRequestEventArgs e)
{
e.WebRequestExecutor.WebRequest.UserAgent = "NONISV|Contoso|GovernanceCheck/1.0";
};
}
catch (Exception ex)
{
WriteLog("Method-getClientContext, Error - " + ex.Message);
}
return ctx;
}
Here is the code which is getting all the assignments assigned to document in document library.
static StringBuilder excelData = new StringBuilder();
static void ProcessWebnLists()
{
try
{
string[] lists = { "ABC", "XYZ", "DEF", "GHI"};
foreach (string strList in lists)
{
using (var ctx = getClientContext())
{
if (ctx != null)
{
Web web = ctx.Site.RootWeb;
ListCollection listCollection = web.Lists;
ctx.Load(web);
ctx.Load(listCollection);
ctx.ExecuteQuery();
List list = web.Lists.GetByTitle(strList);
ctx.Load(list);
ctx.ExecuteQuery();
Console.WriteLine("List Name:{0}", list.Title);
var query = new CamlQuery { ViewXml = "<View/>" };
var items = list.GetItems(query);
ctx.Load(items);
ctx.ExecuteQuery();
foreach (var item in items)
{
var itemAssignments = item.RoleAssignments;
ctx.Load(item, i => i.DisplayName);
ctx.Load(itemAssignments);
ctx.ExecuteQuery();
Console.WriteLine(item.DisplayName);
string groupNames = "";
foreach (var assignment in itemAssignments)
{
try
{
ctx.Load(assignment.Member);
ctx.ExecuteQuery();
groupNames += "[" + assignment.Member.Title.Replace(",", " ") + "] ";
Console.WriteLine($"--> {assignment.Member.Title}");
}
catch (Exception e)
{
WriteLog("Method-ProcessWebnLists, List-" + list.Title + ", Document Title - " + item.DisplayName + ", Error : " + e.Message);
WriteLog("Method-ProcessWebnLists, StackTrace : " + e.StackTrace);
}
}
excelData.AppendFormat("{0},{1},ITEM,{2}", list.Title, (item.DisplayName).Replace(",", " "), groupNames);
excelData.AppendLine();
}
}
excelData.AppendLine();
}
}
}
catch (Exception ex)
{
WriteLog("Method-ProcessWebnLists, Error : " + ex.Message);
WriteLog("Method-ProcessWebnLists, StackTrace : " + ex.StackTrace.ToString());
}
}
Can anyone suggest what else I am missing in this or what kind of changes do I need to make to avoid this error?
The process is taking too much time so I want my application to keep running for couple of hours.
Thanks in advance!
Is there a reason why getClientContext() is inside the foreach loop?
I encountered this error before.
I added this to solve mine.
public static void ExecuteQueryWithIncrementalRetry(this ClientContext context, int retryCount, int delay)
{
int retryAttempts = 0;
int backoffInterval = delay;
if (retryCount <= 0)
throw new ArgumentException("Provide a retry count greater than zero.");
if (delay <= 0)
throw new ArgumentException("Provide a delay greater than zero.");
while (retryAttempts < retryCount)
{
try
{
context.ExecuteQuery();
return;
}
catch (WebException wex)
{
var response = wex.Response as HttpWebResponse;
if (response != null && response.StatusCode == (HttpStatusCode)429)
{
Console.WriteLine(string.Format("CSOM request exceeded usage limits. Sleeping for {0} seconds before retrying.", backoffInterval));
//Add delay.
System.Threading.Thread.Sleep(backoffInterval);
//Add to retry count and increase delay.
retryAttempts++;
backoffInterval = backoffInterval * 2;
}
else
{
throw;
}
}
}
throw new MaximumRetryAttemptedException(string.Format("Maximum retry attempts {0}, have been attempted.", retryCount));
}
Basically, this code backs off for a certain time/interval before executing another query, to prevent throttling.
So instead of using ctx.ExecuteQuery(), use ctx.ExecuteQueryWithIncrementalRetry(5, 1000);
Further explanation here
https://learn.microsoft.com/en-us/sharepoint/dev/general-development/how-to-avoid-getting-throttled-or-blocked-in-sharepoint-online

C# Crystal Reports TimeZone

I am using Crystal Reports ReportDocument object to load, run, and export a report to PDF. The report time is that of the web server. We have users running reports from different time zones. Is there a way to set the time zone of the report?
using (SqlCommand cmd = new SqlCommand(job.sproc, con))
{
cmd.CommandType = CommandType.StoredProcedure;
foreach (KeyValuePair<string, string> p in sprParams)
{
cmd.Parameters.AddWithValue(p.Key, p.Value);
}
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ReportDocument rpt = new ReportDocument();
rpt.Load(Path.Combine(RPT_LOCATION, job.repFileName));
rpt.Database.Tables[0].SetDataSource(ds.Tables[0]);
int i = 1;
foreach (string subReport in job.subReports)
{
using (ReportDocument srpt = rpt.OpenSubreport(subReport))
{
srpt.SetDataSource(ds.Tables[i++]);
}
}
ParameterFieldDefinitions parmFields = rpt.DataDefinition.ParameterFields;
ParameterValues pvals = new ParameterValues();
foreach (ParameterFieldDefinition def in parmFields)
{
if (!def.IsLinked())
{
ParameterDiscreteValue pval = new ParameterDiscreteValue();
if (rptParams.ContainsKey(def.Name))
{
pval.Value = rptParams[def.Name];
}
else
{
switch (def.ParameterValueKind)
{
case ParameterValueKind.BooleanParameter:
pval.Value = false;
break;
case ParameterValueKind.CurrencyParameter:
pval.Value = 0;
break;
case ParameterValueKind.DateParameter:
pval.Value = DateTime.Now.ToShortDateString();
break;
case ParameterValueKind.DateTimeParameter:
pval.Value = DateTime.Now;
break;
case ParameterValueKind.NumberParameter:
pval.Value = 0;
break;
case ParameterValueKind.TimeParameter:
pval.Value = DateTime.Now.ToShortTimeString();
break;
default:
pval.Value = String.Empty;
break;
}
}
pvals.Add(pval);
def.ApplyCurrentValues(pvals);
}
}
//save file
job.fileName = ExfiltrateReport(rpt, exfilType);
job.created = DateTime.UtcNow;
rpt.Dispose();
}

Google API throws exception at specified lat & long position?

Below is my sample code
public static string GetGeoLoc(string latitude, string longitude,
out string Address_ShortCountryName,
out string Address_country,
out string Address_administrative_area_level_1,
out string Address_administrative_area_level_1_short_name,
out string Address_administrative_area_level_2,
out string Address_administrative_area_level_3,
out string Address_colloquial_area,
out string Address_locality,
out string Address_sublocality,
out string Address_neighborhood)
{
Address_ShortCountryName = "";
Address_country = "";
Address_administrative_area_level_1 = "";
Address_administrative_area_level_1_short_name = "";
Address_administrative_area_level_2 = "";
Address_administrative_area_level_3 = "";
Address_colloquial_area = "";
Address_locality = "";
Address_sublocality = "";
Address_neighborhood = "";
XmlDocument doc = new XmlDocument();
try
{
doc.Load("http://maps.googleapis.com/maps/api/geocode/xml?latlng=" + latitude + "," + longitude + "&sensor=false");
XmlNode element = doc.SelectSingleNode("//GeocodeResponse/status");
if (element.InnerText == "ZERO_RESULTS")
{
return ("No data available for the specified location");
}
else
{
element = doc.SelectSingleNode("//GeocodeResponse/result/formatted_address");
string longname = "";
string shortname = "";
string typename = "";
XmlNodeList xnList = doc.SelectNodes("//GeocodeResponse/result/address_component");
foreach (XmlNode xn in xnList)
{
try
{
longname = xn["long_name"].InnerText;
shortname = xn["short_name"].InnerText;
typename = xn["type"].InnerText;
switch (typename)
{
case "country":
{
Address_country = longname;
Address_ShortCountryName = shortname;
break;
}
case "locality":
{
Address_locality = longname;
break;
}
case "sublocality":
{
Address_sublocality = longname;
break;
}
case "neighborhood":
{
Address_neighborhood = longname;
break;
}
case "colloquial_area":
{
Address_colloquial_area = longname;
break;
}
case "administrative_area_level_1":
{
Address_administrative_area_level_1 = longname;
Address_administrative_area_level_1_short_name = shortname;
break;
}
case "administrative_area_level_2":
{
Address_administrative_area_level_2 = longname;
break;
}
case "administrative_area_level_3":
{
Address_administrative_area_level_3 = longname;
break;
}
default:
break;
}
}
catch (Exception e)
{
clsExHandler.Instance.Write(e);
}
}
return (element.InnerText);
}
}
catch (Exception ex)
{
return ("(Address lookup failed: ) " + ex.Message);
}
}
try passing latitude as 33.4965 & longitude as -112.205
i'm getting an exception object reference to invalid object in the line
**typename = xn["type"].InnerText;**
when i debug step by step there is no such attribute like ["type"]
Also there are some other lingual character why?
How could i resolve this issue.
I'm not familiar with c# and Im not sure if your code is correct at all(e.g. types is not an attribute, it's an elementNode).
Assuming that your code is correct and you can select nodes by using node['nameOfChildNode'] , when you inspect the XML-File: http://maps.googleapis.com/maps/api/geocode/xml?latlng=33.4965,-112.205&sensor=false you will see that there are address_components with 2 <type>'s and also address_components without any <type> .
I guess your code breaks not at the missing <type>, it breaks when you try to access a property(InnerText) of the missing <type>.
What you can do: use selectSingleNode to select the <type> and when it returns null implement a fallback or leave the further processing.
http://maps.googleapis.com/maps/api/geocode/json?latlng=33.4965%20,%20-112.205&sensor=false
returns
{
"results" : [],
"status" : "ZERO_RESULTS"
}
Therefore
XmlNode element = doc.SelectSingleNode("//GeocodeResponse/status");
if (element.InnerText == "ZERO_RESULTS")
{
return ("No data available for the specified location");
}
is not catching ZERO_RESULTS.
I am not familiar with C# so I cannot help further.

C# create configuration file

This code How can I create configuration file if so that i can change connection string easy
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Web;
using mshtml;
namespace tabcontrolweb
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string MyConString = "SERVER=192.168.0.78;" +
"DATABASE=webboard;" +
"UID=aimja;" +
"PASSWORD=aimjawork;" +
"charset=utf8;";
MySqlConnection connection = new MySqlConnection(MyConString);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "SELECT urlwebboard FROM `listweb` WHERE `urlwebboard` IS NOT NULL AND ( `webbordkind` = 'เว็บท้องถิ่น' ) and `nourl`= 'n' order by province, amphore limit 4 ";
connection.Open();
Reader = command.ExecuteReader();
string[] urls = new string[4];
string thisrow = "";
string sumthisrow = "";
while (Reader.Read())
{
thisrow = "";
for (int i = 0; i < Reader.FieldCount; i++)
{
thisrow += Reader.GetValue(i).ToString();
System.IO.File.AppendAllText(#"C:\file.txt", thisrow + " " + Environment.NewLine);
sumthisrow = Reader.GetValue(Reader.FieldCount - 1).ToString();
}
for (int m = 0; m < 4 ; m++)
{
urls[m] = sumthisrow;
MessageBox.Show(urls[m]);
}
webBrowser1.Navigate(new Uri(urls[0]));
webBrowser1.Dock = DockStyle.Fill;
webBrowser2.Navigate(new Uri(urls[1]));
webBrowser2.Dock = DockStyle.Fill;
webBrowser3.Navigate(new Uri(urls[2]));
webBrowser3.Dock = DockStyle.Fill;
webBrowser4.Navigate(new Uri(urls[3]));
webBrowser4.Dock = DockStyle.Fill;
}
connection.Close();
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//if (webBrowser1.Document != null)
//{
// IHTMLDocument2 document = webBrowser1.Document.DomDocument as IHTMLDocument2;
// if (document != null)
// {
// IHTMLSelectionObject currentSelection = document.selection;
// IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange;
// if (range != null)
// {
// const String search = "We";
// if (range.findText(search, search.Length, 2))
// {
// range.select();
// }
// }
// }
//}
}
}
}
You can create an XML configuration file looking like this :
<db-config>
<server>192.168.0.78</server>
<database>webboard</database>
<...>...</...>
</db-config>
Then, use XMLTextReader to parse it.
Here is a basic example of how you can use it to parse XML files :
using System;
using System.Xml;
namespace ReadXMLfromFile
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
static void Main(string[] args)
{
XmlTextReader reader = new XmlTextReader ("books.xml");
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an element.
Console.Write("<" + reader.Name);
Console.WriteLine(">");
break;
case XmlNodeType.Text: //Display the text in each element.
Console.WriteLine (reader.Value);
break;
case XmlNodeType.EndElement: //Display the end of the element.
Console.Write("</" + reader.Name);
Console.WriteLine(">");
break;
}
}
Console.ReadLine();
}
}
}
Hint : Use the ReadTofollowing() to get your values.
Once your XML DB Config Reader class is done, you use it each time you need a new connection, and you'll only need to change your DB Config XML file to change your DB Connections configuration.
Edit : there is an interesting article about Storing database connection settings in .NET here.
Use the default
System.Configuration.ConfigurationManager
that C# supports!
See: http://msdn.microsoft.com/en-us/library/bb397750.aspx

Resources