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.
Related
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?
I encounter an interesting issue. For some reason serde is unable to deserialize a chrono::DateTime<Utc> object from a string in the same format it was serialized (but it does if I save a variable with it):
use chrono; // 0.4.11
use serde_json; // 1.0.48
fn main() {
let date = chrono::Utc::now();
println!("{}", date);
let date_str = serde_json::to_string(&date).unwrap();
println!("{}", date_str);
let parsed_date: chrono::DateTime<chrono::Utc> = serde_json::from_str(&date_str).unwrap();
println!("{}", parsed_date);
assert_eq!(date, parsed_date);
let date = "2020-03-28T16:29:04.644008111Z";
let _: chrono::DateTime<chrono::Utc> = serde_json::from_str(&date).unwrap();
}
Here is the playground link
Which outputs:
Compiling playground v0.0.1 (/playground)
Finished dev [unoptimized + debuginfo] target(s) in 1.01s
Running `target/debug/playground`
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error("invalid type: integer `2020`, expected a formatted date and time string or a unix timestamp", line: 1, column: 4)', src/main.rs:17:44
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Standard Output
2020-03-28 17:57:04.222452521 UTC
"2020-03-28T17:57:04.222452521Z"
2020-03-28 17:57:04.222452521 UTC
Why is this happening? How should I be doing it?
You need to put valid json, don't forget double quote:
let date = "\"2020-03-28T16:29:04.644008111Z\"";
You can see it with println!("{:?}", date_str);
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)
Given this example:
let value = try (lazy raise(Exception())).Value with | _ -> false
Why is the exception not captured in the try block. Keep in mind that I raise the exception like this to prove the example. The point is that if I have a lazy code that throws and exception, it seems to be unable to capture in the try block. Do I have to be specific in my match of the exception or do I have to capture the exception inside the lazy expression itself?
The following prints both the exception and the value which is false.
let value =
try
(lazy raise(System.Exception())).Value
with
| exn -> printfn "%A" exn
false
printfn "%A" value
I'm not able to rep your results. What are you seeing?
let value =
try
(lazy raise(Exception())).Value
true
with
| ex ->
printfn "got exception";
false
Gives me
got exception
val value : bool = false
Edit:
Adding debugging image
Do I have to use client/server framework in thrift? Here's my code.
handle(Req, State) ->
{Method, Req2} = cowboy_req:method(Req),
{ok, Echo, Req3} = cowboy_req:body (Req2), %% Echo is a serialized 'hello' in smallTest by json format.
{ok, Trans} = thrift_memory_buffer:new(Echo),
{ok, Protocol} = thrift_json_protocol:new(Trans),
{_Protocol1, {ok, Struct}} = thrift_protocol:read(Protocol, smallTest_types:struct_info('hello')), %% Error here
{ok, Req4} = echo(Method, Echo, Req3),
{ok, Req4, State}.
StackTrace:
** Stacktrace: [{thrift_json_protocol,expect,
[{json_protocol,
{transport,thrift_memory_buffer,
{memory_buffer,
[<<"{\"4\":{\"str\":\"Hello World!\"}}">>]}},
[],undefined},
start_object],
[{file,
"c:/Dev/server/thrift/src/thrift_json_protocol.erl"},
{line,349}]},
{thrift_json_protocol,expect_many_1,4,
[{file,
"c:/Dev/server/thrift/src/thrift_json_protocol.erl"},
{line,371}]},
{thrift_json_protocol,expect_nodata,2,
[{file,
"c:/Dev/server/thrift/src/thrift_json_protocol.erl"},
{line,381}]},
{thrift_protocol,read_specific,2,
[{file,"c:/Dev/server/thrift/src/thrift_protocol.erl"},
{line,186}]},
{thrift_protocol,read,3,
[{file,"c:/Dev/server/thrift/src/thrift_protocol.erl"},
{line,110}]},
{toppage_handler,handle,2,
[{file,"c:/Dev/server/src/toppage_handler.erl"},
{line,19}]},
{cowboy_handler,handler_handle,4,
[{file,"c:/Dev/server/cowboy/src/cowboy_handler.erl"},
{line,119}]},
{cowboy_protocol,execute,4,
[{file,"c:/Dev/server/cowboy/src/cowboy_protocol.erl"},
{line,514}]}]
I read thrift_json_protocol.erl, and found thrift_protocol:read called through thrift_json_protocol:expect_nodata, and passed undefined tag, which should be jsx={event, ...}.It seems that only thrift_json_protocol:read(This0, message_begin) really reads data.