C# class objects - c#

I have a class that I am using below. And I am using this class for my windows application. However, when I call the method from my application ReadInConfig() it successfully reads and fills the datatable, and assigns the _sip_ip address.
In my windows application I have the following. However, it doesn't give me the sip_ip that it has been assigned.
ConfigSIP readIn = new ConfigSIP();
readIn.ReadInConfig();
string sip_ip = readIn.sip_ip(); // Get nothing here.
I am thinking as the _sip_ip that has been assigned by the data table is a different object than doing this readIn.sip_ip();
Is there any way I can solve this problem?
Many thanks,
public class ConfigSIP
{
private string _sip_ip;
// Fill the data table and assign the sip ip.
public void ReadInConfig()
{
DataTable dt = new DataTable("Admin");
dt.ReadXmlSchema(#"C:\Config.xml");
dt.ReadXml(#"C:\Config.xml");
_sip_ip = dt.Rows[0]["Sip_ip"].ToString();
}
// Return the sip ip address.
public string sip_ip()
{
return _sip_ip;
}
}

You forgot to call ReadInConfig:
ConfigSIP readIn = new ConfigSIP();
readIn.ReadInConfig();
string sip_ip = readIn.sip_ip();

If your code is copied verbatim your client code isn't calling the ReadInConfig() method. So the string will never get populated.

Related

Using one variable from a console in a windows form

I have this project:
And I need to use a variable that is in the "TransactionHandler.cs" in the "Enviar Faturas.cs" the TransactioHandler is a class library and the Enviar Faturas is a Windows Form.
Is it possible to do what I want? If so how should I do it?
UPDATE:
I have this variable declares in TransactionHandler.cs
var numfatura = _transaction.TransDocument + _transaction.TransSerial + _transaction.TransDocNumber;
And I need to use it on the Windows Form "Enviar Faturas".
UPDATE 2:
I have this code to select from a datagridview and write a textfile:
FileInfo arquivo = new FileInfo(#"C:\Users\HP8200\Desktop\faturas\" + r.Index + ".txt");
And I want to change the "r.index" for the variable I showed on the first update
I would suggest to use a property instead of a public field:
public class TransactionHandler
{
private static string numfatura = _transaction.TransDocument + _transaction.TransSerial + _transaction.TransDocNumber;
public static string Numfatura
{
get { return numfatura ; }
set { numfatura = value; }
}
}
From another class, you call your variable like this:
public class EnviarFaturas
{
public void DoSomething()
{
string r.Index= TransactionHandler.Numfatura;
}
}
Ok, from what I understand and having no idea of the execution flow you probably need something like this in the TransactionHandler (a property)
public int Numfatura
{
get
{
return this._transaction.TransDocument + this._transaction.TransSerial + this._transaction.TransDocNumber;
}
}
you can change the type to the one that stands behing the "var" in your code example.
To access it in the form you need an instance of the class (again I dont know what your logic is) but once you get it e.g.
var transactionHandler = new TransactionHandler();
you can simply try
r.Index = transactionHandler.Numfactura;
Keep in mind that you can hit the default data value (for int is 0) if your methods depend upon other event to happen.
I strongly suggest you to learn more about C# and Object Oriented Programming as Alexey Zimarev stated in the comments.
Also you should consider how to get/inject a concrete instance in the view.
Another good and related read will be singleton pattern, mvp and dependency injection.

Storing meta data in an Excel.Range object

I am integrating excel with an external service which involves receiving data from that service and showing in excel. I want to be able to store the information I get in the Excel.Range object. Is there any property of an Excel.Range object where one can store meta data?
To clarify, like in Outlook an Outlook.TaskItem has ItemProperties which is an Outlook.ItemProperty Object. So is there anything similar like that in Excel?
And if not, then what is the best way to store meta data for a Excel.Range?
EDIT:
I need to persist this meta data information. So if a user saves, closes and then re opens the workbook, I need to be able to extract this meta data from the Excel.Range object (or any other property)
Since you need the information to be persistent, I was using a simpler and clearer approach.
Create a new WorkSheet, call it something like [YourSheetName]Metadata (in case you have multiple of this kind). Set it to VeryHidden (xlSheetVeryHiddencan't be Unhidden from with Excel you have to unhide it from code):
xl.XlSheetVisibility.xlSheetVeryHidden
Save all your metadata for a Range R1 in metadata sheet in Range R1.
Your code will be very simple and clear in that way.
It may look something like:
Sheet1.Range[row,col].Value = SomeValue;
Sheet1Metadata.Range[row,col].Value = MetaDataOfSomeValue;
I am not sure if there is a such property even if, I was developing my own custom Range Metadata class. In that way, you have the flexibility to do whatever you need or may need later.
Following is a starting example of how you can do it:
class RangeListMetaData
{
private readonly List<RangeMetaData> _rangeList;
public RangeListMetaData()
{
_rangeList = new List<RangeMetaData>();
}
public void Add (RangeMetaData rangeMetaData)
{
_rangeList.Add(rangeMetaData);
}
}
class RangeMetaData
{
public RangeMetaData(xl.Range range)
{
this.Range = range;
}
public RangeMetaData(xl.Range range, object value) : this(range)
{
this.RangeValue = value;
}
public xl.Range Range { get; private set; }
public object RangeValue { get; set; }
}
class TestRangeMetaData
{
void Test()
{
var rangeListMetaData = new RangeListMetaData();
// storing part
RangeMetaData range = new RangeMetaData([Your excel Cells], [You Value]);
rangeListMetaData.Add(range);
// Retrieve Part
rangeListMetaData.FindByRange(...);
rangeListMetaData.FindByValue(...);
rangeListMetaData.FindBySomethingElse(...);
}
}
Since you are working with interops, you need to take care to release COM objects. For that, you can rely to another post, see my answer there

how can i use System.Data.Sql.SqlDataSourceEnumerator class to know available sql datasources...?

how can i use System.Data.Sql.SqlDataSourceEnumerator class to know about available sql datasources...?
because while i am creating connection to sql server if sql server is not ready we will get exception… so first i want to know is sql server is ready to accept request or not… how to know it….
So, according to the following references:
http://social.msdn.microsoft.com/forums/en-US/sqlsmoanddmo/thread/49ba019f-e8b5-457c-80ea-fac5febb9d3d/
http://connect.microsoft.com/SQLServer/feedback/details/146323/enumavailablesqlservers-or-sqldatasourceenumerator-incorrect-list-of-available-databases
http://blogs.msdn.com/b/sushilc/archive/2004/10/14/242395.aspx
http://sqlblogcasts.com/blogs/jonsayce/archive/2008/02/10/programatically-listing-sql-servers.aspx
GetDataSources() is not a perfect method, meaning, it may not list all the available data sources on first try. In fact, I found that it also does not list all of your local sources.
For my purposes, I had some time between when the program started and when I needed to get the list of available sources, both on the network AND local. So, I put the code in a thread that goes on forever collecting all the sources. Here it is below. If you take out the while loop, you can call it manually as many times as you'd like.
private List<string> sqlInstances = new List<string>();
private void collectInstances()
{
while (true)
{
System.Data.Sql.SqlDataSourceEnumerator instance = System.Data.Sql.SqlDataSourceEnumerator.Instance;
System.Data.DataTable dataTable = instance.GetDataSources();
foreach (DataRow row in dataTable.Rows)
{
string instanceName = String.Format(#"{0}\{1}", row["ServerName"].ToString(), row["InstanceName"].ToString());
//Do not add the local instance, we will add it in the next section. Otherwise, duplicated!
if (!sqlInstances.Contains(instanceName) && !instanceName.Contains(Environment.MachineName))
{
sqlInstances.Add(instanceName);
}
}
/*
* For some reason, GetDataSources() does not get local instances. So using code from here to get them
* http://stackoverflow.com/questions/6824188/sqldatasourceenumerator-instance-getdatasources-does-not-locate-local-sql-serv
*/
List<string> lclInstances = GetLocalSqlServerInstanceNames();
foreach (var lclInstance in lclInstances)
{
string instanceName = String.Format(#"{0}\{1}", Environment.MachineName, lclInstance);
if (!sqlInstances.Contains(instanceName)) sqlInstances.Add(instanceName);
}
sqlInstances.Sort();
}
}
//Got code from: http://stackoverflow.com/questions/6824188/sqldatasourceenumerator-instance-getdatasources-does-not-locate-local-sql-serv
/// <summary>
/// get local sql server instance names from registry, search both WOW64 and WOW3264 hives
/// </summary>
/// <returns>a list of local sql server instance names</returns>
public static List<string> GetLocalSqlServerInstanceNames()
{
RegistryValueDataReader registryValueDataReader = new RegistryValueDataReader();
string[] instances64Bit = registryValueDataReader.ReadRegistryValueData(RegistryHive.Wow64,
Registry.LocalMachine,
#"SOFTWARE\Microsoft\Microsoft SQL Server",
"InstalledInstances");
string[] instances32Bit = registryValueDataReader.ReadRegistryValueData(RegistryHive.Wow6432,
Registry.LocalMachine,
#"SOFTWARE\Microsoft\Microsoft SQL Server",
"InstalledInstances");
//FormatLocalSqlInstanceNames(ref instances64Bit);
//FormatLocalSqlInstanceNames(ref instances32Bit);
List<string> localInstanceNames = new List<string>(instances64Bit);
foreach (var item in instances32Bit)
{
if (!localInstanceNames.Contains(item)) localInstanceNames.Add(item);
}
//localInstanceNames = localInstanceNames.Union(instances32Bit).ToList();
return localInstanceNames;
}
GetDataSources() may help you, have you tried it?
SqlDataSourceEnumerator.GetDataSources Method
Currently SqlDataSourceEnumerator isn't available in .NetCore or .Net5 either and
whilst not a direct replacement for SqlDataSourceEnumerator you could try a Udp solution.
This repo is targetted at .Net5, but the code should work just fine on .NetCore flavours.
https://github.com/mrsquish/SqlBrowserClient

JsonConvert - Can not assign string value to a string variable

public void FindCityName()
{
string url = "http://maps.google.com/maps/geo?q=39.920794,32.853902&output=json&oe=utf8&sensor=true&key=MYKEY";
var w = new WebClient();
Observable.FromEvent<DownloadStringCompletedEventArgs>(w, "DownloadStringCompleted").Subscribe(r =>
{
var deserialized = JsonConvert.DeserializeObject<RootObject>(r.EventArgs.Result);
string s = deserialized.Placemark[0].AddressDetails.Country.SubAdministrativeArea.Locality.LocalityName;
/// setCity() and City=s produce the same thing
setCity(s);
City = s;
//foreach (var item in deserialized.Placemark)
//{
// //MessageBox.Show(item.AddressDetails.Country.SubAdministrativeArea.Locality.LocalityName);
// City = (string)item.AddressDetails.Country.SubAdministrativeArea.Locality.LocalityName;
//}
//Problem here >>>>>
////MessageBox.Show(City);
});
w.DownloadStringAsync(new Uri(url));
}
Problem:
I am working on a windows phone 7 application and I need to find the "City Name" from GPS coordinates in order to move forward...
I found the code above on the internet and tried it. I can see the city name by using these codes(Message.Box(City) show exactly what I want, the city name). However, this line of code
deserialized.Placemark[0].AddressDetails.Country.SubAdministrativeArea.Locality.LocalityName;
which gives me the city name seems to give a volatile string value.
For example, I created a method which assigns the value of string variable "s" to the string field of my class, name City. If I try to get the City's content after calling FindCityName() method, I see that City's content is not updated.
Again, same thing happens then I call the code line under the comment "Problem here >>>>>" that MessageBox.Show(City) shows nothing new...
Can someone explain me the reason of my problem?
you put this question on my blog as well, but I will answer it here. I feel a bit responsible for putting up the sample code in the first place ;-)
I am going to assume the class containing your code looks like this:
public class MyClass
{
private void MyMethod()
{
FindCityName();
MessageBox.Show(City);
}
private void FindCityName()
{
// Code omitted - see your question
}
private string City;
}
There is nothing volatile about the string. Your problem is asynchronicity. If you look carefully you will see that I use an observable that fires when the DownloadStringCompleted is fired. The code inside Observable.Event is only called when the download is finished but that happens asynchronously. But what I assume you do is call the FindCityName method and then directly trying to access results like I show in the MyMethod method. That's like directly wanting the result after firing the request. The results are not in yet! It's like a web page downloading - it takes a while. You can fix that with a callback, something like this:
public class MyClass
{
private void MyMethod()
{
FindName();
}
public void FindCityName()
{
string url = "http://maps.google.com/maps/geo?q=39.920794,32.853902&output=json&oe=utf8&sensor=true&key=MYKEY";
var w = new WebClient();
Observable.FromEvent<DownloadStringCompletedEventArgs>(w, "DownloadStringCompleted").Subscribe(r =>
{
var deserialized = JsonConvert.DeserializeObject<RootObject>(r.EventArgs.Result);
City = deserialized.Placemark[0].AddressDetails.Country.SubAdministrativeArea.Locality.LocalityName;
DoneDownloading();
});
w.DownloadStringAsync(new Uri(url));
}
private string City;
private void DoneDownloading
{
MessageBox.Show(City);
}
}
Does that help?
I would recommend you to use this Google Map API
http://maps.googleapis.com/maps/api/geocode/json?latlng=39.920794,32.853902&sensor=true
And once you get JSON response in your request. You can parse easily with NEWTONSOFT for wp7
WebClient wc = new WebClient();
var json = (JObject)JsonConvert.DeserializeObject(wc.DownloadString(url));
var locality= json["results"]
.SelectMany(x => x["address_components"])
.FirstOrDefault(t => t["types"].First().ToString() == "locality");
var name = locality!=null ? locality["long_name"].ToString() : "";

Save Object back to the database

I am working on a project where I am converting some VB.Net class libraries to C# libraries (mostly to learn C# syntax). My problem is that I cannot get the Save function working.
I am building my object with this:
public static StoreEmployee Create(string LoginId)
{
var emp = new StoreEmployee();
using (var dt = DAC.ExecuteDataTable("usp_ActiveEmployeeSelect",
DAC.Parameter(CN_LoginId, LoginId)))
{
emp.StoreId = Convert.ToString(dt.Rows[0][CN_StoreId]);
emp.FirstName = Convert.ToString(dt.Rows[0][CN_FirstName]);
emp.LastName = Convert.ToString(dt.Rows[0][CN_LastName]);
emp.UserName = Convert.ToString(dt.Rows[0][CN_UserName]);
emp.Role = Convert.ToString(dt.Rows[0][CN_Role]);
emp.Description = Convert.ToString(dt.Rows[0][CN_Description]);
}
return emp;
}
And then creating it with this
private static void FillStoreEmployeeObject(string empLoginId)
{
StoreEmployee.Create(empLoginId);
}
And then trying to use this save function to save the object back to the database:
public override Boolean Save(string LoginId)
{
try
{
int retVal = DAC.ExecuteNonQuery("usp_ActiveEmployeeSave",
DAC.Parameter(CN_LoginId, LoginId),
DAC.Parameter(CN_StoreId, StoreId),
DAC.Parameter(CN_FirstName, FirstName),
DAC.Parameter(CN_UserName, UserName),
DAC.Parameter(CN_Role, Role),
DAC.Parameter(CN_Description, Description));
return true;
}
catch
{
return false;
}
}
I don't get a syntax warning for that but I have revised it many times so I want to make sure that is correct before I move on. Does this look correct? By the way I am trying to call the Save function with this
StoreEmployee.Save(Convert.ToString(Login))
which gives me this error An object reference is required for the non-static field, method, or property However when I mark my function as static my Create function shows errors so I am left very confused.
Save is an instance method.
As the error message states,you need to call it on an existing instance of StoreEmployee (such as the one returned by Create).

Categories

Resources