The next code runs normally in SQLSERVER but when i change the web.config to runs with mySQL after the loadbykey the connection is closed.
is there any configuration to make in MYSQL to change that ???
thanks any help !!!
//-----------------------------------------------------------
string tipoBanco = System.Configuration.ConfigurationManager.AppSettings["tipoBanco"];
string conexao = System.Configuration.ConfigurationManager.ConnectionStrings[tipoBanco].ToString();
using (SharedDbConnectionScope scope = new SharedDbConnectionScope(conexao))
{
//-----------------------------------------------------------
using (TransactionScope ts = new TransactionScope())
{
Cargo c = new Cargo();
c.LoadByKey(9999);
SubSonic.StoredProcedure sp = null;
sp = new SubSonic.StoredProcedure("sp_test");
sp.Command.AddParameter("paramTabela", "zzz", DbType.AnsiStringFixedLength, null, null);
Convert.ToInt32(sp.ExecuteScalar());
}
}
the web.config
<SubSonicService defaultProvider="mysql" enableTrace="false" templateDirectory="">
<providers>
<clear/>
<add name="mysql" type="SubSonic.MySqlDataProvider, SubSonic"
regexDictionaryReplace="Empresaendereco,EmpresaEndereco;Empresacontato,EmpresaContato;Franqueadoendereco,FranqueadoEndereco;Franqueadocontato,FranqueadoContato;Funcionarioacesso,FuncionarioAcesso;Funcionarioendereco,FuncionarioEndereco;Funcionariocontato,FuncionarioContato;Clienteendereco,ClienteEndereco;Clientecontato,ClienteContato;Clientehistorico,ClienteHistorico;Agendastatus,AgendaStatus;Historicostatus,HistoricoStatus"
fixDatabaseObjectCasing="true" connectionStringName="mysql"
generateRelatedTablesAsProperties="true"
fixPluralClassNames="false"
generatedNamespace="ModeloDados"
regexIgnoreCase="true"
removeUnderscores="false"
setPropertyDefaultsFromDatabase="true"
generateNullableProperties="true"
useExtendedProperties="true"
useUtc="true" />
</providers>
</SubSonicService>
I think your TransactionScope() and SharedDbConnectionScope() are the wrong way round. You have them in the order they were listed in the docs on the SubSonic web site, but there was a discussion on the old SubSonic forum that implied they should be the other way round.
Certainly I use them reversed (I have just posted an extract of my code to another answer on here), but I have to say I only use MSSQL ATM, and can't comment on MySQL.
Related
I'm having an issue with an Azure SQL DB (SQL PaaS) connection string in my Azure Web App. It is defined in the "Connection Strings" settings of the Application Config. I see the Conn String value (format below) in https://myAppName.scm.azurewebsites.net/Env.cshtml#connectionStrings. My defined Conn String name is "MyApp" and Azure is prefixing it with "SQLAZURECONNSTR_" as you'd expect.
SQLAZURECONNSTR_MyApp = Server=tcp:mysvr.database.windows.net,1433;Initial Catalog=MyApp;Persist Security Info=False;User ID=user#mysvr;Password=passWord;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
In Startup.cs, I have this though I'm not certain it is necessary.
public void ConfigureServices(IServiceCollection services)
{
[...]
services.AddDbContext<MyAppContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyApp")));
And in my database context class, I have the following:
public partial class MyAppContext : DbContext
{
[...]
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true)
.Build();
var connectionString = configuration.GetConnectionString("MyApp");
optionsBuilder.UseSqlServer(connectionString);
}
}
}
When accessing the web app executing a method that connects to the database, I'm receiving a null reference to the conn string.
ArgumentNullException: Value cannot be null. (Parameter 'connectionString')
Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(string value, string parameterName)
Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuilder, string connectionString, Action<SqlServerDbContextOptionsBuilder> sqlServerOptionsAction)
myapp.Models.MyAppContext.OnConfiguring(DbContextOptionsBuilder optionsBuilder) in MyAppContext.cs
No conn strings are defined in the local .json file, though I'll want to add that back for development purposes at some point.
NEWEST
Code First.
Database Initialization in Entity Framework 6
connectionStr should be like this.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="SchoolDBConnectionString" connectionString="tcp:servername.database.windows.net,1433;Initial Catalog=db; Persist Security Info=False; User ID=user;Password=mypassword; MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
PRIVIOUS
DB First.
Your project use ef core, so the connectionstrings should be like below.
<connectionStrings>
<add name="SchoolDBEntities" connectionString="metadata=res://*/SchoolDB.csdl|res://*/SchoolDB.ssdl|res://*/SchoolDB.msl;provider=System.Data.SqlClient;provider connection string="data source=.\sqlexpress;initial catalog=SchoolDB;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient"/>
</connectionStrings>
For more details, you can refer my answer in the post.
Timeout period elasped prior to obtaining a connection from the pool - Entity Framework
You can also refer to this tutorial, which will help you.
Entity Framework Tutorial
Sometimes I need to delete a duplicate record in CRM that has associations. In these cases I have to reassign these associations. The related entities menu allows me to check, one by one, whether the record has associations in any of the entities to which it is related. This forces me to scan through many related entities. Is there a quicker way to view all associations for a record?
You could make a new record form which shows all the associated record as sub grids on a single page - might save a few clicks.
Few considerations with this approach:
You might end up a very long form.
You might end up a very ugly form.
You might have to click to load sub grids depending on your version of CRM and the number of grids you have displayed (though JavaScript can be used to over come this).
Not through the CRM UI, but if you're a SQL Wizard, you could probably come up with some fancy query to do that. Then you could deploy an SSRS report with click through if you want to take it one step further.
You should also consider the OOB Merge for a scenario like this if you are dealing with OOB records like contacts or accounts - as this will automatically reparent child records for you (granted it will reparent all the child records to the new "master" record, but that is usually the intended functionality, so it works in most cases).
I know this question is old, but I created a console app that will show related GUIDs and logical names of the associated records. Currently doesn't work with Many to Many relationships because it wasn't needed for my application. It could easily be made to show links to records, but it wasn't something I needed.
static void Main(string[] args)
{
IOrganizationService OrganizationService = null;
string sourceBaseUrl = "http://server/org";
OrganizationService = CrmHelpers.GetService(sourceBaseUrl);
//OrganizationService = CrmHelpers.GetService("sock-devcrm2015", "acs-training", "80", "http", "username", "password", "domain");
//query for relationships for the desired record
//need to get GUID and LogicalName
Entity get = new Entity();
Console.WriteLine(string.Format("What is the Logical Name?"));
Console.Write("String: ");
get.LogicalName = Console.ReadLine();
Console.WriteLine(string.Format("What is the GUID?"));
Console.Write("GUID: ");
get.Id = Guid.Parse(Console.ReadLine());
RetrieveEntityRequest retrieveEntity = new RetrieveEntityRequest
{
EntityFilters = EntityFilters.Relationships,
LogicalName = get.LogicalName
};
RetrieveEntityResponse response = (RetrieveEntityResponse)OrganizationService.Execute(retrieveEntity);
var oneToN = response.EntityMetadata.OneToManyRelationships;
var nToOne = response.EntityMetadata.ManyToOneRelationships;
foreach (var relationship in oneToN)
{
string fetch = #"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='" + relationship.ReferencingEntity + #"'>
<filter type='and'>
<condition attribute='" + relationship.ReferencingAttribute + #"' operator='eq' value='" + get.Id.ToString() + #"' />
</filter>
</entity>
</fetch>";
var results = OrganizationService.RetrieveMultiple(new FetchExpression(fetch));
foreach (var result in results.Entities)
{
Console.WriteLine(string.Format("1:N || GUID: {0} LogicalName: {1}", result.Id, result.LogicalName));
}
}
Console.WriteLine("----------------------------------------------------------");
Console.WriteLine("----------------------------------------------------------");
foreach (var relationship in nToOne)
{
string fetch = #"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='" + relationship.ReferencedEntity + #"'>
<link-entity name='"+relationship.ReferencingEntity+ #"' from='"+relationship.ReferencingAttribute+#"' to='"+relationship.ReferencedAttribute+#"' alias='a'>
<filter type='and'>
<condition attribute='" + get.LogicalName+ #"id' operator='eq' value='" + get.Id.ToString() + #"' />
</filter>
</link-entity>
</entity>
</fetch>";
var results = OrganizationService.RetrieveMultiple(new FetchExpression(fetch));
foreach (var result in results.Entities)
{
Console.WriteLine(string.Format("N:1 || GUID: {0} LogicalName: {1}", result.Id, result.LogicalName));
}
}
Console.Write("END");
Console.ReadLine();
}
class CrmHelpers
{
public static IOrganizationService GetService(string baseUrl)
{
ClientCredentials credentials = new ClientCredentials();
credentials.Windows.ClientCredential = CredentialCache.DefaultCredentials.GetCredential(new Uri(baseUrl), "negotiate");
Uri endpoint = new Uri(string.Format("{0}/XRMServices/2011/Organization.svc", baseUrl));
OrganizationServiceProxy service = new OrganizationServiceProxy(endpoint, null, credentials, null);
service.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
return service;
}
}
If you need to reassign all the associations, this would work:
create a new record (same name/title)
merge the 2 records
Select the all the data from "old" record and make the new record the master (The master record will be the new one and inherit all of the subordinate record's child records.
Since the "old" record will be deactivated you need to activate it again
You just cloned a record and the new one will have all the associations from the old one.
All the N:1 relationships can be found by querying the filtered view for your entity in SQL, but the fastest solution is just to use the Merge functionality built into CRM, as suggested. It doesn't delete the dupe, but it deactivates it and assigns everything you specify to the 'master' record. From there, you can delete the deactivated record.
Authentication fails to authenticate for forms authentication in my MVC 5 application. Page gets redirected correctly, but User.Identity.IsAuthenticated and User.Identity.Name values are empty.
My webconfig,
<system.web>
<authentication mode="Forms">
<forms cookieless="UseCookies" defaultUrl="~/" loginUrl="~/user/signin" name="MYAPPWeb" timeout="21600" slidingExpiration="true"/>
</authentication>
UserController,
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult SignIn(SignInViewModel user)
{
UserDTO userObj;
using (var services = new ServiceFactory())
{
userObj = services.UserManagement.ValidateLoginDetails(ConfigHelper.EnvironmentString, user.TenantName, user.Username, user.Password);
}
string userID = userObj.UserID.ToString();
//FormsAuthentication.RedirectFromLoginPage(userID, user.RememberMe);
FormsAuthentication.SetAuthCookie(userID.ToString(),true);
FormsAuthentication.RedirectFromLoginPage(userID, false); //DO NOT REMEMBER ME
}
HomeController (Default page)
public ActionResult Index()
{
bool x = User.Identity.IsAuthenticated; //false?
string y = User.Identity.Name; //null?
return View();
}
It looks pretty straight forward, am I missing something? Please help!
Note:
When I create the project I selected windows authentication. It created some Owin authenticaiton related configuration cs files (startup.auth.cs). I have removed them and added the above appsetting entry as it is required to stop loading Owin assemblies.
<add key="owin:AutomaticAppStartup" value="false"/>
If your project has Owin authentication by default, it will remove form authentication from the project.
If you see your web config you may see
<remove name="FormsAuthentication" />
configuration.
Simply remove it.
I had the same problem and it solved the issue.
I am trying to sort my search results by a custom Umbraco property I have created - let's call it sortDate.
Inside my IndexSet, in config/ExamineIndex.config I have this:
<IndexUserFields>
<add Name="sortDate" EnableSorting="true" Type="DateTime" />
...
In my Search user control, I am constructing a criteria and filter and using them to search like so:
var criteria =
ExamineManager.Instance.SearchProviderCollection["MySearcher"].CreateSearchCriteria(
UmbracoExamine.IndexTypes.Content);
var filter =
criteria.GroupedOr(new string[] { "sortDate", "someThing", "someThingElse", "bodyText" }, SearchTerm.ToLower()).Compile();
var MySearchResults =
ExamineManager.Instance.SearchProviderCollection["MySearcher"].Search(filter).Distinct();
I'm guessing I need to add something to specify how Lucene should sort this on my filter?
This is Umbraco 4.6.1 if that matters :)
OK, not sure how I missed this, but it looks like you can just do:
filter.OrderBy( new string[] { "sortDate" } );
Where can I find a log of login attempts to share point 2007?
Thanks.
PS: I have another question too, I 'd be really grateful if anybody helps me on it:
Sharepoint users are logged out
I haven't been able to find much without a third party tool. Our group is looking into acquiring DocAve by AvePoint.
In the mean time you can at least get an idea in your site analytics area of your site settings dashboard to see how many people have encountered the /_layouts/accessdenied.aspx page. It wont tell you much, but perhaps you can find a way to customize and add a snippet of code that will take a user's ID when they hit that page. Its not perfect, so I'd suggest a 3rd party tool unless you can scan all of your web front ends etc.
We had a similar requirement once, where we needed to log the last visited time of all the users on the site. So after some period of time, say 90 days, if a particular user had not logged into the site, the admin could delete his profile.
We overcame this problem with a very simple approach. You can follow the sample code for your reference.
You would need to create a list in your site by the name "UserLoginDetails" and create a column "LastLogIn" in that. Code is self explanatory.
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Xml.Serialization;
using Microsoft.SharePoint;
namespace Ubaid.WebParts
{
[Guid("883a77d6-271d-4b88-9ca2-d5150a00520b")]
[DefaultProperty("Text"), ToolboxData("<{0}:UserLastVisited runat=server></{0}:UserLastVisited>"), XmlRoot(Namespace = "Ubaid.WebParts")]
public class UserLastVisited : System.Web.UI.WebControls.WebParts.WebPart
{
protected override void CreateChildControls()
{
base.CreateChildControls();
string siteName = SPContext.Current.Web.Url;
using (SPSite site = new SPSite(siteName))
{
SPWeb web = site.OpenWeb();
site.AllowUnsafeUpdates = true;
web.AllowUnsafeUpdates = true;
SPList UserLoginDetailsList = web.Lists["UserLoginDetails"];
SPQuery query = new SPQuery();
string uname = SPContext.Current.Web.CurrentUser.LoginName;
query.Query = "<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + uname + "</Value></Eq></Where>";
SPListItemCollection listItemColl = UserLoginDetailsList.GetItems(query);
if (listItemColl.Count > 0)
{
SPListItem item = listItemColl[0];
item["LastLogIn"] = DateTime.Now.ToLocalTime();
item.Update();
}
else
{
SPListItem item = UserLoginDetailsList.Items.Add();
item["Title"] = uname;
item["LastLogIn"] = DateTime.Now.ToLocalTime();
item.Update();
}
}
}
}
}
You can insert this webpart in your masterpage, as the data in this list needs to be updated on every page load.
Not sure which is the best way to do it / performance issues, but since ours was a small site we could manage with this pretty well.