Query String builder Error - asp.net

I'm just trying to use dictionary data to build query string. i use this function.
public static string BuildQueryString(this IDictionary<string, string> source, bool withoutEmptyString)
{
return source != null ? String.Join("&", source.Keys
.Where(key => !withoutEmptyString || source.Values.Any(value => !String.IsNullOrEmpty(value)))
.SelectMany(key => source.Values
.Where(value => !withoutEmptyString || !String.IsNullOrEmpty(value))
.Select(value => String.Format("{0}={1}", HttpUtility.UrlEncode(key), value != null ? HttpUtility.UrlEncode(value) : string.Empty)))
.ToArray())
: string.Empty;
}
but when i send the data like this
var dataDictionary = new Dictionary<string, string>
{ {"one", "1"},
{"two", "2"},
{"three", "3"},
{"four", "4"},
{"five", "5"},
{"six", "6"}
};
i'm getting string like this
"one=1&one=2&one=3&one=4&one=5&one=6&two=1&two=2&two=3&two=4&two=5&two=6&three=1&three=2&three=3&three=4&three=5&three=6&four=1&four=2&four=3&four=4&four=5&four=6&five=1&five=2&five=3&five=4&five=5&five=6&six=1&six=2&six=3&six=4&six=5&six=6"
what is the wrong i did in the code
thanks

How about something simpler like:
var fromSource = source.Where(s => !string.IsNullOrEmpty(s.Value)).Select(s => s.Key + "=" + s.Value);
return string.Join("&", fromSource.ToArray());

return source != null ? string.Join("&",
source.Where(keyValuePair => withoutEmptyString && !string.IsNullOrEmpty(keyValuePair.Value))
.Select(keyValuePair => string.Format("{0}={1}", keyValuePair.Key, keyValuePair.Value)))
: string.Empty;
Please check if my where clause works for you.

Related

How can add several fields to NEST?

I use Generic and Reflection, so the main problem is add several fields. When i use this code with one field it OK but when i try somehow add new fields it doesn't work:
public static ISearchResponse<T> PartSearch<T>(ElasticClient client, string query, List<string> fieldList = null, int from = 0, int size = 1) where T : class
{
if (client == null)
throw new ArgumentNullException();
if (String.IsNullOrEmpty(query))
throw new ArgumentNullException();
ISearchResponse<T> results;
if (fieldList == null)
{
results = client.Search<T>(q =>
q.Query(q =>
q.QueryString(qs => qs.Query(query))
).From(from).Size(size)
);
}
else
{
results = client.Search<T>(q =>
q.Query(q => q
.QueryString(qs =>
{
//This place where i try to add several fields
List<Field> fildArray = new List<Field>();
foreach (var arg in fieldList)
{
var fieldString = new Field(typeof(T).GetProperty(arg));
fildArray.Add(fieldString);
}
qs.Fields(f => f.Field(fildArray));
qs.Query(query);
return qs;
})
).From(from).Size(size)
);
}
return results;
}
I created an example using Lenient() that can help you with your question:
https://github.com/hgmauri/elasticsearch-with-nest/blob/master/src/Sample.Elasticsearch.Domain/Abstractions/NestExtensions.cs
Problem was in one QueryString parameter Lenient:
https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html
Fixed this by setting it on True.

PayUMoney - Android: Only getting **paymentId** from payUMoney SDK after successful payment

I'm integrating payUMoney in my Android application. I'm getting only paymentId after successful payment in both environment i.e Test & Production. I need Transaction Details as well from payUMoney. I have also contacted payUMoney technical team but not getting any response.
See image attached for payUMoney response which I have printed in Logcat.
What I have tried is like below.
public void makePayment() {
String phone = "8882434664";
String productName = "product_name";
String firstName = "piyush";
String txnId = "0nf7" + System.currentTimeMillis();
String email = "piyush.jain#payu.in";
String sUrl = AppConstant.BASE_URL + "/mob-payment/success";
String fUrl = AppConstant.BASE_URL + "/mob-payment/failure";
String udf1 = "";
String udf2 = "";
String udf3 = "";
String udf4 = "";
String udf5 = "";
boolean isDebug = true;
String key = "dRQuiA";
String merchantId = "4928174";
PayUmoneySdkInitilizer.PaymentParam.Builder builder = new PayUmoneySdkInitilizer.PaymentParam.Builder();
builder.setAmount(1.0)
.setTnxId(txnId)
.setPhone(phone)
.setProductName(productName)
.setFirstName(firstName)
.setEmail(email)
.setsUrl(sUrl)
.setfUrl(fUrl)
.setUdf1(udf1)
.setUdf2(udf2)
.setUdf3(udf3)
.setUdf4(udf4)
.setUdf5(udf5)
.setIsDebug(isDebug)
.setKey(key)
.setMerchantId(merchantId);
PayUmoneySdkInitilizer.PaymentParam paymentParam = builder.build();
calculateServerSideHashAndInitiatePayment(paymentParam);
}
private void calculateServerSideHashAndInitiatePayment(final PayUmoneySdkInitilizer.PaymentParam paymentParam) {
String url = "https://test.payumoney.com/payment/op/calculateHashForTest";
StringRequest jsonObjectRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.has(SdkConstants.STATUS)) {
String status = jsonObject.optString(SdkConstants.STATUS);
if (status != null || status.equals("1")) {
String hash = jsonObject.getString(SdkConstants.RESULT);
paymentParam.setMerchantHash(hash);
PayUmoneySdkInitilizer.startPaymentActivityForResult(ActivityConfirmOrder.this, paymentParam);
} else {
Toast.makeText(ActivityConfirmOrder.this,
jsonObject.getString(SdkConstants.RESULT),
Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NoConnectionError) {
Toast.makeText(ActivityConfirmOrder.this,
ActivityConfirmOrder.this.getString(R.string.connect_to_internet),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ActivityConfirmOrder.this,
error.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return paymentParam.getParams();
}
};
Volley.newRequestQueue(this).add(jsonObjectRequest);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PayUmoneySdkInitilizer.PAYU_SDK_PAYMENT_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
StringBuilder str = new StringBuilder();
Bundle bundle = data.getExtras();
if (bundle != null) {
Set<String> keys = bundle.keySet();
Iterator<String> it = keys.iterator();
while (it.hasNext()) {
String key = it.next();
str.append(key);
str.append(":");
str.append(bundle.get(key));
str.append("\n\r");
}
Log.e("res: ", str.toString());
}
} else if (resultCode == RESULT_CANCELED) {
} else if (resultCode == PayUmoneySdkInitilizer.RESULT_FAILED) {
if (data != null) {
if (data.getStringExtra(SdkConstants.RESULT).equals("cancel")) {
} else {
}
}
} else if (resultCode == PayUmoneySdkInitilizer.RESULT_BACK) {
}
}
}
PayUMoney SDK-Version: versionName "6.1.0"
I was also facing the same problem, but after little bit of research, I have found that we need to generate invoice separately using different invoice api. You can find the bellow URL for the documentation for invoice api...
https://www.payumoney.com/dev-guide/products/invoicing.html
#MaulikDodia Actually you need to create success url on your own, then the payumoney will send all the data directly like this in your success url...
Array
(
[mihpayid] => 40399371551*******
[mode] => DC
[status] => success
[unmappedstatus] => captured
[key] => d****A
[txnid] => INV0****0531
[amount] => 1000.0
[addedon] => 2017-05-31 13:16:12
[productinfo] => ****
[firstname] => ****
[lastname] =>
[address1] =>
[address2] =>
[city] => null
[state] =>
[country] => null
[zipcode] =>
[email] => ***#test.xxx
[phone] =>
[udf1] =>
[udf2] =>
[udf3] =>
[udf4] =>
[udf5] =>
[udf6] =>
[udf7] =>
[udf8] =>
[udf9] =>
[udf10] =>
[hash] => ***************
[field1] => 715140****61
[field2] => 99***9
[field3] => 8523310*****511
[field4] => -1
[field5] =>
[field6] =>
[field7] =>
[field8] =>
[field9] => SUCCESS
[PG_TYPE] => HDFCPG
[encryptedPaymentId] => DB****EB8****02A****9FE4C****CB3
[bank_ref_num] => 8****016137****
[bankcode] => MAST
[error] => E000
[error_Message] => No Error
[name_on_card] => payu
[cardnum] => 512345XXXXXXXX46
[cardhash] => This field is no longer supported in postback params.
[amount_split] => {"PAYU":"1000.0"}
[payuMoneyId] => 1******0
[discount] => 0.00
[net_amount_debit] => 1000
)
Then you can generate invoice using that on the server side or do whatever you want.
Source: I have done all the code and it is working. Hope it helps... thanks

Unit Test not passed, since not seen any return from api controller

I have an API as below:
private readonly IMyService _myService;
public MyController(IMyService myService)
{
_myService = myService;
}
//GET: api/values
[HttpGet]
public MyOutput<MyEntity> Get(string f, string o)
{
var fItems = JsonConvert.DeserializeObject<Dictionary<string, string>>(f);
var oItems = GetDictionaryFromStr(o ?? "");
var myInput = new MyInput<MyEntity>()
{
PredicateDictionary = fItems,
OrderByDictionary = oItems
};
var result = _myService.Search(myInput);
return result;
}
It works well. Now, I want to write a unit test for my API, using Moq and Xunit;. I want to set the expected values of result, then mock my DIs and call the controller, What I expect is that the return value of controller and my results be equal. but I don't know why result in var result = api.Get(f, o); is null after returns from controller. Is there anything wrong whit my test?
[Fact]
public void Should_ReturnResult_When_CallingMyApi()
{
//Arrange
var f = "{'Currency':'UR'}";
var o = "+Amount";
var fItems = JsonConvert.DeserializeObject<Dictionary<string, string>>(f);
var oItems = GetDictionaryFromStr(o ?? "");
var baseServiceMock = new Mock<IMyService>();
baseServiceMock
.Setup(x => x.Serach(It.Is<MyInput<MyEntity>>
(i => i.PredicateDictionary== fItems
&& i.OrderByDictionary == oItems
&& i.Paging == pagingItems
)))
.Returns(new MyOutput<MyEntity>()
{
OrderByDictionary = oItems,
PredicateDictionary = fItems
});
var api = new MyController(baseServiceMock.Object);
//Act
var result = api.Get(f, o);
////Assert
Assert.Equal(result.PredicateDictionary, fItems);
Assert.Equal(result.OrderByDictionary, oItems);
}
Update:
Also I changed the baseServiceMock, with and without the It.Is. In case of It.Is I added
baseServiceMock
.Setup(x => x.Search(It.Is<MuInput<MyEntity>>
(i => i.PredicateDictionary.Keys == fItems.Keys
&& i.PredicateDictionary.Values == fItems.Values
&& i.OrderByDictionary.Keys == oItems.Keys
&& i.OrderByDictionary.Values == oItems.Values
&& i.Paging == pagingItems
)))
.Returns.....
The problem was comparing two objects in SetUp(). So I Edited the code as below:
.Setup(x => x.Find(It.Is<MuInput<MyEntity>>
(i => i.PredicateDictionary.First().Key == "Currency"
&& i.PredicateDictionary.First().Value == "CU_UR"
&& i.OrderByDictionary.First().Key == "Amount"
&& i.OrderByDictionary.First().Value == "Asc")))

Need help on using documentdb-lumenize on .net documentdb client sdk

I have a problem using the aggregate storedproc lumenize https://github.com/lmaccherone/documentdb-lumenize with the .net client. I get error when try passing in the parameter and query into the storedproc. Below is my code
public async static void QuerySP() {
using (client = new DocumentClient(new Uri(endpointUrl), authorizationKey))
{
//Get the Database
var database = client.CreateDatabaseQuery().Where(db => db.Id == databaseId).ToArray().FirstOrDefault();
//Get the Document Collection
var collection = client.CreateDocumentCollectionQuery(database.SelfLink).Where(c => c.Id == collectionId).ToArray().FirstOrDefault();
StoredProcedure storedProc = client.CreateStoredProcedureQuery(collection.StoredProceduresLink).Where(sp => sp.Id == "cube").ToArray().FirstOrDefault();
dynamic result = await client.ExecuteStoredProcedureAsync<dynamic>(storedProc.SelfLink, "{cubeConfig: {groupBy: 'publication', field: 'pid', f: 'count'}, filterQuery: 'SELECT pid, publication FROM c'}");
Console.WriteLine("Result from script: {0}\r\n", result.Response);
}
}
I am getting the following error when execute the code
Message: {"Errors":["Encountered exception while executing Javascript. Exception = Error: cubeConfig or savedCube required\r\nStack trace: Error: cubeConfig or savedCube required\n at fn (cube.js:1803:7)\n at __docDbMain (cube.js:1844:5)\n at Unknown script code (cube.js:1:2)"]}
Not sure what I had done wrong. I would really appreciate the help. Thanks.
You almost have it. The problem is that you are sending in the cubeConfig as a string. It needs to be an object. Here is code that does that:
string cubeConfigString = #"{
cubeConfig: {
groupBy: 'publication',
field: 'pid',
f: 'count'
},
filterQuery: 'SELECT * FROM c'
}";
Object cubeConfig = JsonConvert.DeserializeObject<Object>(cubeConfigString);
Console.WriteLine(cubeConfig);
dynamic result = await client.ExecuteStoredProcedureAsync<dynamic>("dbs/dev-test-database/colls/dev-test-collection/sprocs/cube", cubeConfig);
Console.WriteLine(result.Response);
my working code
public async static Task QuerySP2()
{
using (client = new DocumentClient(new Uri(endpointUrl), authorizationKey))
{
//Get the Database
var database = client.CreateDatabaseQuery().Where(db => db.Id == databaseId).ToArray().FirstOrDefault();
//Get the Document Collection
var collection = client.CreateDocumentCollectionQuery(database.SelfLink).Where(c => c.Id == collectionId).ToArray().FirstOrDefault();
StoredProcedure storedProc = client.CreateStoredProcedureQuery(collection.StoredProceduresLink).Where(sp => sp.Id == "cube").ToArray().FirstOrDefault();
string filterQuery = string.Format(#"SELECT * from c");
string cubeConfigString = #"{
cubeConfig: {
groupBy: 'publication',
field: 'id',
f: 'count'
},
filterQuery: '" + filterQuery + "'}";
dynamic cubeConfig = JsonConvert.DeserializeObject<dynamic>(cubeConfigString);
Console.WriteLine(cubeConfig);
string continuationToken = null;
dynamic result=null;
do
{
var queryDone = false;
while (!queryDone)
{
try
{
result = await client.ExecuteStoredProcedureAsync<dynamic>(storedProc.SelfLink, cubeConfig);
cubeConfig = result.Response;
continuationToken = cubeConfig.continuation;
queryDone = true;
}
catch (DocumentClientException documentClientException)
{
var statusCode = (int)documentClientException.StatusCode;
if (statusCode == 429 || statusCode == 503)
System.Threading.Thread.Sleep(documentClientException.RetryAfter);
else
throw;
}
catch (AggregateException aggregateException)
{
if (aggregateException.InnerException.GetType() == typeof(DocumentClientException))
{
var docExcep = aggregateException.InnerException as DocumentClientException;
var statusCode = (int)docExcep.StatusCode;
if (statusCode == 429 || statusCode == 503)
System.Threading.Thread.Sleep(docExcep.RetryAfter);
else
throw;
}
}
}
} while (continuationToken != null);
Console.WriteLine("Result from script: {0}\r\n", result.Response);
}
}

Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>' to 'System.Collections.Generic.List<DAL.HRM_PersonalInformations>'

I am trying to Get some data from Database and Bind them in Drop-Down list.. But getting following error : -
public virtual List<HRM_PersonalInformations>GetAssignePerson(String OCODE, int dptID){
var query = (context.HRM_PersonalInformations.Where
(c => c.OCODE == OCODE && c.DepartmentId == dptID)
.Select(c => new {FullName = (c.FirstName + ' ' + c.LastName), c.EID})).ToList();
return query; // It indicate error line
}
After that I am trying to Bind data in dropdown list and my code is following : -
private void FillAssignPerson()
{
try
{
string OCODE = ((SessionUser)Session["SessionUser"]).OCode;
int dptId = Convert.ToInt32(ddlAssignPerDept.SelectedValue);
var row = enquiryBll.GetAssignePerson(OCODE, dptId).ToList();
//const string list = "SELECT FirstName + ' ' + LastName AS FullName, EID, FirstName, LastName " +
// "FROM HRM_PersonalInformations " +
// "ORDER BY EID ASC"
if (row.Count > 0)
{
ddlAssignPerson.Items.Clear();
ddlAssignPerson.DataSource = row;
ddlAssignPerson.DataTextField = "FullName";
ddlAssignPerson.DataValueField = "EID";
ddlAssignPerson.DataBind();
ddlAssignPerson.Items.Insert(0, new ListItem("----- Select One -----", "0"));
ddlAssignPerson.AppendDataBoundItems = false;
}
}
Is it right way ?? Can anyone help me ? Thanks for Advance ..
Well, in your projection you have:
c => new {FullName = (c.FirstName + ' ' + c.LastName), c.EID}
That's creating an instance of an anonymous typoe - not an instance of HRM_PersonalInformations. If those are the only two properties you need in HRM_PersonalInformations, you could just change it to:
c => new HRM_PersonalInformations {
FullName = (c.FirstName + ' ' + c.LastName),
EID = c.EID
}
Or judging by your query, you may not need a projection at all. You may be fine with:
return context.HRM_PersonalInformations
.Where(c => c.OCODE == OCODE && c.DepartmentId == dptID)
.ToList();
Alternatively, if you only need those properties and don't really need the items of your list to be instances of HRM_PersonalInformations, you could just change the method's signature to be:
public virtual IList GetAssignePerson(...)
and keep the body as it is. You can't explicitly write a method declaration which specifies the anonymous type, because it doesn't have a name - but List<T> implements IList, so the above will certainly compile... it will fail if you later try to cast an element in it to HRM_PersonalInformations though.
EDIT: If the string concatenation is a problem, you might need to do that client-side. For example:
public IList GetAssignePerson(String OCODE, int dptID) {
return context.HRM_PersonalInformations
.Where(c => c.OCODE == OCODE && c.DepartmentId == dptID)
.Select(c => new { c.FirstName, c.LastName, c.EID })
.AsEnumerable() // Do the rest client-side
.Select(c => new {
FullName = c.FirstName + " " + c.LastName,
c.EID
})
.ToList();
}
This methods awaits you HRM_PersonalInformations , why are you return anonymous type ?
It is useful to go back to the expected type
Try this code
.Select(c => new HRM_PersonalInformations()
{
FullName = c.FirstName
// set other prop
});
this is a simple sample,
If you want to customize data business process or UI process you need a new model for example You want to display full name in Dropdown so ,
Add new folder MyCustomizeModels
Add new class DropdownLookUpDecimal in MyCustomizeModels
this DropdownLookUpDecimal class.
public class DropdownLookUpDecimal
{
public decimal Value { get; set; }
public string Text { get; set; }
}
You can use this class all Dropdown in the project.
public List<DropdownLookUpDecimal>GetAssignePerson(string oCode, int dptID)
{
var query = context.HRM_PersonalInformations.Where
(c => c.OCODE == oCode&& c.DepartmentId == dptID)
.Select(c => new DropdownLookUpDecimal
{
Text = c.FirstName + ' ' + c.LastName,
Value = c.EID
});
return query.ToList();
}
Just create new .cs and fill the list with the class and return List.
I hope it helped

Resources