RSS

To Modify The Config File Using C#

We Can modify the configuration files app settings and the Connection Strings through Configuration Manager.

- Add the Reference of System.Configuration for accessing the ConfigurationManager Class.

The Bellow Method is used to Modify the Value of the AppSettings Key Values.


private void ModifyKeyValue(string strKey, string strValue)
{
// Open App.Config of executable
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Check if the key available
if (!Array.Exists(config.AppSettings.Settings.AllKeys, delegate(string s) { return (s == strKey); }))
{
//Create the Key and assign value
config.AppSettings.Settings.Add(strKey, strValue);
}
else
{
// Add an Application Setting.
config.AppSettings.Settings[strKey].Value = strValue;
}
// Save the configuration file.
config.Save(ConfigurationSaveMode.Modified);
// Force a reload of a changed section.
ConfigurationManager.RefreshSection("appSettings");
}



We can also Remove the already available Keys and Values after that recreate the New Keys using the bellow method:


private void DropAndCreateKey()
{
// Open App.Config of executable
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Add an Application Setting.
config.AppSettings.Settings.Remove("Name");
config.AppSettings.Settings.Add("Name", "Krishna");
// Save the configuration file.
config.Save(ConfigurationSaveMode.Modified);
// Force a reload of a changed section.
ConfigurationManager.RefreshSection("appSettings");
String siteID = ConfigurationManager.AppSettings["Name"].ToString(); //GetValue("Name");
}

read comments Read User's Comments

To Listing the Files of the Directroy as a Data Table Using LINQ in C#

Introduction

The LINQ is a set of extensions to the .NET Framework that encompass language-integrated query, set, and transform operations. It extends C# and Visual Basic with native language syntax for queries and provides class libraries to take advantage of these capabilities.

The Bellow class Use the Advantage og the LINQ througth the from,Select and where keys.IEnumerable data type is mainly used to handle the collections of items with different types.


// This class is used to Get the Picture Files from given Path and
// set the list of files as Data Table Using LINQ
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
namespace WindowsFormsApplication1
{
class Helper
{
public String DirPath { get; set; }
public String FileType { get; set; }
public Helper(String sPath, String sFileType)
{
DirPath = sPath;
FileType = sFileType;
}
// To Get the IEnumerable type of Files List
public IEnumerable GetFiles()
{
try
{
// Simple LINQ in Files Systems
IEnumerable ObjFilesList = from String sFile in Directory.GetFiles(DirPath, FileType, SearchOption.AllDirectories)
select sFile;
return ObjFilesList;
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
return null;
}
}
//To Get the Data Table
public DataTable GetDataTable()
{
IEnumerable ObjlstFiles = null;
DataTable Objdt = new DataTable();
try
{
ObjlstFiles = GetFiles(); //"D:\\Siva\\Icons", "*.ico");
Objdt.Columns.Add("ICON File Names");
foreach (String sFileName in ObjlstFiles)
{
DataRow Objdr = Objdt.NewRow();
Objdr["ICON File Names"] = sFileName;//sFileName.Replace(DirPath, String.Empty);
Objdt.Rows.Add(Objdr);
}
return Objdt;
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
return null;
}
}
}
}

// Now we can get the DataTable and display in the DataGrid.

ObjHelper = new Helper(@"D:\Siva\Images\", "*.jpg");
Objdt = ObjHelper.GetDataTable();
if (Objdt.Rows.Count > 0)
{
grdvFiles.DataSource = Objdt.DefaultView;
grdvFiles.AutoResizeColumns();
grdvFiles.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
}
else
{
lblMsg.Text = "Sorry!, No Picture File Found";
lblMsg.ForeColor = Color.Red;
}

Download the sample Application for Image Viewer Click Here

read comments Read User's Comments

Some of the important SQL SERVER Functions


  1. @@CONNECTIONS - return the number of connections since sql server was started.

  2. @@CPU_BUSY
    - return the time in milliseconds that the CPU has been actively doing work since
    sql server was started.

  3. @@CURSOR_ROWS - the number of rows currently in the last cursor set opened on the current connection.

  4. @@DATEFIRST
    - returns the numeric value that corresponds to day of week.
    1 -> Monday to 7 -> Sunday

  5. @@DBTS - returns the last used timestamp for the current database.

  6. @@ERROR - Return the error code of the last sql statement

  7. @@IDENTITY - returns the identity value of the last sql insert statement.
  8. @@FETCH_STATUS - return the indicator of the of the last cursor fetch operation.

  9. Replication is the process of automatically doing what, in a very loose sense, amount of copying some or all the information in your database to some other database. The other database may be on the same physical machine as the original, or it may be located remotely.

  10. To View the total table in database    SELECT NAME FROM SYSOBJECTS WHERE TYPE='U'

  11. Stored Procedure with output parameter       Create Proc USP_GetEmpDetails

  12. Normalization: The process of organizing data to minimize redundancy is called normalization.

  13. De-Normalization:
    De-normalization is the process of attempting to optimize the performance of a database by adding redundant data.

  14.  Use SET NOCOUNT ON/OFF while using SELECT and Other DML Commands.

  15. E.g.
    CREATE PROC dbo.ProcName
    AS
    SET NOCOUNT ON;
    --Procedure code here
    SELECT column1 FROM dbo.TblTable1
    -- Reset SET NOCOUNT to OFF
    SET NOCOUNT OFF;
      GO 
  16.  Use Schema Name with Object Name while writing the Stored Procedures(Sql Server 2005)
    e.g.SELECT EMPNO, NAME FROM Dbo.EMPLOYEE

  17. Do not use the prefix “sp_Trans” in the stored procedure name. Use like
    "USP_Trans"

read comments Read User's Comments

Programmatically Setting meta Tag's Keywords and Description Tags in Asp.Net 4

Programmatically Setting <meta> Keywords and Description Tags

- The <head> element in an HTML document provides metadata about the web page, including the page's title (via the <title> element), and links to external CSS and JavaScript files, among other information.

- ASP.NET offers ways to have this metadata assigned automatically or programmatically. For example, you can programmatically set the page's title using the Page class's Title property. (See Dynamically Setting the Page's Title for more information.) Likewise, when using ASP.NET Themes any stylesheets defined in the theme are automatically included in the page's <head> section.

- When crawling through the pages in a website, a search engine spider will examine the <head> section to determine more information about the page. A page's keywords and a human-friendly description of the page may be included in the <head> section through the use of <meta> elements. For example, the following <head> element includes a hard-coded title and hard-coded keyword and description <meta> tags:


<head runat="server">
<title>The web page title...</title>
<meta name="keywords" Content="your,keywords,each
one delimited by a,comma" />
<meta name="description" content="A description of your web page
goes here." />
</head>


- ASP.NET 4 adds two new properties to the Page class that allow for these two <meta> tags to be specified programmatically:

* MetaKeywords, and
* MetaDescription


- You can set these properties from code just like you can the Page.Title property. For example, to generate the above></meta> tags programmatically we'd simply need to add the following lines of code to the ASP.NET page's code-behind class:
 
Page.MetaKeywords = "your,keywords,each one delimited by a,comma";
Page.MetaDescription = "A description of your web page goes here.";

read comments Read User's Comments

Bulk Copy Using ADO.Net Sql Client

Bulk Copy Using ADO.Net Sql Client

The Namespace System.Data.SqlClient's SqlBulkCopy class is used to copy the data from the one SQl Server table To another other table in the same or another database.

The Metod "WriteToServer" is used to write the source data to destination table.
The Bellow C# Class used for Bulk Copy


public class CopyData
{
string _sourceConnectionString;
string _destinationConnectionString;

public CopyData(string sourceConnectionString,string destinationConnectionString)
{
_sourceConnectionString = sourceConnectionString;
_destinationConnectionString = destinationConnectionString;
}

public void CopyTable(string table)
{
using (SqlConnection source = new SqlConnection(_sourceConnectionString))
{
string sql = string.Format("SELECT * FROM [{0}]",table);
SqlCommand command = new SqlCommand(sql, source);
source.Open();
IDataReader dr = command.ExecuteReader();
using (SqlBulkCopy copy = new SqlBulkCopy(_destinationConnectionString))
{
copy.DestinationTableName = table;
copy.WriteToServer(dr);
}
}
}
}
//To using the bellow code we can create object and call the buk copy method with the table name
CopyData c = new CopyData("Server=server;Database=Northwind;Integrated Security=SSPI", "Server=server;Database=master;Integrated Security=SSPI");
c.CopyTable("Orders");

read comments Read User's Comments

Encrypt and Decrypt your self some of the String

Encrypt and Decrypt your Self Using Base64

- To Encrypt the ASCIIEncoding and ToBase64String

Dim a() As Byte = System.Text.ASCIIEncoding.ASCII.GetBytes("9894465945")
Dim ent As String = Convert.ToBase64String(a)
MsgBox(ent)


- To Decrypt the Encrypted String
Dim k() As Byte = Convert.FromBase64String("OTg5NDQ2NTk0NQ==")
Dim et As String = System.Text.ASCIIEncoding.ASCII.GetString(k)
MsgBox(et)

read comments Read User's Comments