IIS integrated security=SSPI

Informatics webapp can be connected using
a)SQL authentication (not recommended)
b) Windows account credentials (recommended)

Example connection string using SQL authentication
**************************************************

Example connection string using Windows account credentials
***********************************************************

When Integrated Security = false, User ID and Password are specified in the connection. When true, the current Windows account credentials are used for authentication.Recognized values are true, false, yes, no, and sspi (strongly recommended), which is equivalent to true.

Complete guidance to setup windows authentication is on this link:-
https://docs.microsoft.com/en-us/previous-versions/msp-n-p/ff647396(v=pandp.10)

NOTE:-
Example:- Assuming the webserver is part of the Domain Admins

Step 1) Add ROYALSURREY\Domain Admins to the Server(RSCH-INFODEV)->Security->Logins
Step 2)Goto->Server(RSCH-INFODEV)->Security->ServerRoles->sysadmin (double click sysadmin and add ROYALSURREY\Domain Admins)

microsoft.office.interop

https://social.msdn.microsoft.com/Forums/en-US/87e65b6a-f211-4b4a-9d42-a264dcf2a6f4/microsoftofficeinteropexceldll?forum=csharpgeneral

https://social.msdn.microsoft.com/Forums/vstudio/en-US/8bce17fb-eacd-4df3-8c10-bf8ae8a93c55/c-code-to-refresh-excel-data?forum=csharpgeneral

/*
Microsoft SQL Server Integration Services Script Task
Write scripts using Microsoft Visual C# 2008.
The ScriptMain is the entry point class of the script.
*/
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
namespace ST_53932a75e92c44f086535fc017a56e6a.csproj
{
[System.AddIn.AddIn(“ScriptMain”, Version = “1.0”, Publisher = “”, Description = “”)]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
#region VSTA generated code
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
/*
The execution engine calls this method when the task executes.
To access the object model, use the Dts property. Connections, variables, events,
and logging features are available as members of the Dts property as shown in the following examples.
To reference a variable, call Dts.Variables[“MyCaseSensitiveVariableName”].Value;
To post a log entry, call Dts.Log(“This is my log text”, 999, null);
To fire an event, call Dts.Events.FireInformation(99, “test”, “hit the help message”, “”, 0, true);
To use the connections collection use something like the following:
ConnectionManager cm = Dts.Connections.Add(“OLEDB”);
cm.ConnectionString = “Data Source=localhost;Initial Catalog=AdventureWorks;Provider=SQLNCLI10;Integrated Security=SSPI;Auto Translate=False;”;
Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.

To open Help, press F1.
*/

public void Main()
{
// TODO: Add your code here
ExcelRefresh(@”C:\Documents and Settings\ST84879\Desktop\ROBERT_DATA_SET\TEST.xls”);
Dts.TaskResult = (int)ScriptResults.Success;
}

private void ExcelRefresh(string Filename)
{
object NullValue = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
excelApp.DisplayAlerts = false;
Microsoft.Office.Interop.Excel.Workbook Workbook = excelApp.Workbooks.Open(
Filename, NullValue, NullValue, NullValue, NullValue,
NullValue, NullValue, NullValue, NullValue, NullValue,
NullValue, NullValue, NullValue, NullValue, NullValue);
Workbook.RefreshAll();
System.Threading.Thread.Sleep(20000);

Workbook.Save();
Workbook.Close(false, Filename, null);
excelApp.Quit();
Workbook = null;
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
}
}
}

Access Modifiers in C#

Different Access Modifier are – Public, Private, Protected, Internal, Protected Internal
  • Public – When a method or attribute is defined as Public, it can be accessed from any code in the project. For example, in the above Class “Employee” getName() and setName() are public.
  • Private – When a method or attribute is defined as Private, It can be accessed by any code within the containing class only. For example, in the above Class “Employee” attributes name and salary can be accessed within the Class Employee Only. If an attribute or class is defined without access modifiers, it’s default access modifier will be private.
  • Protected – When attribute and methods are defined as protected, it can be accessed by any method in the inherited classes and any method within the same class. The protected access modifier cannot be applied to classes and interfaces. Methods and fields in a interface can’t be declared protected.
  • Internal – If an attribute or method is defined as Internal, access is restricted to classes within the current project assembly.
  • Protected Internal – If an attribute or method is defined as Protected Internal, access is restricted to classes within the current project assembly and types derived from the containing class.

Inherit a class with Private Constructor

Private constructor are used for implementing the singelton pattern.

http://msdn.microsoft.com/en-us/library/ms998558.aspx

A can be inherited by a nested class

public class A {
  private A() { }

  public class Derived : A { }
}

Difference between sealed class and a class with private contructor:-

https://stackoverflow.com/questions/16639518/what-is-the-difference-between-a-class-having-private-constructor-and-a-sealed-c

Possible C# array initialization syntaxes

Non-empty arrays

  • var data0 = new int[3]
  • var data1 = new int[3] { 1, 2, 3 }
  • var data2 = new int[] { 1, 2, 3 }
  • var data3 = new[] { 1, 2, 3 }
  • var data4 = { 1, 2, 3 } is not compilable. Use int[] data5 = { 1, 2, 3 } instead.

Empty arrays

  • var data6 = new int[0]
  • var data7 = new int[] { }
  • var data8 = new [] { } and int[] data9 = new [] { } are not compilable.
  • var data10 = { } is not compilable. Use int[] data11 = { } instead.

As an argument of a method

Only expressions that can be assigned with the var keyword can be passed as arguments.

  • Foo(new int[2])
  • Foo(new int[2] { 1, 2 })
  • Foo(new int[] { 1, 2 })
  • Foo(new[] { 1, 2 })
  • Foo({ 1, 2 }) is not compilable
  • Foo(new int[0])
  • Foo(new int[] { })
  • Foo({}) is not compilable

C# Notes Part I

Verbatim variable

Special chars don’t need to be escaped, since you informed the compiler to expect special characters, and to ignore them. A common use case might be to specify a connection string:

string sqlServer = @"SERVER01\SQL"; 

?? Operator

Null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand

int.parse vs convert.toint

Convert.ToInt32 is for dealing with any object that implements IConvertible and can be converted to an int. Also, Convert.ToInt32 returns 0 for null, while int.Parse throws a ArgumentNullException.

int.Parse is specifically for dealing with strings.

As it turns out, the string type’s IConvertible implementation merely uses int.Parse in its ToInt32 method.

So effectively, if you call Convert.ToIn32 on a string, you are calling int.Parse, just with slightly more overhead (a couple more method calls).

This is true for any conversion from string to some primitive type (they all call Parse). So if you’re dealing with strongly-typed string objects;  Parse it’s more direct.

params

By using the params keyword, you can specify a method parameter that takes a variable number of arguments.

public static void ParamsMethod(params int[] Numbers

The above function can be invoked by

ParamsMethod() // Without any arguments

ParamsMethod(Numbers) //an array

ParamsMethod(1,2,3,4,5) // the arguments seperated by commas

Method hiding (Shadowing)

public class BaseClass
{
  public void WriteNum()
  {
    Console.WriteLine(12);
  }
  
}

public class DerivedClass : BaseClass
{
  public new void WriteNum()
  {
    Console.WriteLine(42);
  }

}

BaseClass isReallyBase = new BaseClass();
BaseClass isReallyDerived = new DerivedClass();
DerivedClass isClearlyDerived = new DerivedClass();

isReallyBase.WriteNum(); // writes 12
isReallyDerived.WriteNum(); // writes 12
isClearlyDerived.WriteNum(); // writes 42

Using new keyword to hide base class method. 
Note:Using Base class object will invoke base class method

Hiding protects against a subsequent base class modification.

Overriding

public class BaseClass
{
  
  public virtual void WriteStr()
  {
    Console.WriteLine("abc");
  }
}

public class DerivedClass : BaseClass
{
 
  public override void WriteStr()
  {
    Console.WriteLine("xyz");
  }
}
/* ... */
BaseClass isReallyBase = new BaseClass();
BaseClass isReallyDerived = new DerivedClass();
DerivedClass isClearlyDerived = new DerivedClass();


isReallyBase.WriteStr(); // writes abc
isReallyDerived.WriteStr(); // writes xyz
isClearlyDerived.writeStr(); // writes xyz

 

Using override keyword to override  virtual base class method.
Note: Derived object class will always will invoke derived class method. Overriding is a type of polymorphism (in which method behaviour will difffer depending on the objects type at runtime)

Overriding achieves polymorphism

Struct vs Class

Struct

Struct – value type (stack), public members by default, no inheritance , no polymorphism, no declared parameterless contructor, no declared destructor

The reason value types can’t support inheritance is because of arrays https://stackoverflow.com/questions/1222935/why-dont-structs-support-inheritance

Interface vs Classs

Interface – only singatures no implementation, multiple inheritance possible, only inherit from other interfaces only.

Explicit interface implementation

When a class inherits from two interface which both of those interfaces have the method with same signature, there is a an ambiguity, to solve this typecast the class object to point to the method we want. See part 31 C# Tutorial – Venkat.

Abstract class vs Interface

Abstract class can have method implementations, can have variables (fields), No multiple inheritance since it is a class.

Type safe

Type-safe code accesses only the memory locations it is authorized to access. Consider this simple C# code below:

int mynumber = 3;
string mystring = “3”;
int result = mynumber + mystring;

The code above will not compile or run, displaying an error like Cannot implicitly convert type ‘string’ to ‘int’.

Delegate

A delegate is a type safe function pointer. Delegate are reference types.

Extension Methods

Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods

Clone() vs CopyTo()

The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element’s object, resulting in a different, yet identical object.

So the difference are :

1- CopyTo require to have a destination array when Clone return a new array.
2- CopyTo let you specify an index (if required) to the destination array.

 

Polymorphism in C#

The ability of a programming language to process objects in different ways depending on their data type or class is known as Polymorphism. There are two types of polymorphism

  • Compile time polymorphism. Best example is Overloading
  • Runtime polymorphism. Best example is Overriding

 

 

Some advanced QandAs: http://www.geekinterview.com/Interview-Questions/Microsoft/C-Sharp/page1

 

 

Install EntityFramework 5

Open the project

PM> install-package entityframework -version 5.0.0.0

 

Installing ‘EntityFramework 5.0.0’.
Successfully installed ‘EntityFramework 5.0.0’.
Adding ‘EntityFramework 5.0.0’ to MVCDemoTest.
Successfully added ‘EntityFramework 5.0.0’ to MVCDemoTest.

Type ‘get-help EntityFramework’ to see all available Entity Framework commands.

 

 

PM>

Read and Parse an XML file in C#?

using XMLReader

The XmlReader is a faster and less memory-consuming  than XMLDocument

http://csharp.net-tutorials.com/xml/reading-xml-with-the-xmlreader-class/

using System;
using System.Text;
using System.Xml;

namespace ParsingXml
{
    class Program
    {
        static void Main(string[] args)
        {            
            XmlReader xmlReader = XmlReader.Create("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");
            while(xmlReader.Read())
            {
                if((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "Cube"))
                {
                    if(xmlReader.HasAttributes)
                        Console.WriteLine(xmlReader.GetAttribute("currency") + ": " + xmlReader.GetAttribute("rate"));                    
                }
            }
            Console.ReadKey();
        }
    }
}

 

 

Using XMLDocument

*************************

 

XmlDocument to read an XML from string or from file.

XmlDocument doc = new XmlDocument();
doc.Load("c:\\temp.xml");

or

doc.LoadXml("<xml>something</xml>");

then find a node below it ie like this

XmlNode node = doc.DocumentElement.SelectSingleNode("/book/title");

or

foreach(XmlNode node in doc.DocumentElement.ChildNodes){
   string text = node.InnerText; //or loop through its children as well
}

then read the text inside that node like this

string text = node.InnerText;

or read an attribute

string attr = node.Attributes["theattributename"]?.InnerText