ServiceStack OrmLite-Oracle: Can't insert object with sequence attribute - servicestack

I'm testing ServiceStack.OrmLite.Oracle (5.5.1) but can't save data to database when create model with Sequence attribute. Try to test with API & generated SQL, API not insert data but generated SQL is correct. How to fix this?
using System;
using System.Data;
using NUnit.Framework;
using ServiceStack.DataAnnotations;
using ServiceStack.OrmLite;
namespace Tests
{
public class DatabaseTest
{
private readonly IDbConnection _db;
public DatabaseTest()
{
var dbFactory = new OrmLiteConnectionFactory(
#"Data Source = (DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = ora-test)(PORT = 1521))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = twcms12c))); User Id=scott; Password=Ab123456",
OracleDialect.Provider);
_db = dbFactory.OpenDbConnection();
}
[Test]
public void CustomerInsertTest()
{
_db.DropAndCreateTable<Person>();
var customer = new Person {FirstName = "John", LastName = "Smith", Age = 20};
//Insert by API not work
_db.Insert(customer);
var customers = _db.Select<Person>();
Console.WriteLine("Person count (API) = {0}",customers.Count);
//Insert by SQL working
_db.ExecuteSql(_db.ToInsertStatement(customer));
customers = _db.Select<Person>();
Console.WriteLine("Person count (SQL) = {0}",customers.Count);
}
}
public class Person
{
[AutoIncrement]
[Sequence("PERSON_SEQ")]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int? Age { get; set; }
}
}
And output result is:
Person count (API) = 0
Person count (SQL) = 1

In ServiceStack.OrmLite.Oracle (5.5.1) have a bug in method GetNextValue (ServiceStack.OrmLite.Oracle.OracleOrmLiteDialectProvider.cs):
private object GetNextValue(IDbCommand dbCmd, string sequence, object value)
{
if (value.ToString() != "0")
{
object retObj;
if (long.TryParse(value.ToString(), out var nv))
{
LastInsertId = nv;
retObj = LastInsertId;
}
else
{
LastInsertId = 0;
retObj = value;
}
return retObj;
}
dbCmd.CommandText = $"SELECT {Quote(sequence)}.NEXTVAL FROM dual";
long result = (long)dbCmd.LongScalar();
LastInsertId = result;
return result;
}
I change it to:
private object GetNextValue(IDbCommand dbCmd, string sequence, object value)
{
if (value.ToString() != "0")
{
object retObj;
if (long.TryParse(value.ToString(), out var nv))
{
LastInsertId = nv;
retObj = LastInsertId;
}
else
{
LastInsertId = 0;
retObj = value;
}
return retObj;
}
var lastSql = dbCmd.CommandText;
dbCmd.CommandText = $"SELECT {Quote(sequence)}.NEXTVAL FROM dual";
long result = (long)dbCmd.LongScalar();
LastInsertId = result;
dbCmd.CommandText = lastSql;
return result;
}
and it work well.
P/s: I have create a pull request it was accepted by ServiceStack.

Related

Hazelcast Predicate SQL into map

I'm trying to build a method that deletes entries with attributes that are not null, but I keep failing in predicates and I don't know how to implement properly the predicate because hazelcast doesn't take "NOT NULL" or "IS NULL" as a where clause Any idea how can I find into the map the values I need to search to delete them?
the method
public int removeEntry(String CacheName, String claveReq, int id_interno_pe, String cod_nrbe_en, int num_sec_ac) {
int counter = 0;
IMap<String, ResponseSerializablePlus> map = clientInstance.getMap(CacheName);
// Predicate claveReqQuery = Predicates.equal("claveReq", claveReq);
// Predicate idInternoQuery = Predicates.equal("id_interno_pe", id_interno_pe);
// Predicate codNrbeQuery = Predicates.equal("cod_nrbe_en", cod_nrbe_en);
// Predicate numSecQuery = Predicates.equal("num_sec_ac", num_sec_ac);
// Predicate query = Predicates.and(idInternoQuery,codNrbeQuery,numSecQuery);
Predicate query = Predicates.sql("id_interno_pe IS NOT NULL");
if (!map.isEmpty()) {
for (ResponseSerializablePlus entry : map.values(query)) {
System.out.println("Entry "+entry.toString()+" Found");
map.delete(entry);
counter++;
}
System.out.println("Map Size ->"+map.size());
System.out.println("Deleted entries -> "+counter);
return counter;
}else {
System.out.println("No matches");
return 0;
}
}
the main class ResponseSerializablePlus
public class ResponseSerializablePlus implements IdentifiedDataSerializable{
private int id_interno_pe;
private String cod_nrbe_en;
private int num_sec_ac;
private int statusCode;
private HashMap<String,List<String>> headers;
private byte[] content;
public ResponseSerializablePlus(int id_interno_pe, String cod_nrbe_en, int num_sec_ac, int statusCode,
HashMap<String, List<String>> headers, byte[] content) {
this.id_interno_pe = id_interno_pe;
this.cod_nrbe_en = cod_nrbe_en;
this.num_sec_ac = num_sec_ac;
this.statusCode = statusCode;
this.headers = headers;
this.content = content;
}
public ResponseSerializablePlus() {
}
public void writeData(ObjectDataOutput out) throws IOException {
out.writeInt(id_interno_pe);
out.writeString(cod_nrbe_en);
out.writeInt(num_sec_ac);
out.writeInt(statusCode);
out.writeObject(headers);
out.writeByteArray(content);
}
public void readData(ObjectDataInput in) throws IOException {
this.id_interno_pe = in.readInt();
this.cod_nrbe_en = in.readString();
this.num_sec_ac = in.readInt();
this.statusCode = in.readInt();
this.headers = in.readObject();
this.content = in.readByteArray();
}
public int getFactoryId() {
return ResponseSerializablePlusFactory.FACTORY_ID;
}
public int getClassId() {
return ResponseSerializablePlusFactory.RESPONSE_SERIALIZABLE_PLUS_CLASS;
}
#Override
public String toString() {
return "ResponseSerializablePlus [id_interno_pe=" + id_interno_pe + ", cod_nrbe_en=" + cod_nrbe_en
+ ", num_sec_ac=" + num_sec_ac + ", statusCode=" + statusCode + ", headers=" + headers + ", content="
+ Arrays.toString(content) + "]";
}
}
It's indeed not supported, and it's document, along with the alternative option. Have a look here: https://github.com/hazelcast/hazelcast/blob/3cb8ce1fc3bb848aced6c87a30bf7b31aec16cf7/hazelcast/src/main/java/com/hazelcast/query/Predicates.java#L492-L497

How can I export tables in Excel file using ASP.Net MVC?

My View consists of multiple tables, and I am looking to Export multiple tables from View in Excel file. My current function only helps me to export 1 table.
Can any one help me to complete this code so that multiple tables can be exported?
Report VM
public class ReportVM
{
public string ScenName { get; set; }
public int Count { get; set; }
public string CreateTickYes { get; set; }
public int TickYes { get; set; }
public string RegionName { get; set; }
public int RegionCount { get; set; }
public string UserName { get; set; }
public int ChatCountUser { get; set; }
}
Action Method to export
public FileContentResult DownloadReport(DateTime start, DateTime end)
{
//var uName = User.Identity.Name;
var fileDownloadName = String.Format("Report.xlsx");
const string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
// Pass your ef data to method
ExcelPackage package = GenerateExcelFile(db.Chats.Where(x => System.Data.Entity.DbFunctions.TruncateTime(x.ChatCreateDateTime) >= start && System.Data.Entity.DbFunctions.TruncateTime(x.ChatCreateDateTime) <= end)
.GroupBy(a => a.ScenarioList).Select(b => new ReportVM()
{
ScenName = b.Key,
Count = b.Count()
}).ToList());
var fsr = new FileContentResult(package.GetAsByteArray(), contentType);
fsr.FileDownloadName = fileDownloadName;
return fsr;
}
private static ExcelPackage GenerateExcelFile(IEnumerable<ReportVM> datasource)
{
ExcelPackage pck = new ExcelPackage();
//Create the worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet 1");
// Sets Headers
ws.Cells[1, 1].Value = "Scenario";
ws.Cells[1, 2].Value = "No.Of Chats";
// Inserts Data
for (int i = 0; i < datasource.Count(); i++)
{
ws.Cells[i + 2, 1].Value = datasource.ElementAt(i).ScenName;
ws.Cells[i + 2, 2].Value = datasource.ElementAt(i).Count;
}
//Sheet2
// Format Header of Table
using (ExcelRange rng = ws.Cells["A1:B1"])
{
rng.Style.Font.Bold = true;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid; //Set Pattern for the background to Solid
rng.Style.Fill.BackgroundColor.SetColor(Color.Gold); //Set color to DarkGray
rng.Style.Font.Color.SetColor(Color.Black);
}
return pck;
}
So, now it export data for Table GroubBy = ScenarioList. I want to also include another column in groupBy = Username. So when Export data, Excel file should contain 2 Sheets. 1 for Table ScenarioList, and 2nd for Table Username.
Help is much appreciated. Thank you in advance.
You need create div/table under which put all tables and then by using below javascript function. Please call this javascript function on button click on same page which have all data. This is working for me which I already used in my project.
function DownloadToExcel() {
var htmls = $("#compareBodyContent")[0].innerHTML; // this main element under which
//all you data
var uri = 'data:application/vnd.ms-excel;base64,';
var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>';
var base64 = function (s) {
return window.btoa(unescape(encodeURIComponent(s)))
};
var format = function (s, c) {
return s.replace(/{(\w+)}/g, function (m, p) {
return c[p];
})
};
var ctx = {
worksheet: 'Worksheet',
table: '<table>' + htmls + '</table>'
}
var compareLink = document.createElement("a");
compareLink.download = "Compare_Test.xls";
compareLink.href = uri + base64(format(template, ctx));
compareLink.click();
}
Hope this will help you. Let me know if you have any question on this.

Passing Objects through Heap Sort

Having issues trying to pass an object class to be sorted via Heap Sort. Basically I have a class which holds employee data such as names, address, phone numbers and employee ID. We are to use Heap Sort to pass this class as a object and sort it by employee ID. My main issue is converting my heap sort structures to where they can take objects. This is for a beginning data structures course so we're not allowed to use advanced techniques. My road block is I'm stumped as to how to pass my objects into the heap sort methods which currently only take primitive data types.
Office Class:
public class Office_Staff
{
public String Name , Dept , Phonenumber;
public int Id, years;
Office_Staff()
{
Id = ("");
Name = ("");
Dept = ("");
Phonenumber = ("");
years = 0;
}
Office_Staff(int empid ,String empname, String empdept , String empphone, int service)
{
Id = empid;
Name = empname;
Dept = empdept;
Phonenumber = empphone;
years = service;
}
public void setId(int empid)
{
Id = empid;
}
public void setName(String empname)
{
Name = empname;
}
public void setDept(String empdept)
{
Dept = empdept;
}
public void setPhone(String empphone)
{
Phonenumber = empphone;
}
public void setYears(int service)
{
years = service;
}
public String getId()
{
return Id;
}
public String getName()
{
return Name;
}
public String getDept()
{
return Dept;
}
public String getPhone()
{
return Phonenumber;
}
public int getYears()
{
return years;
}
public String toString()
{
String str = "Office_Staff Name : " + Name + "Office_Staff ID : " + Id +
"Office_Staff Deaprtment : " + Dept + "Office_Staff Phone Number : "
+ Phonenumber + "Years Active : " + years;
return str;
}
}
Heap Sort:
import java.util.Scanner;
import java.util.ArrayList;
import java.io.*;
class zNode
{
private int iData;
public zNode(int key)
{
iData = key;
}
public int getKey()
{
return iData;
}
public void setKey(int k)
{
iData = k;
}
}
class HeapSort
{
private int [] currArray;
private int maxSize;
private int currentSize;
private int currIndex;
HeapSort(int mx)
{
maxSize = mx;
currentSize = 0;
currArray = new int[maxSize];
}
//buildheap
public boolean buildHeap(int [] currArray)
{
int key = currIndex;
if(currentSize==maxSize)
return false;
int newNode = key;
currArray[currentSize] = newNode;
siftUp(currArray , currentSize++);
return true;
}
//siftup
public void siftUp(int [] currArray , int currIndex)
{
int parent = (currIndex-1) / 2;
int bottom = currArray[currIndex];
while( currIndex > 0 && currArray[parent] < bottom )
{
currArray[currIndex] = currArray[parent];
currIndex = parent;
parent = (parent-1) / 2;
}
currArray[currIndex] = bottom;
}
//siftdown
public void siftDown(int [] currArray , int currIndex)
{
int largerChild;
int top = currArray[currIndex];
while(currIndex < currentSize/2)
{
int leftChild = 2*currIndex+1;
int rightChild = leftChild+1;
if(rightChild < currentSize && currArray[leftChild] < currArray[rightChild] )
largerChild = rightChild;
else
largerChild = leftChild;
if( top >= currArray[largerChild] )
break;
currArray[currIndex] = currArray[largerChild];
currIndex = largerChild;
}
currArray[currIndex] = top;
}
//remove max element
public int removeMaxElement(int [] currArray)
{
int root = currArray[0];
currArray[0] = currArray[--currentSize];
siftDown(currArray , 0);
return root;
}
//heapsort
private void _sortHeapArray(int [] currArray)
{
while(currentSize != 0)
{
removeMaxElement(currArray);
}
}
public void sortHeapArray()
{
_sortHeapArray(currArray);
}
//hepify
private int[] heapify(int[] currArray)
{
int start = (currentSize) / 2;
while (start >= 0)
{
siftDown(currArray, start);
start--;
}
return currArray;
}
//swap
private int[] swap(int[] currArray, int index1, int index2)
{
int swap = currArray[index1];
currArray[index1] = currArray[index2];
currArray[index2] = swap;
return currArray;
}
//heapsort
public int[] _heapSort(int[] currArray)
{
heapify(currArray);
int end = currentSize-1;
while (end > 0)
{
currArray = swap(currArray,0, end);
end--;
siftDown(currArray, end);
}
return currArray;
}
public void heapSort()
{
_heapSort(currArray);
}

Limit string to eight characters and return it with asterisk

I have a studentDto. I want to determine the number
of characters for LastName. If number of characters is greater
than 8, I want to return the last name of 8 characters with two asterisk thus
cutting off the other characters
e.g Abumadem**
Here is how I started.I am unable to get it to work. Can you please assist?
public class StudentDto
{
public string Firstname { get; set; }
public string EmailAddress { get; set; }
public string LastName
{
get
{
var checkLength = LastName.Length;
string First8Chars = string.Empty;
int count=0;
List<char> storeStrings = new List<char>();
if (checkLength > 8)
{
foreach (var c in LastName)
{
storeStrings.Add(c);
if ()
{
}
count++;
}
}
}
}
}
Here is new attempt and no luck yet.
public class StudentDto
{
public string Firstname { get; set; }
public string EmailAddress { get; set; }
public string LastName
{
get
{
var checkLength = LastName.Length;
string First8Chars = string.Empty;
if (checkLength > 8)
{
First8Chars = LastName.Substring(0, 7) + "**";
return First8Chars;
}
}
set { }
}
}
Just do it like this:
string _backingFieldLastName;
public string LastName
{
get
{
return _backingFieldLastName == null || backingFieldLastName.Length <=8 ?
_backingFieldLastName :
_backingFieldLastName.Substring(0,8) +"**"; // second parameter of substring is count of chars from the start index (first parameter)
}
set
{
_backingFieldLastName = value;
}
}
If you cant use library functions for some reason:
private string _lastName = "";
public string LastName
{
get
{
var checkLength = _lastName.Length;
string First8Chars = string.Empty;
string storeStrings = "";
if (checkLength > 8)
{
foreach (var c in _lastName)
{
storeStrings += c;
if (storeStrings.Length == 8)
{
storeStrings += "**";
return storeStrings;
}
}
}
return storeStrings;
}
set { _lastName = value; }
}
One thing I noticed is your use of LastName in the LastName property getter, a big no no, its causing recursion and you probably are getting a stack overflow exception
This could be written more concise, but I'll leave that as an exercise for you
The Linq way:
var lastname = "Abumademal";
var formatted = (new string(lastname.Take(8).ToArray())).PadRight(lastname.Length, '*');
// will yield "Abumadem**"
"Take 8 chars and create a new string from this array, then pad it with as many * as needed."
full implementation:
private string lastname;
public string LastName
{
get
{
if (null == this.lastname)
{
return null;
}
char[] firsteight = this.lastname.Take(8).ToArray();
string tmp = new string(firsteight);
// padding this way wasn't the actual requirement ...
string result = tmp.PadRight(this.lastname.Length, '*');
return result;
}
set
{
this.lastname = value;
}
}

How to sort recordstore records based on a certain field in it?

For example there are three records in a recordstore , and the structure of a record in the recordstore is like this : lastname;firstname;moneyborrowed
I want to show these three records inside a LWUIT Table and I want them to be sorted by the lastname column. How to achieve that ?
save using
Preferences preferences = new Preferences("mydbname");
preferences.put("key","lastname;firstname;moneyborrowed");
preferences.save();
and retrieve using
String val = (string) preferences.get("key");
Preferences.java
import java.util.Enumeration;
import java.util.Hashtable;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
public class Preferences {
private final String mRecordStoreName;
private final Hashtable mHashtable;
public Preferences(String recordStoreName)
throws RecordStoreException {
mRecordStoreName = recordStoreName;
mHashtable = new Hashtable();
load();
}
public String get(String key) {
return (String)mHashtable.get(key);
}
public void put(String key, String value) {
if (value == null) value = "";
mHashtable.put(key, value);
}
private void load() throws RecordStoreException {
RecordStore rs = null;
RecordEnumeration re = null;
try {
rs = RecordStore.openRecordStore(mRecordStoreName, true);
re = rs.enumerateRecords(null, null, false);
while (re.hasNextElement()) {
byte[] raw = re.nextRecord();
String pref = new String(raw);
// Parse out the name.
int index = pref.indexOf('|');
String name = pref.substring(0, index);
String value = pref.substring(index + 1);
put(name, value);
}
}
finally {
if (re != null) re.destroy();
if (rs != null) rs.closeRecordStore();
}
}
public void save() throws RecordStoreException {
RecordStore rs = null;
RecordEnumeration re = null;
try {
rs = RecordStore.openRecordStore(mRecordStoreName, true);
re = rs.enumerateRecords(null, null, false);
// First remove all records, a little clumsy.
while (re.hasNextElement()) {
int id = re.nextRecordId();
rs.deleteRecord(id);
}
// Now save the preferences records.
Enumeration keys = mHashtable.keys();
while (keys.hasMoreElements()) {
String key = (String)keys.nextElement();
String value = get(key);
String pref = key + "|" + value;
byte[] raw = pref.getBytes();
rs.addRecord(raw, 0, raw.length);
}
}
finally {
if (re != null) re.destroy();
if (rs != null) rs.closeRecordStore();
}
}
}

Resources