i have a class and method
public class Datas
{
public string Name { get; set; }
public int Value { get; set; }
}
public void Funnel()
{
string commandText = "select sc.stagename, count(cs.stages_id) as StageCount from currentstage cs inner join stagesconfig sc on cs.stages_id = sc.stages_id group by cs.stages_id,sc.stagename";
string constrings = WebConfigurationManager.ConnectionStrings["Data"].ToString();
SqlConnection myConn = new SqlConnection(constrings);
SqlCommand myComm = new SqlCommand(commandText, myConn);
myConn.Open();
List<Datas> fruitinfo = new List<Datas>();
SqlDataReader reader = myComm.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
fruitinfo.Add(new Datas
{
Name = reader.GetValue(0).ToString(),
Value = Convert.ToInt32(reader.GetValue(1))
});
}
}
how do you loop through fruitinfo list saving it in form of an array.the array must be similar to this form.intended to replace the items in Data parenthesis with fruitinfo looped list
Data = new Data(new object[]
{
new object[] { "Website visits", 10000 },
new object[] { "Downloads", 5000 },
new object[] { "Requested price list", 2000 },
new object[] { "Invoice sent", 1000 },
new object[] { "Finalized", 500 }
}),
var myArray = fruitinfo.Select(x => new object[] { x.Name, x.Value }).ToArray();
And the use it with your Data-object.
Data = new Data(myArray);
var myArray = fruitinfo.Select(d => new object[] { d.Name, d.Value }).ToArray();
I am not too sure why you need to produce an array of anonymous objects, but you can use a dictionary.
private static void Funnel()
{
var datas = new List<Datas>
{
new Datas { Name = "Website visits", Value = 10000 },
new Datas { Name = "Downloads", Value = 5000 },
new Datas { Name = "Requested price list", Value = 2000 },
new Datas { Name = "Invoice sent", Value = 1000 },
new Datas { Name = "Finalized", Value = 500 }
};
var data = datas.ToDictionary(datas1 => datas1.Name, datas1 => datas1.Value);
foreach (var item in data)
{
Console.WriteLine(string.Format("{0}, {1}",item.Key, item.Value));
}
var arry = data.ToArray();
foreach (var item in arry)
{
Console.WriteLine(string.Format("{0}, {1}", item.Key, item.Value));
}
}
Related
I have 3 methods that do same stuff. One difference, they work with different models.
Here is the methods code:
public IEnumerable<PropertyImportDto> ImportStandardCsv(string fileData)
{
List<PropertyImportDto> data;
using (var memoryStream =
new MemoryStream(Convert.FromBase64String(fileData.Substring(fileData.IndexOf(',') + 1))))
{
using (var streamWriter = new StreamReader(memoryStream))
using (var csvReader = new CsvReader(streamWriter))
{
var records = csvReader.GetRecords<PropertyImportDto>();
data = records.ToList();
}
}
return data;
}
public IEnumerable<ArthurPropertiesImportDto> ImportArthurCsv(string fileData)
{
List<ArthurPropertiesImportDto> data;
using (var memoryStream =
new MemoryStream(Convert.FromBase64String(fileData.Substring(fileData.IndexOf(',') + 1))))
{
using (var streamWriter = new StreamReader(memoryStream))
using (var csvReader = new CsvReader(streamWriter))
{
var records = csvReader.GetRecords<ArthurPropertiesImportDto>();
data = records.ToList();
}
}
return data;
}
public IEnumerable<LandlordVisionImportDto> ImportLandlordVision(string fileData)
{
List<LandlordVisionImportDto> data;
using (var memoryStream =
new MemoryStream(Convert.FromBase64String(fileData.Substring(fileData.IndexOf(',') + 1))))
{
using (var streamWriter = new StreamReader(memoryStream))
using (var csvReader = new CsvReader(streamWriter))
{
var records = csvReader.GetRecords<LandlordVisionImportDto>();
data = records.ToList();
}
}
return data;
}
And I call it like this
public async Task ImportProperties(PM101ImportDto input)
{
switch (input.fileTypeId)
{
case 1:
{
var properties = _csvAppService.ImportStandardCsv(input.FileBase64);
foreach (var item in properties)
{
var property = new Property
{
PropertyTypeId = 1,
BuildingTypeId = 12,
PhoneNumber = item.PhoneNumber,
PropertyTitleId = 1,
AccountManagerId = AbpSession.TenantId,
Addresses = new List<PropertyAddress>
{
new PropertyAddress
{
Line1 = item.Line1,
Line2 = item.Line2,
Line3 = item.Line3,
PostCode = item.PostalCode,
PostTown = item.Town,
Country = item.Country,
County = item.County,
Latitude = item.Latitude,
Longitude = item.Longitude
},
},
Sites = new List<Site>
{
new Site
{
NumberOfWindows = 0,
NumberOfBedRooms = 0,
ApproximateYearBuilt = 1970,
PropertyAge = 50,
FuelTypeId = 1,
ParkingTypeId = 1,
FurnishingTypeId = 1
}
},
MarketingInformation = new List<PropertyMarketingInformation>
{
new PropertyMarketingInformation
{
MarketingDescription = "", IsBillsIncluded = false
}
}
};
await _propertyRepository.InsertAsync(property);
}
break;
}
case 2:
{
var properties = _csvAppService.ImportLandlordVision(input.FileBase64);
foreach (var item in properties)
{
var property = new Property
{
PropertyTypeId = 1,
BuildingTypeId = 12,
PropertyTitleId = 1,
AccountManagerId = AbpSession.TenantId,
Addresses = new List<PropertyAddress>
{
new PropertyAddress
{
Line1 = item.Line1,
Line2 = item.Line2,
PostCode = item.PostCode,
PostTown = item.Town,
County = item.County
}
},
Sites = new List<Site>
{
new Site
{
NumberOfWindows = 0,
NumberOfBedRooms = 0,
ApproximateYearBuilt = 1970,
PropertyAge = 50,
FuelTypeId = 1,
ParkingTypeId = 1,
FurnishingTypeId = 1
}
},
MarketingInformation = new List<PropertyMarketingInformation>
{
new PropertyMarketingInformation
{
MarketingDescription = "", IsBillsIncluded = false
}
}
};
await _propertyRepository.InsertAsync(property);
}
break;
}
case 3:
{
var properties = _csvAppService.ImportArthurCsv(input.FileBase64);
foreach (var item in properties)
{
var property = new Property
{
PropertyTypeId = 1,
BuildingTypeId = 12,
PropertyTitleId = 1,
AccountManagerId = AbpSession.TenantId,
Addresses = new List<PropertyAddress>
{
new PropertyAddress
{
Line1 = item.Line1,
Line2 = item.Line2,
Line3 = item.Line3,
PostCode = item.PostCode,
PostTown = item.City,
County = item.County,
Country = item.Country,
Latitude = item.Latitude,
Longitude = item.Longitude
}
},
Sites = new List<Site>
{
new Site
{
NumberOfWindows = 0,
NumberOfBedRooms = 0,
ApproximateYearBuilt = 1970,
PropertyAge = 50,
FuelTypeId = 1,
ParkingTypeId = 1,
FurnishingTypeId = 1
}
},
MarketingInformation = new List<PropertyMarketingInformation>
{
new PropertyMarketingInformation
{
MarketingDescription = "", IsBillsIncluded = false
}
}
};
await _propertyRepository.InsertAsync(property);
}
}
break;
}
}
How I can rewrite those 3 methods to one gneric method?
Typical use case for generic type parameters
public IEnumerable<T> ImportStandardCsv<T>(string fileData)
{
var bytes = Convert.FromBase64String(fileData.Substring(fileData.IndexOf(',') + 1));
using (var memoryStream = new MemoryStream(bytes))
using (var streamReader = new StreamReader(memoryStream))
using (var csvReader = new CsvReader(streamReader))
return csvReader.GetRecords<T>();
}
call
IEnumerable<PropertyImportDto> result = ImportStandardCsv<PropertyImportDto>(input.FileBase64);
Querying a table on Secondary Index, using a BeginsWith Operator does not always return the correct records. What could be the reason for that?
I have sample Code and tried it against a local DynamoDB table and against a table in AWS. The results are the same.
Defining the secondary index:
var gsiKey1Index = new GlobalSecondaryIndex
{
IndexName = "GSIKey1Index",
ProvisionedThroughput = new ProvisionedThroughput
{
ReadCapacityUnits = 1,
WriteCapacityUnits = 1
},
Projection = new Projection { ProjectionType = "ALL" }
};
var indexKey1Schema = new List<KeySchemaElement> {
{
new KeySchemaElement
{
AttributeName = "HashKey", KeyType = KeyType.HASH
}
}, //Partition key
{
new KeySchemaElement
{
AttributeName = "GSISortKey1", KeyType = KeyType.RANGE
}
} //Sort key
};
gsiKey1Index.KeySchema = indexKey1Schema;
Creating the table:
var request = new CreateTableRequest
{
TableName = "TestTable",
AttributeDefinitions = new List<AttributeDefinition>
{
new AttributeDefinition
{
AttributeName = "HashKey",
// "S" = string, "N" = number, and so on.
AttributeType = "S"
},
new AttributeDefinition
{
AttributeName = "SortKey",
AttributeType = "S"
},
new AttributeDefinition
{
AttributeName = "GSISortKey1",
// "S" = string, "N" = number, and so on.
AttributeType = "S"
},
},
KeySchema = new List<KeySchemaElement>
{
new KeySchemaElement
{
AttributeName = "HashKey",
// "HASH" = hash key, "RANGE" = range key.
KeyType = "HASH"
},
new KeySchemaElement
{
AttributeName = "SortKey",
KeyType = "RANGE"
},
},
GlobalSecondaryIndexes = { gsiKey1Index },
ProvisionedThroughput = new ProvisionedThroughput
{
ReadCapacityUnits = 10,
WriteCapacityUnits = 5
},
};
response2 = await _client.CreateTableAsync(request);
The Entity looks like this:
[DynamoDBTable("TestTable")]
public sealed class TestResult
{
[DynamoDBHashKey]
public string HashKey {get;set;}
public string SortKey {get;set;}
public string GSISortKey1 {get; set;}
}
The code to query looks like this:
public async Task<List<TestResult>> GetTestResultByDateTimeAsync(Guid hashid, Guid someId, string someName, DateTime timestamp)
{
var key2 = $"TR-{someId}-{someName}-{timestamp:yyyy-MM-ddTHH\\:mm\\:ss.fffZ}";
var key = $"TR-{someId}-{someName}-{timestamp:yyyy-MM-dd}";
//var filter = new QueryFilter();
//filter.AddCondition("HashKey", ScanOperator.Equal, hashid.ToString());
//filter.AddCondition("GSISortKey1", ScanOperator.BeginsWith, key);
//var queryConfig = new QueryOperationConfig
//{
// Filter = filter
//};
DynamoDBOperationConfig operationConfig = new DynamoDBOperationConfig()
{
OverrideTableName = "DEVTransponderTR",
IndexName = "GSIKey1Index",
QueryFilter = new List<ScanCondition>()
};
var sc = new ScanCondition("GSISortKey1", ScanOperator.BeginsWith, new[] { key });
operationConfig.QueryFilter.Add(sc);
var search = _context.QueryAsync<TestResult>(tenantid.ToString(), operationConfig);
var testresults = await search.GetRemainingAsync();
bool keywasok = true;
foreach (var testresult in testresults)
{
keywasok = testresult.GSISortKey1.StartsWith(key2) && keywasok;
}
if (keywasok) // this means I should find the same values if I use key2
{
DynamoDBOperationConfig operationConfig2 = new DynamoDBOperationConfig()
{
OverrideTableName = "TestTable",
IndexName = "GSIKey1Index",
QueryFilter = new List<ScanCondition>()
};
var sc2 = new ScanCondition("GSISortKey1", ScanOperator.BeginsWith, new[] { key2 });
operationConfig2.QueryFilter.Add(sc2);
var search2 = _context.QueryAsync<TestResult>(tenantid.ToString(), operationConfig);
var testresults2 = await search.GetRemainingAsync();
}
return testresults;
}
Then I add three instances to the table. importants is that all information is the same except the GSISortKey1 value. This is the GSISortKey1 value for the three items:
"TR-0d798900-a852-4a75-bef0-5dd5c96c657c-Module1-2019-04-02T12:24:19.000Z-Open"
"TR-0d798900-a852-4a75-bef0-5dd5c96c657c-Module1-2019-04-02T12:24:19.000Z-Send"
"TR-0d798900-a852-4a75-bef0-5dd5c96c657c-Module1-2019-04-02T12:24:19.000Z-Test"
So in the example I first query on "BeginsWith" with a value of "TR-0d798900-a852-4a75-bef0-5dd5c96c657c-Module1-2019-04-02" (this is var key)
It returns all three items.
Then I check if the whole GSISortKey1 value of three returned items would also begin with the value "TR-0d798900-a852-4a75-bef0-5dd5c96c657c-Module1-2019-04-02T12:24:19.000Z-", and that is true.
If that is true I just query again with a BeginsWith using the value "TR-0d798900-a852-4a75-bef0-5dd5c96c657c-Module1-2019-04-02T12:24:19.000Z-"
It should return all three items. it returns 0 items.
I guess I am doing something wrong, some help appreciated.
I need to use several filters (range and terms) for query request with ElasticSearch 5.1. If I use them separately (only one filter) it is OK:
var o = new
{
size = 20,
query = new
{
#bool = new
{
must = new
{
query_string = new
{
fields = new[] { "Title" },
query = search_query
}
},
filter = new
{
terms = new
{
SourceId = new[] {10,11,12}
}
}
}
}
};
OR
var o = new
{
size = 20,
query = new
{
#bool = new
{
must = new
{
query_string = new
{
fields = new[] { "Title" },
query = search_query
}
},
filter = new
{
range = new
{
PostPubDate = new
{
gte = "2015-10-01T00:00:00",
lte = "2015-11-01T12:00:00"
}
}
}
}
}
};
If I use them both I get response 400 error:
string url = "http://localhost:9200/neg_collector/posts/_search";
var request = (HttpWebRequest)HttpWebRequest.Create(url);
var o = new
{
size = 20,
query = new
{
#bool = new
{
must = new
{
query_string = new
{
fields = new[] { "Title" },
query = search_query
}
},
filter = new
{
terms = new
{
SourceId = new[] {10,11,12}
},
range = new
{
PostPubDate = new
{
gte = "2015-10-01T00:00:00",
lte = "2015-11-01T12:00:00"
}
}
}
}
}
};
request.Method = "POST";
var jsonObj = JsonConvert.SerializeObject(o);
var data = Encoding.UTF8.GetBytes(jsonObj);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
string responseString = string.Empty;
var response = (HttpWebResponse)request.GetResponse();
What am I doing wrong? Thank you
Your filter simply needs to be an array of objects:
...
filter = new object[]
{
new {
terms = new
{
SourceId = new[] {10,11,12}
}
},
new {
range = new
{
PostPubDate = new
{
gte = "2015-10-01T00:00:00",
lte = "2015-11-01T12:00:00"
}
}
}
}
Hi is there a way to display a viewbag list and show count
Like:
United Arab Emirates(8)
Angola(4)
Argentina(7)
Austria(0)
Belgium(11)
Currently i have a Checkboxlist(costume helper) in view
#Html.CheckBoxList("checkedLocation", (ViewBag.country_list as MultiSelectList))
Only countries are displayed. Wud be great if the same list has counts
Basically i have a company table with country fields. Just wanna show that in Brazil, ten companies are available like Brazil(10)
This how the viwbag is populated
List<country> listInfo2 = db.countries.Where(row => row.covered == 1).ToList();
List<string> checkedValues = new List<string>();
MultiSelectList checkedValuesList = new MultiSelectList(listInfo2, "country_name", "country_name", checkedValues);
ViewBag.country_list = checkedValuesList
You can return a new dynamic list of objects. Here is the example:
public class country
{
public string Name { get; set; }
public string Covered { get; set; }
}
List<country> contries = new List<country>() {
new country(){ Name = "Siraj", Covered = "1"},
new country(){ Name = "Kumail", Covered = "1"},
new country(){ Name = "Ali", Covered = "1"},
new country(){ Name = "Haider", Covered = "1"}
};
var query = (from x in contries
group x.Id by x.Name into g
select new { CustomName = string.Format("{0} ({1})", g.Key, g.Count()) }).ToList();
Finally got it right
Controller:
//COUNTRIES TO CHECKBOX LIST
List<DeviceGroupViewModel> listInfo2 = db.companies.GroupBy(fu => fu.COM_COUNTRY).Select(g => new DeviceGroupViewModel { Type = g.Key, Count = g.Count() }).ToList();
MultiSelectList checkedValuesList = new MultiSelectList(listInfo2, "Type", "Count");
ViewBag.country_list = checkedValuesList;
View:
#Html.CheckBoxList2("checkedLocation", (ViewBag.country_list as MultiSelectList))
Checkboxlist Helper:
public static MvcHtmlString CheckBoxList2(this HtmlHelper htmlHelper, string name, MultiSelectList listInfos)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException("This parameter cannot be null or empty!", "name");
}
if (listInfos == null)
{
throw new ArgumentException("This parameter cannot be null!", "listInfos");
}
//if (listInfos.Count<SelectListItem>() < 1)
//{
// throw new ArgumentException("The count must be greater than 0!", "listInfos");
//}
List<string> selectedValues = (List<string>)listInfos.SelectedValues;
StringBuilder sb = new StringBuilder();
foreach (SelectListItem info in listInfos)
{
sb.Append("<li class='Navlist'>");
TagBuilder builder = new TagBuilder("input");
if (info.Selected) builder.MergeAttribute("checked", "checked");
//builder.MergeAttributes<string, object>(htmlAttributes);
builder.MergeAttribute("type", "checkbox");
builder.MergeAttribute("value", info.Value);
builder.MergeAttribute("name", name);
builder.MergeAttribute("id", info.Value);
builder.MergeAttribute("class", "filter-classif");
builder.InnerHtml = "<label>" + info.Value + "(" + info.Text + ")</label>";
sb.Append(builder.ToString(TagRenderMode.Normal));
sb.Append("</li>");
}
using System;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
namespace LearningJustCode
{
class Program
{
static void Main(string[] args)
{
Update();
}
static void Update()
{
var quote1 = new { Stock = "DELL", Quote = GetQuote("DELL") };
var quote2 = new { Stock = "MSFT", Quote = GetQuote("MSFT") };
var quote3 = new { Stock = "GOOG", Quote = GetQuote("GOOG") };
var quotes = new object[] { quote1, quote2, quote3 };
foreach (var item in quotes)
{
Console.WriteLine(item.Stock);
Console.WriteLine(item.Quote.ToString());
}
Console.ReadKey();
}
static string GetQuote(string stock)
{
try
{
return InnerGetQuote(stock);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return "N/A";
}
}
static string InnerGetQuote(string stock)
{
string url = #"http://www.webservicex.net/stockquote.asmx/GetQuote?symbol={0}";
var request = HttpWebRequest.Create(string.Format(url, stock));
using (var response = request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
{
return reader.ReadToEnd();
}
}
}
}
}
I am getting an squiggley over item;Variable 'item' is only assigned to. This code has been slightly modified from Paul Kimmel's book C# Unleashed by Sams.
Your array needs to be of the type of your stock quote.
Your stock quote is an anonymous type, so we need to define the array anonymously as well. This can be done cleanly as:
var quotes = new[]{ new { Stock = "DELL", Quote = "123" },
new { Stock = "MSFT", Quote = "123" },
new { Stock = "GOOG", Quote = "123" }};
foreach (var item in quotes)
{
Console.WriteLine(item.Stock);
Console.WriteLine(item.Quote.ToString());
}
i guess the problem is in that line:
var quotes = new object[] { quote1, quote2, quote3 };
quotes is a object array, not an array of that anonymous type. the foreach also has just the object value. you could try to form the array within one line or within a lambda expression
A very dirty workaround is changing 'var' to 'dynamic'
var quote1 = new { Stock = "DELL", Quote = ("DELL") };
var quote2 = new { Stock = "MSFT", Quote = ("MSFT") };
var quote3 = new { Stock = "GOOG", Quote = ("GOOG") };
var quotes = new object[] { quote1, quote2, quote3 };
foreach (dynamic item in quotes)
{
var r = item.Stock;
}
a cleaner solution is leaving out 'object', so the compiler can generate an anonymous typed array
var quote1 = new { Stock = "DELL", Quote = ("DELL") };
var quote2 = new { Stock = "MSFT", Quote = ("MSFT") };
var quote3 = new { Stock = "GOOG", Quote = ("GOOG") };
var quotes = new [] { quote1, quote2, quote3 };
foreach (var item in quotes)
{
var r = item.Stock;
}