Advertisements

Code First Migration – ASP.NET MVC 5 With EntityFrameWork & MySql


Introduction

We know how to use Code First Migration in SQL Server. But in most cases, a customer will think we can use it for the open source database. So that’s the reason we pick the “MySQL” database, and we can follow the same steps we follow in the “SQL” database. In this article, we are going to explain Code First Migration in ASP.NET MVC 5 with Entity FrameWork & MySQL.

Prerequisites

  1. MySQL Installer
  2. Download MySQL Workbench
  3. Visual Studio ( We are using Visual Studio 2017 Community Edition ).

Create a Web Application using MVC 5

Click on File -> New -> Project -> Visual C# -> Web -> ASP.Net Web Application ( .Net Framework ).

Click on “OK” then click on “MVC”.

Install EntityFramework & MySql Entity

Go to Visual Studio “Tools -> Nuget Package Manager -> Manage Nuget Packages for Solution” or Right click on your Web Application then click on “Manage Nuget Packages”.

EntityFramework

Search EntityFramework in the “Browse” Section.

MySql.Data.Entity

Search MySql.Data.Entity in the “Browse” Section.

Once we installed EntityFramework & MySql Entity in our application then it will generate a SQL and MySQL Provider inside the EntityFramework Section in Web.Config.

<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.8.8.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider></providers>
</entityFramework>

Model Class

We just created a sample model class for demo purpose.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebAppWithMySql.Models
{
public class Student
{
public int Id { get; set; }

public string Name { get; set; }

public string Password { get; set; }
}
}

Creation of DBContext

Create a db context class in our application. The following dbcontext will point out our connection string in WebConfig.

using MySql.Data.Entity;
using System.Data.Entity;
using WebAppWithMySql.Models;

namespace WebAppWithMySql
{
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class WebAppContext : DbContext
{
public DbSet<Student> Products
{
get;
set;
}
public WebAppContext()
//Reference the name of your connection string ( WebAppCon )
: base("WebAppCon") { }
}
}

Connection String

We added the same connection string name that we added in the dbcontext class. The following connection string represents “MySql” Db.

<connectionStrings>
<add name="WebAppCon" providerName="MySql.Data.MySqlClient" connectionString="server=localhost;userid=root;password=rajeesh123;database=WebAppMySql;persistsecurityinfo=True" />
</connectionStrings>

Migration Steps

  1. Enable-Migrations – ( We need to enable the migration, only then can we do the EF Code First Migration ).
  2. Add-Migration IntialDb (migration name) – ( Add a migration name and run the command ).
  3. Update-Database -Verbose — if it is successful then we can see this message (Running Seed method).

Once Migration is done; then, we can see that the respective files are auto-generated under the “Migrations” folder.

OutPut

See Also

You can download other ASP.NET Core source codes from MSDN Code, using the link, mentioned below.

Summary

In this article, we are going to explain Code First Migration in ASP.NET MVC 5 with EntityFrameWork & MySql. I hope this article is useful for all Azure beginners.

Advertisements

Channel Configuration : Azure Bot Service to Slack Application


Introduction

This article explains how to configure Azure Bot Service to Slack Applications. So, before reading this article, please read our previous article related to Create and Connect a chat bot with Azure Bot Service. Then, we will get a clear idea of how to create a Bot service in Azure.

Create a Web App Bot in Azure

Click on “New” on the left side menu and it will open an Azure Marketplace. There, we can see the list of services. Click “AI + Cognitive Services” then click on the “Web App Bot” for your bot service app.

Bot Service

Fill the following details and add the location based on your client location or your Geolocation.

Once the build is successful, click on the “Dashboard” and we can see that the “menothbotdemo” bot is created in the All resources list. Bot is ready for use!

Create a Slack Application for our bot

First, we need to create a workspace in Slack Account. Check the following link to create a Slack Account: New slack account

Create an app and assign a Development Slack team or Slack Workspace

  1. Click on the url https://api.slack.com/apps. Then, click on the “Create New App” !!.

Once the Slack workspace is created, then only we can create a slack application under the Workspace. Now, we are going to create and assign our slack app name into the Workspace. We have given our App a name as “menothbotdemo”.

Click on the “Create App” button. Then, Slack will create our app and generate a Client ID and Client Secret. We can use these IDs for channel configuration in Azure Web App bot.

Add a new Redirect URL

Click on the “OAuth & Permission” tab in the left panel. Then, add the redirect URLs as “https://slack.botframework.com&#8221; and save it properly.

Create Bot Users

Click on the “Bot Users” tab in the left panel. Then, click on “Add a Bot User”. In this section, we can give our bot “Display name”. For example, we created our bot user’s name as “menothbotdemo”. If we want our bot to always show as Online, then click on the “On” button. After that, click “Add Bot User” button.

Event Subscriptions

  1. Select “Event Subscriptions” tab in the left panel.
  2. Click Enable Events to On.
  3. In the “Request URL” we need to add the following URL to our “Bot Handle Name”.

https://slack.botframework.com/api/Events/{bot handle name}

The “Bot Handle” name we will get inside the “Web App Bot ( we created our web app as “menothbotdemo”)” Settings.

Finally, we can add the Request URL inside the Event Subscriptions.

4.  In Subscribe to Bot Events, click “Add Bot User Event”.

5. In the list of events, click “Add Bot User Event” and select the following event name.

Subscribe to Bot Events

6. Click “Save Changes”.

Configure Interactive Messages ( Optional )

  1. Select the “Interactive Components” tab and click “Enable Interactive Components”.
  2. Enter https://slack.botframework.com/api/Actions as the request URL.
  3. Click the “Enable Interactive Messages” button, and then click the “Save Changes” button.

App Credentials

Select the “Basic Information” tab and then we will get the ClientID & Client Secret & Verification Token for our channel configuration in Azure Bot Service.

Channel Configuration

There is a very simple way to connect our bot service app to Slack in Azure. Just follow the following steps.

Click on the “Channels” menu on the left side option. Then, it will open a window with channel details where you can see “More channels” options. Then, select “Slack” in the channels list.

Add the following Slack App ( Already Created Slack App ) credentials into the Azure Slack configuration section.

  • ClientID
  • Client Seceret
  • Verification Token

Once the configuration is done, we can see our Slack configured into the channel.

C# Code

We have done some changes in the default code in bot service.

using System;
using System.Threading.Tasks;

using Microsoft.Bot.Connector;
using Microsoft.Bot.Builder.Dialogs;
using System.Net.Http;

namespace Microsoft.Bot.Sample.SimpleEchoBot
{
[Serializable]
public class EchoDialog : IDialog<object>
{
protected int count = 1;

public async Task StartAsync(IDialogContext context)
{
context.Wait(MessageReceivedAsync);
}

public async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> argument)
{
var message = await argument;

if (message.Text == "reset")
{
PromptDialog.Confirm(
context,
AfterResetAsync,
"Are you sure you want to reset the count?",
"Didn't get that!",
promptStyle: PromptStyle.Auto);
}
else if (message.Text == "Hi")
{
await context.PostAsync($"{this.count++}: Slack Configured in Bot App !!");
context.Wait(MessageReceivedAsync);
}
else
{
await context.PostAsync($"{this.count++}: You said {message.Text}");
context.Wait(MessageReceivedAsync);
}
}

public async Task AfterResetAsync(IDialogContext context, IAwaitable<bool> argument)
{
var confirm = await argument;
if (confirm)
{
this.count = 1;
await context.PostAsync("Reset count.");
}
else
{
await context.PostAsync("Did not reset count.");
}
context.Wait(MessageReceivedAsync);
}

}
}

Output

Reference

See Also

You can download other ASP.NET Core source codes from MSDN Code, using the link, mentioned below.

Summary

We learned how to configure Azure Bot Service to Slack application. I hope this article is useful for all Azure beginners.

Create & Deploy an ASP.NET Core web app in Azure


Introduction

Nowadays, most people are choosing web hosting on a cloud platform. Microsoft lovers like us basically select “Microsoft Azure” as our hosting environment.That’s the reason I have written this new article defining a simple way of hosting in Azure.

Before reading this article, you must read the articles given below for ASP.NET Core knowledge.

Azure Account 

First, we need to create an account on the Azure portal. Only then can we host the application in the cloud environment. So, please check the following steps to create an Azure account.

Azure Account Registration

Create an account through this link to Azure Portal.

Domain Registration

We need to host our application in a particular domain. Check the following steps –

  1. Click on “All resources” on the left side menu and it will open a dashboard with an empty or already existing list of resources that we have created earlier.
  2. Click on the “Add” button and it will open another window with multiple options. We can choose an appropriate option to host our application.
  3. As per our requirement, we choose “Web + Mobile” and clicked on the “Web App” on the right side.
App Name Creation

App Name Creation

4. It will open another form to fill up our app details to host. We need to give a unique name in the “Appname” section and It will create a subdomain for our ASP.NET Core application.

5. We choose subscription as “Free Trial” because we created a free account on the Azure portal.

6. We need to host our app resources in Resource group, So first we need to create a resource group name in our Azure account. But we choose existing resource group name “AzureDemo” that we are already created in our Azure account.

7.”OS ( Operating System )” we selected as “Windows”( As per our requirement ).

8. We can create our own App Service Plan name.

9. Application Insight will give you the more clarity about your hosted app. Eg. analytics, etc.

10. Click on the “Create” button and wait for the build success.

Resource Group Name

Resource Group Name

11. Another way to create the Resource Group Name – click on “Resource groups -> Add”.

Resource Group

Resource Group

12. Once the build is succeeded, then we can see this output.

Build Succeeded

Simple steps to create an Asp.Net Core Application

  1. Open our  VisualStudio then click on File > New > Project.
  2. Select Visual C# > Web > ASP.NET Core Web Application.
  3. We have given our application name as “MyFirstAzureWebApp”.
  4. Then, click OK.
  5. Click on the “Ctrl+F5”

App Publishing into Azure
We created a default ASP.NET Core application ( We have done some changes in UI Section) for the publishing process.

  1. Right click on the application and click on the Publish menu.
App Publishing

App Publishing

2. Click on the “Microsoft Azure App Service”

3. We choose our existing resource group name ( That we created ! “AzureDemo” ) in our Azure Portal and It will display the App Name inside the “AzureDemo” folder. This will display only when we are login through the Visual Studio using Azure credentials ( Email & Password).

Resource Name

Resource Name

OutPut

The application is hosted in given domain address  http://menoth.azurewebsites.net/

Reference

See Also

You can download other ASP.NET Core source codes from MSDN Code, using the link, mentioned below.

Summary

We learned how to create and deploy an ASP.NET Core web app in Azure. I hope this article is useful for all ASP.NET Core & Azure beginners.

 

Startup Page In ASP.NET Core


Introduction

I think we all are familiar with the configuration of the default startup page in the previous versions of AP.NET but it’s slightly different in ASP.NET Core applications. In this article, I will explain how to configure the default startup page In ASP.NET Core.

Default Startup Page Configuration

There are two ways to implement the default startup page in ASP.NET Core.

  • Default Configuration
  • Customized Configuration

Before reading this article, you must read the articles given below for ASP.NET Core knowledge.

Default Configuration

We can use UseDefaultFiles() extension method in ASP.NET Core 1.0. UseDefaultFiles() will only search for the files given in “wwwroot”. If any of the files are detected first in “wwwroot”, the files are run as default in the client browser.

  • default.html
  • default.htm
  • index.html
  • index.htm

UseDefaultFiles must be called before UseStaticFiles or any other method (app.Run, app.Use) to serve the default file in the client-side browser. As you state UseStaticFiles() method after UseDefaultFiles(), it will run UseStaticFiles() method as a default and automatically terminates the other files which come after UseStaticFiles() method.

Customized Configuration

In this case, we are calling other customized pages as default startup pages in ASP.NET Core 1.0. Thus, we can use DefaultFilesOptions in ASP.NET Core 1.0. If you want to run other files as default, check the code given below in Startup.cs.

Full Code

The following code containsthe full source code of startup page configuration in ASP.NET Core.

using Microsoft.AspNetCore.Builder;  
using Microsoft.AspNetCore.Hosting;  
using Microsoft.AspNetCore.Http;  
using Microsoft.Extensions.DependencyInjection;  
using Microsoft.Extensions.Logging;  
   
namespace StartupConfig  
{  
    public class Startup  
    {  
        // This method gets called by the runtime. Use this method to add services to the container.  
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 Jump  
        public void ConfigureServices(IServiceCollection services)  
        {  
        }  
   
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)  
        {  
            loggerFactory.AddConsole();  
               
            DefaultFilesOptions DefaultFile = new DefaultFilesOptions();  
            DefaultFile.DefaultFileNames.Clear();  
            DefaultFile.DefaultFileNames.Add("Welcome.html");  
            app.UseDefaultFiles(DefaultFile);  
            app.UseStaticFiles();  
   
            if (env.IsDevelopment())  
            {  
                app.UseDeveloperExceptionPage();  
            }  
   
            app.Run(async (context) =>  
            {  
                await context.Response.WriteAsync("Hello World!");  
            });  
        }  
    }  
}  

project.json

The versions will be change based on the latest version’s updation in ASP.NET Core.

{  
  "dependencies": {  
    "Microsoft.NETCore.App": {  
      "version": "1.0.1",  
      "type": "platform"  
    },  
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",  
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",  
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",  
    "Microsoft.Extensions.Logging.Console": "1.0.0",  
    "Microsoft.AspNetCore.StaticFiles": "1.1.1"  
  },  
   
  "tools": {  
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"  
  },  
   
  "frameworks": {  
    "netcoreapp1.0": {  
      "imports": [  
        "dotnet5.6",  
        "portable-net45+win8"  
      ]  
    }  
  },  
   
  "buildOptions": {  
    "emitEntryPoint": true,  
    "preserveCompilationContext": true  
  },  
   
  "runtimeOptions": {  
    "configProperties": {  
      "System.GC.Server": true  
    }  
  },  
   
  "publishOptions": {  
    "include": [  
      "wwwroot",  
      "web.config"  
    ]  
  },  
   
  "scripts": {  
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]  
  }  
}  

Configuration Code

DefaultFilesOptions DefaultFile = new DefaultFilesOptions();
DefaultFile.DefaultFileNames.Clear();
DefaultFile.DefaultFileNames.Add("Welcome.html");
app.UseDefaultFiles(DefaultFile);
app.UseStaticFiles();

Reference

Output

Startup_Page

Startup_Page

See Also

You can download other ASP.NET Core source codes from MSDN Code, using the link, mentioned below.

Summary

We learned how to configure the default startup page in ASP.NET Core 1.0. I hope this article is useful for all ASP.NET Core 1.0 beginners.

QR Code Generator in ASP.NET Core Using Zxing.Net


Introduction

In this article, we will explain how to create a QR Code Generator in ASP.NET Core 1.0, using Zxing.Net.

Background

I tried to create a QR Code Generator in ASP.NET Core, using third party libraries but in most of the cases codes are not fully supported in ASP.NET Core because of some version issues etc. I searched a lot in Google but finally I found “Zxing.Net” and it is a library, which supports decoding and generating of the barcodes. I had a discussion with MicJahn and came up  with a great solution.

Before reading this article, you must read the articles given below for ASP.NET Core knowledge.

Zxing.Net

A library, which supports decoding and generating of the barcodes (Example: QR Code, PDF 417, EAN, UPC, Aztec, Data Matrix, Codabar) within the images.

Assemblies Required

The assemblies given below are required for QR Code Generator.

using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
using System.IO;
using ZXing.QrCode;

Packages required

We need the packages given below for drawing and creating QR Code Generator.

"CoreCompat.System.Drawing": "1.0.0-beta006",    
"ZXing.Net": "0.15.0" 

C#

QRCodeTagHelper class given below contains QR Code Generator methods etc.

namespace QRCodeApp {  
    [HtmlTargetElement("qrcode")]  
    public class QRCodeTagHelper: TagHelper {  
        public override void Process(TagHelperContext context, TagHelperOutput output) {  
            var QrcodeContent = context.AllAttributes["content"].Value.ToString();  
            var alt = context.AllAttributes["alt"].Value.ToString();  
            var width = 250; // width of the Qr Code    
            var height = 250; // height of the Qr Code    
            var margin = 0;  
            var qrCodeWriter = new ZXing.BarcodeWriterPixelData {  
                Format = ZXing.BarcodeFormat.QR_CODE,  
                    Options = new QrCodeEncodingOptions {  
                        Height = height, Width = width, Margin = margin  
                    }  
            };  
            var pixelData = qrCodeWriter.Write(QrcodeContent);  
            // creating a bitmap from the raw pixel data; if only black and white colors are used it makes no difference    
            // that the pixel data ist BGRA oriented and the bitmap is initialized with RGB    
            using(var bitmap = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb))  
            using(var ms = new MemoryStream()) {  
                var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);  
                try {  
                    // we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image    
                    System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length);  
                } finally {  
                    bitmap.UnlockBits(bitmapData);  
                }  
                // save to stream as PNG    
                bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);  
                output.TagName = "img";  
                output.Attributes.Clear();  
                output.Attributes.Add("width", width);  
                output.Attributes.Add("height", height);  
                output.Attributes.Add("alt", alt);  
                output.Attributes.Add("src", String.Format("data:image/png;base64,{0}", Convert.ToBase64String(ms.ToArray())));  
            }  
        }  
    }  
}   

Index.chtml

The code given below will display QR Code Generator.

@{  
    ViewData["Title"] = "Home";  
}  
   
<h2>@ViewData["Title"].</h2>  
<h3>@ViewData["Message"]</h3>  
   
A library which supports decoding and generating of barcodes (like QR Code, PDF 417, EAN, UPC, Aztec, Data Matrix, Codabar) within images.  
   
<qrcode alt="QR Code" content="https://rajeeshmenoth.wordpress.com/" />  
 https://rajeeshmenoth.wordpress.com/  

_ViewImports.cshtml

The code Injecting TagHelper given below is in the entire Application.

@addTagHelper "*, QRCodeApp"  

project.json

The dependencies given below are required to create QR Code Application.

{  
  "dependencies": {  
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",  
    "Microsoft.AspNetCore.Mvc": "1.1.2",  
    "Microsoft.AspNetCore.Mvc.Core": "1.1.2",  
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",  
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",  
    "Microsoft.AspNetCore.StaticFiles": "1.1.1",  
    "Microsoft.Extensions.Logging.Console": "1.0.0",  
    "CoreCompat.System.Drawing": "1.0.0-beta006",  
    "ZXing.Net": "0.15.0"  
  },  
   
  "tools": {  
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"  
  },  
   
  "frameworks": {  
    "net452": { }  
  },  
   
  "buildOptions": {  
    "emitEntryPoint": true,  
    "preserveCompilationContext": true  
  },  
   
  "publishOptions": {  
    "include": [  
      "wwwroot",  
      "web.config"  
    ]  
  },  
   
  "scripts": {  
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]  
  }  
}  

Output

QRCode Generator

QRCode Generator

Reference

See Also

You can download other ASP.NET Core 1.0 source codes from MSDN Code, using the links, mentioned below.

Conclusion

We learnt how to create a QR Code Generator in ASP.NET Core 1.0 Using Zxing.Net. I hope, you liked this article. Please share your valuable suggestions and feedback.

Composite Words using C#



Introduction :

A composite word is a concatenation of two-or-more other words, such that the minimum length of each constituent word is 3.

In this article the program which accepts a list of words and an integer or string as input and prints the count of composite words which can be constructed by concatenating integer and string or more other words which are also present in the input.

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace ConsoleApplication3
{
    class Program
    {
        static public void charsorting(char[] process, int length)
        {
            for (int a = 1; a < length; a++)
            {
                for (int b = 0; b < length - a; b++)
                {
                    if (process[b] > process[b + 1])
                    {
                        char tempdata = process[b];
                        process[b] = process[b + 1];
                        process[b + 1] = tempdata;
                    }
                }
            }
        }

        static public bool Permuation(char[] permute, int length)
        {
            for (int c = length - 1; c > 0; c--)
            {
                if (permute[c - 1] >= permute[c])
                    continue;
                else
                {
                    if (c <= length - 3)
                    {
                        char charcheck = permute[c - 1];
                        int value = -1;
                        for (int j = length - 1; j >= c; j--)
                        {
                            if (charcheck < permute[j])
                            {
                                value = j;
                                break;
                            }
                        }
                        if (value == -1)
                            return false;
                        char character = permute[c - 1];
                        permute[c - 1] = permute[value];
                        permute[value] = character;

                        char[] process2 = new char[length - c];
                        for (int d = 0; d < length - c; d++)
                            process2[d] = permute[c + d];
                        charsorting(process2, length - c);
                        for (int e = 0; e < length - c; e++)
                            permute[c + e] = process2[e];
                        return true;
                    }
                    else
                    {
                        char[] dump = new char[3];
                        dump[0] = permute[permute.Length - 3];
                        dump[1] = permute[permute.Length - 2];
                        dump[2] = permute[permute.Length - 1];

                        int count = 3;
                        for (int f = count - 1; f > 0; f--)
                        {
                            if (dump[f - 1] >= dump[f])
                                continue;
                            else
                            {
                                if (f <= count - 2)
                                {
                                    if (dump[f + 1] > dump[f - 1])
                                    {
                                        char ch1 = dump[f + 1];
                                        dump[f + 1] = dump[f];
                                        dump[f] = dump[f - 1];
                                        dump[f - 1] = ch1;
                                    }
                                    else
                                    {
                                        char ch2 = dump[f - 1];
                                        dump[f - 1] = dump[f];
                                        dump[f] = dump[f + 1];
                                        dump[f + 1] = ch2;
                                    }
                                }
                                else
                                {
                                    char ch3 = dump[f];
                                    dump[f] = dump[f - 1];
                                    dump[f - 1] = ch3;
                                }
                                permute[permute.Length - 3] = dump[0];
                                permute[permute.Length - 2] = dump[1];
                                permute[permute.Length - 1] = dump[2];
                                return true;
                            }
                        }
                        return false;
                    }
                }
            }
            return false;
        }

        static void Main(string[] args)
        {
           
            string number;
            int counter = 0;
            string line;

            // Read the file and display it line by line.
            System.IO.StreamReader file =
               new System.IO.StreamReader("E:\\Mvc Test\\ConsoleApplication1\\ConsoleApplication1\\File\\test.txt");
            int count = 0;
            Console.WriteLine("Enter the number :");
            number = Console.ReadLine();
            if (number != null)
            {
              
                while ((line = file.ReadLine()) != null)
                {

                    string s = line + number;
                    char[] buffer = s.ToCharArray();
                    while (true)
                    {
                        Console.WriteLine(buffer);
                        count++;
                        if (Permuation(buffer, buffer.Length) == false)
                            break;
                    }


                }

                Console.WriteLine("\nCount: " + count);
                Console.ReadLine();
                counter++;
                file.Close();


                Console.ReadLine();

           
        }
            else
            {
                Console.WriteLine("Enter atleast one value..!!!");
                Console.ReadLine();

            }


        }
    }
}

File Path:

System.IO.StreamReader file = new System.IO.StreamReader("E:\\Mvc Test\\ConsoleApplication1\\ConsoleApplication1\\File\\test.txt");

Change your file path otherwise you got some error.right click the test.txt inside the file folder.then you get file path.

Output:

Output

 

Reference : Click here

Published : http://www.c-sharpcorner.com/Blogs/49159/

“Login failed for user” C# with SQLConnection


This is the Common Problem we are facing in Server DB Connection in Asp.net.If you are using windows authentication to connect to the Server DB, you need to set “Trusted_Connection=True;” if you are using SQL server authentication, you need to declare User “Id=myUsername; Password=myPassword;”

Code Snippet In Web.Config:

Windows authentication

<add name="windowsConnection" connectionString="Server=localhost; Database=databasename; Trusted_Connection=True;" />

SQL server authentication

<add name="Sqlserverconnection" connectionstring="server=localhost; Database=databasename;uid=db; password=123 "/> 
%d bloggers like this: