how to loop throught Dictionary - windows

Am building window form application using VS2010.On my login form i collect useid
and password and then click on the login button, if validation is successful direct
users to the main form.
I want to use a Dictionary to store userid and password read from the DB.
Then close connection. i then compare the inputed values from the textbox againt values:
userd and passward in the dictionary. on sucess direct to main form
here is my code. pls help`
string connectionstring =
"Data Source =localhost;Initial Catalog=HSM;" +
"User Id=sysad;Password=mypassword";
SqlConnection connection = new SqlConnection(connectionstring);
SqlCommand selectcmd = new SqlCommand("Select * from users");
SqlDataReader reader ;
Dictionary<string,string> logintest = new Dictionary<string,string>
try
{
connection.Open();
reader = selectcmd.ExecuteReader();
while (reader.Read())
{
Mainform main1 = new Mainform();
this.Hide();
main1.Show();
}
reader.Close();
`

Simple
foreach (KeyValuePair<string, int> pair in logintest)
{
Console.WriteLine("{0}, {1}", pair.Key, pair.Value);
}

Related

C# Core, OracleDataReader with hasRows as false while select all rows in a table that has data

I am testing Oracle database. I wrote some code but my datareader has no rows, why? My "carros" table has data and I am selecting all of them but I am getting an empty result set it seems.
string constr = "Data Source=localhost:1521/XE;User Id=System;Password=password;";
OracleConnection con = new OracleConnection(constr);
OracleCommand oracleCommand = new OracleCommand();
oracleCommand.Connection = con;
oracleCommand.CommandText = "select preco from carro";
con.Open();
OracleDataReader oracleDataReader = oracleCommand.ExecuteReader();
string resultado = String.Empty;
//My test, I got hasRows as false
if (oracleDataReader.HasRows == false)
{
resultado = "no results";
}
//never enters this loop.
while (oracleDataReader.Read())
{
resultado += (string)oracleDataReader["preco"];
}
// Close and Dispose OracleConnection
con.Close();
con.Dispose();
return resultado;
If HasRows is false after ExecuteReader, the problem is simply that the query is returning no rows so Read will return false as well. Perhaps the someValue variable is not set correctly.
From you description, it seems that your table is named carros while your query has used carro. Try to use
oracleCommand.CommandText = "select preco from carros";
A path towards solving this can include a scattering of logging commands that write to the file system.
System.IO.File.AppendAllText(#"\\server\\C\\log.txt", "put error message here" + "\r\n");
Or for printing a variable:
System.IO.File.AppendAllText(#"\\server\\C\\log.txt", ex.ToString() + "\r\n");
Pepper variations of this command throughout your script to see where failures are happening and to validate variable values.

Insert data from server to SQLite Database

I am inserting 3000 plus data from my server to my SQLite Database. The problem is the inserting process is very slow. Is there a better way to insert the data efficiently and effectively? What I am doing is I converted the data I got from my server to JSON Object and insert it one-by-one. I know what I am doing is inefficient. How can I fix this?
public class AndroidSQLiteDb : ISQLiteDB
{
public SQLiteAsyncConnection GetConnection()
{
var dbFileName = "backend.db3";
var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var path = Path.Combine(documentsPath, dbFileName);
return new SQLiteAsyncConnection(path);
}
}
public async void FirstSyncContacts(string host, string database, string contact)
{
try
{
var db = DependencyService.Get<ISQLiteDB>();
var conn = db.GetConnection();
var sql = "SELECT * FROM tblContacts WHERE Coordinator = '" + contact + "'";
var getContacts = conn.QueryAsync<ContactsTable>(sql);
var resultCount = getContacts.Result.Count;
var current_datetime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:00");
//Check if the retailer has been sync
if (resultCount < 1)
{
try
{
syncStatus.Text = "Syncing Retailer";
var link = Constants.requestUrl + "Host=" + host + "&Database=" + database + "&Contact=" + contact + "&Request=9DpndD";
string contentType = "application/json";
JObject json = new JObject
{
{ "ContactID", contact }
};
HttpClient client = new HttpClient();
var response = await client.PostAsync(link, new StringContent(json.ToString(), Encoding.UTF8, contentType));
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
if (content != "")
{
var contactsresult = JsonConvert.DeserializeObject<List<ContactsData>>(content);
foreach (var item in contactsresult)
{
// update only the properties that you have to...
item.LastSync = Convert.ToDateTime(current_datetime);
item.ServerUpdate = Convert.ToDateTime(item.ServerUpdate);
item.MobileUpdate = Convert.ToDateTime(item.MobileUpdate);
}
await conn.InsertAsync(contactsresult);
}
}
//Proceed to next function
FirstSyncRetailerGroup(host, database, contact);
}
catch (Exception ex)
{
Console.Write("Syncing Retailer Error " + ex.Message);
}
}
//If not get the retailer
else
{
SyncContacts(host, database, contact);
}
}
catch (Exception ex)
{
Console.Write("Syncing Retailer Error " + ex.Message);
}
}
Use the non-async Insert in one background thread, instead of 3000 separate async calls...
Re-use the List from your DeserializeObject step instead of creating new local objects that will just be thrown away on each loop iteration.
No need to assign all those json properties (item.XXX) to another local variable, just update the properties of each existing ContactsData as needed before inserting it into the DB.
Example using SQLiteConnection:
// Use the non-async version of SQLiteConnection
var conn = new SQLiteConnection(dbPath, true, null);
// code removed for example...
await System.Threading.Tasks.Task.Run(() =>
{
var contactsresult = JsonConvert.DeserializeObject<List<ContactsData>>(content);
// start a transaction block so all 3000 records are committed at once.
conn.BeginTransaction();
// Use `foreach` in order shortcut the need to retrieve the object from the list via its index
foreach (var item in contactsresult)
{
// update only the properties that you have to...
item.LastSync = Convert.ToDateTime(current_datetime);
item.ServerUpdate = Convert.ToDateTime(item.ServerUpdate);
item.MobileUpdate = Convert.ToDateTime(item.MobileUpdate);
conn.Insert(item);
}
conn.Commit();
});
Example using SQLiteAsyncConnection:
var db = DependencyService.Get<ISQLiteDB>();
var conn = db.GetConnection();
~~~
var contactsresult = JsonConvert.DeserializeObject<List<ContactsData>>(content);
foreach (var item in contactsresult)
{
// update only the properties that you have to...
item.LastSync = Convert.ToDateTime(current_datetime);
item.ServerUpdate = Convert.ToDateTime(item.ServerUpdate);
item.MobileUpdate = Convert.ToDateTime(item.MobileUpdate);
}
conn.InsertAsync(contactsresult); // Insert the entire list at once...
I had the same problem so even the answer is some years late, maybe can be usefull for somebody.
This is how I did.
First: I get the data all from server as json
var response = await client.GetAsync("your_server_url");
var content = await response.Content.ReadAsStringAsync();
ResponseData = JsonConvert.DeserializeObject<DataModel>(content);
Second: Save data to database
await conn.InsertAllAsync(ResponseData)
But in my case, because our app works offline data, I first insert all data in a temp table, then I get all new records comparing main table with temp table.
NewDataFromTemp = await conn.QueryAsync<DataModel>("SELECT * FROM [TableTemp] t WHERE t.[TABLE_ID] NOT IN (SELECT g.[TABLE_ID] FROM [MainTable] g)");
And insert new records in Main table
await conn.InsertAllAsync(NewDataFromTemp)
Then I check for updated records
UpdatedDataFromTemp = await conn.QueryAsync<DataModel>("SELECT t.* FROM [TableTemp] t, [MainTable] o WHERE t.[TABLE_ID]=o.[TABLE_ID] AND t.[TABLE_UPDATED]>o.[TABLE_UPDATED]");
And update all record in main table
await conn.UpdateAllAsync(UpdatedDataFromTemp);
I use logical delete so when updating the logical delete will be updated too.

Permission to enable certain fields depends on CurrentUserID Epicor ERP10

I need help. I need to enable certain fields depends on CurrentUserID. There is one field which is UltraCombo contains of Employee's name. When the Employee's Name is selected, the other fields should be enabled if the CurrentUserID is matched with the selected Employee's name. Otherwise, the other fields should be locked. I tried to use the CanView method in the code but I don't know how to call in SQL command. Plese help me T-T
private bool CanView(string field)
{
bool result = true;
EpiDataView edv = oTrans.EpiDataViews["CallContextClientData"] as EpiDataView;
string CurrentUser = edv.dataView[edv.Row]["CurrentUserId"].ToString();
string ConnectionString = "Data Source=RWNAERP;Initial Catalog=ERP10TESTRWNA;Persist Security Info=True;User ID=sa;Password=Epicor10";
string CompanyId = ((Ice.Core.Session)(oTrans.Session)).CompanyID;
string UserID = ((Ice.Core.Session)(oTrans.Session)).UserID;
using (SqlConnection connection1 = new SqlConnection(ConnectionString))
{
DataTable dt = new DataTable();
connection1.Open();
SqlCommand cmd = new SqlCommand("SELECT DcdUserID FROM dbo.UserFile WHERE Name=#Name AND EmpID=#EmpID", connection1);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("DcdUserID", SqlDbType.NVarChar).Value = UserID;
SqlDataAdapter sqlDa = new SqlDataAdapter(cmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
result = false;
}
if (CurrentUser != "")
{
result = true;
}
connection1.Close();
connection1.Dispose();
}
What you are trying to do is on the client, but the client only connects to the AppServer and never to the SQL Database. Only the AppServer should connect to the database.
Assuming you are adding this code as a customisation script, it's much easier to get the current user info from the Session variable i.e.
var session = (Ice.Core.Session)oTrans.Session;
var userId = session.UserID;
var userName = session.UserName;
var userEmail = session.UserEmail;
In the Epicor.exe client disabling fields is best done with a RowRule, i.e.
var callContextClientData = oTrans.Factory("CallContextClientData");
var disableFieldsForUser = new RowRule("CurrentUserId", RuleCondition.Equals, ((Ice.Core.Session)trans.Session).UserID);
disableFieldsForUser.AddAction(RuleAction.AddControlSettings(stockDtlEpiDataView, "CallContextClientData.ShortChar01", SettingStyle.Disabled));
callContextClientData.AddRowRule(disableFieldsForUser);
It's not clear which fields you are matching or which you want to disable, but hopefully this should get you started.

SqlAdapter.Fill(DataSet) fills only first datatable returned by stored procedure in Xamarin

I try to fill my dataset with multiple tables using stored procedure on SQLServer. Code is simple:
var execProcedureString = "EXEC dbo.SomeProcedure ..."
var myDataSet = new DataSet();
using (var conn = new SqlConnection(connectionString))
{
using (var command = new SqlCommand(execProcedureString, conn))
{
using (var adapter = new SqlDataAdapter(command))
{
adapter.Fill(myDataSet);
}
}
}
But somehow Fill only creates (and fills) first table (not the others). It is not about procedure because it returns normal data. Am I missing something in the adapter?
I still don't know why Fill is not working. It worked before. There's walkaround (without need to specificate your datatables) but it envolves SqlDataReader
var execProcedureString = "EXEC dbo.SomeProcedure ..."
var myDataSet = new DataSet();
using (var conn = new SqlConnection(connectionString))
{
using (var command = new SqlCommand(execProcedureString, conn))
{
conn.Open();
using (var reader = new command.ExecuteReader())
{
while(!reader.IsClosed) //table.Load closes reader if it contains no more rows
{
var table = new DataTable();
myDataset.Tables.Add(table);
table.Load(reader)
}
}
}
}

How to read extended properties from Outlook contacts using EWS

I'm currently attempting to read certain properties from Outlook Contact objects through Microsoft's EWS managed API. I retrieve these Contact objects from the FindItems() function. Some of these fields are extended properties such as the Title or User1 field and I'm having difficulty reading them. At the moment, I have:
Guid propertySetId = new Guid("{00062004-0000-0000-C000-000000000046}");
ExtendedPropertyDefinition titleProp = new ExtendedPropertyDefinition(propertySetId, 0x3A45, MapiPropertyType.String);
ExtendedPropertyDefinition user1Prop = new ExtendedPropertyDefinition(propertySetId, 0x804F, MapiPropertyType.String);
string title, user1;
contact.TryGetProperty(titleProp, out title);
contact.TryGetProperty(user1Prop, out user1);
When running this, TryGetProperty always returns false. I have verified that these fields are populated in Outlook for the contacts that I am searching for.
Edit: This is how I retrieve the contact objects.
ExchangeService service = //...
Mailbox userMailbox = new Mailbox(emailAddress);
FolderId folderId = new FolderId(WellKnownFolderName.Contacts, userMailbox);
FindItemsResults<Item> results;
const string AQS = "Category:~>\"CategoryTag\"";
ItemView view = new ItemView(200);
results = service.FindItems(folderId, AQS, view);
foreach (var result in results)
{
Contact contact = result as Contact;
//...Try to read fields
}
You need to change the ItemView to include the properties (PropertySet) you wish to access.
var user1Val = string.Empty;
var user1Prop = new ExtendedPropertyDefinition(DefaultExtendedPropertySet.Address, 0x804F, MapiPropertyType.String);
ExtendedPropertyDefinition[] extendedFields = new ExtendedPropertyDefinition[] { user1Prop };
PropertySet extendedPropertySet = new PropertySet(BasePropertySet.FirstClassProperties, extendedFields);
ItemView view = new ItemView(200) { PropertySet = extendedPropertySet };
// ...
var title = contact.CompleteName.Title; // Title value
contact.TryGetProperty(user1Prop, out user1Val); // user field 1 value

Resources