Thursday, 2 February 2023

YouTube: Unsubscribe all the channels in one go (Mass Un Subscribe)

 

Let's learn how to unsubscribe from all the channels in one go. YouTube does not provide a feature to unsubscribe from all the channels. You can run the script manually to unsubscribe from all the channels.


Step 1: Go to YouTube
Step 2: Click on the Subscriptions on the left panel.

Step 3: Click on the Manage button on the top right.











Step 4: Right-click on the page and click Inspect






















Step 5: Go to the Console tab and paste the below script and press enter














var num = 0;
var myVar = setInterval(unSubscribe, 3000);
function unSubscribe () 
{
  var ele = document.getElementById('grid-container').getElementsByClassName('ytd-expanded-shelf-contents-renderer');
if (num < ele.length) 
{
ele[num].querySelector("[aria-label^='Unsubscribe from']").click();
setTimeout(function () 
{
document.getElementsByClassName('yt-spec-button-shape-next yt-spec-button-shape-next--text yt-spec-button-shape-next--call-to-action yt-spec-button-shape-next--size-m')[0].click()
}, 2000);
}
num++;
console.log(num + " unsubscribed");
console.log(ele.length + " Total");
}


The system will start unsubscribing the channel. 












If you have more than 70 subscribe channels. then you can rerun the script once the script is over. Default, it will pick the first 60-100 records.


That's all about this article. 

Sunday, 8 January 2023

A list of common migration errors from .Net Core 2 or .Net Core 3.1 to .Net 6 or .Net 7

You may encounter these errors when migrating your project to .Net 6 or .Net 7. Below is the error.

1.  'The ConnectionString property has not been initialized.'

In .Net 6 or 7, use has to use the keyword ConnectionStrings instead of ConnectionString otherwise you will get an error, connection string property has not been initialized.







2. A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.)'


If you are getting the above error this means you need to make the connection string encrypted false in app settings. 











3. An unhandled exception occurred while processing the request. InvalidOperationException: Unable to resolve service for type 'Service.IService' while attempting to activate


In .Net 6 or 7, we don’t have a start-up file. So, you must include everything in Program.cs. file


// Register interface and classes

builder.Services.AddScoped<IHotelService, HotelService>();

 

In Program.cs file, Register dependency before builder.build() command. It will resolve your issue.











4. InvalidOperationException: Unable to resolve service for type 'Data.LocatorDBContext' while attempting to activate 'Service.HotelService'. or
System.AggregateException: 'Some services are not able to be constructed


If you are facing the above issue this means you have not resolved the context in the program.cs and have not included the connection string in the Program.cs. Add the below lines and it will resolve the dependency.

 

builder.Services.AddDbContext<LocatorDBContext>(options =>

        options.UseSqlServer(builder.Configuration.GetConnectionString("LocatorDB")));







For UseSQLserver keyword, you need to include Nuget package.


Microsoft.EntityFrameworkcore.SQLServer


5. System.InvalidOperationException: 'No service for type 'Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionaryFactory' has been registered.'

This means you have not registered MVC views in Program.cs file. Just add the below line in program.cs file. 


builder.Services.AddControllersWithViews();














6. No web page was found for the web address: http://localhost:5242/hotel/index


This error will occur if you have not registered routing in the program.cs file. Include the below line and it will work.

 

app.MapControllerRoute(

    name: "default",

    pattern: "{controller=Hotel}/{action=Index}/{id?}");












This will resolve the issue. I hope you like the article.

Tuesday, 3 January 2023

Ajax Form in Asp.Net Core MVC and Validations

Let's learn how to send a request to the Controller using Ajax. Sending requests to the Controller is a common need. Here we will learn how we can send the request through ajax. The first step is to include scripts in the folder.

Include Ajax Scripts


First, you need to ensure you have ajax-unobtrusive scripts in the folder. If not please download and add to the wwwroot or you can right-click on Wwwroot
Add-->Client Side Library




Search for ajax and install it. It will automatically add all the scripts in the www root.






Add Ajax in the form tag


 <form method="post" data-ajax="true" data-ajax-complete="mycompelte" data-ajax-success="mysuccess"  asp-action="AddHotel" asp-controller="Hotel" data-ajax-loading="#myloader">

data-ajax="true"
data-ajax-complete="mycompelte" (Complete Event, create javascript method of any name)
data-ajax-success="mysuccess" (Success Event, create javascript method of any name, In this example, I have used mysuccess method name)
asp-action="AddHotel" (MVC Method Name)
asp-controller="Hotel"  (MVC Controller Name)
data-ajax-loading="#myloader" (For Loader)

<div class="d-flex justify-content-center">
                <div role="Status" class="spinner-border" id="myloader" style="display:none;">
                    <span class="sr-only">Loading....</span>
                </div>
 </div>


Once you press the submit button it automatically sends the request to Add Hotel method asynchronously. Once the work is done it runs the success and completes the javascript method.


Now, let's learn how to add validation.

 public class HotelModel
    {
        public int HotelId { get; set; }
      
        [Required(ErrorMessage = "*")]
        public string HotelName { get; set; }
       
        [Required(ErrorMessage = "*")]
        public string Address { get; set; }      
}

For this, you need to use asp-validation-for property in the span tag, shown below. For input control, you can use @Html.TextBoxFor or input asp-for.

  <input asp-for="HotelName" />
 <span asp-validation-for="HotelName" class="text-danger"></span>

 @Html.TextBoxFor(d => d.Address,new{style="width:75%;"})
<span asp-validation-for="Address" class="text-danger"></span>


Also, you need to include the necessary files to run the validations.


1. JQuery
2. JQuery.Validate
3. JQuery.Validate. unobtrusive


<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>

<script type="text/javascript">

  function mysuccess(data) {
    }
</script>

That's all about this article.






Monday, 2 January 2023

Revert Git Changes Through Terminal / Command Prompt

 If you accidentally commit your code then don't worry you can revert your changes with a few commands. you can easily go to your last commit. Let's learn


Here is my code below. I have added one comment below in one of the files and I'll commit that.







I am saving that file with the below comment. Once its saved then let's run few commands.













1. Let's run the first command on the cmd prompt/terminal

 git log











It will give you the commit Id as shown in the snapshot below. Now we need to revert that changes.


2.  Copy the commit Id and run the second command.

git revert 59186cf31db4c520a6cf68343fb55843d0a369b8


You can see the comment has been removed from the code







3. Git changes will show you revert changes. You need to commit to that and that's it.
















If you permanently delete the changes and remove them from history as well then follow the next article.
https://setiasunny.blogspot.com/2023/01/git-remove-last-commit-or-go-to.html


Hope you will like the article.

GIT remove last commit or go to previous commit

 If you commit the changes by mistake and want to remove that commit or want to go to the last commit then here are some simple commands.


In my example, I have added comments in the code and committed it.

Step 1: Run the command on Command Prompt / Terminal


    git log --oneline




It will display all the recent commits. In my example, I have recently committed "7897e22". Not, I want to go to the previous commits.


Step 2: Run the next command
    

            git reset head~1  (or)

            git reset 0e18a7c


Either you can go to the previous commit by (head~1) or you can specify the Id by checking from the git log.


You can use any one of the above commands.


Step 3: Once you run this command, you can see your changes in the Git Changes. If you want to delete all the changes then You can run the reset hard command. Please run this command carefully. If will remove all the recent changes.

       git reset --hard


Now, if you will check the git log again, you can see recent commit has been removed from the log.






If you only want to revert the changes and do not want to delete them from the log then you can follow the below article.
https://setiasunny.blogspot.com/2023/01/revert-git-changes-through-terminal.html

I hope you like the article. Thank you for reading this.




Wednesday, 9 November 2022

How to reset Azure VM username or password?

If you've forgotten your Azure VM username or password, don't worry. Resetting your username and password is easy through Azure Portal.

Below are the steps.

Step 1: Go to Azure Portal and select your VM.
Step 2: Under the options, you will find the Reset password option.

















Step3: Enter your new username and password and click update on the top






















Hurrah, now you can easily connect VM with your new username and password.


Monday, 4 July 2022

Important SQL Queries

 Here we will discuss some of the important SQL queries.

  • Get Database list

        SELECT name as DB_Name,create_date as CreatedDate
        FROM sys.databases

  • Get row count in all the Database tables

           SELECT QUOTENAME(SCHEMA_NAME(sOBJ.schema_id)) + '.' +                                                     QUOTENAME(sOBJ.name) AS [TableName]
           ,SUM(sPTN.Rows) AS [RowCount]
           FROM  sys.objects AS sOBJ  INNER JOIN sys.partitions AS sPTN
           ON sOBJ.object_id = sPTN.object_id
           WHERE sOBJ.type = 'U'    AND sOBJ.is_ms_shipped = 0x0
           AND index_id < 2 -- 0:Heap, 1:Clustered
           GROUP BY sOBJ.schema_id , sOBJ.name
           ORDER BY [TableName]

  • Recent Modified stored procedures and tables

        SELECT name, create_date, modify_date ,type
        FROM sys.objects
        WHERE type = 'P' or  type = 'U'
        ORDER BY modify_date DESC


  • The last query runs on the database

          SELECT  text,*
          FROM    sys.dm_exec_query_stats AS deqs
          CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
          WHERE   deqs.last_execution_time > '5/16/2022'
          order by creation_time desc


  • Check user roles in the database

          SELECT ServerName=@@servername, dbname=db_name(db_id()),
           p.name as UserName, p.type_desc as TypeOfLogin, 
          pp.name as PermissionLevel, pp.type_desc as TypeOfRole 
          FROM sys.database_role_members roles
          JOIN sys.database_principals p ON roles.member_principal_id = p.principal_id
          JOIN sys.database_principals pp ON roles.role_principal_id = pp.principal_id

  • CTE for Recursive Query

    WITH CTE AS      
    (        
    SELECT 1 Number        
    UNION ALL        
    SELECT Number + 1 FROM CTE WHERE Number<20        
    

    SELECT * FROM CTE

  • Create a new user from the query

        CREATE LOGIN [ServiceUser] WITH PASSWORD = 'Admin@27'
        CREATE USER [ServiceUser] FOR LOGIN [ServiceUser] WITH DEFAULT_SCHEMA=[dbo]

Note: Run Create Login query on Master DB, Run User Query on specific DB access.

If you want to create a new login for an Azure AD user then run the below query on Master DB

        

  CREATE LOGIN [ademail] from external provider;

If you want to create a user in the specific DB then use the below query

CREATE USER [User1] WITH PASSWORD = 'Test@12', DEFAULT_SCHEMA = dbo; 

Assign Roles to newly created User

        EXEC sys.sp_addrolemember 'db_datareader', 'serviceuser';
        EXEC sys.sp_addrolemember 'db_datawriter', 'serviceuser'; 
        EXEC sys.sp_addrolemember 'db_owner', 'ServiceUser';

If you got an error, Login failed. You need to check whether mixed Authentication is enabled or not. Run below query.

SELECT SERVERPROPERTY('IsIntegratedSecurityOnly');

  • If the result is 1, it means Windows Authentication mode is enabled (SQL Server logins are disabled).
  • If the result is 0, Mixed Mode (Windows and SQL authentication) is enabled.

    Change to Mixed Mode Authentication:

    1. Open SQL Server Management Studio (SSMS).
    2. Right-click on the SQL Server instance and select Properties.
    3. Go to the Security page.
    4. Select SQL Server and Windows Authentication mode (Mixed Mode).
    5. Restart the SQL Server service.
    • While loop

          DECLARE @ComponentCode int=0
          WHILE EXISTS (SELECT 1 FROM QualityList WHERE QualityId > @ComponentCode)       BEGIN SELECT @ComponentCode = MIN(QualityId) FROM QualityList WHERE QualityId > @ComponentCode SELECT @ComponentCode      END

    • Drop all tables
        SELECT  'DROP TABLE [' + name + '];' FROM    sys.tables

         Run the query copy all the table commands and execute.

    • Remove all Stored Procedures with Query
    DECLARE @procedureName VARCHAR(500)
    DECLARE cur CURSOR
     
        FOR SELECT [name] FROM sys.objects WHERE TYPE = 'p'
        OPEN cur
        FETCH NEXT FROM cur INTO @procedureName
        WHILE @@fetch_status = 0
        BEGIN
            EXEC('DROP PROCEDURE [' + @procedureName + ']')
            FETCH NEXT FROM cur into @procedureName
    END
    CLOSE cur
    DEALLOCATE cur

    • Calculate SQL/Azure SQL Database Size

            SELECT (SUM(reserved_page_count) * 8192) / 1024 / 1024  AS DbSizeInMB
    FROM sys.dm_db_partition_stats

    How to get PowerBI Embed Token

     Here's a step-by-step guide to help you through the process. Step 1: Register Your App in Azure 1. Go to Azure Portal → App registratio...