Wednesday, May 31, 2023

Basic MySQL to LINQ conversion using chatbot group by , distinct , left join


 Convert following MySQL query to Linq query in .net core entity framework

ChatGPT

To convert a MySQL

User
Select teamuser.id, teamduration.createddate, teamduration.startdate ,teamduration.enddate , teamuser.categoryId, teamuser.subcategoryId, supervisorUserId , categorymaster.name, subcategorymaster.name as subcategory , su.user_name as supervisor , ru.user_name Reporting, u.user_name as teammember from teamuser tu inner join teamduration td on teamuser.id = td.teamUserId inner join usermaster su on su.id = td.supervisoruserid left join usermaster ru on ru.id = td.reporterUserId left join usermaster u on u.id = tu.userId left join categorymaster cm on cm.id = tu.categoryId left join subcategorymaster scm on scm.id = tu.subcategoryId
ChatGPT

To convert the given MySQL query to a LINQ query in .NET Core Entity Framework, you can use the LINQ syntax and Entity Framework's DbSet properties. Here's how you can write the LINQ query:

csharp
var query = from tu in dbContext.TeamUsers join td in dbContext.TeamDurations on tu.Id equals td.TeamUserId join su in dbContext.UserMasters on td.SupervisorUserId equals su.Id join ru in dbContext.UserMasters on td.ReporterUserId equals ru.Id into ruGroup from ru in ruGroup.DefaultIfEmpty() join u in dbContext.UserMasters on tu.UserId equals u.Id into uGroup from u in uGroup.DefaultIfEmpty() join cm in dbContext.CategoryMasters on tu.CategoryId equals cm.Id into cmGroup from cm in cmGroup.DefaultIfEmpty() join scm in dbContext.SubcategoryMasters on tu.SubcategoryId equals scm.Id into scmGroup from scm in scmGroup.DefaultIfEmpty() select new { tu.Id, td.CreatedDate, td.StartDate, td.EndDate, tu.CategoryId, tu.SubcategoryId, SupervisorUserId = td.SupervisorUserId, CategoryName = cm.Name, SubcategoryName = scm.Name, SupervisorName = su.UserName, ReportingName = ru.UserName, TeamMemberName = u.UserName }; var results = query.ToList();

Note that you need to replace dbContext with your actual instance of the Entity Framework's DbContext class, and the TeamUsers, TeamDurations, UserMasters, CategoryMasters, and SubcategoryMasters properties with the corresponding DbSet properties in your DbContext class.

The LINQ query uses the join clause to perform inner joins and left joins between the tables. The into keyword and DefaultIfEmpty() method are used to perform left joins. The select clause creates a new anonymous type with the desired properties from the joined tables.

Finally, the ToList() method executes the query and retrieves the results into a list.

User
How to select {CategoryName , SubcategoryName , SupervisorName } from above results grouped or distinct values
ChatGPT

To select distinct or grouped values for CategoryName, SubcategoryName, and SupervisorName from the results obtained in the previous query, you can modify the LINQ query as follows:

csharp
var distinctResults = query .Select(x => new { x.CategoryName, x.SubcategoryName, x.SupervisorName }) .Distinct() .ToList();

In this modified query, the Select() method is used to project the desired properties (CategoryName, SubcategoryName, and SupervisorName) from the results. The Distinct() method is then applied to eliminate duplicate rows based on the selected properties. Finally, the ToList() method is used to execute the query and retrieve the distinct results into a list.

The distinctResults list will contain distinct combinations of CategoryName, SubcategoryName, and SupervisorName from the original query results.

User
How to select using group by?
ChatGPT

To select using the GROUP BY clause in LINQ, you can modify the previous LINQ query to include the group keyword. Here's an example of how you can select using GROUP BY:

csharp
var groupedResults = query .GroupBy(x => new { x.CategoryName, x.SubcategoryName, x.SupervisorName }) .Select(group => new { CategoryName = group.Key.CategoryName, SubcategoryName = group.Key.SubcategoryName, SupervisorName = group.Key.SupervisorName }) .ToList();

In this modified query, the GroupBy() method is used to group the results based on the selected properties (CategoryName, SubcategoryName, and SupervisorName). The Select() method is then used to project the grouped properties into a new anonymous type with the desired property names. Finally, the ToList() method executes the query and retrieves the grouped results into a list.

The groupedResults list will contain distinct combinations of CategoryName, SubcategoryName, and SupervisorName based on the GROUP BY operation.

Monday, May 30, 2022

Open .net framework 4.5 project in VS 2022.

 

·         Download Microsoft.NETFramework.ReferenceAssemblies.net45 from nuget.org

·         Open the package as zip

·         copy the files from build\.NETFramework\v4.5\ to C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5

For more details: Building a project that target .NET Framework 4.5 in Visual Studio 2022

 

Saturday, February 5, 2022

creating-a-wcf-client-part-4-programmatically-configuring-wcf-cl

Copy of this source for reference and personal use https://7thzero.com/blog/creating-a-wcf-client-part-4-programmatically-configuring-wcf-cl Creating a WCF Client Part 4: Programmatically configuring WCF Clients August 18th at 12:00am While using the app.config file is a quick & convenient (Article 2, Article 3) way to get your WCF clients up and running, there are times when you may not want to distribute a .exe.config file alongside your EXE. This article describes how to configure a WCF client on-the-fly in your C# Code. Here are the steps I took to convert one of my WCF Clients to use an on-demand configuration approach: Open the WCF Client project in Visual Studio Cut out the parts of the app.config file pertaining to web services (see Article #2 for an example) and paste them into a notepad document for reference At this point we want to revise the basic client connection code from our earlier articles into something a little more specific. As we have removed the client configuration settings from the app.config file, we need to: Define a Binding Needs a unique Name A number of properties must be set Define an Endpoint Address Should have a unique Name Needs a URI of the web service you want to hit Instantiate the WCF Client object by constructor Explicit Binding Explicit Endpoint Address Note: You can find all of the necessary settings for the Binding and Endpoint Address by looking through the sections of the app.config that you copied out in Step 2 above. Our code goes from looking something like this: // Instantiates a client object SomeServiceClient client = new SomeServiceClient(); // Opens the client object client.Open(); // // Between the open & close, you would use any methods made available in the class. // For example, if the client provided a method named ReturnDataTable which // Returns a data table, you could do something like this: DataTable results = client.ReturnDataTable(); // Closes the client object client.Close(); To something that is a little more complex. I've added comments around the major sections for clarity: // ----- Programmatic definition of the SomeService Binding ----- System.ServiceModel.BasicHttpBinding SomeServiceBinding = new System.ServiceModel.BasicHttpBinding(); SomeServiceBinding.Name = "SomeServiceServiceBinding"; SomeServiceBinding.CloseTimeout = new TimeSpan(0, 1, 0); SomeServiceBinding.OpenTimeout = new TimeSpan(0, 1, 0); SomeServiceBinding.ReceiveTimeout = new TimeSpan(0, 1, 0); SomeServiceBinding.SendTimeout = new TimeSpan(0, 1, 0); SomeServiceBinding.AllowCookies = false; SomeServiceBinding.BypassProxyOnLocal = false; SomeServiceBinding.HostNameComparisonMode = System.ServiceModel.HostNameComparisonMode.StrongWildcard; SomeServiceBinding.MaxBufferSize = 65536; SomeServiceBinding.MaxBufferPoolSize = 524288; SomeServiceBinding.MaxReceivedMessageSize = 65536; SomeServiceBinding.MessageEncoding= System.ServiceModel.WSMessageEncoding.Text; SomeServiceBinding.TextEncoding = System.Text.Encoding.UTF8; SomeServiceBinding.TransferMode = System.ServiceModel.TransferMode.Buffered; SomeServiceBinding.UseDefaultWebProxy = true; SomeServiceBinding.ReaderQuotas.MaxDepth = 32; SomeServiceBinding.ReaderQuotas.MaxStringContentLength = 8192; SomeServiceBinding.ReaderQuotas.MaxArrayLength = 16384; SomeServiceBinding.ReaderQuotas.MaxBytesPerRead = 4096; SomeServiceBinding.ReaderQuotas.MaxNameTableCharCount = 16384; SomeServiceBinding.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.Transport; SomeServiceBinding.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.None; SomeServiceBinding.Security.Transport.ProxyCredentialType = System.ServiceModel.HttpProxyCredentialType.None; SomeServiceBinding.Security.Message.ClientCredentialType = System.ServiceModel.BasicHttpMessageCredentialType.UserName; SomeServiceBinding.Security.Message.AlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Default; // ----------- End Programmatic definition of the SomeServiceServiceBinding -------------- // ---------- Configure a Remote Address Manually ---------------- System.ServiceModel.EndpointAddress SomeServiceServerAddress = new System.ServiceModel.EndpointAddress("https://someservices.mydomain.com:809/Services/SomeOtherServices.svc"); // -----------End configure remote address manually -------------- // ----------- Instantiate & Open the Client object ---------- SomeServiceClient client = new SomeServiceClient(SomeServiceBinding, SomeServiceServerAddress); client.Open(); // // Between the open & close, you would use any methods made available in the class. // For example, if the client provided a method named ReturnDataTable which // Returns a data table, you could do something like this: DataTable results = client.ReturnDataTable(); // Close the client object client.Close(); ~Troubleshooting~ Configuration system failed to initialize See the end of this message for details on invoking just-in-time (JIT) debugging instead of this dialog box. ** Exception Text ** System.Configuration.ConfigurationErrorsException: Configuration system failed to initialize ---> System.Configuration.ConfigurationErrorsException: Unrecognized configuration section userSettings. (C:\Users\Administrator\AppData\Local\SomeCompany\SomeWCFClient.exe_Url_fwt2rqjtqtwa4i3g42pr3zwuekhsbjwz\1.7.6.0\user.config line 3) at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal) at System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors() at System.Configuration.ClientConfigurationSystem.OnConfigRemoved(Object sender, InternalConfigEventArgs e) --- End of inner exception stack trace --- You may need to remove the user.config file or the automatically generated "program name" folder for your executable from C:\Users\appdata\local\CompanyName (for Windows Server 2008 R2). It looks like settings from app.config can become cached here, and when the app starts again it receives a configuration it doesn't quite understand.

Thursday, August 26, 2021

MySQL: How to create Column if not exists?

https://dba.stackexchange.com/questions/169458/mysql-how-to-create-column-if-not-exists SELECT count(*) INTO @exist FROM information_schema.columns WHERE table_schema = 'mydatabase' and COLUMN_NAME = 'mycolumn' AND table_name = 'mytable' LIMIT 1; set @query = IF(@exist <= 0, 'ALTER TABLE mydatabase.`mytable` ADD COLUMN `mycolumn` MEDIUMTEXT NULL', 'select \'Column Exists\' status'); prepare stmt from @query; EXECUTE stmt;

Friday, July 16, 2021

Regular expression to find non-ascii characters in a large file in notepad++

Recently I face an issue while importing a large xml file because of a some invalid characters in XML content. Since it is a large file, the regular expression search in notepad++ helps to find the non ascii characters. [^\s\x20-\x7E] Thanks to :https://notepad-plus-plus.org/ , https://stackoverflow.com/questions/43334055/notepad-remove-non-alpanumeric-characters

Friday, May 21, 2021

Articles reference

https://hbr.org/2005/10/the-hard-side-of-change-management https://www.businesstoday.in/opinion/columns/6-billion---the-hidden-cost-of-90-day-notice-period-to-companies-economy/story/439603.html

Tuesday, November 19, 2019

Packages used while Converting .Net core 2.0 project to .netcore 3.0


Packages used while Converting .Net core 2.0 project to .netcore 3.0

Install-Package Microsoft.IdentityModel.Tokens -Version 5.6.0
Install-Package Microsoft.AspNetCore.Authentication.JwtBearer -Version 3.0.0-preview-19075-0444
Install-Package Swashbuckle.AspNetCore -Version 5.0.0-rc4

   services.AddMvc(option => option.EnableEndpointRouting = false);