In the B Viewcontroller, I store data into NSUserDefaults and retrieve them in AViewController.
During the execution, it performs as it expected. However, once I close and re-run the app, I figure out that these information (dictionary) does not being stored.
Here is the BViewController where I store the data in NSUserDefaults
partial class BViewController : UIViewController
{
const string server = "server";
const string port = "port";
const string password = "password";
const string username = "username";
const string inboxuserid = "inboxuserid";
.............
.............
public override void ViewWillDisappear (bool animated)
{
var appDefaults = new NSDictionary (server, serverTF.Text, port, portTF.Text, password, passwordTF.Text,username,usernameTF.Text, inboxuserid,inboxuserTF.Text);
NSUserDefaults.StandardUserDefaults.RegisterDefaults (appDefaults);
NSUserDefaults.StandardUserDefaults.Synchronize ();
}
}
and retrieve them in the A ViewController as follows:
partial class AViewController : UIViewController
{
public override void ViewWillAppear(bool animated)
{
var username = NSUserDefaults.StandardUserDefaults.StringForKey ("username");
Console.WriteLine (username);
}
}
Based on the following article: https://moovendan.wordpress.com/2012/12/26/monotouch-nsuserdefaults-store-values-in-settings/
I would propose the following code, I have tested with a small example and it worked.
BViewController, store the dictionary in the NSUserDefaults:
NSDictionary appDefaults= new NSDictionary(server, serverTF.Text, port, portTF.Text, password, passwordTF.Text, username, usernameTF.Text, inboxuserid, inboxuserTF.Text);
NSString key = new NSString ("dict");
NSUserDefaults.StandardUserDefaults.SetValueForKey (appDefaults, key);
AViewController, retrive the dictionary from NSUserDefaults:
NSString key = new NSString ("dict");
NSDictionary d2 = NSUserDefaults.StandardUserDefaults.DictionaryForKey (key);
Console.WriteLine (d2["username"]);
Related
i have tried to pass data gave in textfield from one application to another application through Url Scheme
First i have set the url scheme and identifier in the receiver app info.plist.
i have added LsApplicationQueriesScheme in info.list in receiver app
i have put this code in first sender App. namefield is the Textfield i given in this app.
partial void clicked(UIButton sender)
{ string text = namefield.Text;
var urlToSend = new Uri("soWhat://" + text);
Console.WriteLine(urlToSend);
UIApplication.SharedApplication.OpenUrl(urlToSend);
}
and i have put receiver app AppDelegate.cs
public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options)
{
UIAlertView alert = new UIAlertView();
var uri = new Uri(url.Host);
sun = uri.ToString();
alert.Message = sun;
Console.WriteLine(sun);
alert.Show();
alert.DangerousRelease();
return base.OpenUrl(app, url, options);
}
i have to pass data from one app to another app through urlscheme
Step1: first app sender-app..
info.plist Add this points
<Array>
LSApplicationQuerieScheme
<string>receiverapp</string>
</Array>
Step 2. add this code in this viewcontroller button action
partial void btnact(UIButton sender)
{
string name = namefield.Text;
var names = name.ToString();
var app = UIApplication.SharedApplication;
var na = "receiverapp://" + (names ?? "");
var uri = new NSUrl(na);
var dict = new NSDictionary();
if (app.CanOpenUrl(uri))
{
app.OpenUrl(uri, options: dict, completion: null);
Console.WriteLine(uri);
}
Step 3: In receiverapp
info.plist add url types
url-scheme = receiverapp
url-identifier = com.receiverapp
Role = Editor
Step 4: in Appdelegate.cs in receiverapp
add this code
public string message;
NSNotificationCenter nc = NSNotificationCenter.DefaultCenter;
public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options)
{
message = url.Host;
nc.PostNotificationName("AppInput", null);
Console.WriteLine(message);
return true;
//return base.OpenUrl(app, url, options);
}
Step5: ViewController.cs in receiverapp
add this code
AppDelegate dele = (AppDelegate)UIApplication.SharedApplication.Delegate;
public override void ViewDidLoad()
{
base.ViewDidLoad();
NSNotificationCenter.DefaultCenter.AddObserver(this, new ObjCRuntime.Selector("GetData:"), new NSString("AppInput"), null);
}
[Export("GetData:")]
private void GetData(NSNotification notification)
{
label.Text = dele.message;
Console.WriteLine(label.Text);
}
I am trying to do an export to excel button when it gets hit I want to call this api and download an excel sheet.
my controller code looks like this and I am honestly stuck because I am unsure what I should be returning back. I am new to .net core api sorry
[Route("api/excel")]
public class ExportToExcel : Controller
{
private readonly ScadaContext _context;
public ExportToExcel(ScadaContext context)
{
_context = context;
}
// GET: api/values
[HttpGet]
public ActionResult GetExcelMainView()
{
var query = _context.Main_View.Where(x => !x.MeterId.StartsWith("HOGC"));
List<Object[]> MainViewList = new List<Object[]>();
foreach(var p in query)
{
MainViewList.Add(new Object[] { "Battery Voltage", p.BatteryVoltage });
}
MemoryStream stream = new MemoryStream();
using (ExcelPackage pck = new ExcelPackage(stream))
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("MainView");
ws.Cells["A1"].LoadFromArrays(MainViewList);
Response.Clear();
Response.Headers.Add("content-disposition", "attachment; filename=Clients.xlsx");
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
var bytes = pck.GetAsByteArray();
Response.Body.WriteAsync(bytes, 0, bytes.Length);
}
}
}
Your simplest way to use one of the FileResult subclassess,
such as FileStreamResult
The controller method File(stream,...,...) does it for you:
return File(stream, contentTypeString, willbeSavedWithThisFileName);
should just work. I'm not sure if you'll have to re-"wrap" your package in a memorystream again
var streamagain = new MemoryStream(package.GetAsByteArray());
(with the "handrolled" code you've already written, I'd try return StatusCode(200) as the way to get your Content back to the client).
I have the following code on server:
public class UploadController : ApiController
{
public void Put(string filename, string description)
{
...
}
public void Put()
{
...
}
and try to call it from client:
var clientDescr = new HttpClient();
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("filename", "test"));
postData.Add(new KeyValuePair<string, string>("description", "100"));
HttpContent contentDescr = new FormUrlEncodedContent(postData);
clientDescr.PutAsync("http://localhost:8758/api/upload", contentDescr).ContinueWith(
(postTask) =>
{
postTask.Result.EnsureSuccessStatusCode();
});
but this code calls second put method (without parameters). Why and how to call first put method correctly?
You have several options here:
You can either choose to pass the parameters in the query string, by just changing the URI to:
http://localhost:8758/api/upload?filename=test&description=100
or you can have Web API parse the form data for you by changing your action to look like this:
public void Put(FormDataCollection formData)
{
string fileName = formData.Get("fileName");
string description = formData.Get("description");
}
You can also choose to create a class that has a fileName and a description property and use that as your parameter and Web API should be able to bind it correctly for you.
Using Monotouch 5.2.11 iOS
I have followed this tutorial (http://tirania.org/monomac/archive/2011/Jan-18.html), created a custom cell with an image and have also added the IElementSizing Interface. The GetHeight is never called.
Similar questions have been asked and the generally accepted solution was to make sure and create the RootElements first, set the UnEvenRows=true before adding them to the Controller. This did not work. I've tried that as well as about every other combination of adding sections to root elements and have not ever seen the GetHeight fired.
The MyDataElement is an image that is 320x200 which displays fine, but the string element that comes after it is not shown (assuming it is behind it). Consequently if I drag the custom cell up above the top, it disappears, reappears, and the second stringelement displays on top of it.
Here is the code I've tried:
public class MyDataElement : Element, IElementSizing {
static NSString key = new NSString ("myDataElement");
public MyData MyData;
public MyDataElement (MyData myData) : base (null)
{
MyData = myData;
}
public float GetHeight (UITableView tableView, NSIndexPath indexPath){
return 200f; // break point here is never hit ever
}
public override UITableViewCell GetCell (UITableView tv)
{
var cell = tv.DequeueReusableCell (key) as MyDataCell;
if (cell == null)
cell = new MyDataCell (MyData, key);
else
cell.UpdateCell (MyData);
return cell;
}
public partial class TableTester : DialogViewController
{
public TableTester () : base (UITableViewStyle.Grouped, null)
{
var re = new RootElement("Sample") {
new Section("Testy") {
new MyDataElement(new MyData() { stuff="hello"}),
new StringElement("Sample")
}
};
re.UnevenRows = true;
this.Root = re;
//this.Root = root;
}
}
In addition to that I've even done this which didn't work either:
public class TestNavigator : UINavigationController {
public TestNavigator() {
TabBarItem = new UITabBarItem("Test", null, 1);
var re = new RootElement("Sample") {
new Section("Sammy") {
new StringElement("Sample"),
new MyDataElement(new MyData() { stuff="sam"}),
new StringElement("Sample 2")
}
};
re.UnevenRows = true;
var dv = new DialogViewController(re);
re.UnevenRows = true;
PushViewController(dv, true);
}
After plenty of trial and error, I had to make sure and remove the reference to Monotouch.Dialog that I had downloaded from github and use the built in reference. It seems that the getheight maybe broken in github.
We have a problem with SharePoint's search box. Whenever we try to search for something we get:
Unable to validate data. at
System.Web.Configuration.MachineKeySection.EncryptOrDecryptData(Boolean
fEncrypt, Byte[] buf, Byte[] modifier,
Int32 start, Int32 length, IVType
ivType, Boolean useValidationSymAlgo)
at
System.Web.UI.ObjectStateFormatter.Deserialize(String
inputString) exeption.
Does any one know the reason for this exception, or a way to work around it?
New entry:
I'm using a SPGridView where i use the datakeys property in a web part. The webpart works, but we found that using the datakeys property breaks seach in that if you try to use the search textbox and click the seach button it gets this exception:
Unable to validate data. at System.Web.Configuration.MachineKeySection.EncryptOrDecryptData(Boolean fEncrypt, Byte[] buf, Byte[] modifier, Int32 start, Int32 length, IVType ivType, Boolean useValidationSymAlgo)
at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString)
This is what i have tryed to do:
Make the gridview not spgridview and set autogenerate true (works)
Remove the datakeynames (works)
Test with a empty gridvew (failes)
Test with a non-empty gridview (failes)
Change Machine Keys (failes)
Turn of view state on the gridvew (failes)
Move the gridview ti a ascx file (failes)
I can't seem to figure this one out. Have enyone got this error and been able to work around it?
EDit 10.09.2009
This is the last code I tested. I used a MSDN excample as referance. I have also tried without Data table MSDN Example
public class TestErrorGridView : System.Web.UI.WebControls.WebParts.WebPart
{
Control ascxToAdd;
protected DataTable PropertyCollection = new DataTable();
private DataColumn key;
public TestErrorGridView()
{
key = PropertyCollection.Columns.Add("ID", typeof(string));
PropertyCollection.Columns.Add("Name", typeof(string));
}
public void AddProperty(TestBindObject data)
{
DataRow newRow = PropertyCollection.Rows.Add();
newRow["ID "] = data.ID;
newRow["Name"] = data.Name;
}
public void BindGrid(SPGridView grid)
{
SPBoundField fldPropertyName = new SPBoundField();
fldPropertyName.HeaderText = "ID";
fldPropertyName.DataField = "ID";
grid.Columns.Add(fldPropertyName);
SPBoundField fldPropertyValue = new SPBoundField();
fldPropertyValue.HeaderText = "Name";
fldPropertyValue.DataField = "Name";
grid.Columns.Add(fldPropertyValue);
PropertyCollection.PrimaryKey = new DataColumn[] { key };
grid.DataSource = PropertyCollection.DefaultView;
grid.DataKeyNames = new string[] { key.ColumnName };
grid.DataBind();
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
}
protected override void CreateChildControls()
{
base.CreateChildControls();
TestBindObject t1 = new TestBindObject() { ID = 1, Name = "Test3" };
this.AddProperty(t1);
SPGridView testGrid = new SPGridView() { AutoGenerateColumns = false };
this.BindGrid(testGrid);
this.Controls.Add(testGrid);
}
}
[Serializable]
public class TestBindObject
{
public int ID { get; set; }
public string Name { get; set; }
}
From the error message I'd say that you are operating in a web-farm environment. Have you set the same machineKey in each of the SharePoint web.config files? See this link for a little more info.