Ved's profileASP.Net, C#, SQL ServerPhotosBlogListsMore ![]() | Help |
|
ASP.Net, C#, SQL Server27 November Coupling, Cohesion, Encapsulation, Polymorphism Coupling is the unnecessary dependance of one component upon another component's implementation. An example would be if you had a Dog class that should be able to bark and jump. You could write it like this: class Dog { void doAction(int number) { if(number==1) //Jump code goes here if(number==2) //Bark code goes here } } However, this way whoever used your class would have to follow your convention that doAction(1) means jump and doAction(2) means bark. A less-coupled way would be to write separate bark() and jump() methods. Cohesion occurs when components are wired together in a smart, logical way. If you have ever used a Controller class, that's a great example of acheiving cohesion. Highly cohesive components interact with each other semantically, in other words, they tell each other what they want to do. In a Bank example, an ATM object should be able to tell an Account object to getBalance(), or withdrawFunds(), etc. These are sensible ways for the ATM and Account to interact, not specific ways that are only useful in one program. So good OOD requires that components can interact powerfully, but independently of each other's implementation details. (Think of Console.WriteLine() - most people have no idea how that works, but when you want to output some text, you can just use the method.) Encapsulation is the process of combining data and functions into a single unit called class. Using the method of encapsulation, the programmer cannot directly access the data. Data is only accessible through the functions present inside the class. Data encapsulation led to the important concept of data hiding. Data hiding is the implementation details of a class that are hidden from the user. The concept of restricted access led programmers to write specialized functions or methods for performing the operations on hidden members of the class. Attention must be paid to ensure that the class is designed properly. Neither too much access nor too much control must be placed on the operations in order to make the class user friendly. Hiding the implementation details and providing restrictive access leads to the concept of abstract data type. Encapsulation leads to the concept of data hiding, but the concept of encapsulation must not be restricted to information hiding. Encapsulation clearly represents the ability to bundle related data and functionality within a single, autonomous entity called a class. It's not available in procedural languages like C. There are advantages of using this encapsulated approach. One advantage is that it reduces human errors. The data and functions bundled inside the class take total control of maintenance and thus human errors are reduced. Now it should be clear that the encapsulated objects act as a black box for other parts of the program through interaction. Although encapsulated objects provide functionality, the calling objects will not know the implementation details. This enhances the security of the application. The key strength behind Data Encapsulation is that the keywords or the access specifiers can be placed in the class declaration as public, protected or private. A class placed after the keyword public is accessible to all the users of the class. The elements placed after the keyword private are accessible only to the methods of the class. In between the public and the private access specifiers, there exists the protected access specifier. Elements placed after the keyword protected are accessible only to the methods of the class or classes derived from that class. The concept of encapsulation shows that a non-member function cannot access an object's private or protected data. This adds security, but in some cases the programmer might require an unrelated function to operate on an object of two different classes. Encapsulation alone is a powerful feature that leads to information hiding and abstract data type. Features and Advantages of the concept of Encapsulation:
Note: In order to benefit from the powerful feature of encapsulation in object-oriented programming languages, the programmer must use encapsulation properly. To maximize the benefits of encapsulation, the user must minimize the implementation details in external interfaces as needed. Thus encapsulation is the use of hiding implementation details within your code. Changing the above Dog code from doAction() to jump() and bark() would be a step toward good encapsulation. This is getting frighteningly nerdy, but I think you could say "A program with high cohesion and low coupling exhibits good encapsulation". In other words, encapsulation is the goal you're trying to reach when you reduce coupling. A class with good encapsulation, in turn, lends it self to being a cohesive part of a system. Polymorphism is fairly unrelated to the above concepts. It refers to the ability of an object to act like its parent object if needed. So let's say the Dog class extends the Animal class. If an Animal can eat(), then you call call myDog.eat(), even if Dog doesn't have an implementation of eat() in it's definition, because Animal does, and Dog inherits all of Animal's functionality. There are other definitions of this term, but this is the most Java-ish one I can think of. 26 November iif statement in c#[CODE] string str1= "The Data"; string str2 = (str1.Trim() = string.Empty ? "OK" : "Empty"); [/CODE] 26 October How to ensure that only a single instance of a .NET application is running?static void Main(string[] args) { bool isAnotherInstanceRunning; Object obj = new System.Threading.Mutex(true, "YourNameHere", out isAnotherInstanceRunning); if (!isAnotherInstanceRunning) { Console.WriteLine("Another instance is already running."); } else { Console.WriteLine("Only this instance is already running."); GC.KeepAlive(obj); } Console.ReadLine(); } Explanation: A "mutex" (short for "mutual exclusion") is an operating-system object that can be used to keep processes from interfering with each other. Basically, the process that doesn't want to be interfered with will create a mutex, which the operating system will keep track of. Other processes will try to obtain the same mutex and will be blocked from executing if they do not do so. See any book on threading to learn more about this. A popular and quick way to ensure that only one instance of your program is running is to have it create a mutex with a specific name, or bail out if it cannot do so (because another copy of it is already running and owns the mutex). 19 October MSDN: Difference between MultipleActivation & RetailMAKs (MultipleActivation) allow a predetermined number of activations. This number depends on the type of agreement you have.The number of activations can be revised (at the request of the customer or by Microsoft) to accommodate your regular usage. On the other hand, One retail product key can only be activated for 10 times. 01 October This product is pre-pidded. -What does it mean?It means that the product key is actually built into the installer and you do not need a separate one to install it. 22 September Shared DLL Count Clarification In RegEdit, you can take a look in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\SharedDLLs to get the list of shared dlls. If application "A" installs a dll, then application "B" tries to install the same dll, instead of copying over it, Windows Installer (WI) will increment the reference count for that file.. When uninstalling app "A" (or "B"), WI will check the reference count to see if any other applications are still using that dll. If they are, then WI will decrement the counter by 1 and leave the dll behind. When that counter hits zero, the dll will be uninstalled by the next application that tries to remove it. 15 September Default parameter in C# 4.0Two new features to C# 4.0 are optional parameters and named parameters. Optional parameters have been a part of VB.Net but it's now possible to do this in C#. Instead of using overload methods, you can do this in C#: private string Method1(string givenName, The second and third parameters, surname & age, both have default values. The only parameter required is givenName. To call this method you can either write this: string name = null; That will return Ved Prakash. You can also do this: string name = null; The value returned is Prakash Tejwani. But what if you didn't want to specify a surname but you did want to pass the age? You can do this by using named parameters: string name = null; These are nice additions to the language. 02 April Polymorphism, Method Hiding and Overriding in C#Overview
Example Class Hierarchy
Inherited Methods
Virtual and Overridden Methods
Method Hiding
Combining Method Overriding and Hiding
class
A
class
C : B Conclusion
30 March ASP.NET Caching FeaturesWhen clients access an ASP.NET page, there are basically two ways to provide them with the information they need:
Retrieving information from a resource outside the application will require more processing steps, and will therefore require more time and resources on the server than if the information can be obtained from within the application space. If the information that will be sent to the browser has already been prepared by a previous request, the application will be able to retrieve that information faster if it has been stored in memory, somewhere along the request/response stream. Known as caching, this technique can be used to temporarily store page output or application data either on the client or on the server, which can then be re-used to satisfy subsequent requests and thus avoid the overhead of re-creating the same information. Caching is particularly suitable when you expect to return the same information in the same format for many different requests. ASP.NET provides the following types of caching that can be used to build highly responsive Web applications:
OutputCache Declaratively controls the output caching policies of an ASP.NET page or a user control contained in a page. <%@ OutputCache Duration = "#ofseconds" Attributes
RemarksSetting values for the page output cache is the same as manipulating the SetExpires and SetCacheability methods of the Response.Cache onject. Setting the VaryByParam attribute when creating a user control implements partial-page caching for that control. If a Web Forms page requires authorization to be viewed by a user, the output cache sets the Syntax ExampleThe below code snippet demonstrates how you can set the duration ( in seconds ) that a page or user control is output cached. <%@ OutputCache Duration = "10" VaryByParam = "none" %> The next example demonstrates how you can instruct the output cache to cache a page or user control based on parameter values passed by a form's GET or POST method. Each HTTP request that arrives with a different parameter is cached for ten seconds. Any subsequent requests with the same parameter values are satisfied from the cache until the entry expires. <%@ OutputCache Duration = "10" VaryByParam = "myParam1; myParam2" %> Application Variables:Application variables were under-used on my site, but not for long! I
realized recently that a list box that I was populating with data from
my database changed very rarely. So why should every visitor to the site have to cause an identical database query? The simple answer is to take advantage of Application variables. Think of the "Application" in this case being IIS - the server. Once set, Application variables are available to all pages on your site. But it's important to remember that they are gone forever if the server is restarted. Using Application variables is easy - all you need are statements like:// to set the data
14 March OOP BasicsVisual Basic was Object-Based, Visual Basic .NET is Object-Oriented, which means that it's a true Object-Oriented Programming Language. Visual Basic .NET supports all the key OOP features like Polymorphism, Inheritance, Abstraction and Encapsulation. It's worth having a brief overview of OOP before starting OOP with VB.
Why Object Oriented approach?
Concepts of OOP:
Briefly on Concepts:
Putting all the data and related functions in a
Instead of Trigger in SQL Server CREATE TRIGGER myTrigger ON [dbo].[Dept] instead of update AS begin declare @n1 decimal select @n1=id from inserted update dept set name='aa' where id=@n1 end Reflection: GetType() & TypeOf() All .NET assemblies contain vivid type information which describes the structure of every internal and external type (this can be verified by loading an assembly into ildasm.exe and clicking the ctrl-m keystroke). On a related note, many methods in the .NET base class libraries require you to pass in type information for a given item. When you need to obtain type information for a given method invocation, you have numerous approaches. First, all types inherit the public System.Object.GetType() method: // Obtain type information from a variable. SomeType c = new SomeType(); Type t = c.GetType(); INeedYourTypeInfo(t);While this works, it is overkill to create a type simply to call the inherited GetType() method. To streamline the process, the C# language offers the typeof operator. The benefit is you are not required to create the item in question, rather simply specify the name of the type as an argument: // Obtain type information via typeof. INeedYourTypeInfo(typeof(SomeType)); Conceptsref Vs out parameters "out" parameters are output only parameters meaning they can only pass back a value from a function. We create a "out" parameter by preceding the parameter data type with the out modifier. When ever a "out" parameter is passed only an unassigned reference is passed to the function. class ParameterTest { static void Mymethod(out int Param1) { Param1=100; } static void Main() { int Myvalue=5; MyMethod(Myvalue); Console.WriteLine(out Myvalue); } } "ref" parameters are input/output parameters meaning they can be used for passing a value to a function as well as to get back a value from a function. We create a "ref" parameter by preceding the parameter data type with the ref modifier. When ever a "ref" parameter is passed a reference is passed to the function. class ParameterTest { static void Mymethod(ref int Param1) { Param1=Param1 + 100; } static void Main() { int Myvalue=5; MyMethod(Myvalue); Console.WriteLine(ref Myvalue); } }
boxing & unboxing class Test { static void Main() { int i = 1; object o = i; // boxing: value type to object type int j = (int) o; // unboxing: object type to value type } }
Overloading Vs overriding Method overloading means having two or more methods with the same name but different signatures in the same scope. These two methods may exist in the same class or another one in base class and another in derived class. Generally, you should consider overloading a method when you have required same reason that take different signatures, but conceptually do the same thing. Method overriding means having a different implementation of the same method in the inherited class. These two methods would have the same signature, but different implementation. One of these would exist in the base class and another in the derived class. These cannot exist in the same class.
CLR - CTS - CLS The .NET Framework provides a runtime environment called the Common Language Runtime or CLR (similar to the Java Virtual Machine or JVM in Java), which handles the execution of code and provides useful services for the implementation of the program. The Common Language Runtime is the underpinning of the .NET Framework. CLR takes care of code management at program execution and provides various beneficial services such as memory management, thread management, security management, code verification, compilation, and other system services. The managed code that targets CLR benefits from useful features such as cross-language integration, cross-language exception handling, versioning, enhanced security, deployment support, and debugging. Common Type System (CTS) describes how types are declared, used and managed in the runtime and facilitates cross-language integration, type safety, and high performance code execution. Common Language Specification (CLS) is an agreement among language designers and class library designers to use a common subset of basic language features that all languages have to follow.
sessionState modes <sessionState mode="Off|InProc|StateServer|SQLServer" cookieless="true|false" timeout="number of minutes" stateConnectionString="tcpip=server:port" sqlConnectionString="sql connection string" stateNetworkTimeout="number of seconds"/> Required Attributes
Optional Attributes
Remarks To use StateServer mode
To use SQLServer mode
Example The following example specifies several session state configuration settings. <configuration> <system.web> <sessionState mode="InProc" cookieless="true" timeout="20"/> </sessionState> </system.web> </configuration>
Authentication Modes Authentication is the process of obtaining identification credentials from a user (such as name and password), and validating those credentials against some authority. It sets the authentication policies of the application. Possible modes are "Windows", "Forms", "Passport" and "None" "None" No authentication is performed. "Windows" IIS performs authentication (Basic, Digest, or Integrated Windows) according to its settings for the application. Anonymous access must be disabled in IIS. "Forms" You provide a custom form (Web page) for users to enter their credentials, and then you authenticate them in your application. A user credential token is stored in a cookie. "Passport" Authentication is performed via a centralized authentication service provided by Microsoft that offers a single logon and core profile services for member sites. <location path="Default.aspx"> <system.web> <authorization> <allow users="*" /> </authorization> </system.web> </location>
Shared and Private Assembly
A private assembly is an assembly that is available to particular applications where they are kept. And cannot be references outside the scope of the folder where they are kept.
In contrast, Shared Assemblies are the assemblies that are accessible globally/shared across the machine to all the applications. For using the shared assemblies you need to register the assembly with a strong name in the global assembly cache (GAC) using gacutil.exe. GAC can be found on all the computers with .Net framework installed.
Oracle Vs SQL Server
The dialect of SQL supported by Microsoft SQL Server 2000 is called Transact-SQL (T-SQL). The dialect of SQL supported by Oracle 9i Database is called PL/SQL. PL/SQL is more powerful language than T-SQL. This is the brief comparison of PL/SQL and T-SQL:
Feature
PL/SQL(Oracle)
T-SQL(SQL Server)
Indexes
B-Tree indexes, B-Tree indexes
Tables
Relational tables, Relational tables, Triggers
BEFORE triggers, AFTER triggers, Procedures
PL/SQL statements, T-SQL statements
Arrays
Supported
Not Supported
The SQL Server 2000 advantages:
The Oracle 9i Database advantages:
Stored Procedures Vs Functions
Unlike stored procedures,
Stored Procedure: System.Data.DataSet objResultDS = new System.Data.DataSet();
SqlDataAdapter objDataAdapter = new SqlDataAdapter(“Select * from emp”,”Data Source=webserver;Initial catalog=360Feedback;uid=sa;pwd=sa”);
objDataAdapter.Fill(objResultDS);
XML Serialization
Serialization allows program to persist objects by storing then in files. In this case, into XML files. XML has become the standard for storage in the recent years and it’s good to see that with XML serialization built into the .NET framework
Reflection
It enables us to get some information about object in runtime. That information contains data of the class. Also it can get the names of the methods that are inside the class and constructors of that object. To write a C# .Net program which uses reflection, the program should use the namespace System.Reflection. To get type of the object, the typeof operator can be used. There is one more method GetType(). This also can be used for retrieving the type information of a class. The Operator typeof allow us to get class name of our object and GetType() method uses to get data about object?s type.
ConceptsWebservice Vs Remoting Unlike Remoting
interface Vs abstract class
readonly Vs const
static Vs private constructor 1. Static constructor is used to initialize static data members as soon as the class is referenced first time, whereas an instance constructor is used to create an instance of that class with <new> keyword. A static constructor does not take access modifiers or have parameters and can't access any non-static data member of a class. 2. Since static constructor is a class constructor, they are guaranteed to be called as soon as we refer to that class or by creating an instance of that class. 3. The static constructor for a class executes before any instance of the class is created.
SQL Server & Crystal ReportStored Procedure:
CREATE PROCEDURE DBO.GetUserName@UseName varchar(50) =' ' output,@UID int =1 ASSELECT @UseName= FNAME+' ' + LNAME FROM USERS WHERE USERID=@UIDreturn @@rowcountGO----Calling a SP: private string GetUserName(int UID) { string strConn = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString; SqlConnection conn = new SqlConnection(strConn); conn.Open(); SqlCommand cmd = new SqlCommand("GetUserName", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@UseName", SqlDbType.VarChar,50); cmd.Parameters[0].Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@UID",UID); cmd.ExecuteNonQuery(); conn.Close(); return cmd.Parameters[0].Value.ToString(); }
Crystal Report Schema(*.xsd) <?xml version="1.0" encoding="utf-8"?> <xs:schema id="CompanyDS" targetNamespace="http://tempuri.org/CompanyDS.xsd" elementFormDefault="qualified" xmlns="http://tempuri.org/CompanyDS.xsd" xmlns:mstns="http://tempuri.org/CompanyDS.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="Survey"> <xs:complexType> <xs:sequence> <xs:element name="SID" type="xs:int" /> <xs:element name="UID" type="xs:int" /> <xs:element name="UNAME" type="xs:string" /> <xs:element name="SNAME" type="xs:string" /> <xs:element name="DATE" type="xs:date" /> <xs:element name="ISACTIVE" type="xs:boolean" /> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> ---- <CR:CrystalReportViewer AutoDataBind="False" ID="CrystalReportViewer1" runat="server" Height="50px" Width="350px" /> ----- using System.Data; //--SqlClient for SqlConnection and etc. using System.Data.SqlClient; //--for CrystalReports's ReportDocument. using CrystalDecisions.CrystalReports.Engine;
private void GenerateReport() { string strConn = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString; //--Sql string String strCmd = "SELECT S.SURVEY_ID [SID],S.USER_ID [UID],U.FNAME+' ' +U.LNAME [UNAME],S.SURVEY_NAME [SNAME],S.CREATED_DATE [DATE],S.ACTIVE [ISACTIVE] FROM SURVEYS S,USERS U WHERE S.USER_ID=U.USERID"; //--Opening Sql Connection //string strConn = ConfigurationManager.AppSettings["Conn"]; SqlConnection sqlConn = new SqlConnection(strConn); DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(strCmd, sqlConn); //--this statement is very important, here the table name //should match with the XML Schema table name da.Fill(ds, "Survey"); //--Closing Sql Connection sqlConn.Close(); //--(Optional) I have used it to disable the properties CrystalReportViewer1.DisplayGroupTree = false; CrystalReportViewer1.HasCrystalLogo = false; //--Initializing CrystalReport ReportDocument myReportDocument; myReportDocument = new ReportDocument(); myReportDocument.Load(Server.MapPath("MyCompanyRpt.rpt")); myReportDocument.SetDataSource(ds); //--Binding report with CrystalReportViewer CrystalReportViewer1.ReportSource = myReportDocument; CrystalReportViewer1.DataBind(); } ----------------- SELECT * FROM EMPLOYEE, LEAVE
è If EMPLOYEE contains 5 records & Leave contains 3 records then the query returns 5X3=15 records. è If EMPLOYEE contains 5 records & Leave contains 0 records then the query returns 5X0=0 records. Select * from employee where (substring (name, 1, 1) in ('v')) and (substring (name,len(name),1) in ('h')) è It fetches all emps whose name starts with ‘v’ and ends with ‘h’
SELECT DEPT.NAME, COUNT (*) FROM employee,DEPT WHERE employee.DEPTID=DEPT.ID GROUP BY DEPT.NAME HAVING COUNT(*)>1
-----------------
JOIN Join is to query data from more than one table. Normally, there are five different joining schemes. 1. Cartesian product. If no joining condition is specified, every row in the first table with be matched to the every row of the second tables and so on for the second table and the third joining table. This should be avoided. 2. Equal-Join. Tables are joined based on some column equality condition. 3. Non-equal Join. Tables are joined based on some column inequality condition. 4. Outer-Join. Tables are joined and rows that do NOT meet the join condition are also returned. 5. Self-Join. Joining a table with itself. The schemes 2 to 4 are described in details in the following.
Use table prefix to qualify column names to remove column ambiguity. For example, SQL> SELECT empno, employee.name, employee.dept_no, dept.name FROM employee, dept WHERE employee.dept_no = dept.dept_no;
Use Between-And clause in non-equal join queries. For example, to answer the query "find the students whose mark falls in Grade A range" (assuming the student mark table only stores the raw marks (with values ranging from 0 from 100, and the grade_class table stores the low-end and high-end marks for each grade.), the query is: SQL> SELECT a.name, a.matric_no, a.mark FROM student_marks a, grade_class b WHERE b.grade = 'A' AND a.mark BETWEEN b.low_end AND b.high_end; Outer-join operator is the plus sign (+). Out join queries return the normal joining results plus the rows in two tables that do not meet the join condition. For example, assume we have a module_taken table which keeps the relationship on what modules taken by which student, and a module table which keeps the module details. The following statement returns the student matric no, and module names taken that student, and in addition to this, it also list the modules which are not taken by anyone. SQL> SELECT a.matric_no, a.module_no, b.module_name FROM module_taken a, module b WHERE a.module_no (+) = b.module_no; Assume module CS9999 is not taken by any student but is listed in the module table, then this module will also appear in the result, with empty value for matric_no. To join the table with itself, a table must be given an alias to distinguish each other. For example, the following statement retrieves all employees who have a manager (who don't have a boss :)). SQL> SELECT worker.name || ' works for ' || mgr.name FROM employee worker, employee mgr WHERE worker.mgr_no = mgr.empno;
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|