Can I remove a namespace import from a linqpad query? - namespaces

I am trying to run a linqpad query, but one of the default namespace imports has a type that is apparently shadowing the type I am trying to reference. System.Xml is one of the default imports in linqpad, but I rarely use it. Is it possible to remove that default namespace import, so I can use my own Formatting enum?

This isn't a direct answer to your immediate question, but you can can tell LINQPad which one you want Formatting to mean. In your query, press the F4 key and then under the Additional Namespace Imports tab you can add the following:
Formatting = Newtonsoft.Json.Formatting
This tells LINQPad to declare a using alias directive for your script. Note that you should not include the word using before the line, LINQPad handles theat for you.

Related

How to resolve SQL table with prefix in PhpStorm?

I'm working on PhpStorm to develop my Prestashop websites and I can't resolve this issue. I work on localhost and successfully connected PhpStorm to my MySQL Server.
Now PhpStorm throws warnings like "unable to resolve table '${_DB_PREFIX_}cms'". Prestashop uses prefixes for table names and it seems PhpStorm can't resolve those tables with prefixes.
Is there a workaround for this ?
Here is a code exemple from Prestashop-1.6 sources :
$sql = 'SELECT c.`id_cms`, cl.`meta_title`, cl.`link_rewrite`
FROM `'._DB_PREFIX_.'cms` c
INNER JOIN `'._DB_PREFIX_.'cms_shop` cs
ON (c.`id_cms` = cs.`id_cms`)
INNER JOIN `'._DB_PREFIX_.'cms_lang` cl
ON (c.`id_cms` = cl.`id_cms`)
WHERE c.`id_cms_category` = '.(int)$id_cms_category.'
AND cs.`id_shop` = '.(int)$id_shop.'
AND cl.`id_lang` = '.(int)$id_lang.
$where_shop.'
AND c.`active` = 1
ORDER BY `position`';
The reason why this isn't work is because you are most likely only loading one schema, you need to load the information_schema.*
To do this, go to the database tab in the top right and where you have added your MySQL database right click and select properties.
Now you'll have a screen called Data Sources and Drivers, it should open on a tab called General, click the third tab called Schemas and and add information_schema.* to this list of loaded Schemas.
Click apply and okay and then PhpStorm will now know your database structure and then be intelligently able to work with you, therefor removing all the errors.
Edit: As mentioned here, this has been fixed in PhpStorm 2018.2, but only for constants.
I have a solution that doesn't involve throwing your IDE away. :)
However, a word of caution: it's an ugly hackā„¢ that comes without guarantees.
Assuming you already have a connection to the db in PhpStorm, generate the ddl for the desired db (Right Click on the connection -> SQL Scripts -> Generate DDL to Clipboard):
Paste the content into some sql file somewhere inside your project. You should probably gitignore this file.
Replace all the tables' prefix in this ddl file with the one from your code. Use the PhpStorm typehint as a guideline. For example '._DB_PREFIX_.'cms would become ${_DB_PREFIX_}cms:
Note that you may have to use backticks to avoid breaking sql syntax due to curly brackets.
Add the ddl to your phpstorm project:
Everything should now work:
Add this comment above the $sql query.
/** #noinspection SqlResolve */
This will suppress the warning only for this statement.
For future readers, this is now supported:
https://www.jetbrains.com/help/phpstorm/2021.1/ide-advanced-metadata.html#set-up-dynamic-prefixes-for-table-names-in-sql-language-injections
.phpstorm.meta.php
<?php
namespace PHPSTORM_META {
override(
// Virtual function to indicate that all SQL
// injections will have the following replacement rules.
sql_injection_subst(),
map([
'{' => "", // all `{` in injected SQL strings will be replaced with a prefix
'}' => '', // all `}` will be replaced with an empty string
]));
}
Edit: At time of writing (2016) there was no solution to this issue. But since 2018, as mentioned in Christian's answer, you can now use constants in SQL queries.
Actually there is no way to handle that. But you may disable inspection for such warning.
Open File > Settings > Editor > Inspections
Expand SQL
Uncheck Unresolved reference

XmlReaderParsingException: The start element with name <...> and namespace "http..." was unexpected

This is for BizTalk 2010. I am running into a very strange issue that I've not been able to find a solution either using my favorite search engine's results or elsewhere.
I added several SQL Server 2008 table schemas to BizTalk. Set up orchestration and mapping without any problems. BizTalk was able to use WCF_Custom SQL Adapter using XML/BTSAction to insert data to the SQL tables identified in the XML.
Some of those tables had data inserted just fine, except two. Both had the same error. The error was pulling from a third table's namespace. Here's the error in full -- notice that the namespace, ns, is for ns46:professionalAddendum as is expected, but somehow, somewhere, BizTalk is pulling a different namespace, ns35, from a different table:
Microsoft.ServiceModel.Channels.Common.XmlReaderParsingException: The start element with name "ClaimFilingIndicatorCode" and namespace "http://schemas.microsoft.com/Sql/2008/05/TableOp/dbo/professionalCOBAdjustmentsAncillary" was unexpected. Please ensure that your input XML conforms to the schema for the operation.
<ns2:Insert xmlns:ns2="http://schemas.microsoft.com/Sql/2008/05/TableOp/dbo/professionalAddendum">
<ns2:Rows>
<ns46:professionalAddendum xmlns:ns46="http://schemas.microsoft.com/Sql/2008/05/Types/Tables/dbo">
<ns46:uid_claim>1b8f20e9-0517-4f00-9ee2-99d5f04d1573</ns46:uid_claim>
ERROR>>>>> <ns35:ClaimFilingIndicatorCode xmlns:ns35="http://schemas.microsoft.com/Sql/2008/05/TableOp/dbo/professionalCOBAdjustmentsAncillary">17</ns35:ClaimFilingIndicatorCode>
<ns46:ClaimFrequencyTypeCode>1</ns46:ClaimFrequencyTypeCode>
<ns46:ProviderAcceptAssignmentCode>B</ns46:ProviderAcceptAssignmentCode>
<ns46:BenefitsAssignmentCertificationIndicator>Y</ns46:BenefitsAssignmentCertificationIndicator>
<ns46:ReleaseofCode>Y</ns46:ReleaseofCode>
<ns46:ProviderOrSupplierSignatureIndicator>N</ns46:ProviderOrSupplierSignatureIndicator>
</ns46:professionalAddendum>
</ns2:Rows>
</ns2:Insert>
Is there a way to fix this? Really weird.
Thanks all!
It's tough to know exactly what is going on without seeing your full schema, but I have seen it where the case of a table name changes somewhere, and then the corresponding namespace no longer matches.
For example:
http://schemas.microsoft.com/Sql/2008/05/TableOp/dbo/professionalAddendum
vs
http://schemas.microsoft.com/Sql/2008/05/TableOp/dbo/ProfessionalAddendum
I'm posting up what I found. The map and orchestration are both fine for the most part. There was a Scripting functoid in the mapper that used an inline XSLT to map from the source schema to the destination schema, and the offending namespace was in that XSLT code. When I changed the schema's tables, their corresponding namespace #s changed as well thus causing this problem to manifest itself. Having said that, I fixed it up to be flexible should the schema tables' namespace #s change again.
Problem solved. Now I got to fix up a few of those. :)
Thanks all for your help.

SqlException: Syntax Error Near 'GO'

I am having trouble sending a SQL statement through a DbContext using context.Database.ExecuteSqlCommand().
I am trying to execute
CREATE TABLE Phones([Id] [uniqueidentifier] NOT NULL PRIMARY KEY,
[Number] [int],[PhoneTypeId] [int])
GO
ALTER TABLE [dbo].[Phones] ADD CONSTRAINT [DF_Phones_Id]
DEFAULT (newid()) FOR [Id]
GO
This fails with the error string
Incorrect syntax near the keyword 'ALTER'.
Incorrect syntax near 'GO'.
However running that exact statement in SSMS runs without errors? Any issues I need to resolve regarding the default constraint throught the DbContext. I have see problems with people using constraints and not having IsDbGenerated set to true. I am not sure how that would apply here though.
GO is not a part of SQL, so it can't be executed with ExecuteSqlCommand(). Think of GO as a way to separate batches when using Management Studio or the command-line tools. Instead, just remove the GO statements and you should be fine. If you run into errors because you need to run your commands in separate batches, just call ExecuteSqlCommand() once for each batch you want to run.
I know, necroposting is bad maner, but may be this post would save someone's time. As it was mentioned in Dave's post, GO is not a part of SQL, so we can create little workaround to make it work
var text = System.IO.File.ReadAllText("initialization.sql");
var parts = text.Split(new string[] { "GO" }, System.StringSplitOptions.None);
foreach (var part in parts) { context.Database.ExecuteSqlCommand(part); }
context.SaveChanges();
In this case your commands would be splitted and executed without problems
Dave Markle beat me to it. In fact, you can change "GO" to any other string to separate batches.
An alternative implementation here is to use SMO instead of the Entity Framework. There is a useful method there called ExecuteNonQuery that I think will make your life a lot simpler. Here is a good implementation example.

How to change update statement before executing: Linq2Sql Classes

I have implemented Change Tracking (http://msdn.microsoft.com/en-us/library/cc280462.aspx) on some tables I am using Linq2Sql on.
As a part of this I need to add the below SQL to the start of the update statements generated.
DECLARE #originator_id varbinary(128);
SET #originator_id = CAST('SyncService' AS varbinary(128));
WITH CHANGE_TRACKING_CONTEXT (#originator_id)
....generated statements....
....
....
I know I can create stored procedures and manually map the fiels but I would like to avoid this if possible.
does anyone know a way to override and edit the SQL on SubmitChanges()?
You can override the Update method by implementing partial classes on your datacontext that LINQ to SQL will call instead. Just give it the signature:
partial void UpdateClassName(ClassName instance)
You can also pass through to what it would normally do using:
ExecuteDynamicInsert(instance);
Unfortunately there is no mechanism just to get the intended SQL back for inserts/update/deletes (you can get SELECT statements with GetCommand on the DataContext)

Linq to SQL null values in GridView

Normally if I'm linking an ObjectDataSource to a GridView and I have a TemplateColumn that has an Eval in it and it's Null, I can just put a ".ToString()" it works fine. For some reason, this doesn't work the same when you're using Linq to SQL.
I originally was using XSD files for my DAL with a custom BLL. I tied it to the GridView with an ObjectDataSource. I'm in the middle of swapping out the XSD files with Linq to SQL and everything is working just like the old way except for the columns that can have Null values.
Has anyone run into this before and if so, how do I work around this problem?
Most everything that LINQ returns is of Nullable types. So in your binding expressions you need to use GetValueOrDefault().ToString() or the new "??" null coalescing operator rather than just plain old ToString(). I hope this helps. Check this link out to.
Example:
// this will output the int if not null otherwise an empty string.
<%# (int?)Eval("MyIntegerField") ?? "" %>