MySql + EF 6 GroupBy cause NullReferenceException - mysql

After migration from MSSQL to the MySql I faced this issue with some queries.
Packets - .Net 4.8, EF 6.4.4, MySql.Data 8.0.22, MySql.Data.EntityFramework 8.0.22
For example, this query with GroupBy statement caused NRE:
var finalActivities = from examActivity in activitiesFilteredForReport
orderby examActivity.CreateTime descending
group examActivity by axamActivity.CreateTime into gr
select gr.FirstOrDefault();
Exception StackTrace:
System.NullReferenceException: Object reference not set to an instance of an object.
at MySql.Data.EntityFramework.CaseFragment.Accept(SqlFragmentVisitor visitor)
at MySql.Data.EntityFramework.CaseFragment.Accept(SqlFragmentVisitor visitor)
at MySql.Data.EntityFramework.BinaryFragment.Accept(SqlFragmentVisitor visitor)
at MySql.Data.EntityFramework.BinaryFragment.Accept(SqlFragmentVisitor visitor)
at MySql.Data.EntityFramework.BinaryFragment.Accept(SqlFragmentVisitor visitor)
at MySql.Data.EntityFramework.BinaryFragment.Accept(SqlFragmentVisitor visitor)
at MySql.Data.EntityFramework.BinaryFragment.Accept(SqlFragmentVisitor visitor)
at MySql.Data.EntityFramework.SelectGenerator.Visit(DbApplyExpression expression)
at MySql.Data.EntityFramework.SqlGenerator.VisitInputExpression(DbExpression e, String name, TypeUsage type)
at MySql.Data.EntityFramework.SelectGenerator.HandleJoinExpression(DbExpressionBinding left, DbExpressionBinding right, DbExpressionKind joinType, DbExpression joinCondition)
at MySql.Data.EntityFramework.SelectGenerator.Visit(DbJoinExpression expression)
at MySql.Data.EntityFramework.SqlGenerator.VisitInputExpression(DbExpression e, String name, TypeUsage type)
at MySql.Data.EntityFramework.SelectGenerator.VisitInputExpressionEnsureSelect(DbExpression e, String name, TypeUsage type)
at MySql.Data.EntityFramework.SelectGenerator.Visit(DbFilterExpression expression)
at MySql.Data.EntityFramework.SqlGenerator.VisitInputExpression(DbExpression e, String name, TypeUsage type)
at MySql.Data.EntityFramework.SelectGenerator.VisitInputExpressionEnsureSelect(DbExpression e, String name, TypeUsage type)
at MySql.Data.EntityFramework.SelectGenerator.Visit(DbProjectExpression expression)
at MySql.Data.EntityFramework.SelectGenerator.GenerateSQL(DbCommandTree tree)
at MySql.Data.MySqlClient.MySqlProviderServices.CreateDbCommandDefinition(DbProviderManifest providerManifest, DbCommandTree commandTree)
at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition..ctor(DbProviderFactory storeProviderFactory, DbCommandTree commandTree, DbInterceptionContext interceptionContext, IDbDependencyResolver resolver, BridgeDataReaderFactory bridgeDataReaderFactory, ColumnMapFactory columnMapFactory)
at System.Data.Entity.Core.EntityClient.Internal.EntityProviderServices.CreateDbCommandDefinition(DbProviderManifest providerManifest, DbCommandTree commandTree, DbInterceptionContext interceptionContext)
at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlanFactory.CreateCommandDefinition(ObjectContext context, DbQueryCommandTree tree)
at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlanFactory.Prepare(ObjectContext context, DbQueryCommandTree tree, Type elementType, MergeOption mergeOption, Boolean streaming, Span span, IEnumerable`1 compiledQueryParameters, AliasGenerator aliasGenerator)
at System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass41_0.<GetResults>b__1()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass41_0.<GetResults>b__0()
at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__31_0()
at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
at System.Linq.Lookup`2.Create[TSource](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
at System.Linq.GroupedEnumerable`3.GetEnumerator()
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
But if I write code like this:
var finalActivities = from examActivity in activitiesFilteredForReport
orderby examActivity.CreateTime descending
group examActivity by axamActivity.CreateTime into gr
select gr.FirstOrDefault().Id;
It gives me Ids without any exception.
In this case, I apply some workaround to make code work:
var ids = activitiesFilteredForReport.GroupBy(activity => activity.OrderExamId)
.Select(g => g.FirstOrDefault().Id);
var finalActivities = from examActivity in activitiesFilteredForReport
join id in ids on examActivity.Id equals id
orderby examActivity.CreateTime descending
select examActivity;
But I not sure is it a good solution. Can anyone help me to sort this issue? What I do wrong?

Related

MySQL Entity Framework: Can't create index

I'm using MySql.Data.Entity version 6.10.8 with Entity Framework.
I'm doing "Code first" to let the MySql-provider create the database structure.
Whenever the migrations contains a creation of a Index my migration fails when running the update-database command. The error message and stack trace are as follows:
System.FormatException: Input string was not in a correct format.
at System.Number.ParseDouble(String value, NumberStyles options,
NumberFormatInfo numfmt) at System.Convert.ToDouble(String value)
at
MySql.Data.Entity.MySqlMigrationSqlGenerator.Generate(CreateIndexOperation
op) at
MySql.Data.Entity.MySqlMigrationSqlGenerator.<.ctor>b__22_4(MigrationOperation> op) at
MySql.Data.Entity.MySqlMigrationSqlGenerator.Generate(IEnumerable 1
migrationOperations, String providerManifestToken) at
System.Data.Entity.Migrations.DbMigrator.GenerateStatements(IList 1
operations, String migrationId) at System.Data.Entity.Migrations.Infrastructure.MigratorBase.GenerateStatements(IList`1 operations, String migrationId) at
System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String
migrationId, VersionedModel targetModel, IEnumerable 1 operations,
IEnumerable 1 systemOperations, Boolean downgrading, Boolean auto)
at System.Data.Entity.Migrations.DbMigrator.ApplyMigration(DbMigration
migration, DbMigration lastMigration) at
System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ApplyMigration(DbMigration
migration, DbMigration lastMigration) at
System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable 1
pendingMigrations, String targetMigrationId, String lastMigrationId)
at
System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable 1
pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String
targetMigration) at
System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClasse.b__d()
at
System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action
mustSucceedToKeepDatabase) at
System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action
mustSucceedToKeepDatabase) at
System.Data.Entity.Migrations.DbMigrator.Update(String
targetMigration) at
System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String
targetMigration) at
System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore()
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
Input string was not in a correct format.
How to repeat:
Use Swedish Windows (or any other language which do not use "." as the decimal separator).
Create a migration file with an index, such as:
CreateTable(
"dbo.AspNetRoles",
c => new
{
Id = c.String(nullable: false, maxLength: 128, storeType: "nvarchar"),
Name = c.String(nullable: false, maxLength: 256, storeType: "nvarchar"),
})
.PrimaryKey(t => t.Id)
.Index(t => t.Name, unique: true, name: "RoleNameIndex"); // This line causes the exception
Run database-update
(A bug report has been sent to MySql: https://bugs.mysql.com/bug.php?id=92561)
This error is due to MySqlMigrationSqlGenerator.Generate(CreateIndexOperation op) which checks the version of the database by converting a string to double. However it does so without specifying an IFormatProvider. Since Swedish use "," as the decimal separator this conversion fails (the version number is separated by ".").
By overriding MySqlMigrationSqlGenerator.Generate(CreateIndexOperation op) this can be avoided. Use the code from this answer https://stackoverflow.com/a/51756143/1037864 (which is an answer for a different question)

QueryDSL: compare array

I am having issue with QueryDSL array comparing. The issue is comparing on byte arrays is missing in QueryDSL because ArrayPath extends SimpleExpression which only has methods like eq, ne, in, isNull...
Using Kotlin, Hibernate 5.2, QueryDSL 4.1.4, MySQL 5.7
Having Hibernate ebmeddable object IpAddress
#Embeddable
class IpAddress(
var ipAddressBinary: ByteArray
)
which in DB is mapped to type VARBINARY(4) (for IPv4 addresses, IPv6 support planned in future). I store there ip address in binary form which I need for searching in range.
I wanted to create kotlin extension function to support goe and loe functions on my embedded object
So far i came up with this:
fun ArrayPath<ByteArray, Byte>.goe(ipBytes: ByteArray): BooleanExpression {
return Expressions.booleanOperation(Ops.GOE, ConstantImpl.create(ipBytes))
}
fun QIpAddress.goe(ipAddressStr: String): BooleanExpression {
val ipBytes = MapperUtils.IPv4.normalizedToBytes(ipAddressStr)
return this.ipAddressBinary.goe(ipBytes)
}
but calling
query.where(QBlackListRecord.blackListRecord.startAddress.goe(someByteArrayRepresentingIpAddress))
results in an exception:
[exec-10]java.lang.IndexOutOfBoundsException: index (1) must be less than size (1)
at com.google.common.base.Preconditions.checkElementIndex(Preconditions.java:310)
at com.google.common.base.Preconditions.checkElementIndex(Preconditions.java:292)
at com.google.common.collect.SingletonImmutableList.get(SingletonImmutableList.java:45)
at com.querydsl.core.types.Template$ByIndex.convert(Template.java:190)
at com.querydsl.core.support.SerializerBase.visitOperation(SerializerBase.java:256)
at com.querydsl.jpa.JPQLSerializer.visitOperation(JPQLSerializer.java:426)
at com.querydsl.core.support.SerializerBase.visit(SerializerBase.java:231)
at com.querydsl.core.support.SerializerBase.visit(SerializerBase.java:31)
at com.querydsl.core.types.OperationImpl.accept(OperationImpl.java:83)
at com.querydsl.core.support.SerializerBase.handle(SerializerBase.java:92)
at com.querydsl.core.support.SerializerBase.visitOperation(SerializerBase.java:267)
at com.querydsl.jpa.JPQLSerializer.visitOperation(JPQLSerializer.java:437)
at com.querydsl.core.support.SerializerBase.visit(SerializerBase.java:231)
at com.querydsl.core.support.SerializerBase.visit(SerializerBase.java:31)
at com.querydsl.core.types.OperationImpl.accept(OperationImpl.java:83)
at com.querydsl.core.support.SerializerBase.handle(SerializerBase.java:92)
at com.querydsl.jpa.JPQLSerializer.serialize(JPQLSerializer.java:220)
at com.querydsl.jpa.JPAQueryBase.serialize(JPAQueryBase.java:60)
at com.querydsl.jpa.JPAQueryBase.serialize(JPAQueryBase.java:50)
at com.querydsl.jpa.impl.AbstractJPAQuery.createQuery(AbstractJPAQuery.java:98)
at com.querydsl.jpa.impl.AbstractJPAQuery.createQuery(AbstractJPAQuery.java:94)
at com.querydsl.jpa.impl.AbstractJPAQuery.fetch(AbstractJPAQuery.java:201)
at org.springframework.data.jpa.repository.support.QuerydslJpaRepository.findAll(QuerydslJpaRepository.java:164)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:377)
at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:200)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:629)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:593)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:578)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:135)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.data.repository.core.support.MethodInvocationValidator.invoke(MethodInvocationValidator.java:99)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy144.findAll(Unknown Source)
I am not sure whether my approach to the matter is correct. Is there any other way to compare byte arrays in QueryDSL which produces simple SQL with simple comparison operators?
All I need is to only produce SQL like this
select *
from black_list_record
where start_ip_address_binary >= #binary_value
or like this
select *
from black_list_record
where start_ip_address_binary >= inet6_aton('10.20.0.1')
The error was caused by function
fun ArrayPath<ByteArray, Byte>.goe(ipBytes: ByteArray): BooleanExpression {
return Expressions.booleanOperation(Ops.GOE, ConstantImpl.create(ipBytes))
}
which should look like this
fun ArrayPath<ByteArray, Byte>.goe(ipBytes: ByteArray): BooleanExpression {
return Expressions.booleanOperation(Ops.GOE, this, ConstantImpl.create(ipBytes))
}
I did not pass "this" argument for operation GOE which expects two arguments because its template is {0} >= {1}. That is all...
If you dont use Kotlin but Java you can use QueryDSL build-in method delegating - http://www.querydsl.com/static/querydsl/4.2.1/reference/html_single/#d0e2474

Error: itgeneor003 Object metadata could not be retrieved for 'customers1' when creating table

When trying to execute the query below with the Exact Online Adapter in the Excel 2016 for Windows on Windows 10. We get the error Object metadata could not be retrieved for 'customers'. with error code itgeneor003.
create or replace table customers#inmemorystorage
as
select act.id ctr_id
, act.code ctr_code
, act.name ctr_name
, prt.code parent_code
, prt.name parent_name
from exactonlinerest..Accounts act
left
outer
join exactonlinerest..accounts prt
on prt.id = act.parent
We got the stacktrace exception below:
Type: Invantive.Configuration.InvantiveSystemException
bij Invantive.Configuration.ValidationException..ctor(String errorCode, String errorMessage, String kindRequest, String localStackTrace, String nk, Exception innerException)
bij Invantive.Configuration.InvantiveSystemException..ctor(String validationCode, String errorMessage, String kindRequest, String stackTrace, String nk, Exception innerException)
bij Invantive.Data.ExactOnlineProvider.GetObjectMetadataForCall(EntityFieldCollection entityFields, EntityFieldCollection& correctedEntityFields)
bij Invantive.Data.ExactOnlineProvider.InsertReturnAffectedCount(EntityFieldCollection entityFields, ParameterList values, Int32& result)
bij Invantive.Data.ConnectionManager.ExecuteProviderInsertReturnAffectedCount(EntityFieldCollection entityFields, ParameterList values, String& handlingPath)
bij Invantive.Data.ConnectionManager.InsertQueryWithAffectedCount(EntityFieldCollection entityFields, ParameterList values)
bij Invantive.Sql.DdlStatementTree.OnExecute(ParameterList parameters, ExpressionParser expressionParser)
bij Invantive.Sql.QueryTree.Execute(ParameterList parameters, ExpressionParser expressionParser)
bij Invantive.Sql.QueryPlan.ForcePlan()
bij Invantive.Sql.QueryPlan.get_Fields()
bij Invantive.Data.ConnectionManager.ExecuteProviderPassthroughSqlActionTable(String actionSql, ParameterList parameters, String& handlingPath)
bij Invantive.Data.ConnectionManager.PassthroughSqlActionTable(String actionSql, ParameterList parameters)
bij Invantive.Data.ActionProceduresBase.PassthroughSqlActionTable(String actionSql, ParameterList parameters)
bij Invantive.Producer.Windows.Forms.QueryTool.ExecuteStatement(IProgressNotifier notifier, String statement, ParameterList bindVariables, Boolean showResultsInGrid, Boolean showStatistics, Boolean memorizeStatisticsInSqlHistory, Boolean allowPaging)
bij Invantive.Producer.Windows.Forms.QueryTool.FetchResultsFromSql()
bij Invantive.Producer.Windows.Forms.QueryTool.<>c__DisplayClass109_0.<FetchData>b__0()
bij System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
bij System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
bij System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
bij System.Threading.ThreadHelper.ThreadStart()
bij Invantive.Data.ExactOnlineProvider.GetObjectMetadataForCall(EntityFieldCollection entityFields, EntityFieldCollection& correctedEntityFields) in File299:regel 1791
bij Invantive.Data.ExactOnlineProvider.InsertReturnAffectedCount(EntityFieldCollection entityFields, ParameterList values, Int32& result) in File299:regel 1054
bij Invantive.Data.ConnectionManager.ExecuteProviderInsertReturnAffectedCount(EntityFieldCollection entityFields, ParameterList values, String& handlingPath) in File39:regel 3413
bij Invantive.Data.ConnectionManager.InsertQueryWithAffectedCount(EntityFieldCollection entityFields, ParameterList values) in File39:regel 1529
bij Invantive.Sql.DdlStatementTree.OnExecute(ParameterList parameters, ExpressionParser expressionParser) in File121:regel 216
bij Invantive.Sql.QueryTree.Execute(ParameterList parameters, ExpressionParser expressionParser) in File141:regel 100
bij Invantive.Sql.QueryPlan.ForcePlan() in File140:regel 77
bij Invantive.Sql.QueryPlan.get_Fields() in File140:regel 65
bij Invantive.Data.ConnectionManager.ExecuteProviderPassthroughSqlActionTable(String actionSql, ParameterList parameters, String& handlingPath) in File39:regel 4021
--- Einde van stacktracering vanaf vorige locatie waar uitzondering is opgetreden ---
bij System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
bij Invantive.Data.ConnectionManager.ExecuteProviderPassthroughSqlActionTable(String actionSql, ParameterList parameters, String& handlingPath) in File39:regel 4053
bij Invantive.Data.ConnectionManager.PassthroughSqlActionTable(String actionSql, ParameterList parameters) in File39:regel 2093
--- Einde van stacktracering vanaf vorige locatie waar uitzondering is opgetreden ---
bij System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
bij Invantive.Data.ConnectionManager.PassthroughSqlActionTable(String actionSql, ParameterList parameters) in File39:regel 2107
bij Invantive.Data.ActionProceduresBase.PassthroughSqlActionTable(String actionSql, ParameterList parameters) in File29:regel 134
bij Invantive.Producer.Windows.Forms.QueryTool.ExecuteStatement(IProgressNotifier notifier, String statement, ParameterList bindVariables, Boolean showResultsInGrid, Boolean showStatistics, Boolean memorizeStatisticsInSqlHistory, Boolean allowPaging) in File949:regel 2825
bij Invantive.Producer.Windows.Forms.QueryTool.FetchResultsFromSql() in File949:regel 2451
The error can be reproduced when the InMemoryStorage provider is not available. Although the message is confusing, it signals that an error occurred during creation of the in memory table.
Please make sure that the InMemoryStorage provider is available and licensed. Some ways to do this:
Look at the list of available objects in the Query Tool of Invantive Control, it should list the InMemoryStorage provider as shown below:
Note that the Conversion provider is probably not available on your PC; it is only for complex data conversions between platforms.
Or query the availability using:
select *
from exactonlinerest..systemproviders
The resulting list should display it:
When not available please check which product you are using. With Invantive Control it should be available always (see Help -> License -> Components), but for instance with Invantive Query Tool it is not available. Use a product that has it and ensure your license includes it too.

SSRS - IIF/Switch/Replace multiple conditions in a field

Have a nvarchar column in ms sql that, based on user input, may or may not have a carriage return and a line break together (CHR(13)&CHR(10)), just a carriage return (CHR(13)), just a line break (CHR(10)). In using that column in ssrs, I need to find if any of the above exist and replace them with the string \x0D\x0A, \x0D, or \x0A respectively.
I'm getting lost in this expression, any help is appreciated.
=SWITCH
(
(InStr(Fields!Info.Value, CHR(13)&CHR(10) > 0, REPLACE(Fields!Info.Value, CHR(13)&CHR(10)), "\x0D\x0A")),
(InStr(Fields!Info.Value, CHR(13) > 0, REPLACE(Fields!Info.Value, CHR(13)), "\x0D")),
(InStr(Fields!Info.Value, CHR(10) > 0, REPLACE(Fields!Info.Value, CHR(10)), "\x0A"))
)
Error is:
System.Web.Services.Protocols.SoapException: The Value expression for
the textrun ‘Info.Paragraphs[0].TextRuns[0]’ contains an error:
[BC30455] Argument not specified for parameter 'Replacement' of
'Public Function Replace(Expression As String, Find As String,
Replacement As String, [Start As Integer = 1], [Count As Integer =
-1], [Compare As Microsoft.VisualBasic.CompareMethod = Microsoft.VisualBasic.CompareMethod.Binary]) As String'. at
Microsoft.ReportingServices.Library.ReportingService2005Impl.SetReportDefinition(String
Report, Byte[] Definition, Guid batchId, Warning[]& Warnings) at
Microsoft.ReportingServices.Library.ReportingService2010Impl.SetItemDefinition(String
ItemPath, Byte[] Definition, String expectedItemTypeName, Property[]
Properties, Warning[]& Warnings) at
Microsoft.ReportingServices.WebServer.ReportingService2010.SetItemDefinition(String
ItemPath, Byte[] Definition, Property[] Properties, Warning[]&
Warnings)
Try this:
=SWITCH(
InStr(Fields!Info.Value, CHR(13) & CHR(10)) > 0,
REPLACE(Fields!Info.Value,CHR(13) & CHR(10), "\x0D\x0A"),
InStr(Fields!Info.Value,CHR(13)) > 0,
REPLACE(Fields!Info.Value, CHR(13), "\x0D"),
InStr(Fields!Info.Value, CHR(10)) > 0,
REPLACE(Fields!Info.Value, CHR(10), "\x0A")
)
Note if you use Switch function it will execute only the first case
that is true, so if the first condition is true the second and the
third will not be evaluated therefore not executed.
If you want to replace every char you should just use multiple REPLACE nested functions.
=Replace(
Replace(
REPLACE(Fields!Info.Value,CHR(13) & CHR(10), "\x0D\x0A"),
CHR(13),"\x0D"),
CHR(10),"\x0A")

Error does not get caught

I wrote a script that upload a xml file, look at the following code snippet:
open System.Xml
open System.IO
open System
type XmlErrorLoad =
| Success of XmlDocument
| FileNotFound of FileNotFoundException
| OtherException of Exception
let doc (filename:string) =
try
let file = XmlDocument()
file.Load(filename)
Success file
with
| :? FileNotFoundException as ex -> FileNotFound ex
| :? Exception as ex -> OtherException ex
let fileNotExists = doc("C:\Temp\ip2.xml")
match fileNotExists with
| Success s -> ()
| FileNotFound ex -> printfn "File not found: %s" ex.Message
| OtherException ex -> printfn "Exception: %s" ex.Message
In this case, ip2.xml file does not exist and it should throw an error FileNotFound and print on the screen.
"File not found: %s" ex.Message
But I've got the message
val fileNotExists : XmlErrorLoad =
FileNotFound
System.IO.FileNotFoundException: Could not find file 'C:\Temp\ip2.xml'.
File name: 'C:\Temp\ip2.xml'
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize)
at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials, IWebProxy proxy, RequestCachePolicy cachePolicy)
at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
at System.Xml.XmlTextReaderImpl.OpenUrlDelegate(Object xmlResolver)
at System.Threading.CompressedStack.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.CompressedStack.Run(CompressedStack compressedStack, ContextCallback callback, Object state)
at System.Xml.XmlTextReaderImpl.OpenUrl()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
at System.Xml.XmlDocument.Load(XmlReader reader)
at System.Xml.XmlDocument.Load(String filename)
at FSI_0004.doc(String filename) in D:\f#\samples\ip.fsx:line 20
I've tried your code as input on F# Interactive and got the desired message
File not found: Could not find file 'C:\Temp\ip2.xml'.
Besides the output F# Interactive lists all the values defined in the code, so I also got following printed:
type XmlErrorLoad =
| Success of XmlDocument
| FileNotFound of FileNotFoundException
| OtherException of Exception
val doc : filename:string -> XmlErrorLoad
val fileNotExists : XmlErrorLoad =
FileNotFound
System.IO.FileNotFoundException: Could not find file 'C:\Temp\ip2.xml'.
File name: 'C:\Temp\ip2.xml'
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize)
at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials, IWebProxy proxy, RequestCachePolicy cachePolicy)
at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
at System.Xml.XmlTextReaderImpl.OpenUrlDelegate(Object xmlResolver)
at System.Threading.CompressedStack.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.CompressedStack.Run(CompressedStack compressedStack, ContextCallback callback, Object state)
at System.Xml.XmlTextReaderImpl.OpenUrl()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
at System.Xml.XmlDocument.Load(XmlReader reader)
at System.Xml.XmlDocument.Load(String filename)
at FSI_0003.doc(String filename)
val it : unit = ()
You get this output only in F# Interactive as part of REPL feedback. In a normal program this output wouldn't be produced.