I have two .xaml pages LoginPage and child page - Workloads_New . I need to pass LoginID from LoginPage to Workloads_New. But in Workloads_New I keep getting LoginID value 0. Here is my code in LoginPage:
void webService_GetUserIDCompleted(object sender, GetUserIDCompletedEventArgs e)
{
int ID = e.Result; //for example i get ID=2
if (ID > 0)
{
this.Content = new MainPage();
Workloads_New Child = new Workloads_New();
Child.LoginID = ID; //In debug mode i see that ID=2 and LoginID=2
}
}
and in Workloads_New I have:
public int LoginID { get; set; }
private void ChildWindow_Loaded(object sender, RoutedEventArgs e)
{
//to test i just want to see that id in textblock but i keep getting LoginID=0 why?
this.ErrorBlock.Text = this.LoginID.ToString();
}
The UriMapper object also supports URIs that take query-string arguments. For example, consider
the following mapping:
In XAML :
<navigation:UriMapping Uri="Products/{id}"
MappedUri="/Views/ProductPage.xaml?id={id}"></navigation:UriMapping>
In C# you can also see this
consider the following code, which embeds two numbers into a URI as
query-string arguments:
string uriText = String.Format("/Product.xaml?productID={0}&type={1}",productID, productType);
mainFrame.Navigate(new Uri(uriText), UriKind.Relative);
A typical completed URI might look something like this:
/Product.xaml?productID=402&type=12
You can retrieve the product ID information in the destination page with code like this:
int productID, type;
if (this.NavigationContext.QueryString.ContainsKey("productID"))
productID = Int32.Parse(this.NavigationContext.QueryString["productID"]);
if (this.NavigationContext.QueryString.ContainsKey("type"))
type = Int32.Parse(this.NavigationContext.QueryString["type"]);
I found answer.
In App.xaml.cs
public int LoginID { get; set; }
In LoginPage.xaml.cs where I set LoginID value I wrote
((App)App.Current).LoginID = ID;
In Workloads_New.xaml.cs where I use LoginID I wrote
this.ErrorBlock.Text = ((App)App.Current).LoginID.ToString();
Related
I have mapped the service with a linq to Sql classes and I am using wcf library for vs 2019 and in client a win form app.
I am trying sending the class created for linq to sql the next way
public List<Trades> GetAllTradings()
{
context = new DCStockTradingDataContext();
List<Trades> tradings = (from t in context.Trades
select t).ToList();
return tradings;
}
and the client
private void btnRun_Click(object sender, EventArgs e)
{
Service1Client client = new Service1Client();
var trades = client.GetAllTradings();
dgViewStocks.DataSource = trades;
//string ret = client.GetData("Hello");
//Console.WriteLine(ret);
}
I din´t know what is happening and I don´t know what is wrong
The service
and the client receives all null
I would appreciate any help about this and thank you in advance
If you get null response in WCF client, some advices:
try to call the service in SoapUi with Validation of request and response turned on. It may be useful in detecting problems.
debug Reference.cs file to see more closely what is going on
use MessageInspector to see what is received in AfterReceiveReply method
examine namespaces attentively, response often cannot be deserialized because of the difference in namespaces that are in Reference.cs and in real service
Thanks for your response and everything if this I did.
I found how I have to work with linq to sql classes and wcf. We need to take into account that you need to convert the List of linq classes to List<string. What I did
enter code here
public List<string[]> GetAllStocks()
{
context = new DCStockTradingDataContext();
System.Data.Linq.Table<Stocks> stocks = context.GetTable<Stocks>();
var allStock = (from st in stocks
select new
{
stockId = (string) st.CodeID,
currency = (char) st.Currency,
stName = st.Name,
price = (decimal) st.Price,
volument = (decimal) st.Volumen
}).ToList();
List<string[]> listRetruned = new List<string[]>();
foreach (var tr in allStock)
{
string[] t = new string[5];
t[0] = tr.stockId;
t[1] = tr.currency.ToString();
t[2] = tr.stName;
t[3] = tr.price.ToString();
t[4] = tr.volument.ToString();
listRetruned.Add(t);
}
return listRetruned;
}
and the client
I have created a model class with the expected data
public class TradingModel
{
public string TradeID { get; set; }
public string StockId { get; set; }
public decimal Bid { get; set; }
public int BidQty { get; set; }
public decimal Ask{get;set;}
public int AskQty { get; set; }
public decimal Last { get; set; }
}
and finally the method
List<TradingModel> models = new List<TradingModel>();
for(int i = 0; i < trades.Length; i++)
{
TradingModel model = new TradingModel()
{
Ask = Convert.ToDecimal(trades[i][0]),
Bid = Convert.ToDecimal(trades[i][1]),
BidQty = Convert.ToInt32(trades[i][2]),
AskQty = Convert.ToInt32(trades[i][3]),
Last = Convert.ToDecimal(trades[i][4]),
StockId = trades[i][5],
TradeID = trades[i][6],
};
models.Add(model);
}
dgViewStocks.DataSource = models;
I am not sure if this is the best way to jump to next step, but it worked for me. If someone is looking for this info as I did, wasting several days chasing the solution, I leave what I did.
There is off course changing the service and generate the proxy again
I am working on connecting to SQL database and setting variables in my C# application to match returned values from a Dapper Query.
I am able to return the correct row information (I used a datagridview to show that i get the correct row, and when i debug i see the right data) but how do I set a program variable to just one of the columns? here is some code showing my process
Connect & run stored procedure:
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MfgDataCollector"].ToString()))
{
DynamicParameters param = new DynamicParameters();
param.Add("#UserID", txt_userid.Text.Trim());
List<User> userinfo = conn.Query<User>("GetUserInfo", param, commandType: CommandType.StoredProcedure).ToList<User>();
Variables.UserID = txt_userid.Text.Trim();
datagridview1.DataSource = userinfo; //this displays the right information, however I want to store the information as a public variable(like above)
Variables.Userfull = userinfo; //when debugging this shows I have the right information but its all columns of user
User Class:
class User
{
public string UserID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int AccessLevel { get; set; }
public int FirstUse { get; set; }
public string Password { get; set; }
public int LoginCounter { get; set; }
public string LastLogin { get; set; }
public string FirstLogin { get; set; }
public string UserFullName { get; set; }
}
EDIT
per answer, I have tried to switch the command to executescalar with this code:
var userinfo = conn.ExecuteScalar<User>("GetUserInfo", param, commandType: CommandType.StoredProcedure);
This allows me to set
Variables.UserID = userinfo.UserID;
without red-squiggle lines however during run-time i get an error on the execute scalar of "System.InvalidCastException: 'Invalid cast from 'System.String' to 'Name_Space.User'.'
I have checked the User Class to ensure the data type matches with the Database and i see no problems there, I'm not sure what I'm doing wrong?
If you want value from only one column of only one row, use ExecuteScalar which is similar to ADO.NET ExecuteScalar. It will return object with which you have to deal further.
string sql = "SELECT COL1 FROM Table1 WHERE ID = 1";
//OR
//string sql = "SELECT TOP 1 COL1 FROM Table1";
//OR similar
object colValue = conn.ExecuteScalar(sql, ....);
If matching record not found, return value will be null.
Check Dapper documentation for other generic variants of method:
public static T ExecuteScalar<T>(this IDbConnection cnn, CommandDefinition command);
If you want single column from multiple rows, the way you are doing this now is correct. Just modify your SQL query/Stored Procedure to return the same. Dapper will only map returned column. All other properties in your User will remain unassigned.
If you simply want to assign values to Variables.UserID instead of binding those using DataSource, then just do that like:
Variables.UserID = userinfo.UserID;
Variables.Userfull = userinfo.UserFullName;
//and so on....
So, complete code will be something like below:
using(SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MfgDataCollector"].ToString()))
{
DynamicParameters param = new DynamicParameters();
param.Add("#UserID", txt_userid.Text.Trim());
User userinfo = conn.Query<User>("GetUserInfo", param, commandType: CommandType.StoredProcedure).ToList<User>().First();
Variables.UserID = userinfo.UserID;
Variables.Userfull = userinfo.UserFullName;
}
I want to add a button to my opportunity header record that is called Insert Products. This will send the opportunity ID to a visualforce page which will have a select file button and an insert button that will loop through the CSV and insert the records to the related opportunity.
This is for non technical users so using Data loader is not an option.
I got this working using standard apex class however hit a limit when i load over 1,000 records (which would happen regularly).
I need to convert this to a batch process however am not sure how to do this.
Any one able to point me in the right direction? I understand a batch should have a start, execute and finish. However i am not sure where i should split the csv and where to read and load?
I found this link which i could not work out how to translate into my requirements: http://developer.financialforce.com/customizations/importing-large-csv-files-via-batch-apex/
Here is the code i have for the standard apex class which works.
public class importOppLinesController {
public List<OpportunityLineItem> oLiObj {get;set;}
public String recOppId {
get;
// *** setter is NOT being called ***
set {
recOppId = value;
System.debug('value: '+value);
}
}
public Blob csvFileBody{get;set;}
public string csvAsString{get;set;}
public String[] csvFileLines{get;set;}
public List<OpportunityLineItem> oppLine{get;set;}
public importOppLinesController(){
csvFileLines = new String[]{};
oppLine = New List<OpportunityLineItem>();
}
public void importCSVFile(){
PricebookEntry pbeId;
String unitPrice = '';
try{
csvAsString = csvFileBody.toString();
csvFileLines = csvAsString.split('\n');
for(Integer i=1;i<csvFileLines.size();i++){
OpportunityLineItem oLiObj = new OpportunityLineItem() ;
string[] csvRecordData = csvFileLines[i].split(',');
String pbeCode = csvRecordData[0];
pbeId = [SELECT Id FROM PricebookEntry WHERE ProductCode = :pbeCode AND Pricebook2Id = 'xxxx HardCodedValue xxxx'][0];
oLiObj.PricebookEntryId = pbeId.Id;
oLiObj.Quantity = Decimal.valueOf(csvRecordData[1]) ;
unitPrice = String.valueOf(csvRecordData[2]);
oLiObj.UnitPrice = Decimal.valueOf(unitPrice);
oLiObj.OpportunityId = 'recOppId';;
insert (oLiObj);
}
}
catch (Exception e)
{
ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR, e + ' - ' + unitPrice);
ApexPages.addMessage(errorMessage);
}
}
}
First problem that I can sense is that the insert DML statement is inside FOR-loop. Can you put the new "oLiObj" into a List that is declared before the FOR-loop starts and then try inserting the list after the FOR-loop ?
It should bring some more sanity in your code.
I have a simple query and Poco that I'm using with Dapper like so:
var jc = this.dbConnection.ExecuteScalar<JcUser>("SELECT loginid as Username,Password,coalesce(CustomerId,0) as CustomerId,TextProfileId,UxProfileId from \"user\" where id = #id", new {id = id});
Poco:
public class JcUser
{
public string UserName { get; set; }
public string Password { get; set; }
public int CustomerId{ get; set; }
public int TextProfileId { get; set; }
public int UxProfileId { get; set; }
}
When this executes it throws an exception with the message
Value is not a convertible object: System.String to JcUser
The stack trace ends up at: at System.Convert.ToType (System.Object value, System.Type conversionType, IFormatProvider provider, Boolean try_target_to_type)
Any ideas why its doing this?
Thanks
UPDATE: Using var jc = this.dbConnection.Query<JcUser>("SELECT loginid as Username,Password,coalesce(CustomerId,0) as CustomerId,TextProfileId,UxProfileId from \"user\" where id = #id", new {id = id}).First(); appears to work. I also realise I'm a moron and ExecuteScalar is only for one value. However, is my update the best way to retrieve only one row?
ExecuteScalar maps to the ADO.NET method of the same name. It returns at most one cell: one grid, one row, one column. As such, it is not intended for use with complex objects, and cannot work correctly in your case as you have multiple columns.
Dapper assumes you would only use that with simple types like int, string etc.
In your case, use:
var jc = this.dbConnection.Query<JcUser>(
sql, args).SingleOrDefault();
If you want to avoid a hidden List<> allocation you could also pass buffered: false.
I am completely new to silverlight and WCF. Still reading online stuff and trying to write some code to get going. :)
My question is, I want to insert data into database and my insert method returns a bool. How would I catch the return value in silverlight in the button click event and display confirmation message to the user.
My Service code is:
[OperationContract]
public bool insertData(string Name, string Address, string cType, string postcode, string city, string phone, string email)
{
bussAppDataContext dc = new bussAppDataContext();
TestTable tt = new TestTable();
tt.CompanyName = Name;
tt.Address = Address;
tt.CompanyType = cType;
tt.Postcode = postcode;
tt.City = city;
tt.Telephone = phone;
tt.Email = email;
dc.TestTables.InsertOnSubmit(tt);
dc.SubmitChanges();
return true;
}
And the silverlight client code is:
private void btnSend_Click(object sender, System.Windows.RoutedEventArgs e)
{
FirstServiceReference.FirstServiceClient webServc = new FirstServiceReference.FirstServiceClient();
webServc.insertDataAsync(txtCName.Text.Trim(), txtAddress.Text.Trim(), cmbCType.SelectedValue.ToString(), txtPostcode.Text.Trim(), txtCity.Text.Trim(), txtPhone.Text.Trim(), txtEmail.Text.Trim());
}
all webservice calls are async in silverlight so you need to add a handler to the insertDataCompleted event. This event is called when the operation is done.
Something like this:
webServc.insertDataCompleted += MyHandler;
webServc.insertDataAsync(txtCName.Text.Trim(), txtAddress.Text.Trim(), cmbCType.SelectedValue.ToString(), txtPostcode.Text.Trim(), txtCity.Text.Trim(), txtPhone.Text.Trim(), txtEmail.Text.Trim());
}
private void MyHandler(object sender, MyEventArgs args) {}
The args have the boolean as result.
Have a look here Calling web services with Silverlight Tim Heuer.
Hope this helps.
BR,
TJ