Skip to main content

Posts

Showing posts from 2019

Converting List to DataTable in C#

public static DataTable ConvertToDataTable<T>(IList<T> data)         {             PropertyDescriptorCollection properties =                TypeDescriptor.GetProperties(typeof(T));             DataTable table = new DataTable();             foreach (PropertyDescriptor prop in properties)                 table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);             foreach (T item in data)             {                 DataRow row = table.NewRow();                 foreach (PropertyDescriptor prop in properties)                     row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;                 table.Rows.Add(row);             }             return table;         }

Introduction to Entity Framework

Entity Framework is an object-relational mapper (O/RM) that enables .NET developers to work with a database using .NET objects. It eliminates the need for most of the data-access code that developers usually need to write.  It enables developers to work with data using objects of domain specific classes without focusing on the underlying database tables and columns where this data is stored. It eliminates the    ADO.NET code that we write to connect to Database,Execute Query and read data from DataSet and convert to .net objects and vice versa. It Reduces the pain of developers and provides higher level of abstraction for faster development of .net applications.

Adding User To Role Using Identity

First Create a viewmodel  public class ApplicationUserRoleViewModel     {         public string UserId { get; set; }         public string RoleId { get; set; }       } Create an Empty Controller with name UserAndRolesConroller and add the following actions   public async Task<ActionResult> AddUserToRole()         {             ApplicationUserRoleViewModel vm = new ApplicationUserRoleViewModel();             var Users = await dbCon.Users.ToListAsync();             var roles = await dbCon.Roles.ToListAsync();             ViewBag.UserId = new SelectList(Users, "Id", "UserName");             ViewBag.RoleId = new SelectList(roles, "Id", "Name");             return View(vm);         }         [HttpPost]         public async Task<ActionResult> AddUserToRole(ApplicationUserRoleViewModel model)         {             var role = dbCon.Roles.Find(model.RoleId);             if (role != null)             {            

Converting DataTable to List

Calling from Controller  public ActionResult Index()         {             //join use             //change view model.             String sql = "SELECT * FROM faculties ";             db.List(sql);             var dt = db.List(sql);             var model = new Faculty().List(dt);             return View(model);         } Add a method to class List<Faculty> list = new List<Faculty>();         public List<Faculty> List(DataTable dt)         {             for (int i = 0; i < dt.Rows.Count; i++)             {                 Faculty fac = new Faculty();                 fac.FacultyId = Convert.ToInt32(dt.Rows[i]["FacultyId"]);                 fac.Name = dt.Rows[i]["Name"].ToString();                 fac.Description = dt.Rows[i]["Description"].ToString();                 list.Add(fac);             }             return list;         }

Using SqlDataAdapter to fill DataTable in c#

public DataTable List(string sql)         {             SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);             SqlCommand cmd = new SqlCommand(sql, con);             DataTable dt = new DataTable();             SqlDataAdapter da = new SqlDataAdapter(cmd);             try             {                              con.Open();                 da.Fill(dt);             }             finally             {                 con.Close();             }             return dt;         }

Connection String in ASP.NET With SQL Server

Connection string can be placed in web.config file found in root directory of the application from .NET 3.5 onward. connection string can be specified with an xml tag  <connectionStrings>  inside  <configuration>  section of web.config file. < connectionStrings > < add name = "myConnectionString" connectionString = "Data Source=databaseServerName; database=database-name; uid=sqlUserName;password=sqlPassword; Integrated Security =True|false|SSPI (any one options) ; " providerName = " System.Data.SqlClient System.Data.SqlClient" /> </ connectionStrings > We can use local database server of SQL Server by using Data Source= (LocalDb)\MSSQLLocalDB we can attach a local database file to the app_data directory by using the property AttachDBFilename=|DataDirectory|\appDatabaseName.mdf in the connection string Connection String can be

Knowing Nuget and installing a Package

 For .NET Microsoft-supported mechanism for sharing code is  NuGet , which defines how packages for .NET are created, hosted, and consumed, and provides the tools for each of those roles. It has been an essential tool for through which developers can create, share, and consume useful code. Often such code is bundled into "packages" that contain compiled code (as DLLs) along with other content needed in the projects that consume these packages. How to add Nuget Package to an application Right click Refrences -> Manage Nuget Packages 2.  Type Nuget Package Name you need for the application here we add Entity Framework 3.   After the search result is shown click install and accept the agreement asked After this the package is installed and you can use the functionalities that are provided by the package.

Models In Asp.net MVC

What is a Model? Model is a class that represents domain specific data and business logic in a dot net application. Adding A Model  Right click the Models folder in the solution explorer->Add -> Class After that Select Visual C#-> Class  and provide a suitable name for your model class Sample Model Class In Model validation logic can be added using Attributes in C# . Some validation attributes like StringLength,RegularExpression are used in the model.

Getting Started With ASP.NET MVC First Application

Requirements: Visual Studio (i am using VS 2017 for demo) Open up the visual studio and Click File -> New ->Project   Click Visual C# -> Asp.Net Web Application (.NET Framework)                                              In the Name i.e Project Name and Solution give the name as required here I have given      Name: WebApp                                                                                                                              Solution Name: StudentInformation Select MVC and then click OK The application will open with the following view Run the application from the menu bar or can press F5 or CTRL+F5  The first ASP.NET MVC Application is up and running in your web browser. It opens the applications home page and opens in the web browser with localhost:port . Visual studio assigns the random port number and hence the port number you see differs.

Introduction to ASP.NET MVC

What Is Asp.Net MVC ?  Asp.net MVC is a framework introduced by microsoft in 2008 for building web application. Asp.net MVC is an architectural pattern built on top of ASP.Net Framework for development of application based on three main logical components. Asp.net MVC is lightweight and testable framework and can be used to develop highly scalable and extensible enterprise level applications. Three main components of MVC 1. Model   Model is a data specific logic that the application works with.It generally represents the data that is transferred between storage layer and application and between view and controller. In general Model is a class that contains properties specific to the application domain and transfer data between different components. 2.View View is an user interface that can use model to populate data to the users. They are results of the request made by an user to the application and is returned from controller. 3. Controller Controller is a component that

Introduction to Microsoft SQL Server

Microsoft SQL Server is a Relational Database Management System(RDBMS) developed by Microsoft. It is one of the most popular RDBMS. SQL server has evolved from sql 1.0 in 1989  to the latest release of SQL Server 2019 (preview)  to become one of the best enterprise level database server's. SQL server is released with different editions. Express: Free to use entry level database which can use 1 core cpu, 1 GB ram and have maximum size of 10GB. Compact : Free embedded database for mobile app development and can have maximum size of 4GB. Enterprise : Full featured top end edition. Standard : Have less features than enterprise. WorkGroup: suitable for a company to use among the group. Developer: Same features like enterprise but is  licensed  to one user only. Web: Specially targeted for web application There are some other editions like Datacenter, Enterprise evaluation and Business Intelligence. These all editions are not available on all version of SQL Server. No

Update column with data from another table in SQL

  At different point of time we come up with a situation  where we need to update a column in a table from another  table based on some condition.   So a Basic Syntax for update is: UPDATE table SET column1 = expression1, column2 = expression2, ... [WHERE conditions]; For us to update based on another table we will be using the same syntax for update applying join with another table from  where we need the data. UPDATE t1 SET t1 .column_to_update = t2 .column_from_update FROM Table1 t1 INNER JOIN Table2 AS t2 ON t1 .common_column = t2 .common_column

Configure DNS to use an external mail server in Windows Server

External mail server can be used in the hosting server by configuring Mail Exchange ( MX ) Record. The Domain Name System(DNS) has several types of resource records that full fill the name to ip address translation(Directly or indirectly). One of the widely used record is MX Record.        An MX record should return the fully qualified domain name of an email server and its preference value . MX Record can be configured by following the step below. 1. Open DNS Manager 2. Add A Record for your mail          (eg: mail.domain.com with the ip address of another server) 3. Add  MX Record and set FQDN  to the name assigned in A Record           (i.e mail.domain.com)      Preference number can have any value between 0 to 65535 and lower number sets for higher            priority. After completing this step, The mail server is pointed to the ip addres provided in the A record for the specific domain.

SqlException: Login failed for user 'IIS APPPOOL\

This issue is related with the permission for application pool to connect with the sql. We can create login user with the name as specified in the exception  IIS APPPOOL\<name> and grant permission to the database. We can create new login user by opening the SSMS(Sql server management studio) navigate to Security>Login  Then Add the user by right clicking Login and selecting new login While creating user Navigate to UserMapping and tick the database for the specific user. This process will create the new user and gran permission to the user. Another Work Around Yet another simple way will be to change the application pool Identity property  To LocalSystem by navigating to the application pool and then advance setting.

Bubble Sort in C-Sharp

Bubble Sort is a simple sorting algorithms that iterates through a list and compares adjacent item and swaps them in the order if they are in the wrong order.  The iteration is completed after the  items bubble to there specific position and the list is sorted ascending or descending. Bubble sort is simple but too slow and impractical in most of the cases. Figure : Algorithm: for all elements in Array if Array [ i ] > Array [ i + 1 ] swap ( Array [ i ], Array [ i + 1 ]) end if end for return Array CODE :

Reading and Writing to a file text file in C#

Lets start by taking the below  code as an example:    private void WriteToAFile(){             string data = "hi ! what's up";             string path = "data.txt";             if (!File.Exists(path))             {                 File.Create(path);             }             using (StreamWriter writer = new StreamWriter(path, append: true))             {                 writer.WriteLine(data);             } } Writing to a text file can be achieved by using StreamWriter class . To use this class we need to use System.IO namespace. if we are writing to a file then exception might occur if the file doesn't exists. So firstly we need to check if the File Exists. If it doesn't exist we can create a file in the path specified. Here in example I haven't provided the fully qualified path like  "C:\Users\Mypc\project\Sample" absolute path  but rather used relative path by providing only the file name. Th

Classes and Objects In C#

Class  is a collection of fields, properties and methods. It depicts real life entities and is a fundamental concept in Object Oriented Programming.  A class is a user-defined blueprint  from which objects are created . A class is a user defined data type of  reference type. Lets take a example of a Car . It has different attributes like color,maximum speed,no of gears on with a built in audio player  and so on. public class Car {     private string  _color; //a variable and a field with data type string     // a variable and  a property       public string Color       {         get         {             return _color;         }         set         {             _color= value;         } public void  PlayAudio() { //implementation logic } } Declaration Of Class:  <access specifier><keyword:class> <class name: Car> public class car if access identifier is not explicitly mentioned a class has internal access identifier a

Installing Windows Service

What is a windows Service ?  Windows service is a long running process that runs as a background process in windows OS.           We create windows service when we need to perform tasks without the user interaction. Like regular application windows services lacks UI for user interaction. We can install windows service by navigating to installutil.exe file that resides in Microsoft.Net Folder inside Windows folder. For for .net version 4 the file path is  C:\Windows\Microsoft.NET\Framework\v4.0.30319  we can install the service by running the following command in CommandLine  opening it as an Administrator. "C:\Windows\Microsoft.NET\Framework\v4.0.30319\installutil.exe" "E:\servicename.exe"   See the following command run for installing the merotrackerlistener in the system.      After running the command windows service is installed in the system.