CategoriesUncategorized

Shared Session Management for Classic ASP and .NET Core Integration

Organizations often face challenge of maintaining legacy Classic ASP applications while developing new features in .NET Core. Complete system migration is not always practical solution due to complexity, risk, and cost. In this article, we are going to explore how to implement distributed session management that allows both systems to work together effectively.

Understanding the Architecture

In typical scenario, legacy Classic ASP application serves as main website (e.g., www.company.com), while new .NET Core application runs on subdomain (e.g., app.company.com). Main challenge is maintaining user session across these separate applications. Solution is to implement centralized session management using shared database.

Database Design

Here is simple but effective database structure:

CREATE TABLE [dbo].[DistributedSessions]
(
    [SessionId] VARCHAR(50) PRIMARY KEY,
    [Username] NVARCHAR(100) NOT NULL,
    [UserData] NVARCHAR(MAX),
    [LastAccessed] DATETIME NOT NULL,
    [CreatedOn] DATETIME NOT NULL,
    [ExpiresOn] DATETIME NOT NULL
)

CREATE INDEX IX_Sessions_Username ON [dbo].[DistributedSessions] ([Username])
CREATE INDEX IX_Sessions_Expiration ON [dbo].[DistributedSessions] ([ExpiresOn])

Classic ASP Implementation

Here is helper class for Classic ASP (saved as session.asp):

<%
Class DistributedSession
    Private connString
    Private sessionId

    Private Sub Class_Initialize()
        connString = "your_connection_string_here"
        sessionId = Request.Cookies("DistSessionId")

        If sessionId = "" Then
            sessionId = CreateNewSession()
        End If
    End Sub

    Private Function CreateNewSession()
        ' Generate unique session ID
        Dim newId
        newId = Replace(CreateObject("Scriptlet.TypeLib").GUID, "-", "")

        ' Create cookie
        Response.Cookies("DistSessionId") = newId
        Response.Cookies("DistSessionId").Domain = ".company.com"

        CreateNewSession = newId
    End Function

    Public Function GetUserData()
        Dim conn, rs
        Set conn = CreateObject("ADODB.Connection")
        conn.Open connString

        Set rs = conn.Execute("SELECT UserData FROM DistributedSessions " & _
                            "WHERE SessionId = '" & sessionId & "' " & _
                            "AND ExpiresOn > GETDATE()")

        If Not rs.EOF Then
            GetUserData = rs("UserData")
        End If

        rs.Close
        conn.Close
    End Function

    Public Sub SetUserData(userData)
        Dim conn
        Set conn = CreateObject("ADODB.Connection")
        conn.Open connString

        conn.Execute "UPDATE DistributedSessions " & _
                    "SET UserData = '" & Replace(userData, "'", "''") & "', " & _
                    "LastAccessed = GETDATE() " & _
                    "WHERE SessionId = '" & sessionId & "'"

        conn.Close
    End Sub
End Class
%>

.NET Core Implementation

Create SessionService class in your .NET Core project:

public class DistributedSessionService
{
    private readonly string _connectionString;
    private readonly IHttpContextAccessor _httpContextAccessor;

    public DistributedSessionService(
        IConfiguration configuration,
        IHttpContextAccessor httpContextAccessor)
    {
        _connectionString = configuration.GetConnectionString("SessionDb");
        _httpContextAccessor = httpContextAccessor;
    }

    public async Task<UserSessionData> GetUserDataAsync()
    {
        var sessionId = _httpContextAccessor.HttpContext.Request
            .Cookies["DistSessionId"];

        if (string.IsNullOrEmpty(sessionId))
            return null;

        using var connection = new SqlConnection(_connectionString);
        await connection.OpenAsync();

        var userData = await connection.QueryFirstOrDefaultAsync<string>(
            @"SELECT UserData 
              FROM DistributedSessions 
              WHERE SessionId = @SessionId 
              AND ExpiresOn > GETDATE()",
            new { SessionId = sessionId });

        return userData != null 
            ? JsonSerializer.Deserialize<UserSessionData>(userData)
            : null;
    }

    public async Task SetUserDataAsync(UserSessionData userData)
    {
        var sessionId = _httpContextAccessor.HttpContext.Request
            .Cookies["DistSessionId"];

        using var connection = new SqlConnection(_connectionString);
        await connection.OpenAsync();

        await connection.ExecuteAsync(
            @"UPDATE DistributedSessions 
              SET UserData = @UserData,
                  LastAccessed = GETDATE()
              WHERE SessionId = @SessionId",
            new { 
                SessionId = sessionId,
                UserData = JsonSerializer.Serialize(userData)
            });
    }
}

Implementation Benefits

This approach provides several important advantages:

  1. Cost Effective
    • Allows continued use of stable legacy system
    • Minimizes risk of full migration
    • Reduces immediate development costs
  2. Technical Benefits
    • Shared authentication state
    • Consistent user experience
    • Scalable solution
  3. Business Benefits
    • Gradual migration path
    • Maintain business operations
    • Lower training costs

Important Considerations

When implementing this solution, remember these points:

  1. Security
    • Use parameterized queries to prevent SQL injection
    • Implement proper session timeout
    • Encrypt sensitive session data
    • Use secure cookie settings
  2. Performance
    • Implement caching where appropriate
    • Create maintenance job to clean expired sessions
    • Monitor database growth
  3. Maintenance
    • Log session operations for troubleshooting
    • Monitor session timeouts
    • Regular cleanup of expired sessions

    Conclusion

    Distributed session management provides practical solution for organizations that need to maintain legacy Classic ASP applications while developing new features in .NET Core. This approach reduces migration risks and costs while providing consistent user experience.

    Implementation requires careful planning and consideration of security implications, but benefits often outweigh complexity of setup. Organizations can continue using valuable legacy systems while gradually transitioning to modern technology stack.

    CategoriesUncategorized

    Blazor Will Change the Game

    For many years, front-end development has been dominated by single-page applications (SPA) frameworks like React and Angular. These frameworks allow developers to create rich, dynamic web applications, but they come with one significant drawback: they require developers to use JavaScript (or TypeScript). At the same time, the backend often uses a completely different language such as C#, Java, or Python. This means organizations need separate teams or developers with expertise in both frontend and backend technologies.

    The Challenge of Separate Teams

    Having different languages for the frontend and backend creates several challenges. First, it adds complexity because teams must maintain two codebases written in different languages, each with its own set of libraries, frameworks, and design patterns. Secondly, this setup can make communication between frontend and backend teams difficult, slowing down development and leading to potential inconsistencies in how the two sides of the system work together.

    Maintaining a system built with two different technologies is also costly in the long term. Your organization not only needs to hire developers who specialize in both frontend (React, Angular) and backend (C#, Java), but you also have to deal with the overhead of keeping these two parts of your application in sync.

    Enter Blazor

    Blazor offers a solution to this problem by allowing developers to write the entire application—both the frontend and the backend—in C#. With Blazor, the need for JavaScript for frontend development is eliminated. This means that your team can now build everything from the user interface to the business logic in the same language.

    Lowering Cost of Ownership and Maintenance

    By using a single language for both sides of the application, Blazor significantly reduces the complexity of maintaining the system. Your organization no longer has to maintain two separate codebases, reducing the overall effort required to keep the system running smoothly. This also means fewer bugs, as developers will only have to focus on mastering one language, which lowers the risk of errors caused by switching between languages.

    In the long run, this translates to lower costs for maintaining and updating your system. Because there is less complexity, fewer issues arise, and the time needed to fix problems or implement updates is greatly reduced. Blazor simplifies development, resulting in faster turnaround times for bug fixes and new features.

    Simplifying Hiring

    Another advantage of Blazor is that it makes hiring much easier. With traditional setups, you often need to hire separate specialists for frontend and backend development. But with Blazor, your development team can work across the entire stack using C#. This reduces the need for multiple skill sets, making it easier to find qualified developers.

    Additionally, Blazor makes it easier to onboard new developers. Instead of learning multiple languages and frameworks, new team members can focus on mastering just one language, speeding up their ability to contribute to the project.

    Other Benefits of Blazor

    Blazor also provides other benefits. For example, it offers strong integration with the .NET ecosystem, meaning that developers can take advantage of familiar tools, libraries, and frameworks. Blazor applications can also run server-side or client-side, offering flexibility based on the needs of your application.

    Additionally, because Blazor is a .NET framework, it has the backing of Microsoft, which provides a strong level of support and a long-term commitment to the technology.

    Conclusion

    Blazor is a game-changer for organizations looking to simplify their development process and reduce costs. By using a single language, C#, for both frontend and backend development, Blazor lowers the cost of ownership and maintenance, simplifies hiring, and reduces complexity. For organizations already invested in the .NET ecosystem or looking for ways to streamline their development, Blazor is a smart choice for building modern web applications.