Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Cold on a Cob
Feb 6, 2006

i've seen so much, i'm going blind
and i'm brain dead virtually

College Slice

EssOEss posted:

My experience with Entity Framework is that it tends to get in trouble very fast once you start using fancy words like group by and join. I immediately ran into client-side evaluation or EF just giving up with some internal query builder exception when I last tried to use it for nontrivial cases. I only have positive experience using it as a simple row serializer/deserializer and suggest you expect no more from it.

Thus I do not know if EF can actually turn this into nice SQL but my first try at this would be something like:

code:
record Row(int Id, string Message);

class Program
{
    static void Main(string[] args)
    {
        var data = new Row[]
        {
            new(1, "apple"),
            new(2, "apple"),
            new(3, "apple"),
            new(4, "apple"),
            new(5, "banana"),
            new(6, "banana"),
            new(7, "dusty"),
            new(8, "elephant"),
            new(9, "elephant"),
            new(10, "hello"),
        };

        var groupedByMessage = data.GroupBy(row => row.Message);

        var messageAndMaxId = groupedByMessage.Select(group => new
        {
            Message = group.Key,
            MaxId = group.Max(row => row.Id)
        });

        var fiveMostRecentMessages = messageAndMaxId
            .OrderByDescending(x => x.MaxId)
            .Select(x => x.Message)
            .Take(5);

        Console.WriteLine(string.Join(", ", fiveMostRecentMessages));
    }
}

If EF can't translate that to nice SQL (which is very likely), the SQL is easy enough to write and can be parameterized:
code:
declare @table as table (id int, val nvarchar(max))

insert into @table (id, val) values (1	, 'apple'	 );
insert into @table (id, val) values (2	, 'apple'	 );
insert into @table (id, val) values (3	, 'apple'	 );
insert into @table (id, val) values (4	, 'apple'	 );
insert into @table (id, val) values (5	, 'banana'	 );
insert into @table (id, val) values (6	, 'banana'	 );
insert into @table (id, val) values (7	, 'dusty'	 );
insert into @table (id, val) values (8	, 'elephant' );
insert into @table (id, val) values (9	, 'dusty'	 );
insert into @table (id, val) values (10	, 'hello'	 );

declare @n int = 5;

select top (@n) max(id) id, val from @table group by val order by max(id) desc
An alternative, if it absolutely has to be in EF, is to just sort and grab chunks while filling a dictionary until you get your TOP N. I'd only consider this if the number of records you need to take is relatively low though.

Cold on a Cob fucked around with this message at 18:19 on Jun 21, 2021

Adbot
ADBOT LOVES YOU

Supersonic
Mar 28, 2008

You have used 43 of 300 characters allowed.
Tortured By Flan
I'm looking to upload a file to Amazon S3 in multiple parts using C# and either WebClient or HttpClient. The upload process is a 4-step operation:

1. Initiate a multipart upload
2. Create pre-signed URLs for each part
3. Upload the object’s parts
4. Complete multipart upload

I've written methods for step 1, 2, and 4, but I'm not clear as to how to actually upload a file in parts. The parts need to be 5mb in size (or less for the final part), and I've created a method which calculates how many parts the chosen file should be split into.

Here is a working example of uploading a file in a single part with a presigned URL:

C# code:
public void UploadSingleFilePresignedUrl(string filePath, string fileName)
{
    string preSignedUrl = _server.GeneratePreSignedURL(fileName);

    HttpWebRequest httpRequest = WebRequest.Create(preSignedUrl) as HttpWebRequest;
    httpRequest.Method = "PUT";
    using (Stream dataStream = httpRequest.GetRequestStream())
    {
        byte[] buffer = new byte[8000];
        using FileStream fileStream = new(filePath, FileMode.Open, FileAccess.Read);
        int bytesRead = 0;
        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            dataStream.Write(buffer, 0, bytesRead);
        }
    }
        HttpWebResponse response = httpRequest.GetResponse() as HttpWebResponse;
}
In step 2, I've created a list of presigned URLs for each part. I plan to iterate over the list and pass the presigned URL and part number to the method for each part. Do I make a stream and send segments to a method that uploads it?

In addition, whenever you upload a part, Amazon S3 returns an ETag header in its response. For each part upload, I need to record the part number and the ETag value.

raminasi
Jan 25, 2005

a last drink with no ice

Supersonic posted:

I'm looking to upload a file to Amazon S3 in multiple parts using C# and either WebClient or HttpClient. The upload process is a 4-step operation:

1. Initiate a multipart upload
2. Create pre-signed URLs for each part
3. Upload the object’s parts
4. Complete multipart upload

Is there a reason you're not just using the utility class AWS provides for this?

Mr Shiny Pants
Nov 12, 2012

epswing posted:

I believe Distinct for both Linq to Entities and Linq to Objects will not maintain ordering.

For objects it should work: https://stackoverflow.com/questions/4734852/does-distinct-method-keep-original-ordering-of-sequence-intact

It isn't documented it seems.

mistermojo
Jul 3, 2004

New Yorp New Yorp posted:

Although I'm not a huge fan of "throw another nuget package at it!" and I'm not sure if it works with IQueryable vs IEnumerable, MoreLINQ has a DistinctBy extension method that probably fits the bill here.

Personally I'd just do the groupby.

yeah groupby should be what you want

code:
var tupleList = new List<(int id, string message)>
  {
    (1, "apple"),
    (2, "apple"),
    (3, "apple"),
    (4, "apple"),
    (5, "banana"),
    (6, "banana"),
    (7, "dusty"),
    (8, "elephant"),
    (9, "elephant"),
    (10, "hello")
 };

var last5distinct = tupleList.OrderByDescending(x => x.id).GroupBy(p => p.message).Select(y => y.First().message).Take(5);

Console.WriteLine(string.Join(Environment.NewLine, last5distinct));
gets

hello
elephant
dusty
banana
apple


.NET 6 finally adds DistinctBy so we won't even need to use another package soon!

e: if you know its always ordered by id you could simplify it with something like

code:
var last5distinct = tupleList.GroupBy(p => p.message).Select(y => y.First().message).Reverse().Take(5);

mistermojo fucked around with this message at 20:47 on Jun 21, 2021

ThePeavstenator
Dec 18, 2012

:burger::burger::burger::burger::burger:

Establish the Buns

:burger::burger::burger::burger::burger:

mistermojo posted:

yeah groupby should be what you want

code:
var tupleList = new List<(int id, string message)>
  {
    (1, "apple"),
    (2, "apple"),
    (3, "apple"),
    (4, "apple"),
    (5, "banana"),
    (6, "banana"),
    (7, "dusty"),
    (8, "elephant"),
    (9, "elephant"),
    (10, "hello")
 };

var last5distinct = tupleList.OrderByDescending(x => x.id).GroupBy(p => p.message).Select(y => y.First().message).Take(5);

Console.WriteLine(string.Join(Environment.NewLine, last5distinct));
gets

hello
elephant
dusty
banana
apple


.NET 6 finally adds DistinctBy so we won't even need to use another package soon!

e: if you know its always ordered by id you could simplify it with something like

code:
var last5distinct = tupleList.GroupBy(p => p.message).Select(y => y.First().message).Reverse().Take(5);

IEnumerable and IQueryable are different things with different behaviors even though it looks like you’re just writing the same Linq syntax. This is one of the reasons I hate EF. Linq is very powerful but also has some footguns that devs run into when they don’t understand the difference between when a Linq query is describing functions performed on a sequence (IEnumerable) and when a Linq query is actually building an expression tree (IQueryable) that can be evaluated and executed on a sequence or any arbitrary data source that has a way to translate the expression tree into instructions it understands. EF just papers over this and says “Look at all the poo poo Linq can do! No need to worry about all that complicated poo poo like knowing what your databases are actually capable of or how you should structure your data for your chosen DB(s). Oop your app is eating up all your memory and/or CPU and/or what look like simple queries are taking way longer than expected to evaluate? You should have read the docs and known how all this poo poo works under the hood before deploying it!”

The paradox of EF is that it demands you understand the various intricacies of Linq and how the data providers work internally in order to avoid firing one of the many footguns it hands to you, but once you understand what EF is doing for you and how it works internally, your best choice is usually “don’t use EF and write the queries/HTTP calls/etc myself”.

ThePeavstenator fucked around with this message at 21:12 on Jun 21, 2021

Supersonic
Mar 28, 2008

You have used 43 of 300 characters allowed.
Tortured By Flan

raminasi posted:

Is there a reason you're not just using the utility class AWS provides for this?

The software has a client and server component, and we don't want to put the AWS keys on the client (like the class requires). With a pre-signed URL supplied by the server, the client can initiate an upload without needing to have access to the AWS secret keys and gives us more flexibility for our needs.

distortion park
Apr 25, 2011


Re the EF question, just write some SQL (assuming you want the logic to happen on the db) rather than fighting with EF. Most SQL variants are really good at that sort of logic and it's easy to develop with interactive queries.

NecroBob
Jul 29, 2003

pointsofdata posted:

Re the EF question, just write some SQL (assuming you want the logic to happen on the db) rather than fighting with EF. Most SQL variants are really good at that sort of logic and it's easy to develop with interactive queries.

Seconding this.

I whipped this up in a few minutes in T-SQL:

code:
DROP TABLE IF EXISTS [dbo].[idk];
GO

CREATE TABLE [dbo].[idk] (
    [Id] INTEGER NOT NULL
    ,[Message] NVARCHAR(16) NOT NULL

    CONSTRAINT [PK_idk]
        PRIMARY KEY
        ([Id])
)
GO

INSERT INTO [dbo].[idk] VALUES (1  , 'apple'   )
INSERT INTO [dbo].[idk] VALUES (2  , 'apple'   )
INSERT INTO [dbo].[idk] VALUES (3  , 'apple'   )
INSERT INTO [dbo].[idk] VALUES (4  , 'apple'   )
INSERT INTO [dbo].[idk] VALUES (5  , 'banana'  )
INSERT INTO [dbo].[idk] VALUES (6  , 'banana'  )
INSERT INTO [dbo].[idk] VALUES (7  , 'dusty'   )
INSERT INTO [dbo].[idk] VALUES (8  , 'elephant')
INSERT INTO [dbo].[idk] VALUES (9  , 'elephant')
INSERT INTO [dbo].[idk] VALUES (10 , 'hello'   )
GO

WITH [Ranking] AS (
    SELECT [Id]
           , [Message]
           , RANK() OVER (
               PARTITION BY [Message]
                   ORDER BY [Id] DESC
           ) AS [Rank]
      FROM [dbo].[idk]
)
  SELECT TOP 5 [Message]
    FROM [Ranking]
   WHERE [Rank] = 1
ORDER BY [Id] DESC
and the result is indeed

code:
hello
elephant
dusty
banana
apple
If you put the index on Id, the execution plan shows a simple Clustered Index Scan then a pipeline of assorted scalar operations (filter, sort, sequences, etc) so it ought to scale decently well.


For reference, the interim ranking CTE looks like:

code:
Id          Message          Rank
----------- ---------------- --------------------
10          hello            1
9           elephant         1
8           elephant         2
7           dusty            1
6           banana           1
5           banana           2
4           apple            1
3           apple            2
2           apple            3
1           apple            4

Cold on a Cob
Feb 6, 2006

i've seen so much, i'm going blind
and i'm brain dead virtually

College Slice
You don’t need a cte for this, you can order by the max(Id) desc and grab the top 5 from that. Check the post I made earlier. This is easy as hell in sql.

NecroBob
Jul 29, 2003
Oh yeah, guess you could to that too. I just like CTEs because they break stuff down into smaller units, and I use them quite often. :D

E: poo poo yeah, way cleaner with the same result and shorter execution plan

code:
  SELECT TOP 5 [Message]
    FROM [dbo].[idk]
GROUP BY [Message]
ORDER BY MAX([Id]) DESC

NecroBob fucked around with this message at 18:33 on Jun 22, 2021

epswing
Nov 4, 2003

Soiled Meat

NecroBob posted:

code:
  SELECT TOP 5 [Message]
    FROM [dbo].[idk]
GROUP BY [Message]
ORDER BY MAX([Id]) DESC

Blindly mimicking this with linq works
C# code:
messageTable
    .GroupBy(msg => msg.Message)
    .OrderByDescending(grp => grp.Max(msg => msg.Id))
    .Select(grp => grp.Key)
    .Take(5);
Here's the generated SQL (results in a Clustered Index Scan)
SQL code:
SELECT TOP (5) 
    [GroupBy1].[K1] AS [Message]
    FROM ( SELECT 
        [Extent1].[Message] AS [K1], 
        MAX([Extent1].[Id]) AS [A1]
        FROM [dbo].[Messages] AS [Extent1]
        GROUP BY [Extent1].[Message]
    )  AS [GroupBy1]
    ORDER BY [GroupBy1].[A1] DESC
Thanks folks!

epswing fucked around with this message at 14:24 on Jun 23, 2021

Supersonic
Mar 28, 2008

You have used 43 of 300 characters allowed.
Tortured By Flan
Edit: Ended up solving this.

Supersonic fucked around with this message at 16:40 on Jun 24, 2021

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe
Found a nasty bug in one of our WPF apps where things like checkboxes lose state when the user "switches user", the machine wakes from sleep etc.

Found it can be eliminated by changing bindings from "OneWayToSource" to "TwoWay". Turns out when the window is recreated, it sets the state of the checkbox to the default unchecked state and that gets communicated to the data context. Trouble is, if we have a modal dialog showing and this changes the state of the viewmodel that spawned the modal dialog in a way we didn't anticipate (e.g. you wouldn't have been allowed to click the button that spawned the modal dialog, if the checkbox hadn't been clicked).

At best it undoes the user's work, if they had decided to check the checkbox before locking their workstation and letting it sleep or w/e.

This seems like a really obtuse behaviour. Why would you ever want "OneWayToSource" if it's going to gently caress you like this?

epswing
Nov 4, 2003

Soiled Meat
I honestly can't think of a place I've ever needed to use OneWayToSource in a decade+ of WPF (mostly LOBs)

epswing fucked around with this message at 15:37 on Jun 28, 2021

Canine Blues Arooo
Jan 7, 2008

when you think about it...i'm the first girl you ever spent the night with



Grimey Drawer
I don't think I've ever used OneWayToSource, but what an obnoxious edge case. Thanks for sharing! I feel like that's the kind of thing you'd Google forever and only find answers to if you got obscenely lucky.

EssOEss
Oct 23, 2006
128-bit approved
What is all y'all's experience with nullable reference types? Any great success stories to tell? I tried them out and just found it to be a nice idea that in practice is just a nuisance that did not help me at all. Wondering if this is a common experience or if there is a scenario where they prove worth bothering about.

Mr Shiny Pants
Nov 12, 2012

EssOEss posted:

What is all y'all's experience with nullable reference types? Any great success stories to tell? I tried them out and just found it to be a nice idea that in practice is just a nuisance that did not help me at all. Wondering if this is a common experience or if there is a scenario where they prove worth bothering about.

None actually, although I've been reading on how they want to implement it in F# and I am not excited. F# already has an option type to describe the absence of something but that wasn't good enough apparently. While I do like the pattern matching they did for C#; the language itself seems to be getting more and more top heavy. Instead of trying to keep things simple, they are going whole hog the other way with their development tools it seems. Trying to get websockets running on Kestrel you need to write your own middleware? Why? That seems like such base functionality.

Something else; wanting to use audio or video on .Net is such a pain on something that is not Windows, I've decided to use Python. My god, the amount of libraries available to do almost anything is just wonderful. video4linux bindings? Here you go. Port audio? Sure.

So now I use F# for the core logic, because it is just wonderful to use, and use Python for the devices. Websockets are used to get them talking to each other. It works pretty well.

Mr Shiny Pants fucked around with this message at 08:32 on Jul 11, 2021

LOOK I AM A TURTLE
May 22, 2003

"I'm actually a tortoise."
Grimey Drawer

EssOEss posted:

What is all y'all's experience with nullable reference types? Any great success stories to tell? I tried them out and just found it to be a nice idea that in practice is just a nuisance that did not help me at all. Wondering if this is a common experience or if there is a scenario where they prove worth bothering about.

It took me a couple of days to convert almost all of our API code to use NNRTs (don't know the LOC, but probably somewhere between 100,000 and 1,000,000, and closer to the bottom of that range), and in the process I was able to fix some actual/potential bugs and also remove a lot of superfluous null checks. Definitely not a nuisance.

The only annoying thing I've encountered is when libraries I'm using don't support them yet, forcing me to temporarily disable them in a a few cases. This is the the case that comes to mind:

C# code:
// Defined in 3rd party library:
public interface IFooGetter
{
    Foo GetFoo(int fooId);
}

// In my code:
public class FooGetter : IFooGetter
{
    private readonly IDictionary<int, Foo> _foos;

    public Foo GetFoo(int fooId) => _foos.TryGetValue(fooId, out var result) ? result : null;
}
The compiler doesn't allow this. GetFoo can't return null because Foo isn't nullable, but you can't make the return type Foo?, because then you're not implementing the interface as defined. The workaround is to either return null!, or temporarily disable NNRTs with the #nullable disable pragma.

One other nuisance is that I've had occasional compiler/IDE bugs where the compiler is convinced that I need to either add a null check for some non-nullable value before using it, or that a null check for an actually nullable value is superfluous. I had that just the other day, and had to delete the bin/obj folders in the project to fix it.

Other than that I have nothing but good things to say about it. The thing about it, though, is that making the plunge is similar to introducing async/await to code that didn't originally have it. It's a bit of an all or nothing, otherwise you don't get the benefits. So in a larger project I could see the risks/workload outweighing the benefits.

Chrungka
Jan 27, 2015

LOOK I AM A TURTLE posted:

The only annoying thing I've encountered is when libraries I'm using don't support them yet, forcing me to temporarily disable them in a a few cases. This is the the case that comes to mind:

C# code:
// Defined in 3rd party library:
public interface IFooGetter
{
    Foo GetFoo(int fooId);
}

// In my code:
public class FooGetter : IFooGetter
{
    private readonly IDictionary<int, Foo> _foos;

    public Foo GetFoo(int fooId) => _foos.TryGetValue(fooId, out var result) ? result : null;
}
The compiler doesn't allow this. GetFoo can't return null because Foo isn't nullable, but you can't make the return type Foo?, because then you're not implementing the interface as defined. The workaround is to either return null!, or temporarily disable NNRTs with the #nullable disable pragma.

Are you sure about example above? When I try to implement interface from library that does not support NNRTs, I have no problem implementing the interface method with Foo? return type. On the other hand, if library does support NNRTs, then compiler rightfully complains and correct implementation would be to throw exception instead of returning null.

NihilCredo
Jun 6, 2011

iram omni possibili modo preme:
plus una illa te diffamabit, quam multæ virtutes commendabunt

LOOK I AM A TURTLE posted:

The workaround is to either return null!

I understand why this is necessary (if nothing else for the exact scenario you described) but lol that this is even allowed.

LOOK I AM A TURTLE
May 22, 2003

"I'm actually a tortoise."
Grimey Drawer

Chrungka posted:

Are you sure about example above? When I try to implement interface from library that does not support NNRTs, I have no problem implementing the interface method with Foo? return type. On the other hand, if library does support NNRTs, then compiler rightfully complains and correct implementation would be to throw exception instead of returning null.

Hmm, you may be right. Perhaps the scenario I'm describing actually only applies to cases where the library has <Nullable>enable</Nullable>, but the particular interface hasn't been updated to correctly reflect the true nullability of the return value? I had this problem specifically with the IUserStore<T> interface in the Identity part of ASP.NET Core, where the FindById/Name/Email methods are defined as returning T rather than T?. I could implement the interface as IUserStore<User?>, but then it ends up being nullable in lots of other methods where it isn't desirable (UpdateUser etc.).

NihilCredo posted:

I understand why this is necessary (if nothing else for the exact scenario you described) but lol that this is even allowed.

The first time I tried it I fully expected it to give some sort of "this expression is hosed" error, like when you do if (0 == 1), but nope.

Chrungka
Jan 27, 2015

LOOK I AM A TURTLE posted:

Hmm, you may be right. Perhaps the scenario I'm describing actually only applies to cases where the library has <Nullable>enable</Nullable>, but the particular interface hasn't been updated to correctly reflect the true nullability of the return value? I had this problem specifically with the IUserStore<T> interface in the Identity part of ASP.NET Core, where the FindById/Name/Email methods are defined as returning T rather than T?. I could implement the interface as IUserStore<User?>, but then it ends up being nullable in lots of other methods where it isn't desirable (UpdateUser etc.).
I think you should go with IUserStore<User?>. Having to implement Task<IdentityResult> UpdateAsync(User? user, CancellationToken cancellationToken) with regular null check via ArgumentNullException might be inconvenient. But returning null when contract explicitly says it doesn't return null is IMHO a bug in code.

LOOK I AM A TURTLE posted:

The first time I tried it I fully expected it to give some sort of "this expression is hosed" error, like when you do if (0 == 1), but nope.

This: https://www.youtube.com/watch?v=V9qTsDg-RPo

Chasiubao
Apr 2, 2010


EssOEss posted:

What is all y'all's experience with nullable reference types? Any great success stories to tell? I tried them out and just found it to be a nice idea that in practice is just a nuisance that did not help me at all. Wondering if this is a common experience or if there is a scenario where they prove worth bothering about.

At best/most I'll use
code:
<Nullable>warnings</Nullable>
My opinion on it is that there's two scenarios. In scenario one where things can be statically proven to never be null, it's great and a nice little time saver of writing
code:
if (blah == null)
But in the scenarios where it doesn't work or hold - per the docs arrays and structs - the author of the code still has to null check. And so you end up in a world where the developer has to keep that additional cognitive load in their head where they always have to be asking "Is it scenario one or two?". And if they get a false positive on one, okay so you burned a few cycles on a need-less null check. But the opposite leads to a null ref exception.

LOOK I AM A TURTLE
May 22, 2003

"I'm actually a tortoise."
Grimey Drawer

Chrungka posted:

I think you should go with IUserStore<User?>. Having to implement Task<IdentityResult> UpdateAsync(User? user, CancellationToken cancellationToken) with regular null check via ArgumentNullException might be inconvenient. But returning null when contract explicitly says it doesn't return null is IMHO a bug in code.

No, the FindByX methods are definitely intended to return null if the user isn't found. That's what the default implementation for EF Core does, for example: https://github.com/dotnet/aspnetcore/blob/69eb4b38bca90bb830f290a6eaa5a61650dc87ac/src/Identity/EntityFrameworkCore/src/UserStore.cs#L234 (you have to dig through the references a bit to see that it returns null, but trust me, it does).

Either they just haven't changed the definition to TUser? yet, or there's some reason (like backward compat) that prevents them from changing it.

Edit: To clarify, I agree that it's reasonable enough to implement it as TUser?, but seeing as how the default FindByX methods return null, while all the other methods explicitly throw if the input is null, it seems clear to me that the ideal interface would mark the Find methods with a question mark, but not the others.

LOOK I AM A TURTLE fucked around with this message at 21:46 on Jul 12, 2021

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe
Has anyone used Npgsql? Connected by specifying a DbProviderFactory in app.config?

I'm trying to get this to work, but when I run the app it always throws "The connection string for the database 'database_name' does not exist or does not have a valid provider. ---> The requested database database_name does not have a valid ADO.NET provider name set in the connection string. (C:\...\connectionStrings.config line 3)"

These lines are taken from app.config:

code:
  <system.data>
    <DbProviderFactories>
      <!--<remove invariant="Oracle.ManagedDataAccess.Client" />-->
      <!--<add name="ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client" description="Oracle Data Provider for .NET, Managed Driver" type="Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess, Version=4.122.19.1, Culture=neutral, PublicKeyToken=89b483f429c47342" />-->
      <remove invariant="Npgsql" />
      <add name="Npgsql" invariant="Npgsql" description="PostgreSQL" type="Npgsql.NpgsqlFactory, Npgsql, Version=5.0.7.0, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7, processorArchitecture=MSIL" />
    </DbProviderFactories>
  </system.data>
These lines are taken from the project's csproj file:

code:
  <ItemGroup>
    ...
    <Reference Include="Npgsql, Version=5.0.7.0, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7, processorArchitecture=MSIL">
      <HintPath>path_to_nuget_cache\Npgsql.5.0.7\lib\netstandard2.0\Npgsql.dll</HintPath>
    </Reference>
    ....
  </ItemGroup>
These lines are taken from the connectionStrings.config file:

code:
<connectionStrings>
  <add name="database_name" connectionString="Host=localhost;Database=database_name" providerName="Npgsql" />
</connectionStrings>
This is the utility class that is used to get a database instance:

code:
namespace OurApp
{
	internal class DBCommon
	{
		static bool _factorySet = false;
		internal static void SetFactory()
		{
			if (!_factorySet)
			{
				DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory());
				_factorySet = true;
			}
		}

		internal static Microsoft.Practices.EnterpriseLibrary.Data.Database CreateDatabase(string name)
		{
			SetFactory();
			return DatabaseFactory.CreateDatabase(name);
		}
	}
}
This has been working up to now under Oracle, using Oracle.ManagedDataAccess.Client. If I don't find a way to get it working I will experiment with explicitly constructing the database connection using the types from Npgsql, but I was hoping that at least in this aspect it'd prove to be a drop-in replacement...

Small White Dragon
Nov 23, 2007

No relation.
Speaking of nullables, is it possible to enable them in a shared project (shproj)? I've been doing "#nullable enable" in every file, but that's kind of annoying for an on-going project.

Mr Shiny Pants
Nov 12, 2012

Hammerite posted:

snip

This has been working up to now under Oracle, using Oracle.ManagedDataAccess.Client. If I don't find a way to get it working I will experiment with explicitly constructing the database connection using the types from Npgsql, but I was hoping that at least in this aspect it'd prove to be a drop-in replacement...

Not trough app.config. This is what I've used inside code:
code:
let connString  = "Host=fqdn;Username=usr;Password=bla;Database=database;Keepalive=180"

let checkDb() =
    try 
        use conn = new Npgsql.NpgsqlConnection(connString)
        conn.Open()
        Success "Database online"
    with 
    | e -> Failure e.Message
It's been a while, but this always worked.

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

I've got it working now. The problem was something much dumber - I was putting that db provider stuff in the app.config of the library that communicates with the db, and it needed to be in the app.config of the C++ app that uses the library. Now I'm on to the next problem.

Mr Shiny Pants
Nov 12, 2012

Hammerite posted:

I've got it working now. The problem was something much dumber - I was putting that db provider stuff in the app.config of the library that communicates with the db, and it needed to be in the app.config of the C++ app that uses the library. Now I'm on to the next problem.

Good luck :) Glad you got it working.

I always found working with Npgsql pretty nice.

Mr Shiny Pants
Nov 12, 2012
Anyone working with ArrayPools? I am doing some work which uses quite a lot of arrays (framebuffers) and I was just wondering if the speedup is worthwhile.

I also use arrays for websockets, would these also be a good candidate? I have quite a lot of 64K arrays coming in.

I am mostly looking for anyone who has some experience using them.

Another question: how would I profile this?

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe
I'm going to ask this here too because it doesn't look likely that Stack Overflow is going to be much help.

How do I get C# to print out the exact value represented by a floating-point number in memory?

I'm looking to create a function f such that this code:

code:
float myFloat = 0.1;
string s = f(myFloat);
Console.WriteLine(s);
prints 0.100000001490116119384765625

... which is, if I got my maths right, the actual value represented by the bit pattern of the float.

myFloat.ToString("F50") is no help. It just prints out 0.10000...000, which is :wrong:

mystes
May 31, 2006

Hammerite posted:

I'm going to ask this here too because it doesn't look likely that Stack Overflow is going to be much help.

How do I get C# to print out the exact value represented by a floating-point number in memory?

I'm looking to create a function f such that this code:

code:
float myFloat = 0.1;
string s = f(myFloat);
Console.WriteLine(s);
prints 0.100000001490116119384765625

... which is, if I got my maths right, the actual value represented by the bit pattern of the float.

myFloat.ToString("F50") is no help. It just prints out 0.10000...000, which is :wrong:
Try G50 instead.

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

mystes posted:

Try G50 instead.

G50 gets you 0.100000001

the Microsoft docs specify that using G with enough decimal places will give you a representation that should round-trip correctly (which I assume is borne out here; I've not tested it). It doesn't say you will get the value actually represented in memory.

No Pants
Dec 10, 2000

It gives the number you wanted in your example at least, on .NET 5. You only need G9 to round-trip a float, so it seems to be formatting as much as it can. Maybe. :shrug:

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe
drat, it does the right thing on net core 3.1 as well. Just Framework where it doesn't. Unfortunately the place where I wanted to do this is a framework app. Well, I will just have to do without.

Just-In-Timeberlake
Aug 18, 2003

Hammerite posted:

drat, it does the right thing on net core 3.1 as well. Just Framework where it doesn't. Unfortunately the place where I wanted to do this is a framework app. Well, I will just have to do without.

Create a .dll in netCore or .NET 5 that does what you want and reference it? I’ve managed to make things work that way when there was no way to switch to a higher framework that supported TLS2.1

NihilCredo
Jun 6, 2011

iram omni possibili modo preme:
plus una illa te diffamabit, quam multæ virtutes commendabunt

https://devblogs.microsoft.com/dotnet/preview-features-in-net-6-generic-math/

We're getting THIS close to having typeclasses in .NET :v:

mystes
May 31, 2006

Someone on Reddit a couple months ago claimed that they didn't want to try to add typeclasses to f# because there was a distinct possibility they were actually going to get added to .net in general.

Adbot
ADBOT LOVES YOU

distortion park
Apr 25, 2011


I don't understand the theory, but my question is: would typeclasses give us discriminated unions in c#?

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply