-
Oct12No Comments
Hi friends.. sometime back I had a discussion with few of my friends on different topics on OOPS. Just thought to put a post of some of the important facts which might help others as well. Starting with Abstract classes. Will be writing on more topics in next posts.
Abstract Classes- Abstract classes can have a non abstract ctor and they can’t be instantiated.
- Since abstract classes can’t be instantiated one should not use Public and Protected Internal modifier with Abstract class Ctor.
- Abstract class can be derived from a concrete class.
- Abstract class can have non abstract members (methods, events, properties) but non abstract class can’t have abstract members.
- An abstract class may contain abstract methods and accessors.
- An abstract method is implicitly a virtual method.
- Static and Virtual modifiers can’t be used with abstract methods
- An abstract inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.
- Abstract classes can have concrete static methods.
Hope this helps..Please put your comments and any additional info about abstract class which may help others as well.

-
Jan177 Comments
So what is the difference between CONST and READONLY? Let’s examine the difference between these two with an example.
So we can clearly see that we can initialize readonly variables during the declaration and in the constructor of the class. So its possible to initialize readonly variables once at run time but we can’t change value of const variables.Happy coding!

-
Aug233 Comments
Hi,
Recently I need to show multi-line string in a datagridview cell. To achieve that we need to write code in CellFormatting event of DataGridview. Following is the code
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (e.Value.Equals("Error")) { e.CellStyle.BackColor = Color.Red; e.CellStyle.ForeColor = Color.White; } else { if ((!e.Value.Equals("OK")) && e.ColumnIndex==2) { e.CellStyle.BackColor = Color.Green; e.CellStyle.ForeColor = Color.White; e.CellStyle.WrapMode = DataGridViewTriState.True; dataGridView1.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells; dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells; } } }I hope this help!
Kshitij

-
Dec8
Add text to the beginning of a file using C#
Filed under: C#;2 CommentsHi,
Few days back i needed a code snippet to write a text in starting of all files in a directory. Searched net but could not find any working code. Then i decide to write my own code and come up with following code.
I hope this will help guys who are looking to do same.using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace AddTextToFiles { class Program { private static DirectoryInfo ds; static void Main(string[] args) { Console.WriteLine("*********************Written By Kshitij Sharma ***********************"); Console.WriteLine("Please Enter the path and Press enter "); string sPath = Console.ReadLine(); Console.WriteLine("Please Enter <B style="BACKGROUND-COLOR: #a0ffff; COLOR: black">Text</B> "); string sText = Console.ReadLine(); addText(sPath,sText); Console.WriteLine("*****************Reach Me @ k.sharma78@gmail.com****************"); Console.Read(); } private static void addText(string pth,string txt) { try { if (!string.IsNullOrEmpty(pth)) { ds = new DirectoryInfo(pth); } else { ds = new DirectoryInfo("c:\\testfiles"); } if (string.IsNullOrEmpty(txt)) { txt = "<!--#Include File=\"CheckSQL.inc\"-->"; } foreach (FileInfo f in ds.GetFiles("*.asp")) { Console.WriteLine("Writing to file-->" + f.Name); string strPath = ds.Root + ds.Name + "\\" + f.Name; StreamReader sr = new StreamReader(strPath); string fileContent = sr.ReadToEnd(); sr.Close(); StreamWriter sw = new StreamWriter(strPath, false); StringReader gr = new StringReader(fileContent); sw.WriteLine(txt); sw.WriteLine(gr.ReadToEnd()); sw.Close(); } } catch(Exception ex) { Console.WriteLine(ex.Message); Console.Read(); } } } }
-
Jun166 Comments
So what basically is reflection:
Using a class library methods at runtime without adding its reference in your project is done through Reflection. In this article I will show you how to use reflection using a simple example.
Let’s first create a Class Library.let’s code our ReflectionTest Class
Namespace reflectionclass Public Class ClsReflection #Region "Methods" Public Function add(ByVal x As Integer, ByVal y As Integer) As Integer Return x + y End Function Public Function [sub](ByVal x As Integer, ByVal y As Integer) As Integer Return x - y End Function #End Region End Class End Namespace
let’s make a test project now. Add a windows form application to the solution.

so after putting two command buttons two listview controls and four textbox controls our form should look like this.Let’s code our form now
Imports System.Reflection Public Class Form1 Dim objAssembly As Assembly 'Declare an array of Types to Hold All Classes of Assembly Dim arrTypes As Type() Dim objType As Type 'Delcare an array to hold all methods of Assembly Dim arrMethods As MethodInfo() Dim objMethod As MethodInfo Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Try OpenFileDialog1.ShowDialog() txtAssembly.Text = OpenFileDialog1.FileName objAssembly = System.Reflection.Assembly.LoadFrom(txtAssembly.Text) For Each cls In objAssembly.GetTypes ' If cls.FullName.IndexOf("ClsReflection") > 0 Then lstClasses.Items.Add(cls.FullName) End If Next Catch ex As Exception MessageBox.Show(ex.Message) End Try End Sub Private Sub lstClasses_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstClasses.SelectedIndexChanged Try lstMethods.Items.Clear() objType = objAssembly.GetType(Me.lstClasses.SelectedItem.ToString) arrMethods = objType.GetMethods For Each method In objType.GetMethods lstMethods.Items.Add(method.Name) Next Catch ex As Exception MessageBox.Show(ex.Message) End Try End Sub Private Sub cmdCallMethod_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCallMethod.Click Try objMethod = objType.GetMethod(lstMethods.SelectedItem.ToString()) Dim obj As Object obj = Activator.CreateInstance(objType) 'Let's Create Array of Parameter Dim objParameters As Object() = {Int32.Parse(txtNum1.Text), Int32.Parse(txtNum2.Text)} 'If there is no parameter in method then on the place of oo pass the null txtResult.Text = objMethod.Invoke(obj, objParameters).ToString() Catch ex As Exception MessageBox.Show(ex.Message) End Try End Sub End ClassSelect Add and put any two numbers in the first and second number textbox and click on execute method and you should get the result.

Now select Sub and enter any two number in first number and second number textbox and press execute method and you should get the desired result.This article show you how you can call method dynamically at runtime without referencing the assembly in your project. It is a very basic example but I think it will help you to understand how reflection works in .Net.
If you have any point you are not getting in this article please let me know i will try to explain.
Happy Coding!
Kshitij

-
Jun58 Comments
Recently i faced lots of problem with my hosting company as almost daily my site was down due to some problems in their servers. They usually send me a link to trace my site. Basically that site provide service to ping back any URL from their servers which are located in different countries. So it is like first their US server pings the URL and sends back the results weather site is responding or not and then all of the servers located in different part of the word do the same thing and finally giving a summery. For me it was annoying to go again and again to that site and then type URL to trace it back. Furthermore they charge for their services if you wants to check your site (or any other URL) 24×7. So i decided to write my own service. In this service i write the ping back results to windows log but you can always enhance this code to send mails or even SMS if your site is down.
So lets start and create a Windows Web Service Project
-
May28
Dynamically create controls at runtime
Filed under: ASP.NET;6 CommentsHi,
I was searching an article about creating controls at runtime based on a master table. But I couldn’t find one. So I decided to write my own code and here is the result. I hope this post will help other guys who are looking to do same thing.So let’s first create a master table which will store details about fields need to appear on our page.
Let’s call this table tblFieldMaster.
Now Insert some data in it. 
Now add a new webForm to your website project ( i assume you know how to create a website project with visual studio 2005 or 2008). Let’s Name it createControl.aspx.
Add following code to newly added webform between tag.<body> <form id="frmMain" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <table width="550px" cellspacing="1" cellpadding="1" class="outerBG" align="center"> <tr> <td align="center"> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:Panel ID="Panel1" runat="server" CssClass="innerTabBg"> </asp:Panel> </ContentTemplate> </asp:UpdatePanel> </td></tr></table> </div> </form> </body>
As you review this code i have added a scriptmanager so this form supports AJAX feature. Then i added an updatepanel and a Normal Panel inside this update panel. I will now add code to my code behind file which in this case will be createcontrol.vb.
Imports System.Data Imports System.Data.OleDb Partial Class createControl Inherits System.Web.UI.Page Private WithEvents cmdBtn As System.Web.UI.WebControls.Button Private req As Web.UI.WebControls.RequiredFieldValidator Private tbl As System.Web.UI.WebControls.Table Private styl As System.Web.UI.WebControls.TableStyle Private tr As System.Web.UI.WebControls.TableRow Private td As System.Web.UI.WebControls.TableCell Private txt As System.Web.UI.WebControls.TextBox Private lbl As System.Web.UI.WebControls.Label Private conn As OleDbConnection Private da As OleDbDataAdapter Private cmd As New OleDbCommand Private ds As DataSet Private dbPath As String = Server.MapPath('App_Data/regdb.mdb') Private connString As String = 'Provider=Microsoft.Jet.OLEDB.4.0; Data source=' & dbPath & ';' Private strSQL As String Private Sub RenderForm() conn = New OleDbConnection(connString) conn.Open() strSQL = 'Select * from tbl_IVS_Noida' cmd.Connection = conn cmd.CommandText = strSQL cmd.CommandType = CommandType.Text Dim dr As OleDb.OleDbDataReader = cmd.ExecuteReader tbl = New Table tbl.ID = 'tblForm' tbl.Width = 550 'tbl.CssClass = ' Me.Panel1.Controls.Add(tbl) While (dr.Read) Select Case dr('Field_Type') Case 'Character', 'Number' tr = New TableRow tbl.Controls.Add(tr) td = New TableCell td.Width = 230 lbl = New Label lbl.Text = dr('Field_Label') td.Controls.Add(lbl) tr.Controls.Add(td) td = New TableCell td.Width = 320 txt = New TextBox txt.ID = dr('Field_Name') td.Controls.Add(txt) If dr('Required') Then req = New RequiredFieldValidator req.ControlToValidate = txt.ID req.ErrorMessage = txt.ID & ' Is Required' td.Controls.Add(req) End If tr.Controls.Add(td) Case 'Date' End Select End While 'Now create Save Button tr = New TableRow td = New TableCell td.ColumnSpan = 2 tr.Controls.Add(td) cmdBtn = New Button cmdBtn.ID = 'btnSave' cmdBtn.Text = 'Save!' td.Controls.Add(cmdBtn) tbl.Controls.Add(tr) End Sub Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init RenderForm() End Sub Private Sub btn_click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdBtn.Click End Sub End ClassI think the code is quite self explanatory. Please ask away if you don’t get any point of this code.I hope this will help others who are looking to do same. 


Recent Comments