create adatabase through CreateDatabaseDocument() function - database

I want to create a database in ravendb , I used EnsureDatabaseExist() function. I am not able to use the function CreateDatabaseDocument() from namespace Raven.Client.Extensions and class is public static class MultiDatabase{} in my c# code. Intellisense in vs2010 not showing this function.
my code is :enter code here
public CreateDatabaseOpResult CreateDatabase(ConnectionOperationResult connection,string name)
{
DocumentDatabase database;
CreateDatabaseOpResult databaseOperationResult = new CreateDatabaseOpResult();
if (connection.IsOperationSuccessfull == true)
{
try
{
var doc = connection.documentStore.DatabaseCommands.ForDefaultDatabase();
var docId = doc.Get("Raven/Databases/" + name);
if (docId == null)
{
//static class
//multidatabase
connection.documentStore.DatabaseCommands.EnsureDatabaseExists(name);
}
else
{
databaseOperationResult.IsOperationSuccessfull = false;
throw new ArgumentException("Database already exists");
}
databaseOperationResult.IsOperationSuccessfull = true;
databaseOperationResult.database = database;
}
//and i want to use this function from
namespace Raven.Client.Extensions
{
///<summary>
/// Methods to create mutli tenants databases
///</summary>
public static class MultiDatabase
{
public static RavenJObject CreateDatabaseDocument(string name)
{
AssertValidName(name);
var doc = RavenJObject.FromObject(new DatabaseDocument
{
Settings =
{
{"Raven/DataDir", Path.Combine("~", Path.Combine("Tenants", name))}
}
});
doc.Remove("Id");
return doc;
}
thanks in advance...:)

CreateDatabase is an internal method which just returned the database document. EnsureDatabaseExist used this method and also stores that document if it doesn't exists.
You should use EnsureDatabaseExist method.

Related

Entity Framework 6 Disable Interception temporarily

I am using an IDbCommandTreeInterceptor to enable soft deletes on my model.
System.Data.Entity.Infrastructure.Interception.DbInterception.Add(
new SoftDeleteInterception());
I want to be able to disable the interceptor temporarily so that I can select a "deleted" entity for auditing purposes.
However, It seems like the DbInterception collection is assembly-wide.
Is there any way to create a new DbContext without interception on?
Or even a way to add the interceptor to the DbContext every time it is created?
I have extended my db context class with additional property
[DbConfigurationType(typeof(DbConfig))]
public partial class YourEntitiesDB
{
public bool IgnoreSoftDelete { get; set; }
}
Then in the TreeCreated(...) method i check this flag and if true then it just doesn't go further to the QueryVisitor
public class SoftDeleteInterceptor : IDbCommandTreeInterceptor
{
public SoftDeleteInterceptor()
{
}
public void TreeCreated(DbCommandTreeInterceptionContext interceptionContext)
{
var db = interceptionContext.DbContexts.FirstOrDefault() as YourEntitiesDB;
if (db!=null && db.IgnoreSoftDelete)
{
// Ignore soft delete interseptor (Used in archives)
return;
}
if (interceptionContext.OriginalResult.DataSpace == DataSpace.CSpace)
{
var queryCommand = interceptionContext.Result as DbQueryCommandTree;
if (queryCommand != null)
{
var newQuery = queryCommand.Query.Accept(new SoftDeleteQueryVisitor());
interceptionContext.Result = new DbQueryCommandTree(
queryCommand.MetadataWorkspace,
queryCommand.DataSpace,
newQuery);
}
var deleteCommand = interceptionContext.OriginalResult as DbDeleteCommandTree;
if (deleteCommand != null)
{
var column = SoftDeleteAttribute.GetSoftDeleteColumnName(deleteCommand.Target.VariableType.EdmType);
if (column != null)
{
var setClauses = new List<DbModificationClause>();
var table = (EntityType)deleteCommand.Target.VariableType.EdmType;
if (table.Properties.Any(p => p.Name == column))
{
setClauses.Add(DbExpressionBuilder.SetClause(
DbExpressionBuilder.Property(
DbExpressionBuilder.Variable(deleteCommand.Target.VariableType, deleteCommand.Target.VariableName),
column),
DbExpression.FromBoolean(true)));
}
var update = new DbUpdateCommandTree(
deleteCommand.MetadataWorkspace,
deleteCommand.DataSpace,
deleteCommand.Target,
deleteCommand.Predicate,
setClauses.AsReadOnly(),
null);
interceptionContext.Result = update;
}
}
}
}
}
In order to use it i just set the flag to true when needed
YuorEntitiesDB DB = new YuorEntitiesDB();
DB.IgnoreSoftDelete = true;
DB.Records.Where(...)

How to change the schema at runtime in Dapper-Extensions?

I am using Dapper Extensions but I have multiple schema names in My DB.
I found the an answer in below link but it assumes that I have only one schema name and this is not my case.
Dapper Extensions Change Schema
What is the right way to change the schema name at the runtime?
Probably you won't use it anymore, but maybe there are more guys up there trying to figure it out.
I've been checking out how dapper works when running GetAll<> and Insert<>.
What it does:
var type = typeof(T);
var cacheType = typeof(List<T>);
if (!GetQueries.TryGetValue(cacheType.TypeHandle, out string sql))
{
GetSingleKey<T>(nameof(GetAll));
var name = GetTableName(type); <--- key thing
sql = "select * from " + name;
GetQueries[cacheType.TypeHandle] = sql;
}
So I've checked what GetTableName was doing:
private static string GetTableName(Type type)
{
if (TypeTableName.TryGetValue(type.TypeHandle, out string name)) return name;
if (TableNameMapper != null)
{
name = TableNameMapper(type); <-- key thing
}
else
{
//NOTE: This as dynamic trick should be able to handle both our own Table-attribute as well as the one in EntityFramework
var tableAttr = type
#if NETSTANDARD1_3
.GetTypeInfo()
#endif
.GetCustomAttributes(false).SingleOrDefault(attr => attr.GetType().Name == "TableAttribute") as dynamic;
if (tableAttr != null)
{
name = tableAttr.Name;
}
else
{
name = type.Name + "s";
if (type.IsInterface() && name.StartsWith("I"))
name = name.Substring(1);
}
}
TypeTableName[type.TypeHandle] = name;
return name;
}
Solution:
So I thought I can implement my own table name mapper with code like this:
SqlMapperExtensions.TableNameMapper = DapperMapper.TableNameMapper();
And
public static SqlMapperExtensions.TableNameMapperDelegate TableNameMapper()
{
return (type) =>
{
var has = Attribute.GetCustomAttribute(type, typeof(CastleTableAttribute));
if (has != null)
{
return $"{ConfigurationProvider.Schema}.{type.Name}";
}
else
{
return type.Name;
}
};
}
With that name mapper you just need to mark your table with that.
[CastleTable]
class CubeTimestamps
{
[ExplicitKey]
public int cube_id { get; set; }
public DateTime cube_timestamp { get; set; }
}
you can implement your name mapper to use [TableName] attribute also. Because my simple implementation hides this feature.
Enjoy :)

It it possible to use existing SQLite database in windows phone?

I am newbie to windows phone development. I have a requirement to develop a app which was developed in Android and iOS. I need to use the same SQLite database which was used in Android and iOS. Is it possible to use existing SQLite database in windows phone? If it is yes how to do it ?
for basic setup of sqlite use this link
first add the database file to project and change its properties to COPYALWAYS and "CONTENT" and now copy it to you local folder and make connection to the database using sqlite like this.
public static SQLiteAsyncConnection connection;
public static bool isDatabaseExisting;
public static async void ConnectToDB()
{
try
{
StorageFile storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync("DatabaseFinal.db");
isDatabaseExisting = true;
}
catch
{
isDatabaseExisting = false;
}
if (!isDatabaseExisting)
{
try
{
StorageFile databaseFile = await Package.Current.InstalledLocation.GetFileAsync("DatabaseFinal.db");
await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder);
isDatabaseExisting = true;
}
catch
{
isDatabaseExisting = false;
}
}
if(isDatabaseExisting)
connection = new SQLiteAsyncConnection(Path.Combine(ApplicationData.Current.LocalFolder.Path, "DelhiMetroDatabaseFinal.db"), true);
}
}
}
this will create your connection too and for using databse for getting data from your db file use can use query like this
public List<dataclass> getdata(string line_id, ref Boolean isdata)
{
List<datadataclass> query = new List<datadataclass>();
try
{
query = dal.connection.Table<dataclass>().Where(i => i._id == line_id).ToListAsync().Result;
isdataclass = true;
return query;
}
catch (NullReferenceException e)
{
isdataclass = false;
}
return query;
}
data class will have properties as your column defined in you database.
class dataclass
{
public string _id { get; set; }
public string name { get; set; }
public int location { get; set; }
}

Easy way to dynamically invoke web services (without JDK or proxy classes)

In Python I can consume a web service so easily:
from suds.client import Client
client = Client('http://www.example.org/MyService/wsdl/myservice.wsdl') #create client
result = client.service.myWSMethod("Bubi", 15) #invoke method
print result #print the result returned by the WS method
I'd like to reach such a simple usage with Java.
With Axis or CXF you have to create a web service client, i.e. a package which reproduces all web service methods so that we can invoke them as if they where normal methods. Let's call it proxy classes; usually they are generated by wsdl2java tool.
Useful and user-friendly. But any time I add/modify a web service method and I want to use it in a client program I need to regenerate proxy classes.
So I found CXF DynamicClientFactory, this technique avoids the use of proxy classes:
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.endpoint.dynamic.DynamicClientFactory;
//...
//create client
DynamicClientFactory dcf = DynamicClientFactory.newInstance();
Client client = dcf.createClient("http://www.example.org/MyService/wsdl/myservice.wsdl");
//invoke method
Object[] res = client.invoke("myWSMethod", "Bubi");
//print the result
System.out.println("Response:\n" + res[0]);
But unfortunately it creates and compiles proxy classes runtime, hence requires JDK on the production machine. I have to avoid this, or at least I can't rely on it.
My question:
Is there another way to dinamically invoke any method of a web service in Java, without having a JDK at runtime and without generating "static" proxy classes? Maybe with a different library? Thanks!
I know this is a really old question but if you are still interested you could use soap-ws github project: https://github.com/reficio/soap-ws
Here you have a sample usage really simple:
Wsdl wsdl = Wsdl.parse("http://www.webservicex.net/CurrencyConvertor.asmx?WSDL");
SoapBuilder builder = wsdl.binding()
.localPart("CurrencyConvertorSoap")
.find();
SoapOperation operation = builder.operation()
.soapAction("http://www.webserviceX.NET/ConversionRate")
.find();
Request request = builder.buildInputMessage(operation)
SoapClient client = SoapClient.builder()
.endpointUrl("http://www.webservicex.net/CurrencyConvertor.asmx")
.build();
String response = client.post(request);
As you can see it is really simple.
With CXF 3.x this could be possible with StaxDataBinding. Follow below steps to get the basics. Of course, this could be enhanced to your needs.
Create StaxDataBinding something like below. Note below code can be enhanced to your sophistication.
class StaxDataBinding extends AbstractInterceptorProvidingDataBinding {
private XMLStreamDataReader xsrReader;
private XMLStreamDataWriter xswWriter;
public StaxDataBinding() {
super();
this.xsrReader = new XMLStreamDataReader();
this.xswWriter = new XMLStreamDataWriter();
inInterceptors.add(new StaxInEndingInterceptor(Phase.POST_INVOKE));
inFaultInterceptors.add(new StaxInEndingInterceptor(Phase.POST_INVOKE));
inInterceptors.add(RemoveStaxInEndingInterceptor.INSTANCE);
inFaultInterceptors.add(RemoveStaxInEndingInterceptor.INSTANCE);
}
static class RemoveStaxInEndingInterceptor
extends AbstractPhaseInterceptor<Message> {
static final RemoveStaxInEndingInterceptor INSTANCE = new RemoveStaxInEndingInterceptor();
public RemoveStaxInEndingInterceptor() {
super(Phase.PRE_INVOKE);
addBefore(StaxInEndingInterceptor.class.getName());
}
public void handleMessage(Message message) throws Fault {
message.getInterceptorChain().remove(StaxInEndingInterceptor.INSTANCE);
}
}
public void initialize(Service service) {
for (ServiceInfo serviceInfo : service.getServiceInfos()) {
SchemaCollection schemaCollection = serviceInfo.getXmlSchemaCollection();
if (schemaCollection.getXmlSchemas().length > 1) {
// Schemas are already populated.
continue;
}
new ServiceModelVisitor(serviceInfo) {
public void begin(MessagePartInfo part) {
if (part.getTypeQName() != null
|| part.getElementQName() != null) {
return;
}
part.setTypeQName(Constants.XSD_ANYTYPE);
}
}.walk();
}
}
#SuppressWarnings("unchecked")
public <T> DataReader<T> createReader(Class<T> cls) {
if (cls == XMLStreamReader.class) {
return (DataReader<T>) xsrReader;
}
else {
throw new UnsupportedOperationException(
"The type " + cls.getName() + " is not supported.");
}
}
public Class<?>[] getSupportedReaderFormats() {
return new Class[] { XMLStreamReader.class };
}
#SuppressWarnings("unchecked")
public <T> DataWriter<T> createWriter(Class<T> cls) {
if (cls == XMLStreamWriter.class) {
return (DataWriter<T>) xswWriter;
}
else {
throw new UnsupportedOperationException(
"The type " + cls.getName() + " is not supported.");
}
}
public Class<?>[] getSupportedWriterFormats() {
return new Class[] { XMLStreamWriter.class, Node.class };
}
public static class XMLStreamDataReader implements DataReader<XMLStreamReader> {
public Object read(MessagePartInfo part, XMLStreamReader input) {
return read(null, input, part.getTypeClass());
}
public Object read(QName name, XMLStreamReader input, Class<?> type) {
return input;
}
public Object read(XMLStreamReader reader) {
return reader;
}
public void setSchema(Schema s) {
}
public void setAttachments(Collection<Attachment> attachments) {
}
public void setProperty(String prop, Object value) {
}
}
public static class XMLStreamDataWriter implements DataWriter<XMLStreamWriter> {
private static final Logger LOG = LogUtils
.getL7dLogger(XMLStreamDataWriter.class);
public void write(Object obj, MessagePartInfo part, XMLStreamWriter writer) {
try {
if (!doWrite(obj, writer)) {
// WRITE YOUR LOGIC HOW you WANT TO HANDLE THE INPUT DATA
//BELOW CODE JUST CALLS toString() METHOD
if (part.isElement()) {
QName element = part.getElementQName();
writer.writeStartElement(element.getNamespaceURI(),
element.getLocalPart());
if (obj != null) {
writer.writeCharacters(obj.toString());
}
writer.writeEndElement();
}
}
}
catch (XMLStreamException e) {
throw new Fault("COULD_NOT_READ_XML_STREAM", LOG, e);
}
}
public void write(Object obj, XMLStreamWriter writer) {
try {
if (!doWrite(obj, writer)) {
throw new UnsupportedOperationException("Data types of "
+ obj.getClass() + " are not supported.");
}
}
catch (XMLStreamException e) {
throw new Fault("COULD_NOT_READ_XML_STREAM", LOG, e);
}
}
private boolean doWrite(Object obj, XMLStreamWriter writer)
throws XMLStreamException {
if (obj instanceof XMLStreamReader) {
XMLStreamReader xmlStreamReader = (XMLStreamReader) obj;
StaxUtils.copy(xmlStreamReader, writer);
xmlStreamReader.close();
return true;
}
else if (obj instanceof XMLStreamWriterCallback) {
((XMLStreamWriterCallback) obj).write(writer);
return true;
}
return false;
}
public void setSchema(Schema s) {
}
public void setAttachments(Collection<Attachment> attachments) {
}
public void setProperty(String key, Object value) {
}
}
}
Prepare your input to match the expected input, something like below
private Object[] prepareInput(BindingOperationInfo operInfo, String[] paramNames,
String[] paramValues) {
List<Object> inputs = new ArrayList<Object>();
List<MessagePartInfo> parts = operInfo.getInput().getMessageParts();
if (parts != null && parts.size() > 0) {
for (MessagePartInfo partInfo : parts) {
QName element = partInfo.getElementQName();
String localPart = element.getLocalPart();
// whatever your input data you need to match data value for given element
// below code assumes names are paramNames variable and value in paramValues
for (int i = 0; i < paramNames.length; i++) {
if (paramNames[i].equals(localPart)) {
inputs.add(findParamValue(paramNames, paramValues, localPart));
}
}
}
}
return inputs.toArray();
}
Now set the proper data binding and pass the data
Bus bus = CXFBusFactory.getThreadDefaultBus();
WSDLServiceFactory sf = new WSDLServiceFactory(bus, wsdl);
sf.setAllowElementRefs(false);
Service svc = sf.create();
Client client = new ClientImpl(bus, svc, null,
SimpleEndpointImplFactory.getSingleton());
StaxDataBinding databinding = new StaxDataBinding();
svc.setDataBinding(databinding);
bus.getFeatures().add(new StaxDataBindingFeature());
BindingOperationInfo operInfo = ...//find the operation you need (see below)
Object[] inputs = prepareInput(operInfo, paramNames, paramValues);
client.invoke("operationname", inputs);
If needed you can match operation name something like below
private BindingOperationInfo findBindingOperation(Service service,
String operationName) {
for (ServiceInfo serviceInfo : service.getServiceInfos()) {
Collection<BindingInfo> bindingInfos = serviceInfo.getBindings();
for (BindingInfo bindingInfo : bindingInfos) {
Collection<BindingOperationInfo> operInfos = bindingInfo.getOperations();
for (BindingOperationInfo operInfo : operInfos) {
if (operInfo.getName().getLocalPart().equals(operationName)) {
if (operInfo.isUnwrappedCapable()) {
return operInfo.getUnwrappedOperation();
}
return operInfo;
}
}
}
}
return null;
}

Can't find InsertOnSubmit() method

I'm new to Entity Framework, and I'm think there is something that I misunderstand here.
I'm trying to insert a row in a table, and everywhere I found code example, they call the method InsertOnSubmit(), but the problem is that I can't find anywhere the method InsertOnSubmit, or SubmitChanges.
The error tell me:
System.Data.Object.ObjectSet do not contain the definition for InsertOnSubmit, ...
What I'm doing wrong??
http://msdn.microsoft.com/en-us/library/bb763516.aspx
GMR_DEVEntities CTX;
CTX = new GMR_DEVEntities();
tblConfig Config = new tblConfig { ID = Guid.NewGuid(), Code = "new config code" };
CTX.tblConfigs.InsertOnSubmit(Config); // Error here
Edit:
Using Visual Studio 2010 on FW 4.0
InsertOnSubmit is a Linq-to-SQL method and not in the Entity Framework.
However, since our project was a conversion from Linq-to-SQL we have some extension methods that might help:
public static class ObjectContextExtensions
{
public static void SubmitChanges(this ObjectContext context)
{
context.SaveChanges();
}
public static void InsertOnSubmit<T>(this ObjectQuery<T> table, T entity)
{
table.Context.AddObject(GetEntitySetName(table.Context, entity.GetType()), entity);
}
public static void InsertAllOnSubmit<T>(this ObjectQuery<T> table, IEnumerable<T> entities)
{
var entitySetName = GetEntitySetName(table.Context, typeof(T));
foreach (var entity in entities)
{
table.Context.AddObject(entitySetName, entity);
}
}
public static void DeleteAllOnSubmit<T>(this ObjectQuery<T> table, IEnumerable<T> entities) where T : EntityObject, new()
{
var entitiesList = entities.ToList();
foreach (var entity in entitiesList)
{
if (null == entity.EntityKey)
{
SetEntityKey(table.Context, entity);
}
var toDelete = (T)table.Context.GetObjectByKey(entity.EntityKey);
if (null != toDelete)
{
table.Context.DeleteObject(toDelete);
}
}
}
public static void SetEntityKey<TEntity>(this ObjectContext context, TEntity entity) where TEntity : EntityObject, new()
{
entity.EntityKey = context.CreateEntityKey(GetEntitySetName(context, entity.GetType()), entity);
}
public static string GetEntitySetName(this ObjectContext context, Type entityType)
{
return EntityHelper.GetEntitySetName(entityType, context);
}
}
Where EntityHelper is as per the MyExtensions open source library.
Hello this works for me
Entity db = new Entity();
TABLE_NAME table = new TABLE_NAME
{
COLUMN1 = "TEST",
cOLUMN2 = "test"
//etc...
};
db.TABLE_NAME.Add(table);
db.SaveChanges();
Finally found what was wrong, my Entity database was a dbmx file and not a dbml file. I do not understand why this .. but has long as it work. (Need to buy a new book I guess) – Hugo Feb 17 at 19:40
i also have the same problem .we can insert by using Add
GMR_DEVEntities CTX;
CTX = new GMR_DEVEntities();
tblConfig Config = new tblConfig { ID = Guid.NewGuid(), Code = "new config code" };
CTX.tblConfigs.Add(Config);

Resources