”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > C# .NET 代码库中的 Bootstrap 现代化:来自 o 5 的 Python 支持的迁移

C# .NET 代码库中的 Bootstrap 现代化:来自 o 5 的 Python 支持的迁移

发布于2024-07-30
浏览:598

Modernizing Bootstrap in a C# .NET Codebase: A Python-Powered Migration from o 5

Introduction

As a developer, I recently found myself faced with an exciting challenge: modernizing a legacy C# .NET codebase that was still using Bootstrap 3. The goal was clear - bring the project up to speed with the latest Bootstrap 5. However, I quickly realized that making such a significant leap could be risky and time-consuming.

That's when I decided to take a phased approach:

  1. First, migrate from Bootstrap 3 to Bootstrap 4
  2. Then, once stable, make the jump from Bootstrap 4 to Bootstrap 5

This strategy would allow for a more manageable transition, easier debugging, and a smoother overall process. Today, I'm excited to share the first part of this journey - automating the migration from Bootstrap 3 to 4 using a Python script.

A Note on the Code

Before we dive in, it's important to note that the code presented here is a simplified version of the actual script used in the project. For obvious reasons, such as proprietary information and specific project requirements, I've streamlined the code for this blog post. However, the approach and core functionality remain very similar to what was implemented in the real-world scenario.

The Challenge

Migrating from Bootstrap 3 to 4 involves numerous class name changes and deprecated components. Manually updating these across an entire project can be time-consuming and error-prone. That's where our Python script comes in.

The Solution

Our script, which we'll call bootstrap_migrator.py, is designed to scan your project files and automatically update Bootstrap 3 class names to their Bootstrap 4 equivalents. It handles HTML, Razor (cshtml), and even JavaScript files, making it a comprehensive solution for your migration needs.

Breaking Down the Code

Let's dive into the details of our migration script and explain each part.

Importing Required Modules

import os
import re

We start by importing two essential Python modules:

  • os: This module provides a way to use operating system dependent functionality, like navigating the file system.
  • re: This module provides support for regular expressions in Python.

The Main Migration Function

def update_bootstrap_classes(content, file_type):
    class_mappings = {
    r'\bcol-xs-(\d )\b': r'col-\1',
    r'\bcol-sm-(\d )\b': r'col-sm-\1',
    r'\bcol-md-(\d )\b': r'col-md-\1',
    r'\bcol-lg-(\d )\b': r'col-lg-\1',
    r'\bcol-xl-(\d )\b': r'col-xl-\1',
    r'\bbtn-default\b': 'btn-secondary',
    r'\bimg-responsive\b': 'img-fluid',
    r'\bimg-circle\b': 'rounded-circle',
    r'\bimg-rounded\b': 'rounded',
    r'\bpanel\b': 'card',
    r'\bpanel-heading\b': 'card-header',
    r'\bpanel-title\b': 'card-title',
    r'\bpanel-body\b': 'card-body',
    r'\bpanel-footer\b': 'card-footer',
    r'\bpanel-primary\b': 'card bg-primary text-white',
    r'\bpanel-success\b': 'card bg-success text-white',
    r'\bpanel-info\b': 'card text-white bg-info',
    r'\bpanel-warning\b': 'card bg-warning',
    r'\bpanel-danger\b': 'card bg-danger text-white',
    r'\bwell\b': 'card card-body',
    r'\bthumbnail\b': 'card card-body',
    r'\blist-inline\s*>\s*li\b': 'list-inline-item',
    r'\bdropdown-menu\s*>\s*li\b': 'dropdown-item',
    r'\bnav\s navbar\s*>\s*li\b': 'nav-item',
    r'\bnav\s navbar\s*>\s*li\s*>\s*a\b': 'nav-link',
    r'\bnavbar-right\b': 'ml-auto',
    r'\bnavbar-btn\b': 'nav-item',
    r'\bnavbar-fixed-top\b': 'fixed-top',
    r'\bnav-stacked\b': 'flex-column',
    r'\bhidden-xs\b': 'd-none',
    r'\bhidden-sm\b': 'd-sm-none',
    r'\bhidden-md\b': 'd-md-none',
    r'\bhidden-lg\b': 'd-lg-none',
    r'\bvisible-xs\b': 'd-block d-sm-none',
    r'\bvisible-sm\b': 'd-none d-sm-block d-md-none',
    r'\bvisible-md\b': 'd-none d-md-block d-lg-none',
    r'\bvisible-lg\b': 'd-none d-lg-block d-xl-none',
    r'\bpull-right\b': 'float-right',
    r'\bpull-left\b': 'float-left',
    r'\bcenter-block\b': 'mx-auto d-block',
    r'\binput-lg\b': 'form-control-lg',
    r'\binput-sm\b': 'form-control-sm',
    r'\bcontrol-label\b': 'col-form-label',
    r'\btable-condensed\b': 'table-sm',
    r'\bpagination\s*>\s*li\b': 'page-item',
    r'\bpagination\s*>\s*li\s*>\s*a\b': 'page-link',
    r'\bitem\b': 'carousel-item',
    r'\bhelp-block\b': 'form-text',
    r'\blabel\b': 'badge',
    r'\bbadge\b': 'badge badge-pill'
}

This function is the heart of our script. It takes two parameters:

  • content: The content of the file we're updating.
  • file_type: The type of file we're dealing with (HTML, JS, etc.).

The class_mappings dictionary is crucial. It maps Bootstrap 3 class patterns (as regex) to their Bootstrap 4 equivalents. For example, col-xs-* becomes just col-* in Bootstrap 4.

Replacing Classes in HTML and Razor Files

def replace_class(match):
    classes = match.group(1).split()
    updated_classes = []
    for cls in classes:
        replaced = False
        for pattern, replacement in class_mappings.items():
            if re.fullmatch(pattern, cls):
                updated_cls = re.sub(pattern, replacement, cls)
                updated_classes.append(updated_cls)
                replaced = True
                break
        if not replaced:
            updated_classes.append(cls)
    return f'class="{" ".join(updated_classes)}"'

if file_type in ['cshtml', 'html']:
    return re.sub(r'class="([^"]*)"', replace_class, content)

This part handles the replacement of classes in HTML and Razor files:

  1. It finds all class attributes in the HTML.
  2. For each class found, it checks if it matches any of our Bootstrap 3 patterns.
  3. If a match is found, it replaces the class with its Bootstrap 4 equivalent.
  4. Classes that don't match any patterns are left unchanged.

Updating JavaScript Selectors

    def replace_js_selectors(match):
        full_match = match.group(0)
        method = match.group(1)
        selector = match.group(2)

        classes = re.findall(r'\.[-\w] ', selector)

        for i, cls in enumerate(classes):
            cls = cls[1:]  
            for pattern, replacement in class_mappings.items():
                if re.fullmatch(pattern, cls):
                    new_cls = re.sub(pattern, replacement, cls)
                    classes[i] = f'.{new_cls}'
                    break

        updated_selector = selector
        for old_cls, new_cls in zip(re.findall(r'\.[-\w] ', selector), classes):
            updated_selector = updated_selector.replace(old_cls, new_cls)

        return f"{method}('{updated_selector}')"

    if file_type == 'js':
        js_jquery_methods = [
            'querySelector', 'querySelectorAll', 'getElementById', 'getElementsByClassName',
            '$', 'jQuery', 'find', 'children', 'siblings', 'parent', 'closest', 'next', 'prev',
            'addClass', 'removeClass', 'toggleClass', 'hasClass'
        ]

        method_pattern = '|'.join(map(re.escape, js_jquery_methods))
        content = re.sub(rf"({method_pattern})\s*\(\s*['\"]([^'\"] )['\"]\s*\)", replace_js_selectors, content)

        return content

This section handles updating class names in JavaScript files:

  1. It defines a list of common JavaScript and jQuery methods that might use class selectors.
  2. It then uses regex to find these method calls and updates the class names in their selectors.
  3. It also updates class names used in jQuery's .css() method calls.

Processing Individual Files

def process_file(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read()

        file_type = file_path.split('.')[-1].lower()
        updated_content = update_bootstrap_classes(content, file_type)

        if content != updated_content:
            with open(file_path, 'w', encoding='utf-8') as file:
                file.write(updated_content)
            print(f"Updated: {file_path}")
        else:
            print(f"No changes: {file_path}")
    except Exception as e:
        print(f"Error processing {file_path}: {str(e)}")

This function handles the processing of individual files:

  1. It reads the content of the file.
  2. Determines the file type based on its extension.
  3. Calls update_bootstrap_classes to update the content.
  4. If changes were made, it writes the updated content back to the file.
  5. It also handles exceptions and provides feedback on the process.

The Main Function

def main():
    project_dir = input("Enter the path to your project directory: ")
    print(f"Scanning directory: {project_dir}")

    if not os.path.exists(project_dir):
        print(f"The directory {project_dir} does not exist.")
        return

    files_found = False
    for root, dirs, files in os.walk(project_dir):
        for file in files:
            if file.endswith(('.cshtml', '.html', '.js')):
                files_found = True
                file_path = os.path.join(root, file)
                print(f"Processing file: {file_path}")
                process_file(file_path)

    if not files_found:
        print("No .cshtml, .html, or .js files found in the specified directory.")

if __name__ == "__main__":
    main()

The main function ties everything together:

  1. It prompts the user for the project directory.
  2. It then walks through the directory, finding all relevant files (.cshtml, .html, .js).
  3. For each file found, it calls process_file to update its content.
  4. It provides feedback on the process, including if no relevant files were found.

Key Features

  • Comprehensive Class Updates: From grid classes to component-specific classes, the script covers a wide range of Bootstrap changes.
  • JavaScript Support: It updates class names in various JavaScript and jQuery selectors, ensuring your dynamic content doesn't break.
  • Flexibility: The script can be easily extended to include more class mappings or file types.
  • Non-Destructive: It only modifies files where changes are necessary, leaving others untouched.

Using the Script

To use the script, simply run it and provide the path to your project directory when prompted. It will then process all relevant files, updating them as necessary.

python bootstrap_migrator.py

Limitations and Considerations

While this script automates a significant portion of the migration process, it's important to note that it's not a complete solution. You should still:

  1. Thoroughly test your application after running the script.
  2. Be aware of Bootstrap 4's new components and features that may require manual implementation.
  3. Review your custom CSS and JavaScript that might interact with Bootstrap classes.

Conclusion

This script provides a powerful, automated way to handle a large part of the Bootstrap 3 to 4 migration process, saving developers significant time and reducing the chance of manual errors. It represents the first step in our journey to modernize our legacy C# .NET codebase. Once we've successfully migrated to Bootstrap 4 and ensured stability, we'll tackle the next phase: moving from Bootstrap 4 to 5.

Remember, while automation is incredibly helpful, it's not a substitute for understanding the changes between Bootstrap versions. Use this script as a powerful aid in your migration process, but always couple it with your expertise and thorough testing.

Happy migrating!

版本声明 本文转载于:https://dev.to/stokry/modernizing-bootstrap-in-a-c-net-codebase-a-python-powered-migration-from-3-to-5-49ej?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 尽管代码有效,为什么 POST 请求无法捕获 PHP 中的输入?
    尽管代码有效,为什么 POST 请求无法捕获 PHP 中的输入?
    解决 PHP 中的 POST 请求故障在提供的代码片段中:action=''而不是:action="<?php echo $_SERVER['PHP_SELF'];?>";?>"检查 $_POST数组:表单提交后使用 var_dump 检查 $_POST 数...
    编程 发布于2024-12-20
  • 除了“if”语句之外:还有什么地方可以在不进行强制转换的情况下使用具有显式“bool”转换的类型?
    除了“if”语句之外:还有什么地方可以在不进行强制转换的情况下使用具有显式“bool”转换的类型?
    无需强制转换即可上下文转换为 bool您的类定义了对 bool 的显式转换,使您能够在条件语句中直接使用其实例“t”。然而,这种显式转换提出了一个问题:“t”在哪里可以在不进行强制转换的情况下用作 bool?上下文转换场景C 标准指定了四种值可以根据上下文转换为的主要场景bool:语句:if、whi...
    编程 发布于2024-12-20
  • 大批
    大批
    方法是可以在对象上调用的 fns 数组是对象,因此它们在 JS 中也有方法。 slice(begin):将数组的一部分提取到新数组中,而不改变原始数组。 let arr = ['a','b','c','d','e']; // Usecase: Extract till index p...
    编程 发布于2024-12-20
  • 如何在 PHP 中组合两个关联数组,同时保留唯一 ID 并处理重复名称?
    如何在 PHP 中组合两个关联数组,同时保留唯一 ID 并处理重复名称?
    在 PHP 中组合关联数组在 PHP 中,将两个关联数组组合成一个数组是一项常见任务。考虑以下请求:问题描述:提供的代码定义了两个关联数组,$array1和$array2。目标是创建一个新数组 $array3,它合并两个数组中的所有键值对。 此外,提供的数组具有唯一的 ID,而名称可能重合。要求是构...
    编程 发布于2024-12-20
  • 如何使用 MySQL 查找今天生日的用户?
    如何使用 MySQL 查找今天生日的用户?
    如何使用 MySQL 识别今天生日的用户使用 MySQL 确定今天是否是用户的生日涉及查找生日匹配的所有行今天的日期。这可以通过一个简单的 MySQL 查询来实现,该查询将存储为 UNIX 时间戳的生日与今天的日期进行比较。以下 SQL 查询将获取今天有生日的所有用户: FROM USERS ...
    编程 发布于2024-12-20
  • 如何修复 macOS 上 Django 中的“配置不正确:加载 MySQLdb 模块时出错”?
    如何修复 macOS 上 Django 中的“配置不正确:加载 MySQLdb 模块时出错”?
    MySQL配置不正确:相对路径的问题在Django中运行python manage.py runserver时,可能会遇到以下错误:ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Library/Python/2.7/site-...
    编程 发布于2024-12-20
  • 在 Go 中使用 WebSocket 进行实时通信
    在 Go 中使用 WebSocket 进行实时通信
    构建需要实时更新的应用程序(例如聊天应用程序、实时通知或协作工具)需要一种比传统 HTTP 更快、更具交互性的通信方法。这就是 WebSockets 发挥作用的地方!今天,我们将探讨如何在 Go 中使用 WebSocket,以便您可以向应用程序添加实时功能。 在这篇文章中,我们将介绍: WebSoc...
    编程 发布于2024-12-20
  • Bootstrap 4 Beta 中的列偏移发生了什么?
    Bootstrap 4 Beta 中的列偏移发生了什么?
    Bootstrap 4 Beta:列偏移的删除和恢复Bootstrap 4 在其 Beta 1 版本中引入了重大更改柱子偏移了。然而,随着 Beta 2 的后续发布,这些变化已经逆转。从 offset-md-* 到 ml-auto在 Bootstrap 4 Beta 1 中, offset-md-*...
    编程 发布于2024-12-20
  • 插入数据时如何修复“常规错误:2006 MySQL 服务器已消失”?
    插入数据时如何修复“常规错误:2006 MySQL 服务器已消失”?
    插入记录时如何解决“一般错误:2006 MySQL 服务器已消失”介绍:将数据插入 MySQL 数据库有时会导致错误“一般错误:2006 MySQL 服务器已消失”。当与服务器的连接丢失时会出现此错误,通常是由于 MySQL 配置中的两个变量之一所致。解决方案:解决此错误的关键是调整wait_tim...
    编程 发布于2024-12-20
  • 使用“list.List”是创建带有字符串键和列表值的 Go 映射的最佳方法吗?
    使用“list.List”是创建带有字符串键和列表值的 Go 映射的最佳方法吗?
    创建字符串到列表的映射问题:您想要创建一个带有字符串类型键的映射和列表类型的值。以下代码片段是否是正确的方法:package main import ( "fmt" "container/list" ) func main() { x ...
    编程 发布于2024-12-19
  • 使用 html css 和 javascript 幻觉的 Tic-Tac-Toe 游戏 https://www.instagram.com/webstreet_code/
    使用 html css 和 javascript 幻觉的 Tic-Tac-Toe 游戏 https://www.instagram.com/webstreet_code/
    在 Instagram 上关注我们:https://www.instagram.com/webstreet_code/ ?✨ 带有玻璃效果的井字游戏! ✨? 我刚刚使用 HTML、CSS 和 JavaScript 构建了一款经典的 Tic-Tac-Toe 游戏,具有时尚的玻璃态设计。观看视频,看看如...
    编程 发布于2024-12-19
  • TB 级数据库的 MySQL 与 NoSQL:聚集索引何时是正确的解决方案?
    TB 级数据库的 MySQL 与 NoSQL:聚集索引何时是正确的解决方案?
    MySQL:探索数据库设计迷宫优化大型数据库时,必须考虑数据库设计策略以提高性能。在给定的场景中,包含线程的 TB 级数据库由于其庞大的规模而面临性能挑战。本文探讨了 MySQL 和 NoSQL 之间的选择,重点介绍了 MySQL 的 innodb 引擎及其聚集索引的优势。了解 MySQL 的 In...
    编程 发布于2024-12-19
  • 为什么我的 Spring Boot 应用程序不自动创建数据库架构?
    为什么我的 Spring Boot 应用程序不自动创建数据库架构?
    在 Spring Boot 中自动创建数据库架构启动 Spring Boot 应用程序时,可能会遇到自动创建数据库架构的问题。以下故障排除步骤旨在解决此问题:1.实体类包:确保实体类位于使用@EnableAutoConfiguration注解的类的同一个包或子包中。否则,Spring 将不会检测实体...
    编程 发布于2024-12-18
  • CSS3 过渡是否提供事件来检测起点和终点?
    CSS3 过渡是否提供事件来检测起点和终点?
    了解 CSS3 过渡事件CSS3 过渡允许在 Web 元素上实现流畅的动画和视觉效果。为了增强用户体验并使操作与这些转换同步,监控其进度非常重要。本文解决了 CSS3 是否提供事件来检查过渡何时开始或结束的问题。W3C CSS 过渡草案W3C CSS 过渡草案规定CSS 转换会触发相应的 DOM 事...
    编程 发布于2024-12-18
  • Java 中可以手动释放内存吗?
    Java 中可以手动释放内存吗?
    Java 中的手动内存释放与垃圾回收与 C 不同,Java 采用托管内存框架来处理内存分配和释放由垃圾收集器 (GC) 自动执行。这种自动化方法可以提高内存利用率并防止困扰 C 程序的内存泄漏。Java 中可以手动释放内存吗?由于 Java 的内存管理是由GC,它没有提供像 C 中的 free() ...
    编程 发布于2024-12-18

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3