Add Subsonic 3.0.0.4 in Visual Studio 2010 - visual-studio-2010

I've created a console application focused on C#3.5 and added a reference to System.Web, System.Configuration and Subsonic.Core. Also have in config file
<?xml version="1.0"?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="UpdateCotswolds.Properties.Settings.Live_IntegraConnectionString" connectionString="Data Source=POSERVER;Initial Catalog=Live_Integra;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
<startup><supportedRuntime version="v2.0.50727"/></startup></configuration>
I've then edited Settings.ttinclude
const string Namespace = "Integra.Data";
const string ConnectionStringName = "UpdateCotswolds.Properties.Settings.Live_IntegraConnectionString";
//This is the name of your database and is used in naming
//the repository. By default we set it to the connection string name
const string DatabaseName = "Live_Integra";
And dragged in the tt files.
When they run I'm getting the error...
Error 2 Running transformation: System.InvalidOperationException: Sequence contains more than one matching element
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
at Microsoft.VisualStudio.TextTemplating47D0892A160210D689C6B90986A9AE0D.GeneratedTextTransformation.LoadTables() in c:\Programming\UpdateCotswolds\UpdateCotswolds\SQLServer.ttinclude:line 134
at Microsoft.VisualStudio.TextTemplating47D0892A160210D689C6B90986A9AE0D.GeneratedTextTransformation.TransformText() in c:\Programming\UpdateCotswolds\UpdateCotswolds\ActiveRecord.tt:line 23
at Microsoft.VisualStudio.TextTemplating.TransformationRunner.RunTransformation(TemplateProcessingSession session, String source, ITextTemplatingEngineHost host, String& result)
This is the line in question...
var pkColumn=tbl.Columns.SingleOrDefault(x=>x.Name.ToLower().Trim()==tbl.PrimaryKey.ToLower().Trim());
I'm guessing I'm making a silly mistake and hopefully someone can set me straight...
Thanks in advance...

It appears that a certain table has more than one primary key? Can you post your schema up?
Or maybe your PK and FK are names the exact same and SS is getting confused.
Maybe you can play around with the string[] ExcludeTables = new string[]{}; property found under "Settings.ttinclude" until it works and provide the schema for that one table.

Related

using variables in DBUnit load file

Is there a way that i can use variables in my load file in DBUnit so that I can populate dynamic data at runtime
e.g.
<Employee id="var" , name="emp1" />
and I want the var to be something that I can supply.
Sorry if it is a basic questions but I have just started looking at DBUnit on someone's recommendation
I found a solution a couple of days before, you could use ReplacementDataSet. Here is an example(I use it to replace some fields with null)
public static IDataSet flatXml(File file)
throws MalformedURLException, DataSetException {
ReplacementDataSet dataSet = new ReplacementDataSet(
new FlatXmlDataSetBuilder().build(file));
dataSet.addReplacementObject("[NULL]", null);
return dataSet;
}
<dataset>
<T_F2G_PENDING_ORDER
TRACKING_ID="2"
DELIVERY_TIME="2013-04-01 13:44:00"
DELIVERY_ADDRESS_STREET1="North Che Zhan Road"
DELIVERY_ADDRESS_STREET2="Kui Zhao Road"
RESTAURANT_ID="[NULL]" />
</dataset>
Hope this helps.

MVC 4 template with custom membership provider

What I'm wanting to do is use the default MVC 4 template that just shipped with Visual Studio 2012 as base for my new project. However I want to replace the SQL provider with custom membership provider so I can access my RavenDB to get my users. I've implemented the custom provider as I have before but the WebSecurity methods are throwing the following exception.
This line of code:
ViewBag.HasLocalPassword =
OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
Specifically the method:
WebSecurity.GetUserId
Is throwing this exception:
You must call the "WebSecurity.InitializeDatabaseConnection" method
before you call any other method of the "WebSecurity" class. This call
should be placed in an _AppStart.cshtml file in the root of your site.
Now I cannot call InitializeDatabaseConnection because my provider isn't a SQL provider. This method expects a SQL provider and a SQL connection string. Is this a common problem or am I missing something? Why does WebSecurity have to be initialized and why does it expect to only be connected using a SQL provider?
Am I going to have to just change the code to not use the WebSecurity class?
I've been at this all day and I'm pretty tired. I hope I haven't overlooked something simple. Maybe one more rum and coke will help...
Update: 08/19/2012
I decompiled the GetUserId method and found the only reason it's failing is because of the VerifyProvider call.
public static int GetUserId(string userName)
{
WebSecurity.VerifyProvider();
MembershipUser user = Membership.GetUser(userName);
if (user == null)
return -1;
else
return (int) user.ProviderUserKey;
}
private static ExtendedMembershipProvider VerifyProvider()
{
ExtendedMembershipProvider membershipProvider = Membership.Provider as ExtendedMembershipProvider;
if (membershipProvider == null)
throw new InvalidOperationException(WebDataResources.Security_NoExtendedMembershipProvider);
membershipProvider.VerifyInitialized();
return membershipProvider;
}
Now the only reason it's failing in the VerifyProvider method is because of the call to VerifyInitialized which I cannot override in my membership provider. Also if it's not calling my provider then I'm not sure what code is being called when VerifyInitialized is processed.
internal virtual void VerifyInitialized()
{
}
I'm removing all the other membership providers in the Web.Config. At least I think I am. Here is the entry.
<membership defaultProvider="RavenMembershipProvider">
<providers>
<clear />
<add name="RavenMembershipProvider" type="BigGunsGym.Infrastructure.Providers.RavenMembershipProvider" />
</providers>
</membership>
Turns out I had my provider inheriting from SimpleMembershipProvider instead of ExtendedMembershipProvider. I thought it would be OK since SimpleMembershipProvider inherits ExtendedMembershipProvider but it did not work.
After changing my provider to inherit from ExtendedMembershipProvider the error went away.
I also had the same problem, after creating a new Action to create users....
action was...
public ActionResult CreateUsers()
{
string username = "blah blah auto create";
string password = "blah blah auto create";
WebSecurity.CreateUserAndAccount(username, password);
}
but it just needed the filter attrib adding
[InitializeSimpleMembership]
public ActionResult CreateUsers()
{
string username = "blah blah auto create";
string password = "blah blah auto create";
WebSecurity.CreateUserAndAccount(username, password);
}

Removing headers from the response

I need to cloak certain headers generated by ASP.NET and IIS and returned in the responses from a ASP.NET WebAPI service. The headers I need to cloak are:
Server
X-AspNet-Version
X-AspNetMvc-Version
X-Powered-By
The service was earlier hosted in WCF, and the cloaking was done in an HttpModule by subscribing to PreSendRequestHeaders and manipulating HttpContext.Current.Response.Headers. With ASP.NET WebAPI everything is now task based, so HttpContext.Current is null. I tried to insert a message handler and manipulate the returned HttpResponseMessage, but the headers were not present on that stage. X-Powered-By can be removed in the IIS settings, but what is the suggested way to remove the rest of them?
The problem is each one is added at a different point:
Server: added by IIS. Not exactly sure if it can be turned off although you seem to have been to remove it using HttpModule .
X-AspNet-Version: added by System.Web.dll at the time of Flush in HttpResponse class
X-AspNetMvc-Version: Added by MvcHandler in System.Web.dll. It can be overridden so this one should be OK.
X-Powered-By by IIS but can be turned off as you said.
I think your best bet is still using HttpModules.
For the benefit of those who land here through a google/bing search::
Here's the summary of steps:
Step 1: Create a class that derives from IHttpModule (and IDisposable to clean up when we're done):
public class MyCustomModule : IHttpModule, IDisposable
{
private HttpApplication _httpApplication
private static readonly List<string> HeadersToCloak = new List<string>
{
"Server",
"X-AspNet-Version",
"X-AspNetMvc-Version",
"X-Powered-By"
};
..
}
Step 2: Get a reference to the intrinsic context in the IHttpModule.Init method, and assign an event handler to the PreSendRequestHeaders event:
public void Init(HttpApplication context)
{
_httpApplication = context;
context.PreSendRequestHeaders += OnPreSendRequestHeaders;
}
Step 3: Now the headers can be removed like so:
private void OnPreSendRequestHeaders(object sender, EventArgs e)
{
if (null == _httpApplication)
{
return;
}
if (_httpApplication.Context != null)
{
var response = _httpApplication.Response;
HeadersToCloak.ForEach(header => response.Headers.Remove(header));
}
}
Step 4: Now register this module in your root web.config under the system.webserver (if running IIS 7.0 integrated mode more details here):
<configuration>
<system.webServer>
<modules>
<add name="MyCustomModule" type="<namespace>.MyCustomModule "/>
</modules>
</system.webServer>
</configuration>
Hope this helps!
If you're using IIS7 / Azure then have a look at this:
Removing/Hiding/Disabling excessive HTTP response headers in Azure/IIS7 without UrlScan
It shows the best way to disable these headers without using HttpModules.
if you like to remove version go to web.config file
and add these lines
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<!--enableVersionHeader remove the header-->
<httpRuntime targetFramework="4.5.2" enableVersionHeader = "false"/>
also, add these
<httpProtocol>
<customHeaders>
<!--enableVersionHeader remove the header-->
<remove name ="X-Powered-By"/>
</customHeaders>
</httpProtocol>

How to edit the ApplicationSettings section of app.config in WPF application

I have been researching this issue for long. But I haven't come across any satisfying solution.
The scenario is that I have a WPF client application. I have a couple of web references added to the project and I Settings.Designer.cs file was modified and had a hard coded reference to the srever url and port. This started getting reflected in my app.config file in ApplicationSettings section.
Before the user logs in, he can specify the settings for the ServerIP and Port for the server. Now I would like to save these settings in app.config and get the value for server IP and port picked up from there or save it elsewhere and connect to the server through this IP and Port. I would like these changes to persist.
One solution that I could think of was to read the app.config through an XML reader, modify the file, save it and restart the application somehow.
I am not able to think of a better scenario as I think ApplicationSettings section can not be modified from inside the application.
EDIT:
My applicationSettiings section looks something like this:
<applicationSettings>
<ApplicationName.Properties.Settings>
<setting name="Web_Service_Reference_Name1" serializeAs="String">
<value>http://10.1.100.118:8080/AD/WebService1</value>
</setting>
<setting name="Web_Service_Reference_Name2" serializeAs="String">
<value>http://10.1.100.118:8080/AD/WebService2</value>
</setting>
</ApplicationName.Properties.Settings>
</applicationSettings>
Sometimes ago a similar question was posted on this site.
I have a simple solutions that looks like this:
public void WriteLocalValue(string localKey, string curValue)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
KeyValueConfigurationElement k = config.AppSettings.Settings[localKey];
if (k == null)
config.AppSettings.Settings.Add(localKey, curValue);
else
k.Value = curValue;
config.Save();
}
public string ReadLocalValue(string localKey, string defValue)
{
string v = defValue;
try
{
Configuration config = ConfigurationManager.OpenExeConfiguration( Application.ExecutablePath);
KeyValueConfigurationElement k = config.AppSettings.Settings[localKey];
if (k != null) v = (k.Value == null ? defValue : k.Value);
return v;
}
catch { return defValue; }
}

When using MVC3 + SQL CE I get 404 on all pages with scaffolding against the SQL CE Database

The problem only occurs on a server with Windows 2008 Server, locally I run the application and have no issues. I've used the "bin deploy" and "Add Deployable Dependencies..." options and still no luck. Some more context...
The security settings in IIS are set for Windows Authentication, the web.config has a small exclude of anonymous users (not sure this even makes a difference in this scenario).
<authentication mode="Windows" />
In the Global.asax.cs file I have the standard template generated code.
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("elmah.axd");
routes.IgnoreRoute("{*favicon}", new { favicon = #"(.*/)?favicon.ico(/.*)?" });
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
The only addition I've made is for elmah and the favicon. I'm not sure what else to look at from this point forward, so any help would be appreciated.
Also, my connection string to the SQL CE looks like this:
<add name="BillingLogDbEntities" connectionString="metadata=res://*/Models.BillingLog.csdl|res://*/Models.BillingLog.ssdl|res://*/Models.BillingLog.msl;provider=System.Data.SqlServerCe.4.0;provider connection string="Data Source=|DataDirectory|\BillingLogDb.sdf"" providerName="System.Data.EntityClient" />
<add name="BillingLocalDbEntities" connectionString="metadata=res://*/Models.BillingLocal.csdl|res://*/Models.BillingLocal.ssdl|res://*/Models.BillingLocal.msl;provider=System.Data.SqlServerCe.4.0;provider connection string="Data Source=|DataDirectory|\BillingLocalDb.sdf"" providerName="System.Data.EntityClient" />
<add name="OverlayServicesDbEntities" connectionString="metadata=res://*/Models.OverlayServices.csdl|res://*/Models.OverlayServices.ssdl|res://*/Models.OverlayServices.msl;provider=System.Data.SqlServerCe.4.0;provider connection string="Data Source=|DataDirectory|\OverlayServicesDb.sdf"" providerName="System.Data.EntityClient" />
The solution was a combination of two things:
I needed to set the appropriate permissions on the directory that the SQL Server CE files were located inside of.
The Entity Framework needed regenerated to point a the SQL CE databases again. For some reason the application was actually swallowing the errors that were simply a "couldn't connect to the X database" Something in some of the generated code had gotten out of sync.

Resources