Quantcast
Channel: ActiveTopics
Viewing all 72689 articles
Browse latest View live

How to code with Umbraco and Razor pages ?

$
0
0

Hi all,

I'm having a hard time understanding the best way to code something clean with Umbraco. By that, I mean that a lot of code is in my templates which is not the cleanest work ever...

For example, my file "department.cshtml" starts with :

@using System.Runtime.InteropServices.JavaScript

@using Umbraco.Cms.Web.Common.PublishedModels; @inherits Umbraco.Cms.Web.Common.Views.UmbracoViewPage @{ Layout = "master.cshtml"; ViewBag.Title = Model.Value("title");

IPublishedContent? mediaItem = Model.Value<IPublishedContent>("planImage");
string imageUrl = null;
if (mediaItem != null)
{
    imageUrl = mediaItem.Url();
}

string? modelGuid = Model.Key.ToString();

IPublishedContent? team = Umbraco
    .Content(Guid.Parse(modelGuid))?
    .ChildrenOfType("people")?
    .FirstOrDefault(x => x.IsVisible());
string? teamGuid = team?.Key.ToString();
IEnumerable<IPublishedContent>? teamMembers = null;
IEnumerable<IPublishedContent>? managers = null;

if (teamGuid != null) {
    teamMembers = Umbraco.Content(Guid.Parse(teamGuid))?
        .ChildrenOfType("person")?
        .Where(x => x.IsVisible())
        .Where(x => x.Value("manager")?.ToString() == "False")
        .OrderBy(x => x.Value("lastName"));

    managers = Umbraco.Content(Guid.Parse(teamGuid))?
        .ChildrenOfType("person")?
        .Where(x => x.IsVisible())
        .Where(x => x.Value("manager")?.ToString() == "True")
        .OrderBy(x => x.Value("lastName"));
}

All this code would normally go to the file code-behind "department.cs" attached to my Razor page. But, if I try to use this way, I can't use some code for Umbraco like :

Umbraco
    .Content(Guid.Parse(modelGuid))?
    .ChildrenOfType("people")?
    .FirstOrDefault(x => x.IsVisible());

How can I do this ?

Thank you all in advance for your time and patience.

Disclaimer : I'm a baby dev currently doing her first project ever, sorry if all of this sounds stupid, I'm learning. ☺


Banner links on site tab fall off after upgrade

$
0
0

Just upgraded to 7.6.3 on the way to 14

Two things seem to have happened. First, the banner links listed on the home page vanished. Second, the css files don't load.

If I try to open an external link to another page, I get the message

String "26874" is not a valid udi.

Runs on line 6 of NavPage.cshtml

var relatedMedia = CurrentPage.relatedMedia;

In dashboard, the link is exactly correct, but when I preview it, I get a 404 error.

This makes me think the links have actually been changed to new values, which don't match what is in the system.

Umbraco treating certain file types differently

$
0
0

Hello,

I'm running Umbraco 13, and in my wwwroot folder I have 2 files, MyProgram.exe and MyImage.iso. If I try to navigate to ~/MyProgram.exe, it triggers a download, which is what I want. When trying to navigate to the ISO however, it throws a 404 page.

I have both of these mimeMaps configured the same in web.config and IIS, so I'm very confused as to why EXE works, but not ISO.

Is there some setting for types in the backoffice? Is it some implicit thing from Umbraco?

Any pointers are greatly appreciated!

Loop through the Multi node Tree Picker and also loop through a different Doc Type to display the data

$
0
0

I can successfully render content from a different Doc Type using x.ContentType.Alias == "cases", however, I also want the ability to use the Multinode Tree Picker so the editor can reorder the results. Inside of my cases Doc Type I have a text field for pageTitle.

At the moment, my foreach renders the results twice as it looks through the Tree Picker, sees there are two items and then also loops through the foreach() for the .Alias where there are two published items.

I thought a way around this would be to add an extra Where() and compare it to the Name() of the item in typedMultiNodeTreePicker but I get an error:

Operator '==' cannot be applied to operands of type 'method group' and 'string'

Any ideas on how I can do this?

Full code:

@{
var typedMultiNodeTreePicker = Model.Value<IEnumerable<IPublishedContent>>("caseStudies");
if (typedMultiNodeTreePicker != null)
{
    foreach (var item in typedMultiNodeTreePicker)
    {

        <a href="@item.Url()" style="font-size:30px;">

            @item.Name()

            @{

                var works = Model.Children().Where(x => x.ContentType.Alias == "cases" && x.ContentType.Name == item.Name());

                foreach (var work in works)
                {
                    @work.Value("pageTitle")

                    <br>

                }

            }

        </a>

        }
      }
}

Thanks

How to Integrate Data from External SQL Database

$
0
0

I have a blocklist component cProductGrid. cProductGrid lists all children of the Products node in a 4-column grid.

I have an external SQL database that has the price for each of those products.

What I need to be able to do is display the price of each product from the external SQL database in my cProductGrid.

But, I'm struggling to wrap my head around how that would work. I could probably figure it out client side with some ajax, but I was hoping to be able to accomplish this server side.

Any suggestions?

get_ContentSchedule not found after umbraco upgrade

$
0
0

Hi, I have a umbrao 9.4.1 project, that has been updated to 10.5.1.

I did the upgrade, and pushed to to our test-server, which is a windows 10 machine running the project in IIS.

It was then pushed to the production server, which is the same setup.

But now, in production, whenever anyone tries to save or publish anything, I get this error:

One or more errors occurred. (Method not found: 'Umbraco.Cms.Core.Models.ContentScheduleCollection Umbraco.Cms.Core.Models.IContent.get_ContentSchedule()'.)

and when I look in the log, inside umbraco backoffice, it looks like the item actually has been published:

Document "title of content" (id=1625) cultures: "da" have been published.

But it has'nt, no changes have been made. Nothing has happened.

I then tried taking the entire production package, and cloning it on my test server, here it runs fine.

Can someone hint to me, or have a good idea what to look into?

Why would it all of a sudden not be able to find methods inside the umbraco DLL's on one server, but not on another?

Include username in member index

$
0
0

Hi All,

We have a unique requirement where we need the member "username" field added to the members index.

Would anyone know how to achive this?

We alredy have a custom index config where we specify the include fields as per below. I've tried many different varisation of username to include the value however none seem to be correct, any advice much appreciated!

IValueSetValidator IUmbracoIndexConfig.GetMemberValueSetValidator()
{
    var includeFields = new[] {
        "Username",
        "userName",
        "UserName",
        "username",
        "umbracoMember",
        "umbracoMemberUser",
        "umbracoMemberUsername",
        "umbracoMemberUserName",
        "login",
        IndexConstants.Id,
        IndexConstants.NodeName,
        IndexConstants.CreateDate,
        IndexConstants.Email,
        ... the list goes on

Thanks!

Migrating to Azure

$
0
0

Greatings,

I have had a hosting account at a company for a number of years and have hosted my umbraco sites, there..but sometimes when I deploy my sites to the server I have issues, strange umbraco errors, and some times I have to restart my app pool.. etc etc to get it working.

So the other day I tried Windows Azure, directly from Visual Studio I deployed my Umbraco site and it was very quick and worked perfectly.

So the site is running, but the problem is the database is still on the old server, I am having GREAT DIFFICULTY recreating my database on Azure.

I JUST found this on the wiki : http://our.umbraco.org/wiki/install-and-setup/how-to-install-umbraco-on-windows-server-2008/installing-umbraco-to-sql-azure

But step 3 says Add primary key to umbracoUserLogins table (contextID, userID)

What does that mean exactly do I create a new field and make that the primary key? Or do I set the ContextId to a primary key? or is it UserId I need to set to Primary Key or both?

ANY IDEAS WELCOME... :-)

Thanks

BY THE WAY I AM USING UMBRACO 6 MVC mode... if that makes a diffrence I don't know.


Umbraco fails to boot even after database connection is warmed up. It seems the failture to boot is "cached"?

$
0
0

We have an Umbraco installation that takes around a minute to boot. Sometimes Umbraco will successfully boot. But some of the time Umbraco will fail to boot with the "failed to boot" screen and the logs will point to database time-outs as the reason.

However, even after the database is verifiably warmed up and radiply accessible from Umbraco (using a diagnostic page outside of Umbraco), Umbraco still shows the "failed to boot" screen immediately on page refresh, and the logs will still point to database time-outs as the reason. Only now these time-outs are happening immediately.

So it seems Umbraco is "caching" the failure to boot, including the reason for boot failure. Is this correct? Is there a way to turn off this "caching" behavior, so that subsequent page refreshs would result in a successful boot?

If not, is there a way to increase the time-outs during boot, specifically the database time-out? To stop the boot failures occuring in the first place.

Or is there a different way to try to get Umbraco to boot after a "failed to boot"?

The Umbraco connection string is verified to work, and sometimes Umbraco will boot after a restart.

The installation is load-balanced admin/front setup running on Azure Web Apps. We've never had any problems with this type of setup before.

The same solution works in the production environment. This is the test environment with rougly the same server sizing.

The only thing special about this Umbraco solution is that it takes long to start, probably because of custom start-up code or similar.

Umbraco 8.13.

Reconnection to database after lost connection do not work until a restart of the appool is made

$
0
0

Hi all.

We occasionally lose connection to the database, because the database is being maintained by the providers.

System.Data.SqlClient.SqlException (0x80131904): A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - The specified network name is no longer available.) ---> System.ComponentModel.Win32Exception (0x80004005): The specified network name is no longer available.

We can see in the logs that Umbraco is trying to boot and etablish connection every now and then, but keep gettin this error:

Umbraco.Core.Exceptions.BootFailedException: Boot failed. -> System.Data.SqlClient.SqlException: A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - The specified network name is no longer available.))

The connection works again after we restart the appool or bumb the web.config, which i guess is also a restart.

We have an ongoing dialog with the providers about this, because i think its their responsibility. But they say its an faul in Umbraco CMS and that's Umbraco CMS that should handle it.

My question is if its the Umbraco Application Task to make sure to reetablish the connection, by what ever means or is it the providers Task?

How to deal with BootFailedException?

$
0
0

I have observed the following behavior whenever our SQL server is rebooted or our web server loses connectivity to the SQL server..

Umbraco enters a persistent state after the BootFailedException is thrown. The only way I've found to remedy this is to restart the application or app pool in IIS. All subsequent HTTP requests to the site have the same error rather than trying to reconnect to the database.

I see some resolved Github issues about throwing this exception rather than going to the install screen. That makes sense for security but the persistent failed boot state is difficult to manage without manual intervention.

I don't recall this being an issue for us with version 7. It has only come up in 8, 9, and 10 for us.

Here's a series of logs that lead up to the boot failure after our SQL server was restarted after Windows updates were applied.

Site is running Umbraco 8.18.0.

{
    "@t": "2022-11-30T09:05:20.4268190Z",
    "@mt": "Failed (will repeat).",
    "@l": "Error",
    "@x": "System.Data.SqlClient.SqlException (0x80131904): SHUTDOWN is in progress.\r\nLogin failed for user 'REDACTED'.\r\nCannot continue the execution because the session is in the kill state.\r\nA severe error occurred on the current command.  The results, if any, should be discarded.\r\n   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)\r\n   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)\r\n   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)\r\n   at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)\r\n   at System.Data.SqlClient.TdsParser.TdsExecuteTransactionManagerRequest(Byte[] buffer, TransactionManagerRequestType request, String transactionName, TransactionManagerIsolationLevel isoLevel, Int32 timeout, SqlInternalTransaction transaction, TdsParserStateObject stateObj, Boolean isDelegateControlRequest)\r\n   at System.Data.SqlClient.SqlInternalConnectionTds.ExecuteTransactionYukon(TransactionRequest transactionRequest, String transactionName, IsolationLevel iso, SqlInternalTransaction internalTransaction, Boolean isDelegateControlRequest)\r\n   at System.Data.SqlClient.SqlInternalConnection.BeginSqlTransaction(IsolationLevel iso, String transactionName, Boolean shouldReconnect)\r\n   at System.Data.SqlClient.SqlConnection.BeginTransaction(IsolationLevel iso, String transactionName)\r\n   at System.Data.SqlClient.SqlConnection.BeginDbTransaction(IsolationLevel isolationLevel)\r\n   at StackExchange.Profiling.Data.ProfiledDbConnection.BeginDbTransaction(IsolationLevel isolationLevel) in C:\\projects\\dotnet\\src\\MiniProfiler.Shared\\Data\\ProfiledDbConnection.cs:line 138\r\n   at NPoco.Database.BeginTransaction(IsolationLevel isolationLevel)\r\n   at Umbraco.Core.Scoping.Scope.get_Database() in D:\\a\\1\\s\\src\\Umbraco.Core\\Scoping\\Scope.cs:line 330\r\n   at Umbraco.Core.Sync.DatabaseServerMessenger.Sync() in D:\\a\\1\\s\\src\\Umbraco.Core\\Sync\\DatabaseServerMessenger.cs:line 263\r\n   at Umbraco.Web.Compose.DatabaseServerRegistrarAndMessengerComponent.InstructionProcessTask.PerformRun() in D:\\a\\1\\s\\src\\Umbraco.Web\\Compose\\DatabaseServerRegistrarAndMessengerComponent.cs:line 163\r\nClientConnectionId:1e2c38c0-5875-4bd7-965a-808b6ac254c8\r\nError Number:6005,State:1,Class:14",
    "SourceContext": "Umbraco.Web.Compose.DatabaseServerRegistrarAndMessengerComponent+InstructionProcessTask",
    "ProcessId": 16008,
    "ProcessName": "w3wp",
    "ThreadId": 387,
    "AppDomainId": 2,
    "AppDomainAppId": "LMW3SVC78ROOT",
    "MachineName": "REDACTED",
    "Log4NetLevel": "ERROR"
}
{
    "@t": "2022-11-30T09:05:39.4737094Z",
    "@mt": "Failed (will repeat).",
    "@l": "Error",
    "@x": "System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)\r\n   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager)\r\n   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)\r\n   at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)\r\n   at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)\r\n   at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)\r\n   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)\r\n   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)\r\n   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)\r\n   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)\r\n   at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)\r\n   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)\r\n   at System.Data.SqlClient.SqlConnection.Open()\r\n   at NPoco.Database.OpenSharedConnectionImp(Boolean isInternal)\r\n   at NPoco.Database.BeginTransaction(IsolationLevel isolationLevel)\r\n   at Umbraco.Core.Scoping.Scope.get_Database() in D:\\a\\1\\s\\src\\Umbraco.Core\\Scoping\\Scope.cs:line 330\r\n   at Umbraco.Core.Sync.DatabaseServerMessenger.Sync() in D:\\a\\1\\s\\src\\Umbraco.Core\\Sync\\DatabaseServerMessenger.cs:line 263\r\n   at Umbraco.Web.Compose.DatabaseServerRegistrarAndMessengerComponent.InstructionProcessTask.PerformRun() in D:\\a\\1\\s\\src\\Umbraco.Web\\Compose\\DatabaseServerRegistrarAndMessengerComponent.cs:line 163\r\nClientConnectionId:00000000-0000-0000-0000-000000000000\r\nError Number:-1,State:0,Class:20",
    "SourceContext": "Umbraco.Web.Compose.DatabaseServerRegistrarAndMessengerComponent+InstructionProcessTask",
    "ProcessId": 16008,
    "ProcessName": "w3wp",
    "ThreadId": 118,
    "AppDomainId": 2,
    "AppDomainAppId": "LMW3SVC78ROOT",
    "MachineName": "REDACTED",
    "Log4NetLevel": "ERROR"
}
{
    "@t": "2022-11-30T09:05:59.8956668Z",
    "@mt": "Failed (will repeat).",
    "@l": "Error",
    "@x": "System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 0 - The remote computer refused the network connection.) ---> System.ComponentModel.Win32Exception (0x80004005): The remote computer refused the network connection\r\n   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager)\r\n   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)\r\n   at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)\r\n   at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)\r\n   at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)\r\n   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)\r\n   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)\r\n   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)\r\n   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)\r\n   at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)\r\n   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)\r\n   at System.Data.SqlClient.SqlConnection.Open()\r\n   at NPoco.Database.OpenSharedConnectionImp(Boolean isInternal)\r\n   at NPoco.Database.BeginTransaction(IsolationLevel isolationLevel)\r\n   at Umbraco.Core.Scoping.Scope.get_Database() in D:\\a\\1\\s\\src\\Umbraco.Core\\Scoping\\Scope.cs:line 330\r\n   at Umbraco.Core.Sync.DatabaseServerMessenger.Sync() in D:\\a\\1\\s\\src\\Umbraco.Core\\Sync\\DatabaseServerMessenger.cs:line 263\r\n   at Umbraco.Web.Compose.DatabaseServerRegistrarAndMessengerComponent.InstructionProcessTask.PerformRun() in D:\\a\\1\\s\\src\\Umbraco.Web\\Compose\\DatabaseServerRegistrarAndMessengerComponent.cs:line 163\r\nClientConnectionId:00000000-0000-0000-0000-000000000000\r\nError Number:1225,State:0,Class:20",
    "SourceContext": "Umbraco.Web.Compose.DatabaseServerRegistrarAndMessengerComponent+InstructionProcessTask",
    "ProcessId": 16008,
    "ProcessName": "w3wp",
    "ThreadId": 144,
    "AppDomainId": 2,
    "AppDomainAppId": "LMW3SVC78ROOT",
    "MachineName": "REDACTED",
    "Log4NetLevel": "ERROR"
}
{
    "@t": "2022-11-30T09:06:03.1300309Z",
    "@mt": "Failed.",
    "@l": "Error",
    "@x": "System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 0 - The remote computer refused the network connection.) ---> System.ComponentModel.Win32Exception (0x80004005): The remote computer refused the network connection\r\n   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)\r\n   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)\r\n   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)\r\n   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)\r\n   at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)\r\n   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)\r\n   at System.Data.SqlClient.SqlConnection.Open()\r\n   at NPoco.Database.OpenSharedConnectionImp(Boolean isInternal)\r\n   at NPoco.Database.BeginTransaction(IsolationLevel isolationLevel)\r\n   at Umbraco.Core.Scoping.Scope.get_Database() in D:\\a\\1\\s\\src\\Umbraco.Core\\Scoping\\Scope.cs:line 330\r\n   at Umbraco.Core.Persistence.Repositories.Implement.DocumentRepository.HasContentForRelease(DateTime date) in D:\\a\\1\\s\\src\\Umbraco.Core\\Persistence\\Repositories\\Implement\\DocumentRepository.cs:line 1071\r\n   at Umbraco.Core.Services.Implement.ContentService.PerformScheduledPublishingRelease(DateTime date, List`1 results, EventMessages evtMsgs, Lazy`1 allLangs) in D:\\a\\1\\s\\src\\Umbraco.Core\\Services\\Implement\\ContentService.cs:line 1467\r\n   at Umbraco.Core.Services.Implement.ContentService.PerformScheduledPublish(DateTime date) in D:\\a\\1\\s\\src\\Umbraco.Core\\Services\\Implement\\ContentService.cs:line 1396\r\n   at Umbraco.Web.Scheduling.ScheduledPublishing.PerformRun() in D:\\a\\1\\s\\src\\Umbraco.Web\\Scheduling\\ScheduledPublishing.cs:line 68\r\nClientConnectionId:00000000-0000-0000-0000-000000000000\r\nError Number:1225,State:0,Class:20",
    "SourceContext": "Umbraco.Web.Scheduling.ScheduledPublishing",
    "ProcessId": 16008,
    "ProcessName": "w3wp",
    "ThreadId": 125,
    "AppDomainId": 2,
    "AppDomainAppId": "LMW3SVC78ROOT",
    "MachineName": "REDACTED",
    "Log4NetLevel": "ERROR"
}
{
    "@t": "2022-11-30T12:18:15.6465344Z",
    "@mt": "{FailMessage} ({Duration}ms) [Timing {TimingId}]",
    "@l": "Error",
    "@x": "Umbraco.Core.Exceptions.BootFailedException: A connection string is configured but Umbraco could not connect to the database.\r\n   at Umbraco.Core.RuntimeState.DetermineRuntimeLevel(IUmbracoDatabaseFactory databaseFactory) in D:\\a\\1\\s\\src\\Umbraco.Core\\RuntimeState.cs:line 188\r\n   at Umbraco.Core.Runtime.CoreRuntime.DetermineRuntimeLevel(IUmbracoDatabaseFactory databaseFactory, IProfilingLogger profilingLogger) in D:\\a\\1\\s\\src\\Umbraco.Core\\Runtime\\CoreRuntime.cs:line 498\r\n   at Umbraco.Core.Runtime.CoreRuntime.Boot(IRegister register, DisposableTimer timer) in D:\\a\\1\\s\\src\\Umbraco.Core\\Runtime\\CoreRuntime.cs:line 186",
    "FailMessage": "Boot failed.",
    "Duration": 43897,
    "TimingId": "b92353c",
    "SourceContext": "Umbraco.Core.Runtime.CoreRuntime",
    "ProcessId": 4896,
    "ProcessName": "w3wp",
    "ThreadId": 1,
    "AppDomainId": 2,
    "AppDomainAppId": "LMW3SVC78ROOT",
    "MachineName": "REDACTED",
    "Log4NetLevel": "ERROR",
    "HttpRequestNumber": 1,
    "HttpRequestId": "8cb0f869-f3d5-473b-9a5a-14f2667a7a83"
}

How to overwrite a media file with a locale, physical file so it works both with blob and non-blob storage

$
0
0

I can't get Cogworks.Tinifier package working on Umbraco v13 (and have got no solutions here: https://www.facebook.com/groups/umbracowebdevs/posts/2091914831210397/). Therefore I have tried to make my own solution (see code below).

It works a part of the way: When user uploads an image TinifyAPI optimizes it and saves the optimized image in a temporary location (like C:\Users\marti\AppData\Local\Temp\tmpsxjjxj.tmp).

But the part of the code that should overwrite the uploaded, non-optimized image (which is my goal - I don't want the original non-optimized image since it consumes server disc space) does not work. I.e. this part:

using (var fileStream = System.IO.File.OpenRead(tempFilePath))
{
    byte[] fileBytesArray;
    using (var memoryStream = new MemoryStream())
    {
        await fileStream.CopyToAsync(memoryStream);
        fileBytesArray = memoryStream.ToArray();
    }
    var fileBytes = new ByteArrayContent(fileBytesArray);
    var uploadResponse = await httpClient.PutAsync(mediaUrl, fileBytes);
    if (!uploadResponse.IsSuccessStatusCode)
    {
        NotifyUser("Upload Error", $"Failed to upload optimized image.");
    }
}

No error, but also no file is overwritten.

My full code:

using Umbraco.Cms.Core.Events;
using Umbraco.Cms.Core.Notifications;
using Umbraco.Cms.Core.Services;
using TinifyAPI;
using Newtonsoft.Json.Linq;

namespace MartinRud.Notifications
{
    public class MediaNotificationHandler : INotificationHandler<MediaSavedNotification>
    {
        private readonly IMediaService _mediaService;
        private readonly IConfiguration _configuration; 
        private readonly ILogger<MediaNotificationHandler> _logger;
        private readonly IEventMessagesFactory _eventMessagesFactory;
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly string _baseUrl;

        public MediaNotificationHandler(IMediaService mediaService, IConfiguration configuration, ILogger<MediaNotificationHandler> logger, IEventMessagesFactory eventMessagesFactory, IHttpClientFactory httpClientFactory)
        {
            _mediaService = mediaService;
            _configuration = configuration;
            _logger = logger;
            _eventMessagesFactory = eventMessagesFactory;
            _httpClientFactory = httpClientFactory;
            _baseUrl = configuration["MediaBaseUrl"] ?? "https://localhost:44378";
            Tinify.Key = _configuration["TinifierSettings:ApiKey"];
        }

public async void Handle(MediaSavedNotification notification)
{
    var httpClient = _httpClientFactory.CreateClient();

    foreach (var mediaItem in notification.SavedEntities)
    {
        if (mediaItem.ContentType.Alias.Equals("Image"))
        {
            var mediaJson = mediaItem.GetValue<string>("umbracoFile");
            var mediaUrl = ExtractUrlFromJson(mediaJson);

            if (!string.IsNullOrEmpty(mediaUrl))
            {
                if (!Uri.IsWellFormedUriString(mediaUrl, UriKind.Absolute))
                {
                    mediaUrl = new Uri(new Uri(_baseUrl), mediaUrl).ToString();
                }

                _logger.LogInformation($"Attempting to fetch URL: {mediaUrl}");

                var tempFilePath = Path.GetTempFileName();
                var jsonFilePath = Path.ChangeExtension(tempFilePath, "json");

                try
                {
                    var response = await GetWithRetryAsync(httpClient, mediaUrl);

                    if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
                    {
                        NotifyUser("URL Not Found", $"The URL '{mediaUrl}' was not found.");
                        continue;
                    }

                    using (var fileStream = System.IO.File.Create(tempFilePath))
                    {
                        await response.Content.CopyToAsync(fileStream);
                    }

                    if (System.IO.File.Exists(jsonFilePath))
                    {
                        NotifyUser("Image already compressed", "The image has already been optimized.");
                        continue;
                    }

                    NotifyUser("Starting image optimization", $"Starting optimization for image '{mediaItem.Name}'");
                    _logger.LogInformation("Calling CompressImage for: {TempFilePath}", tempFilePath);

                    await CompressImage(tempFilePath, jsonFilePath);

                    _logger.LogInformation("Finished calling CompressImage for: {TempFilePath}", tempFilePath);

                    // Upload the optimized image
                    using (var fileStream = System.IO.File.OpenRead(tempFilePath))
                    {
                        byte[] fileBytesArray;
                        using (var memoryStream = new MemoryStream())
                        {
                            await fileStream.CopyToAsync(memoryStream);
                            fileBytesArray = memoryStream.ToArray();
                        }
                        var fileBytes = new ByteArrayContent(fileBytesArray);
                        var uploadResponse = await httpClient.PutAsync(mediaUrl, fileBytes);
                        if (!uploadResponse.IsSuccessStatusCode)
                        {
                            NotifyUser("Upload Error", $"Failed to upload optimized image.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error processing media item for: {MediaItemName}", mediaItem.Name);
                    NotifyUser("Error", $"Error processing media item: {ex.Message}");
                }
                finally
                {
                    // Clean up temporary files
                    try
                    {
                        if (System.IO.File.Exists(tempFilePath))
                        {
                            //System.IO.File.Delete(tempFilePath);
                            _logger.LogInformation("Deleted temporary file: {TempFilePath}", tempFilePath);
                        }
                        if (System.IO.File.Exists(jsonFilePath))
                        {
                            //System.IO.File.Delete(jsonFilePath);
                            _logger.LogInformation("Deleted JSON file: {JsonFilePath}", jsonFilePath);
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "Error deleting temporary files.");
                    }
                }
            }
        }
    }
}


private string ExtractUrlFromJson(string json)
{
    try
    {
        var jsonObject = JObject.Parse(json);
        var url = jsonObject["src"]?.ToString();
        return url ?? string.Empty;
    }
    catch (Exception ex)
    {
        _logger.LogError(ex, "Error parsing JSON for media URL");
        return string.Empty;
    }
}

private async Task<HttpResponseMessage> GetWithRetryAsync(HttpClient httpClient, string url, int maxRetries = 3)
{
    for (int retry = 0; retry < maxRetries; retry++)
    {
        try
        {
            var response = await httpClient.GetAsync(url);
            response.EnsureSuccessStatusCode(); // Throws if not success code.
            return response;
        }
        catch (HttpRequestException ex)
        {
            if (retry == maxRetries - 1) // Last retry
            {
                _logger.LogError(ex, "Error fetching URL: {Url}", url);
                throw;
            }
            await Task.Delay(1000); // Wait before retrying
        }
    }
    throw new Exception("Failed to fetch URL after multiple retries.");
}
        private async Task CompressImage(string filePath, string jsonFilePath)
        {
            try
            {
                var originalSize = new FileInfo(filePath).Length;
                var source = Tinify.FromFile(filePath);
                await source.ToFile(filePath);

                var compressedSize = new FileInfo(filePath).Length;
                var percentageReduction = (double)(originalSize - compressedSize) / originalSize * 100;

                var compressionInfo = new
                {
                    OriginalSize = originalSize,
                    CompressedSize = compressedSize,
                    PercentageReduction = Math.Round(percentageReduction, 2)
                };

                var json = JObject.FromObject(compressionInfo);
                await System.IO.File.WriteAllTextAsync(jsonFilePath, json.ToString());

                NotifyUser("Image optimization complete", $"Optimization for image completed successfully.");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error compressing image");
                NotifyUser("Image optimization error", $"Error optimizing image: {ex.Message}");
            }
        }

        private void NotifyUser(string title, string message)
        {
            var eventMessages = _eventMessagesFactory.Get();
            eventMessages.Add(new EventMessage(title, message, EventMessageType.Success)); // or .Error if needed
        }
    }
}

Umbraco 13.4, how to set up Examine Index in a distributed environment

$
0
0

Hi there,

I have a Umbraco project, and the deployment is as follows:

  • 1 Umbraco instance for backend editors
  • 2 Umbraco instances provide high availability services to provide API services to frontend web applications
  • All 3 Umbraco instances connect to the same database and the same Examine index file directory to ensure consistency between the frontend and backend content

Issues: The index in Examine Manager in Umbraco(backend) often fails and the index file is missing.

Question: Could this issue be caused by file locks due to multiple Umbraco instances writing to the same Examine index file? If so, how can this be avoided, and how can I ensure that different Umbraco instances read the same index file without conflicts?

Expecting your help, many thanks.

Designing content types in v13

$
0
0

I have started upgrading our U7 sites to v13.

How do I sort property editors for a content type. Right now all inherited editors are at the bottom and content type-specific ones I add end up above. I need to be able to set the sort order per content type and hope I still can use inheritance.

Related question: Is there any way of bringing back tabs in the Content view? Each page has around 25 property editors so the older versions gave a better overview.

Thank you!

Transaction Emails Not Sending in Umbraco Commerce – No Errors in Logs

$
0
0

Hi everyone,

I'm facing an issue with transaction emails in Umbraco Commerce. Whenever an order is placed, the emails are not being sent. Everything seems to be set up correctly, and I’ve double-checked the logs—there are no errors or exceptions anywhere. The emails simply don’t reach the destination (and yes, I’ve checked the spam folder too).

Here’s what I’ve checked so far:

SMTP Configuration: I’m confident the SMTP settings are correct. I even created a simple console app to send a test email using the same config, and that worked perfectly. Umbraco Commerce UI: When using the UI to trigger email sending, it reports that the email was sent, but the email never actually arrives. Logs: There are no warnings, errors, or any signs of issues in the Umbraco or server logs related to the email sending process. I feel like I’ve hit a wall here and don’t know what else to check. Has anyone encountered this before or have suggestions for troubleshooting?

Some specific questions I have:

Could this be a configuration issue inside Umbraco Commerce that I’m overlooking? Are there any specific settings or email templates in Umbraco Commerce that could prevent emails from sending? Could there be something in the way Umbraco handles SMTP or email queuing that isn't obvious in the logs? Is there any way to enable more detailed logging for the email sending process, specifically for Umbraco Commerce, to dig deeper into what’s happening? Any ideas or tips would be much appreciated!

Thanks in advance for your help!

trying to sent email using web ui


How to display URLs containing a dot

$
0
0

Error when trying to display a page containing a dot on a site built with Umbraco.

For example, the URL is as follows. www.test.com/abc.efg

The site was originally built using another CMS, and at that time, pages containing dots could be displayed.

For the sake of SEO, we do not want to change the dots to “_” and so on. How can we display URLs containing dots? Is this not supported by Umbraco?

Error when creating project

$
0
0

Error when creating project

C:\Users\user>dotnet new umbraco -n MyProject --force
The template "Umbraco Project" was created successfully.

Processing post-creation actions...
Restoring C:\Users\user\MyProject\MyProject.csproj:
  Determining projects to restore...
C:\Users\user\MyProject\MyProject.csproj : error NU1100: Unable to resolve 'Umbraco.Cms (>= 12.0.0)' for 'net7.0'. Pack
ageSourceMapping is enabled, the following source(s) were not considered: C:\Program Files\dotnet\library-packs, Micros
oft Visual Studio Offline Packages, nuget.org, Package source.
C:\Users\user\MyProject\MyProject.csproj : error NU1100: Unable to resolve 'Microsoft.ICU.ICU4C.Runtime (>= 68.2.0.9)'
for 'net7.0'. PackageSourceMapping is enabled, the following source(s) were not considered: C:\Program Files\dotnet\lib
rary-packs, Microsoft Visual Studio Offline Packages, nuget.org, Package source.

umbraco forms add extra data to saved entry

$
0
0

Hi,

We need add extra data to each saved form entry. We must collect tracking data from our affiliates.

I can create hidden form fields thru C# and populate their values from JS.

But how do i add the data to each saved form entry, without having to add the field types on each created form in the backoffice?

I tried looking into RecordSavingNotification, but cant figure out how to use this.

Umbraco 10 to Umbraco 13 upgrade

$
0
0

Can direct upgradation from umbraco V10 to umbraco 13 is possible?

I have followed the below link for upgradation. https://docs.umbraco.com/umbraco-cms/fundamentals/setup/upgrading

Did everything as per the document. (Upgraded .Net version, umbraco version, connection string etc).

After followed all the step when I started the project I got the "BootFailedException" exception.

Complete details are

{"@t":"2024-01-19T07:09:39.2807735Z","@mt":"Content root path: {ContentRoot}","ContentRoot":"C:\Users\S979414\UmbracoCore","SourceContext":"Microsoft.Hosting.Lifetime","ProcessId":10960,"ProcessName":"iisexpress","ThreadId":1,"ApplicationId":"347c836d918bffe3f5500a6b123d7477efaa7ecb","MachineName":"CFIN-8ZFLXD3","Log4NetLevel":"INFO "} {"@t":"2024-01-19T07:09:39.5544745Z","@mt":"An unhandled exception has occurred while executing the request.","@l":"Error","@x":"Umbraco.Cms.Core.Exceptions.BootFailedException: Boot failed: Umbraco cannot run. See Umbraco's log file for more details.\r\n at Umbraco.Cms.Core.Exceptions.BootFailedException.Rethrow(BootFailedException bootFailedException)\r\n at Umbraco.Cms.Web.Common.Middleware.BootFailedMiddleware.InvokeAsync(HttpContext context, RequestDelegate next)\r\n at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.InterfaceMiddlewareBinder.<>cDisplayClass2_0.<0>d.MoveNext()\r\n--- End of stack trace from previous location ---\r\n at SixLabors.ImageSharp.Web.Middleware.ImageSharpMiddleware.Invoke(HttpContext httpContext, Boolean retry)\r\n at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)","@tr":"ff3768eed9c025d6d10c0fac89838036","@sp":"dfa145c470b52aea","EventId":{"Id":1,"Name":"UnhandledException"},"SourceContext":"Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware","RequestId":"80000008-0005-fe00-b63f-84710c7967bb","RequestPath":"/","ProcessId":10960,"ProcessName":"iisexpress","ThreadId":8,"ApplicationId":"347c836d918bffe3f5500a6b123d7477efaa7ecb","MachineName":"CFIN-8ZFLXD3","Log4NetLevel":"ERROR"}

Please suggest the way forward.

Using Umbraco to hold back-end data with a Vue front-end

$
0
0

I'm working on a new project where I'd like to use Umbraco to manage content and then use Vue as the front-end app, which queries content using the Content Delivery Service.

The only issue is how to set this up on the dev environment: I'm using Vite.AspNetCore to boot up the front end app, however this is only by setting up a template on the home node, with the app defined within - Umbraco is handling all the routing by default.

Should I effectively be hosting 2 sites? One for the front end, and one for the back, with the front-end app being just an html template with vue, querying content via APIs? Or is it possible to host both on the same server?

The issue I'm seeing right now is that Umbraco is managing the routing, where as I want the Vue app to manage the routing, with the exception of the /umbraco route to log into the CMS. Is this possible?

How have others managed to set this up?

Thanks

Viewing all 72689 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>