Thursday, January 24, 2013

Interface Injection,Dependency Injection Example: Interface Injection


Dependency Injection Example: Interface Injection
using System;

namespace DependencyInjection
{
    public interface IDependentClass
    {
        void DoSomethingInDependentClass();
    }

    public interface IInjectDependent
    {
        void InjectDependent(IDependentClass dependentClass);
    }

    public class MainClass : IInjectDependent
    {
        IDependentClass dependentClass;

        public void DoSomething()
        {
            dependentClass.DoSomethingInDependentClass();
        }

        #region IInjectDependent Members

        public void InjectDependent(IDependentClass dependentClass)
        {
            this.dependentClass = dependentClass;
        }

        #endregion
    }

    public class DependentClass1 : IDependentClass
    {
        public void DoSomethingInDependentClass()
        {
            Console.WriteLine("Hello from DependentClass1: I can be injected into MainClass");
        }
    }

    public class DependentClass2 : IDependentClass
    {
        public void DoSomethingInDependentClass()
        {
            Console.WriteLine("Hello from DependentClass2: I can be injected as well, just change App.Config");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Get the correct dependency based on configuration file
            IDependentClass dependency = GetCorrectDependency();

            // Create our main class and inject the dependency
            MainClass mainClass = new MainClass();
            ((IInjectDependent)mainClass).InjectDependent(dependency);

            // Use the main class, the method references the dependency
            // so behaviour depends on the configuration file
            mainClass.DoSomething();

            Console.ReadLine();
        }

        /// <summary>
        /// Instantiate and return a class conforming to the IDependentClass interface:
        /// which class gets instantiated depends on the ClassName setting in
        /// the configuration file
        /// </summary>
        /// <returns>Class conforming to the IDependentClass interface</returns>
        static IDependentClass GetCorrectDependency()
        {
            string classToCreate = System.Configuration.ConfigurationManager.AppSettings["ClassName"];
            Type type = System.Type.GetType(classToCreate);
            IDependentClass dependency = (IDependentClass)Activator.CreateInstance(type);
            return dependency;
        }
    }
}

Friday, January 18, 2013

Server.MapPath



Server.MapPath specifies the relative or virtual path to map to a physical directory.

Server.MapPath(".") returns the current physical directory of the file (e.g. aspx) being executed
Server.MapPath("..") returns the parent directory
Server.MapPath("~") returns the physical path to the root of the application
Server.MapPath("/") returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)
An example:

Let's say you pointed a web site application (http://www.example.com/) to

C:\Inetpub\wwwroot
and installed your shop application (sub web as virtual directory in IIS, marked as application) in

D:\WebApps\shop
For example, if you call Server.MapPath in following request:

http://www.example.com/shop/products/GetProduct.aspx?id=2342
then:

Server.MapPath(".") returns D:\WebApps\shop\products
Server.MapPath("..") returns D:\WebApps\shop
Server.MapPath("~") returns D:\WebApps\shop
Server.MapPath("/") returns C:\Inetpub\wwwroot
Server.MapPath("/shop") returns D:\WebApps\shop
If Path starts with either a forward (/) or backward slash (\), the MapPath method returns a path as if Path were a full, virtual path.

If Path doesn't start with a slash, the MapPath method returns a path relative to the directory of the request being processed.

Note: in C#, @ is the verbatim literal string operator meaning that the string should be used "as is" and not be processed for escape sequences.

Thursday, January 17, 2013

AjaxControlToolkit in code behind C#


In  this  short post  I  will  show  you using   AjaxControlToolkit in code-behind.
I needed AjaxControlToolkit in my  web  site  because of effects  that  I want to use on it.
So,  first I  get AjaxControlToolkit from :  http://www.asp.net/(S(fu2l2uzphr2u3u45q2dnez55))/ajax/AjaxControlToolkit/Samples/   and  add reference to AjaxControlToolkit dll in my web site project.
  In  picture above  you can see a PanelIT  for which I want  to make some rounded corners and drop shadows.
  The  code : In   first  part we need to made panel corners rounded , so  I  use this.FindControl()  to find a  panel control with name "pIt" to whom we will make our changes. After that  we initialize a AjaxControlToolkit.RoundedCornersExtender and  set the needed values to his  properties and after that  we add those AjaxControlToolkit.RoundedCornersExtender to our TargetControlID = "pIt" panel control.
In the  next step we use  AjaxControlToolkit.DropShadowExtender initialization and setting a properties values and adding to TargetControlID = "pIt" .

   private void panelIt()
    {
        Panel p = (Panel)this.FindControl("pIt");//" + i.ToString());
        p.BackColor = Color.White;

       AjaxControlToolkit.RoundedCornersExtender r = new AjaxControlToolkit.RoundedCornersExtender();
        r.BorderColor = Color.Black;
        r.Corners = AjaxControlToolkit.BoxCorners.All;
        r.Radius = 5;
        r.TargetControlID = p.ID;
        this.Panel1.Controls.Add(r);

        AjaxControlToolkit.DropShadowExtender sh = new AjaxControlToolkit.DropShadowExtender();
        sh.TargetControlID = p.ID;
        sh.Rounded = true;
        sh.Width = 7;
        this.Panel1.Controls.Add(sh);

    }.

Monday, January 14, 2013

OPENDATASOURCE




OpenDataSource(provider_name, init_string)
For example
SELECT
FirstName,
Gender
FROM
OpenDataSource (
'SQLOLEDB',
'DataSource = NOLI\SQL2;UserID=myUserID;Password=myPassword'
).Organisation.dbo.Employees

Another Example




The following example creates an ad hoc connection to the Payroll instance of SQL Server on serverLondon, and queries the AdventureWorks2012.HumanResources.Employee table. (Use SQLNCLI and SQL Server will redirect to the latest version of SQL Server Native Client OLE DB Provider.)
SELECT *
FROM OPENDATASOURCE('SQLNCLI',
    'Data Source=London\Payroll;Integrated Security=SSPI')
    .AdventureWorks2012.HumanResources.Employee
The following example creates an ad hoc connection to an Excel spreadsheet in the 1997 - 2003 format.
SELECT * FROM OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0',
'Data Source=C:\DataFolder\Documents\TestExcel.xls;Extended Properties=EXCEL 5.0')...[Sheet1$] ;



The following example creates an ad hoc connection to the Payroll instance of SQL Server on serverLondon, and queries the AdventureWorks2012.HumanResources.Employee table. (Use SQLNCLI and SQL Server will redirect to the latest version of SQL Server Native Client OLE DB Provider.)
SELECT *
FROM OPENDATASOURCE('SQLNCLI',
    'Data Source=London\Payroll;Integrated Security=SSPI')
    .AdventureWorks2012.HumanResources.Employee
The following example creates an ad hoc connection to an Excel spreadsheet in the 1997 - 2003 format.
SELECT * FROM OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0',
'Data Source=C:\DataFolder\Documents\TestExcel.xls;Extended Properties=EXCEL 5.0')...[Sheet1$] ;

PDF Generate using iTextSharp

using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using System.IO;
protected void btnpdf_Click(object sender, EventArgs e)
    {
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        string fileName = " EmployeeTranferReport.pdf";
        Response.AppendHeader("Content-Type", "application/pdf");
        Response.AppendHeader("Content-disposition", "attachment; filename=" + fileName);
        Response.Cache.SetCacheability(HttpCacheability.NoCache);

        stringWrite.WriteLine("<html><body encoding=" + BaseFont.IDENTITY_H + " style='font-family:Arial Unicode MS;font-size:12;'> <table style='width:100%'><tr><td align='center'><b>अगरतला नगरपालिका परिषद</b></td></tr><tr><td align='center'>अगरतला</td></tr></table> </body></html>");

        HtmlTextWriter hw = new HtmlTextWriter(stringWrite);
        StringReader sr = new StringReader(stringWrite.ToString());
        Document pdfDoc = new Document(PageSize.A4, 20f, 10f, 10f, 0f);
        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        PdfWriter wi = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();

        string fontpath = Environment.GetFolderPath(Environment.SpecialFolder.Fonts) + "\\ARIALUNI.TTF";        //  "ARIALUNI.TTF" file copied from fonts folder and placed in the folder

        BaseFont bf = BaseFont.CreateFont(fontpath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        FontFactory.RegisterDirectory(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), true);
        FontFactory.Register(fontpath, "Arial Unicode MS");
        FontFactory.RegisterFamily("Arial Unicode MS", "Arial Unicode MS", fontpath);     
        htmlparser.Parse(sr);    
        pdfDoc.Close();
        Response.Write(pdfDoc);
        Response.End();
}

PDF Generate in

using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using System.IO;
protected void btnpdf_Click(object sender, EventArgs e)
    {
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        string fileName = " EmployeeTranferReport.pdf";
        Response.AppendHeader("Content-Type", "application/pdf");
        Response.AppendHeader("Content-disposition", "attachment; filename=" + fileName);
        Response.Cache.SetCacheability(HttpCacheability.NoCache);

        stringWrite.WriteLine("<html><body encoding=" + BaseFont.IDENTITY_H + " style='font-family:Arial Unicode MS;font-size:12;'> <table style='width:100%'><tr><td align='center'><b>अगरतला नगरपालिका परिषद</b></td></tr><tr><td align='center'>अगरतला</td></tr></table> </body></html>");

        HtmlTextWriter hw = new HtmlTextWriter(stringWrite);
        StringReader sr = new StringReader(stringWrite.ToString());
        Document pdfDoc = new Document(PageSize.A4, 20f, 10f, 10f, 0f);
        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        PdfWriter wi = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();

        string fontpath = Environment.GetFolderPath(Environment.SpecialFolder.Fonts) + "\\ARIALUNI.TTF";        //  "ARIALUNI.TTF" file copied from fonts folder and placed in the folder

        BaseFont bf = BaseFont.CreateFont(fontpath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        FontFactory.RegisterDirectory(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), true);
        FontFactory.Register(fontpath, "Arial Unicode MS");
        FontFactory.RegisterFamily("Arial Unicode MS", "Arial Unicode MS", fontpath);     
        htmlparser.Parse(sr);    
        pdfDoc.Close();
        Response.Write(pdfDoc);
        Response.End();
}