Skip to main content

Posts

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;         }
Recent posts

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.