When upload on server then respond 500 internal server error - angularjs

It is not hit by service and on console Failed to load resource: the server responded with a status of 500 (Internal Server Error)
http://newalturathadmin.alturath.net/api/ApiFailureDonatorMobile?currentPage=1&recordsPerPage=20&Name=&DateFrom=&DateTo=
public class ApiFailureDonatorMobileController : Application.Global.BaseControllers.ApiControllerBase
{
DateTime frmDate;
DateTime toDate;
public HttpResponseMessage Get(int currentPage, int recordsPerPage, string Name = "", string DateFrom = "", string DateTo = "")
{
try
{
var dataEntryQuery = OUnitOfWork.FailureDonatorRepository.GetAll().OrderByDescending(x => x.Id);
if (DateFrom != null || DateTo != null)
{
frmDate = DateTime.ParseExact(DateFrom, "dd-MM-yyyy", CultureInfo.InvariantCulture);
if (DateTo != null)
{
toDate = DateTime.ParseExact(DateTo, "dd-MM-yyyy", CultureInfo.InvariantCulture);
}
toDate = toDate.AddDays(1);
dataEntryQuery = dataEntryQuery.Where(x =>
(
(!string.IsNullOrEmpty(Name.Trim()) ?
(!string.IsNullOrEmpty(x.Project.ProjectName.Trim()) ? x.Project.ProjectName.Contains(Name.Trim()) : 1 == 2) : 1 == 1)
&& x.Createdon >= (string.IsNullOrEmpty(DateFrom) ? x.Createdon : frmDate.Date)
&& x.Createdon <= (string.IsNullOrEmpty(DateTo) ? x.Createdon : toDate.Date)
)).OrderByDescending(x => x.Id);
}
else
{
dataEntryQuery = dataEntryQuery.Where(x =>
(
(!string.IsNullOrEmpty(Name.Trim()) ?
(!string.IsNullOrEmpty(x.Project.ProjectName.Trim()) ? x.Project.ProjectName.Contains(Name.Trim()) : 1 == 2) : 1 == 1)
)).OrderByDescending(x => x.Id);
}
var _totalCount = dataEntryQuery.Count();
var _totalPages = Math.Ceiling((double)_totalCount / recordsPerPage);
var entries = dataEntryQuery.Skip((currentPage - 1) * recordsPerPage)
.Take(recordsPerPage)
.AsQueryable();
var includeMastersName = (from x in entries.AsEnumerable()
select new
{
Id = x.Id,
Project = x.Project_FK_ID == null ? "" : x.Project.ProjectName,
InvoiceId = x.InvoiceId,
MobileNo = x.MobileNo,
Createdon = x.Createdon,
}).AsQueryable();
var result = new
{
TotalCount = _totalCount,
TotalPages = _totalPages,
AllEntries = includeMastersName
};
return Request.CreateResponse(HttpStatusCode.OK, result);
}
catch (Exception e)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, e.Message + "-------" + e.InnerException.Message + "-------" + e.StackTrace + "-------" + e.Source); ;
}
return Request.CreateResponse(HttpStatusCode.NotFound, new { resul = "Error" });
}
}

Related

Share a TXT file between two android application Android 11 and Android 12

I developed two application, one is a LAUNCHER the other one is the MAIN-APP.
I my MAIN-APP the user can choose the language.
I would like to change automatically the language also in my LAUNCHER.
I would like to create a txt file in Documents folder from my MAIN-APP, so the LAUNCHER can read this file and set the same language.
But now in Android 11 seems impossible to create a file TXT in the Documents folder and read this file from another application.
I tried with MediaStore:
MAIN APP :
private static void saveLanguageOnFile(String lang, String country){
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
File folderDocuments = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
boolean success;
if (!folderDocuments.exists()) {
try {
folderDocuments.mkdir();
} catch (Exception ex) {
ex.printStackTrace();
}
}
success = folderDocuments.exists();
if (success) {
try {
FileOutputStream fos = new FileOutputStream(new File(folderDocuments, "language.txt"));
fos.write((lang + "-" + country).getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
Uri contentUri = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
ContentResolver contentResolver = ActivitiesManager.getInstance().getTopActivity().getApplication().getApplicationContext().getContentResolver();
String selection = MediaStore.MediaColumns.RELATIVE_PATH + "=?";
String[] selectionArgs = new String[]{Environment.DIRECTORY_DOCUMENTS+"/"};
Cursor cursor = contentResolver.query(contentUri, null, selection, selectionArgs, null);
long idFile = -1;
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int columnIndexDisplayName = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME);
int columnIndexId = cursor.getColumnIndex(MediaStore.MediaColumns._ID);
if (columnIndexDisplayName > 0 && columnIndexId > 0) {
String fileName = cursor.getString(columnIndexDisplayName);
if (fileName.equals("language.txt")) {
idFile = cursor.getLong(columnIndexId);
break;
}
}
}
cursor.close();
}
Uri uriFile;
if (idFile > -1) {
uriFile = ContentUris.withAppendedId(contentUri, idFile);
} else {
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DISPLAY_NAME, "language.txt"); // file name
values.put(MediaStore.MediaColumns.MIME_TYPE, "text/plain");
values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOCUMENTS);
uriFile = contentResolver.insert(contentUri, values);
}
try {
if (uriFile != null) {
OutputStream outputStream = contentResolver.openOutputStream(uriFile, "rwt");
if (outputStream != null) {
outputStream.write((lang + "-" + country).getBytes());
outputStream.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
ANDROID LAUNCHER APP :
private fun setLanguage() {
var lang = Locale.getDefault().language
var country = Locale.getDefault().country
val previousLang = lang
val previousCountry = country
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
val language = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS),"language.txt")
if (language.exists()) {
try {
val br = BufferedReader(FileReader(language))
var st: StringTokenizer
var line: String?
while (br.readLine().also { line = it } != null) {
st = StringTokenizer(line, "-")
lang = st.nextToken()
country = st.nextToken()
}
br.close()
} catch (e: IOException) {
Log.e("LauncherDMD", ".loadFile: err: " + e.message)
}
}
} else {
val contentUri = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
val contentResolver: ContentResolver = application.applicationContext.contentResolver
val selection = MediaStore.MediaColumns.RELATIVE_PATH + "=?"
val selectionArgs = arrayOf(Environment.DIRECTORY_DOCUMENTS+"/")
val orderBy = MediaStore.MediaColumns.DATE_ADDED + " DESC"
val cursor = contentResolver.query(contentUri, null, selection, selectionArgs, orderBy)
var idFile: Long = -1
if (cursor != null && cursor.count > 0) {
while (cursor.moveToNext()) {
val columnIndexDisplayName = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)
val columnIndexId = cursor.getColumnIndex(MediaStore.MediaColumns._ID)
if (columnIndexDisplayName > 0 && columnIndexId > 0) {
val fileName = cursor.getString(columnIndexDisplayName)
if (fileName.contains("language")) {
idFile = cursor.getLong(columnIndexId)
break
}
}
}
cursor.close()
}
val uriFile: Uri
if (idFile > -1) {
uriFile = ContentUris.withAppendedId(contentUri, idFile)
try {
val br = BufferedReader(InputStreamReader(getContentResolver().openInputStream(uriFile), "UTF-8"))
var st: StringTokenizer
var line: String?
while (br.readLine().also { line = it } != null) {
st = StringTokenizer(line, "-")
lang = st.nextToken()
country = st.nextToken()
}
br.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
val locale = Locale(lang,country)
Lingver.getInstance().setLocale(this.applicationContext, locale)
if(!previousCountry.equals(country) && !previousLang.equals(lang)){
recreate()
}
Log.i("LauncherDMD", "Utility: Nuova lingua impostata: $lang")
Log.i("LauncherDMD", "Utility: Nuova nazione impostata: $country")
}
This solution works BUT the problem is that every time the MAIN-APP is uninstalled and installed again (sometimes it happens), it cannot access to the language file previously created by itself and instead it create a duplicate.
I obviously I cannot delete the old language file before creating new ones.
I also know that I cannot use the special permission "MANAGE_EXTERNAL_STORAGE" because I have to publish the app on the play store.
Thanks in advance!

how to return response string from $http get request

I want to get dynamic string response from the server by sent date of an object.
for (var i = 0; i < notifications.length; i++) {
let tempNotification = { ...notifications[i] };
tempNotification.Time = convertTime(tempNotification.CreationDate);
tempArray.push(tempNotification);
}
This is the convert Function:
function convertTime(date) {
const today = new Date();
const creationDate = new Date(date);
const months = today.getMonth() - creationDate.getMonth();
//if hours / 24*30 - moth
if (months > 0) {
return new Date(date).toLocaleString();
} else {
const sum = today.getDate() - creationDate.getDate();
if (sum > 0) {
return sum + " " + GetSpecificReactConst("notification-days-ago");
} else {
const hours = today.getHours() - creationDate.getHours();
if (hours > 0) {
return sum + " " + GetSpecificReactConst("notification-hours-ago");
} else {
return 1 + " " + GetSpecificReactConst("notification-houts-ago");
}
}
}
}
and the GetSpecificReact... is an $http get request:
function GetSpecificReactConst (text) {
$http.get(AppConfig.apiUrl + 'Translations/GetSpecificReactConst?constKey=' + text + '&lang=' + $location.url().split('/')[1]).
then(function (response) {
});
}
How i can get the response?

Uploading multiple images to firebase storage and saving the download url to realtime database in android studio kotlin

Hello I am a newbie to android development and I aM trying to upload multiple images to firebase realtime database
the app I am building is an ecommerce app.
here is my addItem activity below
// onActivity result
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode ==
Activity.RESULT_OK && data != null
) {
val result = CropImage.getActivityResult(data)
imageUri1 = result.uri
goodsimage1?.setImageURI(imageUri1)
uploadedImages.add(imageUri1!!)
}
if (requestCode == 2 && resultCode ==
Activity.RESULT_OK && data != null
) {
val result = CropImage.getActivityResult(data)
imageUri2 = result.uri
goodsimage2?.setImageURI(imageUri2)
uploadedImages.add(imageUri2!!)
}
if (requestCode == 3 && resultCode ==
Activity.RESULT_OK && data != null
) {
val result = CropImage.getActivityResult(data)
imageUri3 = result.uri
goodsimage3?.setImageURI(imageUri3)
uploadedImages.add(imageUri3!!)
}
if (requestCode == 4 && resultCode ==
Activity.RESULT_OK && data != null
) {
val result = CropImage.getActivityResult(data)
imageUri4 = result.uri
goodsimage4?.setImageURI(imageUri4)
uploadedImages.add(imageUri4!!)
}
if (requestCode == 5 && resultCode ==
Activity.RESULT_OK && data != null
) {
val result = CropImage.getActivityResult(data)
imageUri5 = result.uri
goodsimage5?.setImageURI(imageUri5)
uploadedImages.add(imageUri5!!)
}
}
//addItem activity
when {
imageUri1 == null && imageUri2 == null && imageUri3 == null && imageUri4 == null && imageUri5 == null ->
Toast.makeText(
activity,
"Please add at least one image.",
Toast.LENGTH_LONG
).show()
TextUtils.isEmpty(itemTitle) -> Toast.makeText(
activity,
"Title is required.",
Toast.LENGTH_LONG
).show()
TextUtils.isEmpty(itemPrice) -> Toast.makeText(
activity,
"Price is required.",
Toast.LENGTH_LONG
).show()
TextUtils.isEmpty(mState) -> Toast.makeText(
activity,
"State is required.",
Toast.LENGTH_LONG
).show()
TextUtils.isEmpty(mLga) -> Toast.makeText(
activity,
"LGA is required.",
Toast.LENGTH_LONG
).show()
TextUtils.isEmpty(mCategory) -> Toast.makeText(
activity,
"Category is required.",
Toast.LENGTH_LONG
).show()
TextUtils.isEmpty(mSubcategory) -> Toast.makeText(
activity,
"Subcategory is required.",
Toast.LENGTH_LONG
).show()
else -> {
val progressDialog = ProgressDialog(activity)
progressDialog.setTitle("Adding an item")
progressDialog.setMessage("Please wait, while we add your item....")
progressDialog.setCanceledOnTouchOutside(false)
progressDialog.show()
var uploadTask: StorageTask<UploadTask.TaskSnapshot>
var up = 0
while(up < uploadedImages.size) {
val perFile : Uri = uploadedImages.get(up)
val photoRef: StorageReference = storageItemPicRef!!.child(uploadedImages.get(up).lastPathSegment!!)
uploadTask = photoRef.putFile(perFile)
uploadTask.continueWithTask(Continuation<UploadTask.TaskSnapshot, Task<Uri>> { task ->
if (!task.isSuccessful) {
task.exception?.let {
throw it
progressDialog.dismiss()
}
}
return#Continuation photoRef.downloadUrl
}).addOnCompleteListener(OnCompleteListener<Uri> { task ->
if (task.isSuccessful) {
mPhotos = ArrayList()
mPhotos.clear()
val downloadUrl = task.result
/* myUrl = downloadUrl.toString()*/
mPhotos.add(downloadUrl!!.toString())
val doc = fStore.reference.child("Items")
val itemId = doc.push().key
val itemMap = HashMap<String, Any>()
itemMap["title"] = itemTitle
itemMap["price"] = itemPrice
itemMap["description"] = itemDescription
itemMap["category"] = mCategory
itemMap["subcategory"] = mSubcategory
itemMap["state"] = mState
itemMap["lga"] = mLga
itemMap["image"] = mPhotos
itemMap["itemId"] = itemId!!
doc.child(itemId).setValue(itemMap)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Toast.makeText(
activity,
"Item has been created successfully!",
Toast.LENGTH_LONG
).show()
progressDialog.dismiss()
val intent =
Intent(activity, HomeActivity::class.java)
startActivity(intent)
activity!!.finish()
} else {
progressDialog.dismiss()
val message = task.exception.toString()
Toast.makeText(
activity,
"Error: $message",
Toast.LENGTH_LONG
)
.show()
}
}
}
})
}
}
}
}
}
I am trying to get an array of images saved for every item added by the user to the app
private fun AddItem() {
val itemName: String = title!!.text.toString()
val itemPrice: String = price!!.text.toString()
val itemDescription: String = description!!.text.toString()
when {
imageUri1 == null && imageUri2 == null && imageUri3 == null && imageUri4 == null && imageUri5 == null -> {
Toast.makeText(
activity,
"Please add at least one image.",
Toast.LENGTH_LONG
).show()
}
TextUtils.isEmpty(itemName) -> Toast.makeText(
activity,
"Title is required.",
Toast.LENGTH_LONG
).show()
TextUtils.isEmpty(itemPrice.toString()) -> Toast.makeText(
activity,
"Price is required.",
Toast.LENGTH_LONG
).show()
TextUtils.isEmpty(itemDescription) -> Toast.makeText(
activity,
"Please write a short description of your item",
Toast.LENGTH_LONG
).show()
else -> {
var uploadTask: StorageTask<UploadTask.TaskSnapshot>
progressBar!!.visibility = view!!.visibility
while (up < uploadedImages.size) {
val itemRef: StorageReference = storageItemPicRef!!.child(firebaseUser.uid)
.child(uploadedImages[k].lastPathSegment!!)
uploadTask = itemRef.putFile(uploadedImages[k])
.addOnSuccessListener { p0 ->
val downloadUrl =
p0!!.storage.downloadUrl
}.addOnFailureListener {
}
up++
k++
uploadTask.continueWithTask(Continuation<UploadTask.TaskSnapshot, Task<Uri>> { task ->
if (!task.isSuccessful) {
task.exception?.let {
throw it
}
}
return#Continuation itemRef.downloadUrl
}).addOnCompleteListener (OnCompleteListener { task ->
if (task.isSuccessful) {
downloadImages = ArrayList()
val downloadUrl = task.result
(downloadImages as ArrayList<Uri>).add(downloadUrl!!)
val itemMap = HashMap<String, Any>()
doc = FirebaseDatabase.getInstance().reference.child("Items")
.child(firebaseUser.uid)
for(element in downloadImages) {
/* mPhotos.put(doc.push().key!!, downloadImages[i].toString())*/
mPhotos.add(element.toString())
}
itemMap["uid"] = firebaseUser.uid
itemMap["state"] = mState
itemMap["title"] = itemName
itemMap["description"] = itemDescription
itemMap["price"] = itemPrice
itemMap["images"] = mPhotos
itemMap["lga"] = mLga
itemMap["category"] = mCategory
itemMap["subcategory"] = mSubcategory
doc.setValue(itemMap)
sendToHomeActivity()
progressBar!!.visibility = View.INVISIBLE
Toast.makeText(activity, "Item has been created successfully", Toast.LENGTH_LONG).show()
}
})
}
}
}
}
private fun sendToHomeActivity() {
val mainIntent = Intent(context, HomeActivity::class.java)
startActivity(mainIntent)
}

Getting error while calling function from element attributes

Trying for creating multiple progress bar with dynamic value
<progressbar class="progress-striped active" value="{{getValue(value.currentStatus)}}"
type="{{getType(this.value, value.currentStatus)}}">
{{ value.currentStatus }}
</progressbar>
following two functions are called above, but getType function is called and working
but getValue function is not called its throw error
Error: [$parse:syntax] Syntax Error: Token 'getValue' is unexpected,
expecting [:] at column 3 of the expression
[{{getValue(value.currentStatus)}}] starting at
[getValue(value.currentStatus)}}]
$scope.getValue = function(Status) {
var tasksLength = 4;
var completedActions;
if (Status != null) {
completedActions = completedActions + 1;
}
var progressActions = (completedActions == tasksLength) ? 0 : 1;
var queuedActions = tasksLength - (completedActions + progressActions);
return Math.ceil(((queuedActions * 0.09) + (progressActions * 0.35) +
completedActions) / tasksLength * 100);
}
$scope.getType = function(value, Status) {
if ((value > 80) && (Status == "FAILED")) {
type = 'danger';
} else if (value > 80) {
type = 'success';
} else if (value > 50) {
type = 'warning';
} else {
type = 'info';
}
return type;
}
please help me to solve this error

Weird Obtics Exception

I am using Obtics library for my live-linq queries.
But I can't get pass this weird exception which makes no sense at all.
Here is my query:
var query = ExpressionObserver.Execute(() =>
from o in _orders.DefaultIfEmpty(new OrderStatusViewModel())
where o.State != OrderStateEnum.Canceled
group o by o.Isin
into g
let name = _referenceData.GetInstrumentName(g.Key)
orderby name ascending
select new ComplexRowViewModel(_referenceData)
{
UnderlyingOrder = g.First(),
PrimaryExchange = (from q in _quotes.DefaultIfEmpty(new QuoteTickViewModel()).Where(w => w.Exchange == _referenceData.GetPrimaryExchangeId(g.Key) && w.Isin == g.Key && w.Provider == ProviderEnum.Bloomberg)
select new SimpleRowViewModel()
{
UnderlyingQuote = q
}).First(),
Groupped = (from y in _orders.DefaultIfEmpty(new OrderStatusViewModel())
join x in _quotes.DefaultIfEmpty(new QuoteTickViewModel()) on new { y.Isin, y.Exchange }
equals new { x.Isin, x.Exchange }
where
y.Isin == g.Key &&
y.State != OrderStateEnum.Canceled &&
x.Provider == ProviderEnum.Tradebase &&
x.Exchange !=
_referenceData.GetPrimaryExchangeId(g.Key)
group x by new { x.Exchange }
into p
select new SimpleRowViewModel()
{
UnderlyingQuote = p.First()
}
),
Uncompressed = (from o in _orders.DefaultIfEmpty(new OrderStatusViewModel())
where o.State != OrderStateEnum.Canceled && o.Isin == g.Key
select new UncompressedRowViewModel() { UnderlyingOrder = o }),
Compressed = (from o in _orders.DefaultIfEmpty(new OrderStatusViewModel())
where o.State != OrderStateEnum.Canceled && o.Isin == g.Key
group o by new { o.LimitPrice, o.OrderSide } into x
select new CompressedRowViewModel()
{
Ask = x.Key.OrderSide == OrderSideEnum.Sell ? (decimal?)x.Key.LimitPrice : (decimal?)null,
AskSize = x.Key.OrderSide == OrderSideEnum.Sell ? x.Select(s => s.Quantity).Aggregate((c, n) => c + n) : 0,
Bid = x.Key.OrderSide == OrderSideEnum.Buy ? (decimal?)x.Key.LimitPrice : (decimal?)null,
BidSize = x.Key.OrderSide == OrderSideEnum.Buy ? x.Select(s => s.Quantity).Aggregate((c, n) => c + n) : 0,
Exchange = string.Join(", ", x.Select(s => s.Exchange)),
Isin = x.First().Isin.ToString(),
OrderBuyCount = x.Key.OrderSide == OrderSideEnum.Buy ? x.Count() : 0,
OrderSellCount = x.Key.OrderSide == OrderSideEnum.Sell ? x.Count() : 0,
RowSide = x.Key.OrderSide == OrderSideEnum.Sell ? RowSide.Sell : RowSide.Buy
})}
).Cascade();
GridData = query;
I uploaded the class which makes all this possible. http://www.4shared.com/file/ce_V8PPh/MarketData.html
The exception is:
InvalidOperationException, Added item does not appear at given index '0'.
But this makes no sense since the item is already there.
Everything works fine until an OrderStatus gets a "Cancelled" state. I think it is because I filter the cancelled orders on top of the query, but how is this relevant I don't know.
I finally found a solution to my problem. It turns out that Obtics has a problem with on the fly class creation with lambda, such as
from o in orders where o.state == "active" select new OrderModel2 {Underlying = o}
new keyword messes all up. you need handle this class creation manually.
Anyways after 2 days of head smashing I ended up having this much code.
private void CreateQueries()
{
var query = ExpressionObserver.Execute(() => (from o in _orders
where o.State != OrderStateEnum.Canceled
group o by o.Isin
into g
let name = _referenceData.GetInstrumentName(g.Key)
orderby name ascending
select GetComplexRowViewModel(
g.First()
,
(from p in _quotes
where
p.Isin == g.Key &&
p.Exchange == _referenceData.GetPrimaryExchangeId(g.Key) &&
p.Provider == ProviderEnum.Bloomberg
select GetSimpleRowViewModel(p))
,
(from q in _quotes
where
q.Isin == g.Key &&
q.Provider == ProviderEnum.Tradebase &&
g.Select(s => s.Exchange).Contains(q.Exchange)
select GetSimpleRowViewModel(q))
,
(from o in _orders
where o.Isin == g.Key
&& o.State != OrderStateEnum.Canceled
group o by new { o.LimitPrice, o.OrderSide } into x
select GetCompressedRowViewModel
(
x.Key.OrderSide == OrderSideEnum.Sell ? (decimal?)x.Key.LimitPrice : (decimal?)null,
x.Key.OrderSide == OrderSideEnum.Sell ? x.Select(s => s.Quantity).Aggregate((c, n) => c + n) : 0,
x.Key.OrderSide == OrderSideEnum.Buy ? (decimal?)x.Key.LimitPrice : (decimal?)null,
x.Key.OrderSide == OrderSideEnum.Buy ? x.Select(s => s.Quantity).Aggregate((c, n) => c + n) : 0,
string.Join(", ", x.Select(s => s.Exchange)),
x.First().Isin.ToString(),
x.Key.OrderSide == OrderSideEnum.Buy ? x.Count() : 0,
x.Key.OrderSide == OrderSideEnum.Sell ? x.Count() : 0,
x.Key.OrderSide == OrderSideEnum.Sell ? RowSide.Sell : RowSide.Buy
))
,
(from o in _orders
where o.Isin == g.Key
&& o.State != OrderStateEnum.Canceled
select GetUncompressedRowViewModel(o))
))).Cascade();
GridData = query;
}
// Obtics
private ConcurrentDictionary<string, ComplexRowViewModel> _complexRowViewModels = new ConcurrentDictionary<string, ComplexRowViewModel>();
private ComplexRowViewModel GetComplexRowViewModel(OrderStatusViewModel model, IEnumerable<SimpleRowViewModel> primaryExchanges, IEnumerable<SimpleRowViewModel> groupped
, IEnumerable<CompressedRowViewModel> compressed, IEnumerable<UncompressedRowViewModel> uncompressed)
{
if (model == null)
return _complexRowViewModels.GetOrAdd("", s2 => new ComplexRowViewModel());
return _complexRowViewModels.GetOrAdd(model.Isin,
s2 =>
new ComplexRowViewModel(_referenceData) { UnderlyingOrder = model, PrimaryExchange = primaryExchanges.DefaultIfEmpty(new SimpleRowViewModel()).First(), Groupped = groupped, Compressed = compressed, Uncompressed = uncompressed });
}
private ConcurrentDictionary<string, SimpleRowViewModel> _simpleRowViewModels = new ConcurrentDictionary<string, SimpleRowViewModel>();
private SimpleRowViewModel GetSimpleRowViewModel(QuoteTickViewModel model)
{
if (model == null)
return _simpleRowViewModels.GetOrAdd("", s2 => new SimpleRowViewModel());
return _simpleRowViewModels.GetOrAdd(model.Isin + model.Exchange,
s2 =>
new SimpleRowViewModel() { UnderlyingQuote = model });
}
private ConcurrentDictionary<string, UncompressedRowViewModel> _uncompressedRowViewModels = new ConcurrentDictionary<string, UncompressedRowViewModel>();
private UncompressedRowViewModel GetUncompressedRowViewModel(OrderStatusViewModel model)
{
if (model == null)
return _uncompressedRowViewModels.GetOrAdd("", s2 => new UncompressedRowViewModel());
return _uncompressedRowViewModels.GetOrAdd(model.InternalId,
s2 =>
new UncompressedRowViewModel() { UnderlyingOrder = model });
}
private ConcurrentDictionary<string, CompressedRowViewModel> _compressedRowViewModels = new ConcurrentDictionary<string, CompressedRowViewModel>();
private CompressedRowViewModel GetCompressedRowViewModel(decimal? Ask, int AskSize, decimal? Bid, int BidSize, string Exchange, string Isin, int OrderBuyCount, int OrderSellCount, RowSide RowSide)
{
return new CompressedRowViewModel()
{
Ask = Ask,
AskSize = AskSize,
Bid = Bid,
BidSize = BidSize,
Exchange = Exchange,
Isin = Isin,
OrderBuyCount = OrderBuyCount,
OrderSellCount = OrderSellCount,
RowSide = RowSide
};
}
It works but looks ugly, if anyone has a way to make it more beautiful I'll be appreciated.
The problem is not with the 'new' keyword but rather that two instances of type OrderModel2 are not equal even though they are created with equal construction arguments.
This can be solved in three ways:
Override the Equals method of your object.
Apply an ObticsEqualityComparerAttribute to your class with the specific equality comparer for Obtics to use.
Create a factory with a repository that returns the same object instance when called with the same construction arguments.
You seem to have used number 3, though I think your code could be more simple and generic.

Resources