I want to read my connection strings from the Web.config or App.Config file. I attempted to follow the advice in another Stackoverflow post.
The suggestion was to:
Set Application Settings in the Linq to Sql DBML file to false. (Double-click on the Linq to Sql file to open it, right-click on white space in the designer surface, select Properties, expand Connection property. )
Set Connection to (None) in the Linq to SQL DBML file.
Add an OnCreated event method in the data context partial class to read the connection string from web.config or app.config.
When I make the above changes and attempt to compile my code I get:
Error 2 Expression of type 'Object' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider.
The error occurs on the 2nd line below:
Using DcObj = New HMR_LinqToSql_QuestionDataContext()
Dim Query = From Q In DcObj.tblQuestions Select Q ' *** Error on this line
Count = Query.Count()
DcObj.tblQuestions.DeleteAllOnSubmit(Query)
DcObj.SubmitChanges()
End Using
The only way, I found, to clear the error is to set Application Settings to True and select a connection string entry in the Connection drop down list. If I revert to Application Settings = True that mean there is still connection strings in the Linq to Sql files.
Any ideas for a solution?
Ed
Related
I have to load the daily csv file from a network location which has the date time stamp with minute and second when it gets exported from api and saved to a network location.
I am trying to make my package dynamic so it does not change when the file name changes every other day. I have tried using an expression in the flat file manager connection properties but that not working either.
My file name looks like following:
DS_All_users_with_additional_fields_2018_12_11_10_00.csv
which i have tried to solve my using the following expression but things gets complicated if there is delay in the csv export and the minute and second changes in the file name:
#[User::DataLoadDir]+"DS_All_users_with_additional_fields_"+(DT_STR,4,1252)YEAR( DATEADD( "dd", -1, getdate() ))+"_"+(DT_STR,4,1252)MONTH( DATEADD( "dd", -1, getdate() ))+"_"+(DT_STR,4,1252)DAY( DATEADD( "dd", 0, getdate() ))+"_10_00.csv"
Any suggestions how to solve this problem?
You can use a foreach loop file enumerator and apply a filespec expression of:
DS_All_users_with_additional_fields*.csv
The * servers as a wild card and will pick up all files matching that string. You can work with this in order to make it flexible based off your needs. In this case, the job will scan for all files that are available in a specific folder that matches the above string. This can then be assigned to a variable, which you can use to dynamically set the connection string.
I don't think you can add the * into the connection string itself.
Update
To set a connection manager's connection string property, see the photo below. It is import to note that this solution will change the work flow. Your initial work flow was telling the connection manager what file to specifically look for. However, by implementing a foreach loop, the job is now searching for any and all files that are available in a specific folder path. Note: you will need to make sure that you include the fully qualified domain name (FQDN) in the connection string variable (i.e., \\networkpath\filename.csv)
Are the files that you need to import the only files in that directory with a name that starts with DS_All_users_with_additional_fields_? If so, use a Script Task to find the most recent one and set the variable used in the connection string to this name. The following example uses LINQ to look for files that begin with the name you listed, then sorts them by the date they were created on, and returns the name of the first one. The Name property below will include the extension. You can also get the complete file path by changing this to the FullName property, in which case you could just use this value for the variable used by the flat file connection string, as opposed to concatenating it with the #[User::DataLoadDir] variable. This example does reference System.IO and System.Linq as specified below.
using System.IO;
using System.Linq;
string filePath = Dts.Variables["User::DataLoadDir"].Value.ToString();
DirectoryInfo di = new DirectoryInfo(filePath);
FileInfo mostRecentFile = (from f in di.GetFiles().Where(x =>
x.Name.StartsWith("DS_All_users_with_additional_fields_"))
orderby f.CreationTime descending
select f).First();
//The Name property below can be changed to FullName to get the complete file path
Dts.Variables["User::VariableHoldingFileName"].Value = mostRecentFile.Name;
I have created f# solution and added one class library. Only one project in the solution and 5 files and 20 lines of code in each file. Still it will take more 2 minutes to build each time.
I have tried to clean solution.
Also created new solution and project and includes same files, still it will take same time to build it.
Note : First I have created it as a Console Application then convert it into the Class Library.
Edit: Code Sample `
open System
open Configuration
open DBUtil
open Definitions
module DBAccess =
let GetSeq (sql: string) =
let db = dbSchema.GetDataContext(connectionString)
db.DataContext.CommandTimeout <- 0
(db.DataContext.ExecuteQuery(sql,""))
let GetEmployeeByID (id: EMP_PersonalEmpID) =
GetSeq (String.Format("EXEC [EMP_GetEntityById] {0}",id.EmployeeID)) |> Seq.toList<EMP_PersonalOutput>
let GetEmployeeListByIDs (id : Emp_PersonalInput) =
GetSeq (String.Format("EXEC [EMP_GetEntityById] {0}",id.EmployeeID)) |> Seq.toList<EMP_PersonalOutput>`
configuration code snippets : `open Microsoft.FSharp.Data.TypeProviders
module Configuration =
let connectionString = System.Configuration.ConfigurationManager.ConnectionStrings.["EmpPersonal"].ConnectionString
//for database,then stored procedure, the getting the context,then taking the employee table
type dbSchema = SqlDataConnection<"", "EmpPersonal">
//let db = dbSchema.GetDataContext(connectionString)
type tbEmpPersonal = dbSchema.ServiceTypes.EMP_Personal`
Okay, seeing your actual code, I think the main problem is that the type provider connects to the database every time to retrieve the schema. The way to fix this is to cache the schema in a dbml file.
type dbSchema = SqlDataConnection<"connection string...",
LocalSchemaFile = "myDb.dbml",
ForceUpdate = false>
The first time, the TP will connect to the database as usual, but it will also write the schema to myDb.dbml. On subsequent compiles, it will load the schema from myDb.dbml instead of connecting to the database.
Of course, this caching means that changes to the database are not reflected in the types. So every time you need to reload the schema from the database, you can set ForceUpdate to true, do a compile (which will connect to the db), and set it back to false to use the updated myDb.dbml.
Edit: you can even commit the dbml file to your source repository if you want. This will have the additional benefit to allow collaborators who don't have access to a development version of the database to compile the solution anyway.
This answer about NGEN helped me once, but the build time of F# is still terrible compared to C#, just not minutes.
I really appreciate any insight anyone can provide.
I've come back to a project that was using the EF6.0 rc preview. After updating the projects EF to 6.1 and updating the SQL Server CE I have two problems.
[UPDATE]
Problems 1 & 2 solved Problem 3 is not.
PROBLEM 3 -
Now with the path set via a connection string as explained above, migrations called via the package manager are not working as its an invalid path. Any ideas anyone?
When I start up the debug process, I get problem 1 and the exceptions crash; but it does create a .sdf file although in the wrong location as explained in problem 2.
1. NOT MAPPED PROPERTY AND UNSUPPORTED BY LINQ ERROR
During the initial creation process I get an exception
List<Equipment> duplicateTags = db.EquipmentReg
.GroupBy(e => e.TagAndLocation)
.Where(g => g.Count() > 1)
.SelectMany(g => g).ToList<Equipment>();
The exception is related to the TagAndLocation. TagAndLocation is defined in the model by
/// <summary>
/// Creates concatenation object that will not be mapped in the database but will be in the
/// Object Relational Mapping (ORM) of the EF model.
/// </summary>
[NotMapped]
public string TagAndLocation { get { return Tag + " (" + Location.Name + ")"; } }
A first chance exception of type 'System.NotSupportedException' occurred in EntityFramework.dll
Additional information: The specified type member 'TagAndLocation' is
not supported in LINQ to Entities. Only initializers, entity members,
and entity navigation properties are supported.
Why is this happening now?
2. CONNECTION STRING NOT APPLYING LOCATION
My connection isn't applying the path properly anymore.
I have it being done by a DbConfiguration class which auto runs, I guess due to its inherited class type. As shown below
class HAIDbJob_EFConfiguration : DbConfiguration
{
public HAIDbJob_EFConfiguration()
{
SetProviderServices(SqlCeProviderServices.ProviderInvariantName, SqlCeProviderServices.Instance);
// Create the connection string programmatically - Setting the filename and path.
SetDefaultConnectionFactory(new System.Data.Entity.Infrastructure.SqlCeConnectionFactory(
"System.Data.SqlServerCe.4.0",
System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Databases"),
#"Data Source=" + System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Databases") +
#"\Hazardous_Area_Database_Job.sdf"));
}
}
Instead of creating a file in the runtime location ...\bin\Debug\Databases\Hazardous_Area_Database_Job.sdf, it creates it at
..\bin\Debug\HA_Inspector.HAI_Database.HAI_Job_EF_Model.Hazardous_Area_Database_Job.sdf
Which is the full namespace of the database model... I have tried a few solutions found for other people problems of a slightly different nature, but none of it works. Any ideas would be extremely appreciate.
1: The EF provider attempt to translate TagAndLocation to SQL and fails. You must use LINQ to Objects for this grouping.
2: Why not have a named connectionstring in your app.config, or pass it in the DbContext constructor.
SOLUTION 1
I did a string compare in the group by statement since location has a string member Location.Name.
SOLUTION 2
When I originally wrote this I wanted to dynamically name the database all the time and this is why I wrote the initialiser class.
To get around the problem, I just followed Erik's advice and put a XAML connection string in app.config using "Source=./Databases"..... to get the subfolder.
I am debugging a website built on the WebForms model, using ASP, C# as codebehind, and SQL Express 2008 R2. I am trying to debug a page that uses an ASPxGridView, which is populated from the .aspx file, and the dataset is uses is created there as well. The data is selected using
SelectCommand="SELECT MachineID, ProgramNo, (CONVERT (VARCHAR(19), Start, 120)) as Start,(CONVERT (VARCHAR(12), Stop,114)) as StopTime, WorkCount, PartCount as TotalWorkCount,(CONVERT (VARCHAR(12), Stop-start,114)) as PartCycle FROM Program WHERE (MachineID = #MachineID) AND (WorkCount > 0) AND (CONVERT (VARCHAR(19), Start, 120) >= #StartDate) AND (CONVERT (VARCHAR(10), Start, 120) <= #EndDate) order by Start Desc">
The problem is that most users can login and the page works perfectly, but a few users see the following error in the web browser:
A field or property with name 'PartCycle' was not found in the selected data source. Possible causes of this error may be the following: an incorrect or case-insensitive spelling of the grid column name; assigning a wrong or not properly initialized data source to the grid.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: A field or property with name 'PartCycle' was not found in the selected data source. Possible causes of this error may be the following: an incorrect or case-insensitive spelling of the grid column name; assigning a wrong or not properly initialized data source to the grid.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[HttpException (0x80004005): A field or property with name 'PartCycle' was not found in the selected data source. Possible causes of this error may be the following: an incorrect or case-insensitive spelling of the grid column name; assigning a wrong or not properly initialized data source to the grid.]
DevExpress.Web.Data.WebDataControllerProvider.GetRowValueByControllerRow(Int32 controllerRow, String fieldName, Boolean isDesignTime) +300
DevExpress.Web.Data.WebDataControllerProvider.GetRowValue(Int32 visibleIndex, String fieldName, Boolean isDesignTime) +203
DevExpress.Web.Data.WebDataProxy.GetRowValue(Int32 visibleIndex, String fieldName) +77
As you can see, PartCycle is not a column in the tables, but is used as an alias for (CONVERT (VARCHAR(12), Stop-start,114)). To put a twist in the plot, I can view the problem data just fine when I am logged into the site as an Administrator. The users who see this error have various ASPNET Roles, but each have access to the data in the tables selected.
Its because ASPxGridView Caches the Columns.
In your case, your datasource is dynamic i.e. different for different users.
Make sure to Clear the Columns before binding ASPxGridView.
To Clear the Columns:
agvObject.Columns.Clear();
I want to notify the user of the macro if something went wrong during the execution of the macro. I was wondering if it would be possible to add an item to the Visual Studio error list?
It is possible to do so from within an AddIn (like here), but I would like to do the same thing from a macro.
Edit
To further clarify what i want to achive, here is the sample from the Samples macro library (Alt+F8 -> Samples -> Utilities -> SaveView())
Sub SaveView()
Dim name As String
name = InputBox("Enter the name you want to save as:", "Save window layout")
If (name = "") Then
MsgBox("Empty string, enter a valid name.")
Else
DTE.WindowConfigurations.Add(name)
End If
End Sub
Instead of the MsgBox("...") alert I want to put the error into the VS error list.
You can add an item in the Task List easily from your macro. Just use the AddTaskToList method from that article and change m_objDTE to DTE. I've tried it and it worked.
However, adding the item in Error List, is probably impossible. You need to call VS services, see how adding an error is done in an add-in. I created a macro from this code and it didn't work. In general, VS services don't work in macros. I was able to create ErrorListProvider successfully. I could access it's methods and properties. But calling ErrorListProvider.Task.Add caused COM exception. If you want to play with it, several notes:
As described in the article, you need to get 4 assemblies out of the GAC e.g. to c:\dlls\ directory. Since Macros IDE doesn't allow you to browse when you Add Reference, you need to copy these dlls into ...\Microsoft Visual Studio 10.0\Common7\IDE\PublicAssemblies directory (change the 10.0 to your VS version). Then, when you Add Reference in Macros IDE, you should see the assemblies.
The GetService function always returned Nothing. Add the following field to the class:
Private serviceProvider As IServiceProvider = New Microsoft.VisualStudio.Shell.ServiceProvider(CType(DTE, Microsoft.VisualStudio.OLE.Interop.IServiceProvider))
and in GetService function change line:
objService = Microsoft.VisualStudio.Shell.Package.GetGlobalService(serviceType)
to
objService = serviceProvider.GetService(serviceType)
As I wrote, everything seems OK then but ErrorListProvider.Task.Add fails.
I think that for your situation outputting something to your own output pane would be more suitable. The error list is generally used for errors within the project the user is working on, not for errors caused by running macros. Especially when someone says it can't be done. :)
Outputting to your own output pane is pretty easy:
DTE.Windows.Item(Constants.vsWindowKindOutput).Activate()
Dim panes As OutputWindowPanes = window.OutputWindowPanes
Dim my_pane As OutputWindowPane
Try
my_pane = panes.Item("SaveView")
Catch exception As System.ArgumentException
my_pane = panes.Add("SaveView")
End Try
my_pane.Activate()
my_pane.OutputString("Empty string, enter a valid name." + vbCrLf)
Hope this helps.
Cheers,
Sebastiaan
Is this not what you want?
HOWTO: Add an error with navigation to the Error List from a Visual Studio add-in
http://www.mztools.com/articles/2008/MZ2008022.aspx