No mapping exists from object type X to a known managed provider native type error while executing storedProcedure with ServiceStack OrmLite? - ormlite-servicestack

This is code:
using (var con = GetWriteConnection())
{
int res = con.Exec(cmd =>
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#Title",Title));
cmd.CommandText = "AddTitle";
return int.Parse(cmd.ExecuteScalar().ToString());
});
return res;
}
there is no Title table.This is complex object. It is serialized to string(nvarchar(MAX)) by ServiceStack.OrmLite.
How can use ServiceStack's serializer?

var str=OrmLiteConfig.DialectProvider.GetQuotedValue(Title, typeof(Title));
str=str.SubString(1,str.Length-2); // (Clearing Quotes)
UPDATE Title.ToJsv() does not work. Because there is "_type" in string.

Related

Using Dapper, how do I pass in the values for a sql type as param?

I'm attempting to use dapper and pass into a stored procedure a list of integers which I have defined here using DDL
CREATE TYPE [dbo].[BrandIDSet] AS TABLE ([BrandID] INT NULL);
I've created this stored procedure:
CREATE PROCEDURE dbo.usp_getFilteredCatalogItems
#BrandIDSet [dbo].[BrandIDSet] READONLY
and attempting to pass in in c# code the value for that parameter as
public async Task<PaginatedCatalogItemsVM> GetFilteredCatalogItems(int pageSize, int pageNumber, List<int> brandIDSet)
{
..
string storedProcName = "dbo.usp_getFilteredCatalogItems";
paginatedItemsVM.CatalogItemResults = await connection.QueryAsync<CatalogItemVM>(storedProcName, new { BrandIDSet = brandIDSet }, commandType: CommandType.StoredProcedure);
However, dapper does not seem to be converting the list as expected. With the above code, it results in the following SQL getting executed
exec dbo.usp_getFilteredCatalogItems #BrandIDSet1=1
Which isn't right, since BrandIDSet1 is not the name of the parameter. Arg.
Thus, it results in
SqlException: #BrandIDSet1 is not a parameter for procedure usp_getFilteredCatalogItems.
How do I get the type to convert to the proper SQL?
You can pass DataTable for proper result. You can try the code below;
var dt = new DataTable();
dt.Columns.Add(new DataColumn("BrandID", typeof(int)));
foreach (var id in brandIDSet)
{
var row = dt.NewRow();
row["BrandId"] = id;
dt.Rows.Add(row);
}
string storedProcName = "dbo.usp_getFilteredCatalogItems";
paginatedItemsVM.CatalogItemResults = await connection.QueryAsync<CatalogItemVM>(storedProcName, new { BrandIDSet = dt }, commandType: CommandType.StoredProcedure);

Application is not working when using SQlite databse in windows phone 8

I developed my first application in windows phone 8.1.It is working fine in my local emulator and device but whenever i upload the app in store it is not working.whenever I open the app it is suddenly come back.I used the SQlite database in my application.When I am not using the Sqlite database it is working fine(I uploaded in beta).Please any one help me solve from this issue.
Thank you in advance
sqlite code:
public async void createdatabase()
{
SQLiteConnectionString c = new SQLiteConnectionString(System.IO.Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, "newDB.db"), true);
var conn = new SQLiteAsyncConnection(c.DatabasePath);
await conn.CreateTableAsync<Operators>();
}
public async void Drop()
{
SQLiteConnectionString c = new SQLiteConnectionString(System.IO.Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, "newDB.db"), true);
using (var dbConn = new SQLiteConnection(c.DatabasePath))
{
SQLiteCommand cmd = new SQLiteCommand(dbConn);
cmd.CommandText = "DROP TABLE IF EXISTS Operators";
int response = cmd.ExecuteNonQuery();
}
public async void insert()
{
rechargeOperator1.Items.Clear();
rechargeCircles1.Items.Clear();
SQLiteConnectionString c = new SQLiteConnectionString(System.IO.Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, "newDB.db"), true);
var conn = new SQLiteAsyncConnection(c.DatabasePath);
var client = new pavandatabase.JsonWebClient();
var resp1 = await client.DoRequestAsync(Url.weburl + "getRechargeCircleList");
string result1 = resp1.ReadToEnd();
JArray jsonArray = JArray.Parse(result1);
for (int j = 0; j < jsonArray.Count; j++)
{
JObject jobj = (JObject)jsonArray[j];
string id = (string)jobj["CircleID"];
string statename = (string)jobj["CircleName"];
//circles combobox......
rechargeCircles1.Items.Add(statename);
Operators op = new Operators();
op.Operatorid = int.Parse(OperatorID);
op.Operatorname = Operator;
op.servicetypeid = int.Parse(ServiceTypeID);
await conn.InsertAsync(op);
}
Try to put the break points on the first line of your application and keep on pressing f10 and see at which line it com out and post that line.
Hope it will help you to get the solution.
Thanks,

ASP.NET & SQL Server : Incorrect syntax near '?'

I am receiving an error
Incorrect syntax near ?
when trying to use a update query function. The code is from SagePay http://www.sagepay.co.uk/file/12136/download-document/DotNetkit%201.2.6.7%20-%202014-08-14.zip?token=BJFwtM7qNnnm5ZCc_l_dOhq4INB0cQTPCxCd5JOpeh4 and relates to their server InFrame implementation.
As far as I can see the order is being passed correctly, and the list of fields, match the database, just not understanding why I am seeing this error. The code was originally created for MySQL but have had to adapt to SQL Server.
I've tried debugging, but cannot actually see what is being committed to the SQL Server from cmd.ExecuteNonQuery(); any help would be much appreciated, here is the code:
private static readonly List<String> FieldNames = new List<String>
{
VendorTxCodeField, AddressResultField, AddressStatusField, AmountField, AvsCv2Field, BankAuthCodeField, BasketField,
BillingFirstnamesField, BillingSurnameField, BillingPhoneField, BillingAddress1Field, BillingAddress2Field, BillingCityField,
BillingPostCodeField, BillingStateField, BillingCountryField, DeclineCodeField, DeliveryFirstnamesField, DeliverySurnameField, DeliveryPhoneField,
DeliveryAddress1Field, DeliveryAddress2Field, DeliveryCityField, DeliveryPostCodeField, DeliveryStateField, DeliveryCountryField,
CapturedAmountField, CardTypeField, CavvField, CurrencyField, CustomerEmailField, Cv2ResultField, ExpiryDateField, FraudResponseField,
GiftAidField, Last4DigitsField, LastUpdatedField, PayerIdField, PayerStatusField, PostCodeResultField,
RelatedVendorTxCodeField, SecurityKeyField, StatusField, StatusMessageField, SurchargeField, ThreeDSecureStatusField,
TransactionTypeField, TxAuthNoField, TokenIdField, VpsTxIdField
};
public static bool UpdateOrder(Order order, string vendorTxCode)
{
var result = false;
SqlConnection conn = null;
try
{
conn = new SqlConnection(ConnectionString);
conn.Open();
var cmd = new SqlCommand
{
Connection = conn, CommandText = "UPDATE Orders SET " + string.Join(",", FieldNames.Select(field => field + "=?" + field).ToList()) + " WHERE " + VendorTxCodeField + " =?" + VendorTxCodeField
};
cmd.Prepare();
AddOrderParameters(cmd, order);
cmd.ExecuteNonQuery();
result = true;
}
catch (SqlException ex)
{
Console.WriteLine("Error: {0}", ex);
}
finally
{
if (conn != null)
{
conn.Close();
}
}
return result;
}
private static void AddOrderParameters(SqlCommand command, Order order)
{
command.Parameters.AddWithValue(VendorTxCodeField, order.VendorTxCode);
command.Parameters.AddWithValue(AddressResultField, order.AddressResult);
command.Parameters.AddWithValue(AddressStatusField, order.AddressStatus);
command.Parameters.AddWithValue(AmountField, order.Amount);
command.Parameters.AddWithValue(AvsCv2Field, order.AvsCv2);
command.Parameters.AddWithValue(BankAuthCodeField, order.BankAuthCode);
command.Parameters.AddWithValue(BasketField, order.Basket);
command.Parameters.AddWithValue(BillingAddress1Field, order.BillingAddress1);
command.Parameters.AddWithValue(BillingAddress2Field, order.BillingAddress2);
command.Parameters.AddWithValue(BillingCityField, order.BillingCity);
command.Parameters.AddWithValue(BillingCountryField, order.BillingCountry);
command.Parameters.AddWithValue(BillingFirstnamesField, order.BillingFirstnames);
command.Parameters.AddWithValue(BillingPhoneField, order.BillingPhone);
command.Parameters.AddWithValue(BillingPostCodeField, order.BillingPostCode);
command.Parameters.AddWithValue(BillingStateField, order.BillingState);
command.Parameters.AddWithValue(BillingSurnameField, order.BillingSurname);
command.Parameters.AddWithValue(CapturedAmountField, order.CapturedAmount);
command.Parameters.AddWithValue(CardTypeField, order.CardType);
command.Parameters.AddWithValue(CavvField, order.Cavv);
command.Parameters.AddWithValue(CurrencyField, order.Currency);
command.Parameters.AddWithValue(CustomerEmailField, order.CustomerEmail);
command.Parameters.AddWithValue(Cv2ResultField, order.Cv2Result);
command.Parameters.AddWithValue(DeclineCodeField, order.DeclineCode);
command.Parameters.AddWithValue(DeliveryAddress1Field, order.DeliveryAddress1);
command.Parameters.AddWithValue(DeliveryAddress2Field, order.DeliveryAddress2);
command.Parameters.AddWithValue(DeliveryCityField, order.DeliveryCity);
command.Parameters.AddWithValue(DeliveryCountryField, order.DeliveryCountry);
command.Parameters.AddWithValue(DeliveryFirstnamesField, order.DeliveryFirstnames);
command.Parameters.AddWithValue(DeliveryPhoneField, order.DeliveryPhone);
command.Parameters.AddWithValue(DeliveryPostCodeField, order.DeliveryPostCode);
command.Parameters.AddWithValue(DeliveryStateField, order.DeliveryState);
command.Parameters.AddWithValue(DeliverySurnameField, order.DeliverySurname);
command.Parameters.AddWithValue(ExpiryDateField, order.ExpiryDate);
command.Parameters.AddWithValue(FraudResponseField, order.FraudResponse);
command.Parameters.AddWithValue(GiftAidField, order.GiftAid);
command.Parameters.AddWithValue(Last4DigitsField, order.Last4Digits);
command.Parameters.AddWithValue(LastUpdatedField, order.LastUpdated);
command.Parameters.AddWithValue(PayerIdField, order.PayerId);
command.Parameters.AddWithValue(PayerStatusField, order.PayerStatus);
command.Parameters.AddWithValue(PostCodeResultField, order.PostCodeResult);
command.Parameters.AddWithValue(RelatedVendorTxCodeField, order.RelatedVendorTxCode);
command.Parameters.AddWithValue(SecurityKeyField, order.SecurityKey);
command.Parameters.AddWithValue(StatusField, order.Status);
command.Parameters.AddWithValue(StatusMessageField, order.StatusMessage);
command.Parameters.AddWithValue(SurchargeField, order.Surcharge);
command.Parameters.AddWithValue(ThreeDSecureStatusField, order.ThreeDSecureStatus);
command.Parameters.AddWithValue(TokenIdField, order.TokenId);
command.Parameters.AddWithValue(TransactionTypeField, order.TransactionType);
command.Parameters.AddWithValue(TxAuthNoField, order.TxAuthNo);
command.Parameters.AddWithValue(VpsTxIdField, order.VpsTxId);
}
You have to use # for sql-parameters. Maybe this fixes your issue although i must admit that i don't understand the query because the column-names are the same as the values. However ...
string sql = #"UPDATE Orders SET {0}
Where {1}=#{1};";
sql = string.Format(sql
, string.Join(",", FieldNames.Select(field => string.Format("{0}=#{0}", field)))
, VendorTxCodeField);
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
for (int i = 0; i < FieldNames.Count; i++)
{
cmd.Parameters.AddWithValue(FieldNames[i], FieldNames[i]);
}
// open connection and execute the command...
}

Xamarin.Forms using SQLite.Net.Async

I have followed the instructions here http://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/databases/ - to connect to the SQLite database synchronously.
public SQLiteConnection GetConnection()
{
var dbFilname = "localDB.db3";
string docsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var path = Path.Combine(docsPath, dbFilname);
var plat = new SQLitePlatformAndroid();
var conn = new SQLiteConnection(plat, path);
return conn;
}
I want to change it to an asynchronous connection (SQLiteAsyncConnection) but can't get it to work.
According to the instructions here - https://components.xamarin.com/gettingstarted/sqlite-net -it just needs the path as a parameter
var conn = new SQLiteAsyncConnection(path);
that doesn't work, the error says that the parameters expected are:
a connection function, a TaskScheduler and TaskCreationOptions
I have no idea what to do and have not been able to find any examples that work.
Thanks in advance
You could simply reuse the GetConnection method you already have and create async connection like this:
var asyncDb = new SQLiteAsyncConnection(() => GetConnection());
Xamarin Platforms Android Config, iOS and WP basicaly equal
public SQLiteAsyncConnection GetConnectionAsync()
{
const string fileName = "MyDB.db3";
var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var path = Path.Combine(documentsPath, fileName);
var platform = new SQLitePlatformAndroid();
var param = new SQLiteConnectionString(path, false);
var connection = new SQLiteAsyncConnection(() => new SQLiteConnectionWithLock(platform, param));
return connection;
}

calling oracle stored procedure from asp.net application

in my asp.net application, i am calling a stored procedure (oracle) to get some values from database.
Following is the sp:
create or replace PROCEDURE GetUserData(
--SQLWAYS_EVAL# ARCHAR(100)
UserName IN NVARCHAR2, v_refcur OUT SYS_REFCURSOR)
as
BEGIN
BEGIN --SQLWAYS_EVAL# =#Password;
open v_refcur for SELECT StaffId,
UserName,
Password,
Pin,
LastUpdateId,
LastUpdateDate,
FullName,
PinFailedAttempts,
PinFailedDate
FROM UserData
WHERE UserName = UserName;
END;
RETURN;
END;
Can anyone help me how to call this sp from my asp.net code.
Using ODP, you'll can do something like the following:
make your stored procedure a function that takes the user name in parameter and returns a refcursor
create or replace FUNCTION GetUserData(UserName IN NVARCHAR2) RETURN SYS_REFCURSOR;
and then
using (var connection = new OracleConnection(connectionString))
{
using (var command = new OracleCommand("GetUserData", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.BindByName = true;
// Return value parameter has to be added first !
var returnValueParameter = new OracleParameter();
returnValueParameter.Direction = ParameterDirection.ReturnValue;
returnValueParameter.OracleDbType = ParameterDirection.RefCursor;
command.Parameters.Add(returnValueParameter);
var userNameParameter = command.Parameters.Add("UserName", userName);
returnValueParameter.Direction = ParameterDirection.In;
using (OracleDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// Read the current record's fields
}
}
}
}
The Microsoft Enterprise Library simplifies the discovery and binding of Oracle Stored Procedures. It is not too difficult to build a Data Access Layer between your Business Objects and the Oracle database. I am more a fan of ORM tools these days like DevExpress's XPO, which in the latest release supports calling stored procedures. However, the Microsoft Entlib is free whereas DevExpress is not.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Your.BusinessObjects;
namespace DataAccess
{
public class UserDataDAL
{
public static Database dataBase = DatabaseFactory.CreateDatabase(); ///< Use default connection string configured in web.config
public static List<UserInfo> GetData(string userName)
{
List<UserInfo> listOfUserInfo = new List<UserInfo>();
UserInfo userInfo;
DbCommand cmd = dataBase.GetStoredProcCommand("SCHEMA.GETUSERDATA");
dataBase.DiscoverParameters(cmd);
dataBase.SetParameterValue(cmd, "USERNAME", userName);
using (IDataReader dr = dataBase.ExecuteReader(cmd))
{
while (dr.Read())
{
userInfo = new UserInfo();
userInfo.StaffId = dr["STAFFID"] != DBNull.Value ? Convert.ToInt32(dr["STAFFID"]) : 0;
userInfo.UserName = dr["USERNAME"] != DBNull.Value ? Convert.ToString(dr["USERNAME"]) : String.Empty;
userInfo.Password = dr["PASSWORD"] != DBNull.Value ? Convert.ToString(dr["PASSWORD"]) : String.Empty;
userInfo.LastUpdateId = Convert.ToInt32(dr["LASTUPDATEID"]);
userInfo.LastUpdateDate = dr["LASTUPDATEDATE"] != null ? Convert.ToDateTime(dr["LASTUPDATEDATE"]) : new DateTime();
listOfUserInfo.Add(userInfo);
}
}
return listOfUserInfo;
}
}
}
If you only ever expect one row to be returned from the procedure, then you can return the first item in the list if present etc.

Resources