How to update dictionary in Swift located at every index of Array - dictionary

This response is coming from server in JSON format
posts =
(
{
commentCount = 0;
"country_id" = 225;
"country_name" = "United States";
dislikeCount = 2;
disliked = 0;
firstname = Test;
imageHeight = 0;
imagePath = "";
imageWidth = 0;
lastname = Test;
likeCount = 2;
liked = 0;
postid = 126;
posttime = "2014-11-10 12:26:43";
shareCount = 0;
statusUpdate = Hello;
"upload_type" = text;
userId = 13;
userimage = "https://Test.com/1409976093.png";
videoHeight = "";
videoPath = "";
videoThumbnail = "";
videoWidth = "";
},
{
commentCount = 0;
"country_id" = 225;
"country_name" = "United States";
dislikeCount = 2;
disliked = 0;
firstname = Test;
imageHeight = 0;
imagePath = "";
imageWidth = 0;
lastname = Test;
likeCount = 3;
liked = 0;
postid = 125;
posttime = "2014-10-28 17:50:00";
shareCount = 0;
statusUpdate = "Happy%20chhata%20puja%20to%20you%20and%20your%20family%0Athanks%0ADr%20shah%20family";
"upload_type" = text;
userId = 78;
userimage = "https://Test.com/1410142960.png";
videoHeight = "";
videoPath = "";
videoThumbnail = "";
videoWidth = "";
}
Now I need to update the value of "liked" from 0 to 1 locally but I am not able to do that. I have stored this array in my array like this:
self.homePageDataArray.addObjectsFromArray(dictionary["posts"] as NSMutableArray)
And I am able to fetch the content from every index and also able to show this in TableView but I want to changed the status of "liked" from 0 to 1 when user will tap on the "Like Button" in my app. Obviously I will update this on server but I want to update that locally as well parallely.
Please let me know how it can be achieved. I tried a lot but every time it is showing some error! For Instance,
var tempDic:Dictionary<AnyObject,AnyObject> = self.homePageDataArray[selectedRow] as Dictionary
I am getting this error
Type 'AnyObject' does not conform to protocol 'Hashable'
Ultimately, I want to able to able to use the "updateValue" method so that I can update the value of my dictionary in my array.

This should work for you:
var tempDic = self.homePageDataArray[selectedRow] as Dictionary<String, AnyObject>
Your version:
var tempDic:Dictionary<AnyObject,AnyObject> = self.homePageDataArray[selectedRow] as Dictionary
Will not work because AnyObject is not conformable to Hashable, a requirement for the generic key type in Dictionary.
And to answer your other question:
var tempDic = self.homePageDataArray[selectedRow] as NSMutableDictionary as Dictionary
The statement above compiles because Dictionary is bridgeable to it's Objective-C counterpart; NSMutableDictionary. Your resultant dictionary will be of type Dictionary<String, AnyObject>. You're probably wondering how the type String was inferred. Well, NSMutableDictionary uses NSString as keys, a type which is bridgeable to it's Swift counterpart, you guessed it; String.

I really don't know WHY, but following solution worked for me
var tempDic = self.homePageDataArray[selectedRow] as NSMutableDictionary as Dictionary
If anyone can explain then it will help others also!

Related

Can this query be changed to add an or?

I'm not sure how to change this query in google app maker language
var query = app.models.folders.newQuery();
query.filters.requestId._equals = request;
query.filters.filecount._equals = null;
var total = 0;
var recx = query.run();
So right now it is the equivalent of
select * from folders
where requestID = request
and filecount = null
But I would like to know if there is a way to change it to the equivalent of
select * from folders
where requestID = request
and (filecount = null or filecount < 0)
Maybe by using query.where?
You could try by just adding another filter to your query:
var query = app.models.folders.newQuery();
query.filters.requestId._equals = request;
query.filters.filecount._equals = null;
query.filters.filecount._lessThan = 0;
var total = 0;
var recx = query.run();

Cosmosdb store procedure get less documents than real

I am preparing store procedure on cosmosdb by Javascript, however, it gets less documents than the real number of documents in collection.
The sproc is called by C#, C# pass a parameter "transmitterMMSI" which is also the partition key of this collection.
First, the following query is executed in sproc:
var query = 'SELECT COUNT(1) AS Num FROM AISData a WHERE a.TransmitterMMSI="' + transmitterMMSI + '"';
The result is output in response, and the value is 5761, which is the same as the real number of documents in collection.
However, when I change the query to the following:
var query = 'SELECT * FROM AISData a WHERE a.TransmitterMMSI="' + transmitterMMSI + '"';
The documents.length is output as 5574, which is smaller than the real number.
I have already changed the pageSize: -1, which should mean unlimited.
I did some search with google and stack overflow, it seems that continuation can be help. However, I tried some examples, and they don't work.
Anyone familiar with this can help?
The following list the scripts.
The sproc js script is here, which is also the file "DownSampling.js" used in the C# code:
function DownSampling(transmitterMMSI, interval) {
var context = getContext();
var collection = context.getCollection();
var response = context.getResponse();
var receiverTime;
var tempTime;
var groupKey;
var aggGroup = new Object();
var query = 'SELECT * FROM AISData a WHERE a.TransmitterMMSI="' + transmitterMMSI + '"';
var accept = collection.queryDocuments(collection.getSelfLink(), query, { pageSize: -1},
function (err, documents, responseOptions) {
if (err) throw new Error("Error" + err.message);
// Find the smallest deviation comparting to IntervalTime in each group
for (i = 0; i < documents.length; i++) {
receiverTime = Date.parse(documents[i].ReceiverTime);
tempTime = receiverTime / 1000 + interval / 2;
documents[i].IntervalTime = (tempTime - tempTime % interval) * 1000;
documents[i].Deviation = Math.abs(receiverTime - documents[i].IntervalTime);
// Generate a group key for each group, combinated of TransmitterMMSI and IntervalTime
groupKey = documents[i].IntervalTime.toString();
if (typeof aggGroup[groupKey] === 'undefined' || aggGroup[groupKey] > documents[i].Deviation) {
aggGroup[groupKey] = documents[i].Deviation;
}
}
// Tag the downsampling
for (i = 0; i < documents.length; i++) {
groupKey = documents[i].IntervalTime;
if (aggGroup[groupKey] == documents[i].Deviation) {
documents[i].DownSamplingTag = 1;
} else {
documents[i].DownSamplingTag = 0;
}
// Remove the items that are not used
delete documents[i].IntervalTime;
delete documents[i].Deviation;
// Replace the document
var acceptDoc = collection.replaceDocument(documents[i]._self, documents[i], {},
function (errDoc, docReplaced) {
if (errDoc) {
throw new Error("Update documents error:" + errDoc.message);
}
});
if (!acceptDoc) {
throw "Update documents not accepted, abort ";
}
}
response.setBody(documents.length);
});
if (!accept) {
throw new Error("The stored procedure timed out.");
}
}
And the C# code is here:
private async Task DownSampling()
{
Database database = this.client.CreateDatabaseQuery().Where(db => db.Id == DatabaseId).ToArray().FirstOrDefault();
DocumentCollection collection = this.client.CreateDocumentCollectionQuery(database.SelfLink).Where(c => c.Id == AISTestCollectionId).ToArray().FirstOrDefault();
string scriptFileName = #"..\..\StoredProcedures\DownSampling.js";
string scriptId = Path.GetFileNameWithoutExtension(scriptFileName);
var sproc = new StoredProcedure
{
Id = scriptId,
Body = File.ReadAllText(scriptFileName)
};
await TryDeleteStoredProcedure(collection.SelfLink, sproc.Id);
sproc = await this.client.CreateStoredProcedureAsync(collection.SelfLink, sproc);
IQueryable<dynamic> query = this.client.CreateDocumentQuery(
UriFactory.CreateDocumentCollectionUri(DatabaseId, AISTestCollectionId),
new SqlQuerySpec()
{
//QueryText = "SELECT a.TransmitterMMSI FROM " + AISTestCollectionId + " a",
QueryText = "SELECT a.TransmitterMMSI FROM " + AISTestCollectionId + " a WHERE a.TransmitterMMSI=\"219633000\"",
}, new FeedOptions { MaxItemCount = -1, EnableCrossPartitionQuery = true, MaxDegreeOfParallelism = -1, MaxBufferedItemCount = -1 });
List<dynamic> transmitterMMSIList = query.ToList(); //TODO: Remove duplicates
Console.WriteLine("TransmitterMMSI count: {0}", transmitterMMSIList.Count());
HashSet<string> exist = new HashSet<string>();
foreach (var item in transmitterMMSIList)
{
//int transmitterMMSI = Int32.Parse(item.TransmitterMMSI.ToString());
string transmitterMMSI = item.TransmitterMMSI.ToString();
if (exist.Contains(transmitterMMSI))
{
continue;
}
exist.Add(transmitterMMSI);
Console.WriteLine("TransmitterMMSI: {0} is being processed.", transmitterMMSI);
var response = await this.client.ExecuteStoredProcedureAsync<string>(sproc.SelfLink,
new RequestOptions { PartitionKey = new PartitionKey(transmitterMMSI) }, transmitterMMSI, 30);
string s = response.Response;
Console.WriteLine("TransmitterMMSI: {0} is processed completely.", transmitterMMSI);
}
}
private async Task TryDeleteStoredProcedure(string collectionSelfLink, string sprocId)
{
StoredProcedure sproc = this.client.CreateStoredProcedureQuery(collectionSelfLink).Where(s => s.Id == sprocId).AsEnumerable().FirstOrDefault();
if (sproc != null)
{
await client.DeleteStoredProcedureAsync(sproc.SelfLink);
}
}
I tried to comment the 2 loops in the JS codes, only the documents.length output, while the response number is still less. However, I changed the query to SELECT a.id, the documents.length is correct. Looks like it is the continuation issue.
The sproc is probably timing out. To use a continuation token in these circumstances, you will need to return it to your C# calling code then make another call to the sproc passing in your token. If you show us your sproc code we can help more.
You can use a continuation token to make repeated calls to queryDocuments() from within the sproc without additional roundtrips to the client. Keep in mind that if you do this too many times your sproc will eventually timeout, though. In your case, it sounds like you're already very close to getting all of the documents you're seeking so maybe you will be OK.
Here is an example of using a continuation token within a sproc to query multiple pages of data:
function getManyThings() {
var collection = getContext().getCollection();
var query = {
query: 'SELECT r.id, r.FieldOne, r.FieldTwo FROM root r WHERE r.FieldThree="sought"'
};
var continuationToken;
getThings(continuationToken);
function getThings(continuationToken) {
var requestOptions = {
continuation: continuationToken,
pageSize: 1000 // Adjust this to suit your needs
};
var isAccepted = collection.queryDocuments(collection.getSelfLink(), query, requestOptions, function (err, feed, responseOptions) {
if (err) {
throw err;
}
for (var i = 0, len = feed.length; i < len; i++) {
var thing = feed[i];
// Do your logic on thing...
}
if (responseOptions.continuation) {
getThings(responseOptions.continuation);
}
else {
var response = getContext().getResponse();
response.setBody("RESULTS OF YOUR LOGIC");
}
});
if (!isAccepted) {
var response = getContext().getResponse();
response.setBody("Server rejected query - please narrow search criteria");
}
}
}

Get value from Array using dynamic key in flex

I have an array as follow.
var array:Array = new Array();
array["Circle"] = 1;
array["Rect"] = 2;
I wantto read the values by using a variable.
var key:String = "Circle";
trace(array[key]);
Can anyone guide me how to achieve this. Its not neccessary to go with Array only. I may switch to whichever collection in which this is possible.
Use Object or Dictionary:
var obj:Object = new Object();
obj["Circle"] = 1;
obj["Rect"] = 2;
// alternative initialization - only for Object
obj = {Circle: 1, Rect: 2};
for (var key:String in obj)
{
trace("key:", key, ",", "value:" obj[key]);
}
// output:
// key: Circle , value: 1
// key: Rect , value: 2
for each (var value:Object in obj)
{
trace(value);
}
// output:
// 1
// 2

Bind dropdown to local (browser) database with HTML5/jQuery/ASP.NET

So I know how to store and retrieve data in a local database (Chrome). My function to retrieve data is
function SelectHandler(transaction, results) {
for (var i = 0; i < results.rows.length; i++) {
var row = results.rows.item(i);
var customer = new Object();
customer.id = row['id'];
customer.fname = row['fname'];
customer.lname = row['lname'];
}
}
I know how to assign the values from the function above to textboxes/labels etc but how do I create options in a dropdownlist with for example text first name and value id? I want to be able to select a name in the dropdown and then populate a textbox with the related last name (simplified example).
Thanks in advance.
for (var i = 0; i < results.rows.length; i++) {
var row = results.rows.item(i);
var newFeature = new Object();
newFeature.id = row['id'];
newFeature.name = row['name']
$('#ddlPatients').append(
$('<option></option>').val(newFeature.id).html(newFeature.name)
);
}

What is the best way to accept a credit card in ASP.NET? (Between ASP.NET and Authorize.NET)

I'm new to creating commerce websites, and now that I need to sell software over the internet, I'm not sure where to start.
I'm using ASP.NET and am considering using Authorize.NET to validate and process the credit cards.
I'm looking for a stable, trusted solution that I can install on a single server. My secondary goal (besides selling products online) is to become familiar with shopping cart software that is popular, and in use by large businesses. Perhaps I should start with MS Commerce server?
There are a million options here, but if you are writing the code, the easiest way code-wise is to use http://sharpauthorize.com/
Authorize.Net is Very easy to implement with ASP.NET
Basically you can make transaction in 3-4 ways:
Simple Checkout Through Button like Paypal (http://developer.authorize.net/api/simplecheckout/)
Direct Post : Suppose you little bit more customization than Simple CheckOut. Create a checkout form that posts directly to Authorize.Net http://developer.authorize.net/api/simplecheckout/
Eg:
<h1><%=ViewData["message"] %></h1>
<%using (Html.BeginSIMForm("http://YOUR_SERVER.com/home/sim",
1.99M,"YOUR_API_LOGIN","YOUR_TRANSACTION_KEY",true)){%>
<%=Html.CheckoutFormInputs(true)%>
<%=Html.Hidden("order_id","1234") %>
<input type = "submit" value = "Pay" />
<%}%>
SIM (Server Integration)
AIM (Advance Integration Method): Give full control & customization.
CIM ( store Customer card no & info on Auth.NET server with tokanization)
*Below is a sample of CIM function to make a transaction, AIM is very much similar to CIM only difference is tokanization *
using ProjName.AuthApiSoap; // USE AUth Webserice Reference
public Tuple<string, string, string> CreateTransaction(long profile_id, long payment_profile_id, decimal amt, string DDD)
{
CustomerProfileWS.ProfileTransAuthCaptureType auth_capture = new CustomerProfileWS.ProfileTransAuthCaptureType();
auth_capture.customerProfileId = profile_id;
auth_capture.customerPaymentProfileId = payment_profile_id;
auth_capture.amount = amt;//1.00m;
auth_capture.order = new CustomerProfileWS.OrderExType();
POSLib.POSManager objManager = new POSLib.POSManager();
auth_capture.order.invoiceNumber = objManager.GetTimestamp(DateTime.Now);
DateTime now = DateTime.Now;
auth_capture.order.description = "Service " + DDD;
CustomerProfileWS.ProfileTransactionType trans = new CustomerProfileWS.ProfileTransactionType();
trans.Item = auth_capture;
CustomerProfileWS.CreateCustomerProfileTransactionResponseType response = SoapAPIUtilities.Service.CreateCustomerProfileTransaction(SoapAPIUtilities.MerchantAuthentication, trans, null);
string AuthTranMsg = "";
string AuthTranCode = "";
for (int i = 0; i < response.messages.Length; i++)
{
AuthTranMsg = response.messages[i].text; // To Get Message n for loop to check the [i] is not empty
}
for (int i = 0; i < response.messages.Length; i++)
{
AuthTranCode = response.messages[i].code; // To Get Code n for loop to check the [i] is not empty
}
var tCompResp = new Tuple<string, string, string>(AuthTranCode, AuthTranMsg, response.directResponse);
return tCompResp;
}
This is how to split the Reponse Msg (Format and Order will be FIXED for all transaction/ on web service responsed )
var tResp = objManager.CreateTransaction(profID, paymProfID, Convert.ToDecimal(PmtToday), DDD);
string respCCNo = "";
string RespCCType = "";
string InvoiceNo = "";
string transType = "";
string approvalCode = "";
string AmtRequested = "";
string respName = "";
string respReasonText = "";
string respMD5Hash = "";
string respEmailId = "";
string respReasonCode = "";
string respMethod = "";
string respAVSResultCode = "";
string responseCode = "";
string transactionId = "0";
if (!string.IsNullOrEmpty(tCompResp.Item3))
{
string[] arrRespParts = tCompResp.Item3.Replace("|", "").Split(',');
responseCode = arrRespParts[0];
respReasonCode = arrRespParts[2];
respReasonText = arrRespParts[3];
approvalCode = arrRespParts[4];
respAVSResultCode = arrRespParts[5];
transactionId = arrRespParts[6].Replace("|", "");
InvoiceNo = arrRespParts[7];
AmtRequested = arrRespParts[9];
transType = arrRespParts[10];
respMethod = arrRespParts[11];
respName = arrRespParts[13] + " " + arrRespParts[14];
respEmailId = arrRespParts[23];
respMD5Hash = arrRespParts[37];
respCCNo = arrRespParts[50];
RespCCType = arrRespParts[51];
}
==================================AIM Code
public Tuple<string, string, string> ECheckCreateTransAIM(string amount, string bankRoutingNo, string bankAccNo, string bankAccType, string bankName, string bankAccName, string echeckType, bool isCustomerEmail, string customerEmail, string mechantEMail)
{
//CustomValidator1.ErrorMessage = "";
string AuthNetVersion = "3.1"; // Contains CCV support
WebClient webClientRequest = new WebClient();
System.Collections.Specialized.NameValueCollection InputObject = new System.Collections.Specialized.NameValueCollection(30);
System.Collections.Specialized.NameValueCollection ReturnObject = new System.Collections.Specialized.NameValueCollection(30);
byte[] ReturnBytes;
string[] ReturnValues;
string ErrorString;
InputObject.Add("x_version", AuthNetVersion);
InputObject.Add("x_delim_data", "True");
InputObject.Add("x_login", MERCHANT_NAME);
InputObject.Add("x_tran_key", TRANSACTION_KEY);
InputObject.Add("x_relay_response", "False");
//----------------------Set to False to go Live--------------------
InputObject.Add("x_test_request", "False");
//---------------------------------------------------------------------
InputObject.Add("x_delim_char", ",");
InputObject.Add("x_encap_char", "|");
if (isCustomerEmail)
{
InputObject.Add("x_email", customerEmail);
InputObject.Add("x_email_customer", "TRUE"); //Emails Customer
}
InputObject.Add("x_merchant_email", mechantEMail);
// FOR echeck
InputObject.Add("x_bank_aba_code", bankRoutingNo);
InputObject.Add("x_bank_acct_num", bankAccNo);
InputObject.Add("x_bank_acct_type", bankAccType);
InputObject.Add("x_bank_name", bankName);
InputObject.Add("x_bank_acct_name", bankAccName);
InputObject.Add("x_method", "ECHECK");
InputObject.Add("x_type", "AUTH_CAPTURE");
InputObject.Add("x_amount", string.Format("{0:c2}", Convert.ToDouble(amount)));
// Currency setting. Check the guide for other supported currencies
//needto change it to Actual Server URL
//Set above Testmode=off to go live
webClientRequest.BaseAddress = eCheckBaseAddress; //"https://apitest.authorize.net/soap/v1/Service.asmx"; //"https://secure.authorize.net/gateway/transact.dll";
ReturnBytes = webClientRequest.UploadValues(webClientRequest.BaseAddress, "POST", InputObject);
ReturnValues = System.Text.Encoding.ASCII.GetString(ReturnBytes).Split(",".ToCharArray());
if (ReturnValues[0].Trim(char.Parse("|")) == "1") // Succesful Transaction
{
//AuthNetCodeLabel.Text = ReturnValues[4].Trim(char.Parse("|")); // Returned Authorisation Code
//AuthNetTransIDLabel.Text = ReturnValues[6].Trim(char.Parse("|")); // Returned Transaction ID
var tCompResp = new Tuple<string, string, string>("I00001", ReturnValues[3].Trim(char.Parse("|")), string.Join(",", ReturnValues));
return tCompResp;
}
else
{
// Error!
ErrorString = ReturnValues[3].Trim(char.Parse("|")) + " (" + ReturnValues[2].Trim(char.Parse("|")) + ")";
if (ReturnValues[2].Trim(char.Parse("|")) == "45")
{
if (ErrorString.Length > 1)
ErrorString += "<br />n";
// AVS transaction decline
ErrorString += "Address Verification System (AVS) " +
"returned the following error: ";
switch (ReturnValues[5].Trim(char.Parse("|")))
{
case "A":
ErrorString += " the zip code entered does not match the billing address.";
break;
case "B":
ErrorString += " no information was provided for the AVS check.";
break;
case "E":
ErrorString += " a general error occurred in the AVS system.";
break;
case "G":
ErrorString += " the credit card was issued by a non-US bank.";
break;
case "N":
ErrorString += " neither the entered street address nor zip code matches the billing address.";
break;
case "P":
ErrorString += " AVS is not applicable for this transaction.";
break;
case "R":
ErrorString += " please retry the transaction; the AVS system was unavailable or timed out.";
break;
case "S":
ErrorString += " the AVS service is not supported by your credit card issuer.";
break;
case "U":
ErrorString += " address information is unavailable for the credit card.";
break;
case "W":
ErrorString += " the 9 digit zip code matches, but the street address does not.";
break;
case "Z":
ErrorString += " the zip code matches, but the address does not.";
break;
}
}
}
var tCompRespFail = new Tuple<string, string, string>(ReturnValues[6].ToString(), ErrorString, string.Join(",", ReturnValues));
return tCompRespFail;
}
CIM CODE (Tokanisation (Card not present method)
public Tuple<string, string, string> CreateTransaction(long profile_id, long payment_profile_id, decimal amt, string DDD)
{
CustomerProfileWS.ProfileTransAuthCaptureType auth_capture = new CustomerProfileWS.ProfileTransAuthCaptureType();
auth_capture.customerProfileId = profile_id;
auth_capture.customerPaymentProfileId = payment_profile_id;
auth_capture.amount = amt;//1.00m;
auth_capture.order = new CustomerProfileWS.OrderExType();
POSLib.POSManager objManager = new POSLib.POSManager();
auth_capture.order.invoiceNumber = objManager.GetTimestamp(DateTime.Now);
DateTime now = DateTime.Now;
auth_capture.order.description = "Service " + DDD;
CustomerProfileWS.ProfileTransactionType trans = new CustomerProfileWS.ProfileTransactionType();
trans.Item = auth_capture;
CustomerProfileWS.CreateCustomerProfileTransactionResponseType response = SoapAPIUtilities.Service.CreateCustomerProfileTransaction(SoapAPIUtilities.MerchantAuthentication, trans, null);
string AuthTranMsg = "";
string AuthTranCode = "";
for (int i = 0; i < response.messages.Length; i++)
{
AuthTranMsg = response.messages[i].text; // To Get Message n for loop to check the [i] is not empty
}
for (int i = 0; i < response.messages.Length; i++)
{
AuthTranCode = response.messages[i].code; // To Get Code n for loop to check the [i] is not empty
}
var tCompResp = new Tuple<string, string, string>(AuthTranCode, AuthTranMsg, response.directResponse);
return tCompResp;
}

Resources