Oracle Data Provider to CLR type mapping - clr

Where can I find the listing of ODP to CLR type mapping?
On Oracle database, the NUMBER(9,0) type comes out in .NET app as System.Decimal from the MS Oracle driver, but as System.Int32 from ODP driver. I need an exact specification of types coming out from database (not the CLR to DB parameter mapping).

Run this simple test to get mappings for SqlServer and Oracle (both MS and ODP.NET drivers):
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using Oracle.DataAccess.Client;
namespace DbOutTypeTest
{
public class Program
{
private static string SqlServerConnectionString = #"";
private static string OracleConnectionString = #"";
private static void WriteHeader(string title)
{
Console.WriteLine("----------------------------------------------------------");
Console.WriteLine("-- {0}", title);
Console.WriteLine("----------------------------------------------------------");
}
private static void WriteRow(string key, string value)
{
Console.WriteLine("{0}\t\t{1}", key.PadRight(30, ' '), value);
}
private static void EnumerateTypes(IDbConnection connection, string template, IEnumerable<string> types)
{
EnumerateTypes(connection, template, types, (arg1, arg2) => { });
}
private static void EnumerateTypes(IDbConnection connection, string template, IEnumerable<string> types, Action<string, string> action)
{
connection.Open();
using (var command = connection.CreateCommand())
{
foreach (var type in types)
{
var value = "";
command.CommandText = string.Format(template, type);
try
{
using (var reader = command.ExecuteReader())
{
if (reader.Read())
value = reader[0].GetType().FullName;
else
value = "<no data read>";
}
}
catch (Exception ex)
{
value = ex.Message;
}
WriteRow(type, value);
action(type, value);
}
}
}
private static IEnumerable<string> SqlServerIntegers()
{
yield return "tinyint";
yield return "smallint";
yield return "int";
yield return "bigint";
for (int precision = 1; precision <= 38; ++precision)
{
yield return "numeric(" + precision + ", 0)";
}
yield break;
}
private static IEnumerable<string> SqlServerFloatings()
{
yield return "real";
yield return "float";
for (int precision = 1; precision <= 38; ++precision)
{
for (int scale = 1; scale <= precision; ++scale)
yield return "numeric(" + precision + ", " + scale + ")";
}
yield break;
}
private static IEnumerable<string> OracleIntegers()
{
for (int precision = 1; precision <= 38; ++precision)
{
yield return "number(" + precision + ", 0)";
}
yield break;
}
private static IEnumerable<string> OracleFloatings()
{
for (int precision = 1; precision <= 38; ++precision)
{
for (int scale = 1; scale <= precision; ++scale)
yield return "number(" + precision + ", " + scale + ")";
}
yield break;
}
public static void Main(string[] args)
{
WriteHeader("C# types - CLR names");
Console.WriteLine("{0}\t\t{1}", "byte".PadRight(30, ' '), typeof(byte).FullName);
Console.WriteLine("{0}\t\t{1}", "short".PadRight(30, ' '), typeof(short).FullName);
Console.WriteLine("{0}\t\t{1}", "int".PadRight(30, ' '), typeof(int).FullName);
Console.WriteLine("{0}\t\t{1}", "long".PadRight(30, ' '), typeof(long).FullName);
Console.WriteLine("{0}\t\t{1}", "float".PadRight(30, ' '), typeof(float).FullName);
Console.WriteLine("{0}\t\t{1}", "double".PadRight(30, ' '), typeof(double).FullName);
var OracleToClrInteger = new Dictionary<string, string>();
var OracleToClrFloating = new Dictionary<string, string>();
var SqlServerToClrInteger = new Dictionary<string, string>();
var SqlServerToClrFloating = new Dictionary<string, string>();
WriteHeader("Oracle integers mapping (Oracle Data Provider)");
using (var connection = new OracleConnection(OracleConnectionString))
{
EnumerateTypes(connection, "SELECT CAST(0 AS {0}) FROM DUAL", OracleIntegers(), (type, value) => OracleToClrInteger.Add(type, value));
}
WriteHeader("SQLServer integers mapping");
using (var connection = new SqlConnection(SqlServerConnectionString))
{
EnumerateTypes(connection, "SELECT CAST(0 AS {0})", SqlServerIntegers(), (type, value) => SqlServerToClrInteger.Add(type, value));
}
WriteHeader("Oracle integers mapping (Microsoft Oracle Client)");
using (var connection = new System.Data.OracleClient.OracleConnection(OracleConnectionString))
{
EnumerateTypes(connection, "SELECT CAST(0 AS {0}) FROM DUAL", OracleIntegers());
}
WriteHeader("Oracle floats mapping (Oracle Data Provider)");
using (var connection = new OracleConnection(OracleConnectionString))
{
EnumerateTypes(connection, "SELECT CAST(0 AS {0}) FROM DUAL", OracleFloatings(), (type, value) => OracleToClrFloating.Add(type, value));
}
WriteHeader("SQLServer floats mapping");
using (var connection = new SqlConnection(SqlServerConnectionString))
{
EnumerateTypes(connection, "SELECT CAST(0 AS {0})", SqlServerFloatings(), (type, value) => SqlServerToClrFloating.Add(type, value));
}
WriteHeader("Oracle floats mapping (Microsoft Oracle Client)");
using (var connection = new System.Data.OracleClient.OracleConnection(OracleConnectionString))
{
EnumerateTypes(connection, "SELECT CAST(0 AS {0}) FROM DUAL", OracleFloatings());
}
WriteHeader("Suggested integer type mapping Oracle -> SqlServer");
foreach (var pair in OracleToClrInteger)
{
if (pair.Value == "System.Decimal")
WriteRow(pair.Key, pair.Key.Replace("number", "numeric"));
else
{
if (!SqlServerToClrInteger.Values.Contains(pair.Value))
WriteRow(pair.Key, "???");
else
WriteRow(pair.Key, SqlServerToClrInteger.First(p => p.Value == pair.Value).Key);
}
}
WriteHeader("Suggested floating type mapping Oracle -> SqlServer");
foreach (var pair in OracleToClrFloating)
{
if (pair.Value == "System.Decimal")
WriteRow(pair.Key, pair.Key.Replace("number", "numeric"));
else
{
if (!SqlServerToClrFloating.Values.Contains(pair.Value))
WriteRow(pair.Key, "???");
else
WriteRow(pair.Key, SqlServerToClrFloating.First(p => p.Value == pair.Value).Key);
}
}
}
}
}
The most interesting part:
----------------------------------------------------------
-- Oracle integers mapping (Oracle Data Provider)
----------------------------------------------------------
number(1, 0) System.Int16
number(2, 0) System.Int16
number(3, 0) System.Int16
number(4, 0) System.Int16
number(5, 0) System.Int32
number(6, 0) System.Int32
number(7, 0) System.Int32
number(8, 0) System.Int32
number(9, 0) System.Int32
number(10, 0) System.Int64
number(11, 0) System.Int64
number(12, 0) System.Int64
number(13, 0) System.Int64
number(14, 0) System.Int64
number(15, 0) System.Int64
number(16, 0) System.Int64
number(17, 0) System.Int64
number(18, 0) System.Int64
number(19, 0) System.Decimal
number(20, 0) System.Decimal
number(21, 0) System.Decimal
number(22, 0) System.Decimal
number(23, 0) System.Decimal
number(24, 0) System.Decimal

Stefan,
I had the same question myself.
You may find the answer here, in the installed DevArt DotConnect for Oracle Help documentation:
ms-help://Devart.Data.Oracle/dcOracle/DataTypeMapping.html
You may want to browse online, in DevArt's website to find the same info:
http://www.devart.com/dotconnect/oracle/docs/DataTypeMapping.html
Both are under the chapter entitled, "Entity Framework Data Type Mapping".
"Oracle to .NET type mapping -
Type mapping rules from this table are used when generating a model from a database with Entity Data Model Wizard in Visual Studio 2008/2010 and Database Reverse Engineering Wizard in Entity Developer...."

Related

asp.net mvc: .net core: how to map stored proc result set to class fields

I got this simple model class:
public class PrvProduct
{
[Key]
public Int32 ProductId
{
get; set;
}
public Int64 ProductLineId;
public String MfgPartNumber;
public String ProductName;
public String ProductDescription;
}
I'm trying to call a stored proc, using .net core, it works fine, returns a list of PrvProduct objects. problem is: their fields are empty, unless I fill them up myself in code. ProductId is always there, not sure why (maybe because i typed there the [key] attribute?) but the rest are not.
is there a simple way to map class fields to results sets, like in ado.net (i would just do SQLDataAdapter.Fill(MyDataTable) and the MyDataTable fields will have the values by field name)... or do i have to do option 2 below every time?
Many thanks!
string sqlQuery = "EXEC Maint.GetProductList '" + sNameFilter + "'";
//option 1: this gets no value in the fields of each PrvProduct (ProductId gets value maybe because its [key], the others don't)
IQueryable results = _context.Products.FromSql(sqlQuery).AsNoTracking();
//option 2: this works, but... do i have to do this for every stored proc i call, every field, or is there a beter way to map class fields to returned results fields?
List<PrvProduct> oList = new List<PrvProduct>();
using (var command = _context.Database.GetDbConnection().CreateCommand())
{
command.CommandText = sqlQuery;
command.CommandType = CommandType.Text;
_context.Database.OpenConnection();
using (var result = command.ExecuteReader())
{
while (result.Read())
{
// Map to your entity
oList.Add(new PrvProduct
{
ProductId = result.GetInt32(0),
ProductName = result.GetString(1)
});
}
}
}
In EF Core, if you execute a stored procedure using one of your DbSet entities then it will map it automatically. The problem is that in many case you need to map a stored procedure to a DTO, for example, and the DTO is not part of your DbSet entities. In those cases you need to go back in time and map it manually which is a waste of time.
In order to avoid mapping the data reader manually, I added a bunch of extension methods that do it for you. The code is not perfect and I'm still improving it but it's good enough in most of the cases.
Once you add the extensions methods I'm gonna describe below, you can use it like this:
return dbContext.Database.SqlQuery<SalesReportDTO>("spGetSalesReport",
SqlParameterBuilder.Build("customerId", customerId),
SqlParameterBuilder.Build("dateFrom", from),
SqlParameterBuilder.Build("dateTo", to)).ToList();
DatabaseFacadeExtensions: adds extensions methods to DatabaseFacade class, allowing you to call the method SqlQuery from dbContext.Database just like we used to do with Entity Framework 6.
public static class DatabaseFacadeExtensions
{
public static List<T> SqlQuery<T>(this DatabaseFacade database, string query, params SqlParameter[] parameters)
{
return SqlQuery<T>(database, query, null, CommandType.StoredProcedure, parameters);
}
public static List<T> SqlQuery<T>(this DatabaseFacade database, string query, CommandType commandType, params SqlParameter[] parameters)
{
return SqlQuery<T>(database, query, null, commandType, parameters);
}
public static List<T> SqlQuery<T>(this DatabaseFacade database, string query, int? commandTimeout, params SqlParameter[] parameters)
{
return SqlQuery<T>(database, query, commandTimeout, CommandType.StoredProcedure, parameters);
}
public static List<T> SqlQuery<T>(this DatabaseFacade database, string query, int? commandTimeout, CommandType commandType, params SqlParameter[] parameters)
{
using (var cmd = database.GetDbConnection().CreateCommand())
{
cmd.CommandText = query;
cmd.CommandType = commandType;
if (commandTimeout.HasValue)
{
cmd.CommandTimeout = commandTimeout.Value;
}
cmd.Parameters.AddRange(parameters);
if (cmd.Connection.State == System.Data.ConnectionState.Closed)
{
cmd.Connection.Open();
}
try
{
using (var reader = cmd.ExecuteReader())
{
return reader.MapToList<T>();
}
}
finally
{
cmd.Connection.Close();
}
}
}
}
DbDataReaderExtensions: adds extensions methods to DbDataReader class so it can map the data reader to your own clases.
public static class DbDataReaderExtensions
{
public static List<T> MapToList<T>(this DbDataReader dr)
{
var objList = new List<T>();
if (dr.HasRows)
{
bool isSingleValue = typeof(T).IsPrimitive || typeof(T) == typeof(string);
IEnumerable<PropertyInfo> props = null;
Dictionary<string, DbColumn> colMapping = null;
if (!isSingleValue)
{
props = typeof(T).GetRuntimeProperties();
colMapping = dr.GetColumnSchema()
.Where(x => props.Any(y => y.Name.ToLower() == x.ColumnName.ToLower()))
.ToDictionary(key => key.ColumnName.ToLower());
}
while (dr.Read())
{
T obj;
if (isSingleValue)
{
obj = (T)dr.GetValue(0);
}
else
{
obj = Activator.CreateInstance<T>();
foreach (var prop in props)
{
string propertyName = prop.Name.ToLower();
if (!colMapping.ContainsKey(propertyName))
{
continue;
}
var val = dr.GetValue(colMapping[propertyName].ColumnOrdinal.Value);
if (val != DBNull.Value)
{
// enum property
if (prop.PropertyType.IsEnum)
{
prop.SetValue(obj, Enum.ToObject(prop.PropertyType, val));
}
// nullable enum property
if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) && Nullable.GetUnderlyingType(prop.PropertyType).IsEnum)
{
prop.SetValue(obj, Enum.ToObject(Nullable.GetUnderlyingType(prop.PropertyType), val));
}
else
{
prop.SetValue(obj, val);
}
}
}
}
objList.Add(obj);
}
}
return objList;
}
public static T MapToObject<T>(this DbDataReader dr)
{
var props = typeof(T).GetRuntimeProperties();
if (dr.HasRows)
{
var colMapping = dr.GetColumnSchema()
.Where(x => props.Any(y => y.Name.ToLower() == x.ColumnName.ToLower()))
.ToDictionary(key => key.ColumnName.ToLower());
if (dr.Read())
{
T obj = Activator.CreateInstance<T>();
foreach (var prop in props)
{
var val = dr.GetValue(colMapping[prop.Name.ToLower()].ColumnOrdinal.Value);
prop.SetValue(obj, val == DBNull.Value ? null : val);
}
return obj;
}
}
return default(T);
}
}
The next class is optional but I use to build parameters in a simpler way and it's needed in the example I described above:
public class SqlParameterBuilder
{
public static SqlParameter Build(string name, bool? value)
{
if (value.HasValue)
{
return new SqlParameter() { ParameterName = name, Value = value.Value };
}
return new SqlParameter() { ParameterName = name, Value = DBNull.Value };
}
public static SqlParameter Build(string name, int? value)
{
if (value.HasValue)
{
return new SqlParameter() { ParameterName = name, Value = value.Value };
}
return new SqlParameter() { ParameterName = name, Value = DBNull.Value };
}
public static SqlParameter Build(string name, string value)
{
if (value != null)
{
return new SqlParameter() { ParameterName = name, Value = value };
}
return new SqlParameter() { ParameterName = name, Value = DBNull.Value };
}
public static SqlParameter Build(string name, DateTime? value)
{
if (value != null)
{
return new SqlParameter { ParameterName = name, SqlDbType = SqlDbType.DateTime, Value = value };
}
return new SqlParameter() { ParameterName = name, Value = DBNull.Value };
}
public static SqlParameter Build(string name, Guid? value)
{
if (value.HasValue)
{
return new SqlParameter { ParameterName = name, SqlDbType = SqlDbType.UniqueIdentifier, Value = value };
}
return new SqlParameter() { ParameterName = name, Value = DBNull.Value };
}
public static SqlParameter Build(string name, int[] values)
{
SqlParameter par = new SqlParameter(name, SqlDbType.Structured);
par.TypeName = "dbo.IntParameterList";
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(int));
par.Value = dt;
if (values != null)
{
foreach (int value in values.Where(p => p != 0))
{
dt.Rows.Add(value);
}
}
return par;
}
public static SqlParameter Build(string name, string[] values, VarcharParameterListEnum varcharParameterListType = VarcharParameterListEnum.Varchar50)
{
SqlParameter par = new SqlParameter(name, SqlDbType.Structured);
switch(varcharParameterListType)
{
case VarcharParameterListEnum.Varchar15:
par.TypeName = "dbo.Varchar15ParameterList";
break;
case VarcharParameterListEnum.Varchar50:
par.TypeName = "dbo.Varchar50ParameterList";
break;
case VarcharParameterListEnum.Varchar100:
par.TypeName = "dbo.Varchar100ParameterList";
break;
case VarcharParameterListEnum.Varchar255:
par.TypeName = "dbo.Varchar255ParameterList";
break;
case VarcharParameterListEnum.Varchar510:
par.TypeName = "dbo.Varchar510ParameterList";
break;
}
DataTable dt = new DataTable();
dt.Columns.Add("textValue", typeof(string));
par.Value = dt;
if (values != null)
{
foreach (var value in values.Where(p => !string.IsNullOrWhiteSpace(p)))
{
dt.Rows.Add(value);
}
}
return par;
}
}

Getting question marks in service response in codenameone

I am calling service using ConnectionRequest class and if i'm getting result in English i'm able to display it but if i'm getting response in Hindi at that time getting as question marks(?) instead of Hindi text. and i'm using Devanagari Font to show the hindi text. is there any solution for this?
here is the code for how we are requesting?
adding parameters using Map like below.
Map<String, Object> map = new HashMap<String, Object>();
map.add("Key","Value");
map.add("Key1","Value1");
etc..
then passing this map object to requestService method.
private static Map<String, Object> requestService(Map<String, Object> data) {
Connection connection = null;
Dialog progress = new InfiniteProgress().showInifiniteBlocking();
try {
connection = new Connection(data);
NetworkManager networkManager = NetworkManager.getInstance();
networkManager.addToQueueAndWait(connection);
networkManager.setTimeout(600000);
if(connection.getResponseData() == null) {
return null;
}
} finally {
progress.dispose();
}
JSONParser jp = new JSONParser();
try {
Map<String, Object> result = jp.parseJSON(new InputStreamReader(new ByteArrayInputStream(connection.getResponseData()), "UTF-8"));
return result;
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
Connection Class:
private static class Connection extends ConnectionRequest {
private final static char escapeS[] = new char[] { '"', '\\', '/', '\b', '\f', '\n', '\r', '\t' };
private final static char escapeR[] = new char[] { '"', '\\', '/', 'b', 'f', 'n', 'r', 't' };
private Map<String, Object> data;
private Connection(Map<String, Object> data) {
this.data = data;
setFailSilently(true);
setPost(true);
setWriteRequest(true);
setContentType("application/json");
setUrl(serverUrl);
}
#Override
protected void buildRequestBody(OutputStream os) throws IOException {
String v = buildJSON(data);
if(shouldWriteUTFAsGetBytes()) {
os.write(v.getBytes("UTF-8"));
} else {
OutputStreamWriter w = new OutputStreamWriter(os, "UTF-8");
w.write(v);
}
}
private static String buildJSON(Map<String, Object> data) {
StringBuilder json = new StringBuilder();
buildJSON(data, json);
return json.toString();
}
#SuppressWarnings("unchecked")
private static void buildJSON(Map<String, Object> data, StringBuilder json) {
json.append('{');
boolean first = true;
Object value;
for(String key: data.keySet()) {
value = data.get(key);
if(value == null) {
continue;
}
if(first) {
first = false;
} else {
json.append(",");
}
json.append('"').append(key).append("\":");
if(value instanceof Map) {
buildJSON((Map<String, Object>) value, json);
} else if(value instanceof Collection) {
buildJSON((Collection<Map<String, Object>>)value, json);
} else {
if(value instanceof Long || value instanceof Integer || value instanceof Double
|| value instanceof Short || value instanceof Float) {
json.append(value);
} else if(value instanceof Boolean) {
json.append((Boolean)value ? "true" : "false");
} else {
json.append('"').append(escape(value)).append('"');
}
}
}
json.append('}');
}
private static void buildJSON(Collection<Map<String, Object>> data, StringBuilder json) {
json.append('[');
boolean first = true;
for(Map<String, Object> e: data) {
if(first) {
first = false;
} else {
json.append(",");
}
buildJSON(e, json);
}
json.append(']');
}
private static String escape(Object any) {
if(any == null) {
return "";
}
String s = any.toString();
if(s == null) {
return "";
}
for(int i = 0; i < escapeS.length; i++) {
s = replace(s, escapeS[i], escapeR[i]);
}
return s;
}
private static String replace(String s, char c, char r) {
int i = s.indexOf(c);
if(i < 0) {
return s;
}
return s.substring(0, i) + "\\" + r + replace(s.substring(i + 1), c, r);
}
}
please guide me to achieve this?
That means the result is encoded in a foreign language encoding and should be read using the correct hindi text encoding.

Using the generic type 'PagedList.StaticPagedList<T>' requires 1 type arguments

I am working on user roles using Asp.net MVC. I am stuck while working on Admin section. I have mentioned one question above and the second question is similar which is Using the generic type 'System.Collections.Generic.List' requires 1 type arguments
Here is my code.
public ActionResult Index(string searchStringUserNameOrEmail, string currentFilter, int? page)
{
try
{
int intPage = 1;
int intPageSize = 5;
int intTotalPageCount = 0;
if (searchStringUserNameOrEmail != null)
{
intPage = 1;
}
else
{
if (currentFilter != null)
{
searchStringUserNameOrEmail = currentFilter;
intPage = page ?? 1;
}
else
{
searchStringUserNameOrEmail = "";
intPage = page ?? 1;
}
}
ViewBag.CurrentFilter = searchStringUserNameOrEmail;
List col_UserDTO = new List();
int intSkip = (intPage - 1) * intPageSize;
intTotalPageCount = UserManager.Users
.Where(x => x.UserName.Contains(searchStringUserNameOrEmail))
.Count();
var result = UserManager.Users
.Where(x => x.UserName.Contains(searchStringUserNameOrEmail))
.OrderBy(x => x.UserName)
.Skip(intSkip)
.Take(intPageSize)
.ToList();
foreach (var item in result)
{
ExpandedUserDTO objUserDTO = new ExpandedUserDTO();
objUserDTO.UserName = item.UserName;
objUserDTO.Email = item.Email;
objUserDTO.LockoutEndDateUtc = item.LockoutEndDateUtc;
col_UserDTO.Add(objUserDTO);
}
// Set the number of pages
// Error appears here
var _UserDTOAsIPagedList =
new StaticPagedList
(
col_UserDTO, intPage, intPageSize, intTotalPageCount
);
return View(_UserDTOAsIPagedList);
}
catch (Exception ex)
{
ModelState.AddModelError(string.Empty, "Error: " + ex);
List col_UserDTO = new List(); // Error appears here
return View(col_UserDTO.ToPagedList(1, 25));
}
}
#endregion
`
StaticPagedList is generic. You need to supply the type of collection(for col_UserDTO), in your case List:
var _UserDTOAsIPagedList =
new StaticPagedList<List<ExpandedUserDTO>>
(
col_UserDTO, intPage, intPageSize, intTotalPageCount
);
See http://www.programering.com/a/MTN2gDNwATM.html
You may need to change List col_UserDTO references to List<ExpandedUserDTO> col_UserDTO
Use this instead
var _UserDTOAsIPagedList =
new StaticPagedList<ExpandedUserDTO>
(
col_UserDTO, intPage, intPageSize, intTotalPageCount
);

System.ArgumentException: Keyword not supported "pwd"

I am developing a unity project which requires a MySQL connection.
My connection works fine in Unity and Android builds, but when I build the whole project into iOS platform, I had an error (I have localized this through a reporter plugin)
First an exception:
System.ArgumentException: Keyword not supported. Parameter name: pwd at MySql.Data.MSqlClient.MySqlConnectionStringBuilder.ValidateKeyword (System.String keyword) [0x000000] in <filename unknown>:0
Later an error:
NullReferenceException: A null value was found where an object instance was required.
HandlerMySQL.Conectar ()
The code is the following
using System.Collections.Generic;
using System.Security.Cryptography;
using MySql.Data;
using MySql.Data.MySqlClient;
public class HandlerMySQL{
public string host, database, user, password;
public bool pooling = true;
private string connectionString;
private static MySqlConnection con = null;
private MySqlCommand cmd = null;
private MySqlDataReader rdr = null;
private MD5 _md5Hash;
public HandlerMySQL(string h,string db, string u, string pw)
{
host = h;
database = db;
user = u;
password = pw;
}
public void Conectar()
{
connectionString = "Server=" + host + ";Database=" + database + ";Uid=" + user + ";Pwd=" + password + ";Pooling=";
if (pooling)
{
connectionString += "true;";
}
else
{
connectionString += "false;";
}
try
{
con = new MySqlConnection(connectionString);
con.Open();
Debug.Log("MySQL State: " + con.State);
}
catch(Exception e)
{
Debug.Log(e);
Debug.Log("MySQL State: " + con.State);
}
}
void OnApplicationQuit()
{
if (con != null)
{
if (con.State.ToString() != "Close")
{
con.Close();
Debug.Log("MySQL Connection closed");
}
con.Dispose();
}
}
public bool GetIsConnected()
{
if (con.State.ToString() == "Open")
{
return true;
}
else
{
return false;
}
}
public bool CreateData(string dnow, string dstart,int dend)
{
DataMySql data = new DataMySql(dnow, dstart, dend);
if (DataToolsMySql.Agregar(data, con) > 0)
{
Debug.Log("Se agrego correctamente");
return true;
}
else
{
Debug.Log("ERROR!!! No se agrego");
return false;
}
}
}

ASP.NET MVC helper js function not working in Razor 4

I have the following razor helper functions in a cshtml file, it works at asp.net mvc 3, after I migrate it mvc 4, it's not working (compiling) any more.
The purpose of the major function PopulateForm is to set values of html controls according to a server model.
I figured out it's because of the syntax at line:
#(SetField(formId, fieldNamePrefix + p.Name, value));
so I changed it to:
#Js.SetField(formId, fieldNamePrefix + p.Name, value);
it compiles but if I debug it, it's not executing the body of SetField function.
#using System.Linq;
#helper Encode(object value) {
#(value != null ? HttpUtility.JavaScriptStringEncode(value.ToString()) : "")
}
#helper SetField(string formId, string fieldName, object value) {
var type = (value != null) ? value.GetType() : typeof(object);
var formattedValue = value;
if (type == typeof(DateTime)) { formattedValue = ((DateTime)value).ToString("dd-MMM-yyyy"); }
if (type == typeof(TimeSpan)) { formattedValue = ((TimeSpan)value).ToString("hh\\:mm"); }
#: $("##formId *[name='#fieldName']").changeVal("#JS.Encode(formattedValue)");
}
#helper PopulateForm(dynamic model, string formId, string[] excludedFields = null, string fieldNamePrefix = "") {
var valueProperties = model.GetType().GetProperties();
foreach (var p in valueProperties)
{
if (excludedFields != null && Array.Exists<string>(excludedFields, f => f == p.Name)) { continue; };
var value = #p.GetValue(model, null);
#(SetField(formId, fieldNamePrefix + p.Name, value));
}
}
Try writing it this way:
#using System.Linq;
#helper Encode(object value) {
#(value != null ? HttpUtility.JavaScriptStringEncode(value.ToString()) : "")
}
#helper SetField(string formId, string fieldName, object value) {
var type = (value != null) ? value.GetType() : typeof(object);
var formattedValue = value;
if (type == typeof(DateTime)) { formattedValue = ((DateTime)value).ToString("dd-MMM-yyyy"); }
if (type == typeof(TimeSpan)) { formattedValue = ((TimeSpan)value).ToString("hh\\:mm"); }
#: $("##formId *[name='#fieldName']").changeVal("#Encode(formattedValue)");
}
#helper PopulateForm(dynamic model, string formId, string[] excludedFields = null, string fieldNamePrefix = "") {
var valueProperties = model.GetType().GetProperties();
foreach (var p in valueProperties)
{
if (excludedFields != null && Array.Exists<string>(excludedFields, f => f == p.Name)) { continue; };
var value = p.GetValue(model, null);
SetField(formId, fieldNamePrefix + p.Name, value);
}
}

Resources