DNK Gif

Dot Net Knowledge

Labels

Tuesday, 21 July 2015

How to Write Object Data to an XML File using C#

Write Object Data to an XML File using C# 

This example writes the object from a class to an XML file using the XmlSerializer class.This code example defines a class named Book, creates an instance of the class, and uses XML serialization
to write the instance to an XML file.

Example:-

public class XMLWrite
{
         static void Main(string[] args)
           {
                  WriteXML();
            }
               public class Book
               {
                    public String title {get; set; };
                }
                
                 public static void WriteXML()
                {
                    Book overview = new Book();
                    overview.title = "Serialization Overview";
                    System.Xml.Serialization.XmlSerializer writer =
                       new System.Xml.Serialization.XmlSerializer(typeof(Book));
                   System.IO.StreamWriter file = new System.IO.StreamWriter(
                                      @"c:\temp\SerializationOverview.xml");
                   writer.Serialize(file, overview);
                   file.Close();
                }
}

Security

This example creates a new file, if the file does not already exist. If an application needs to create a file, that application needs Create access for the folder. If the file already exists, the application needs only Write access, a lesser privilege. Where possible, it is more secure to create the file during deployment, and only grant Read access to a single file, rather than Create access for a folder.

How to Read Object Data from an XML File using C#

Reading Object Data from an XML File using C#

This example reads object data that was previously written to an XML file using the XmlSerializer class.

public class Book
{
        public String title{get; set;};
}

public void ReadXML()
{
System.Xml.Serialization.XmlSerializer reader =
new System.Xml.Serialization.XmlSerializer(typeof(Book));

System.IO.StreamReader file = new System.IO.StreamReader(
@"c:\temp\SerializationOverview.xml");

Book overview = new Book();

overview = (Book)reader.Deserialize(file);

Console.WriteLine(overview.title);
}

Note:- 

By using this method only simple ViewModel data can be read,

Tuesday, 7 July 2015

Opening password protected Excel2013 file using Aspose.cells

How to open Password protected Excel file ?

Hey! I am not going to hack or any thing like that, Of course password is needed to open the file. 

For this latest version of Aspose.cells.dll is needed.
This version  Aspose.Cells for .NET v8.5.0.2 supports this feature, you can download the same.

This is the code to do this programmatically.

            LoadOptions loadoptions = new LoadOptions( );            
            loadoptions.Password = "umesh1";    
            string filepath="C:\\Dev\\MyExcel.xlsx";       
            Workbook workbook = new Workbook(filePath, loadoptions);

Use Excel Sheet as DataBase

How to use Excel sheet as DataBase?

Excel sheet can be used as DataBase. Here it goes.
Latest version of Aspose.cells needed.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aspose.Cells;

namespace BirthDay
{
    public class Decider
    {
        public static string GetRecord()
        {
            string nameList = string.Empty;
            int startColumnDOB = 2;
            int startRowDOB = 1;
            int countExit = 0;
            string filePath = System.AppDomain.CurrentDomain.BaseDirectory;
            string fileName = System.Configuration.ConfigurationSettings.AppSettings["ExcelFileName"];          
            filePath = filePath + fileName;
            Workbook wb = new Workbook(filePath);
            Worksheet ws = wb.Worksheets[0];
            Cells cells = ws.Cells;
            IList<Person> personList = new List<Person>();
            int r = startRowDOB;
            int c = startColumnDOB;
            while (countExit < 5)
            {
                string cellValue = cells[r, c].StringValue;
                if (string.IsNullOrWhiteSpace(cellValue))
                {
                    countExit++;
                    continue;
                }
                string[] dob = cellValue.Split('/');
                int month = 0; 
                int.TryParse(dob[0], out month);
                int day=0;
                int.TryParse(dob[1], out day);
                DateTime dateToday = DateTime.Now.Date;
                if ((month == dateToday.Month) && (day == dateToday.Day))
                {
                    Person person = new Person();
                    person.Id = decimal.Parse(string.IsNullOrWhiteSpace(cells[r, c - 2].StringValue) ? "0" : cells[r, c - 2].StringValue);
                    person.Name = cells[r, c - 1].StringValue;
                    person.DOB = dateToday;
                    nameList += person.Name + Environment.NewLine;
                }
                r++;
            }
            return nameList;
        }
    }
}

For security purpose password protected ExcelSheet can be used.
Download the Sample Project here.

Scheduling Task/Application using C#

How to run a program on a scheduled  basis?

Well this can be done using TaskScheduler of Window.


Download the Sample Project here.

The code goes here

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32.TaskScheduler;

namespace Event.Schedule
{
    public class Scheduler
    {
        public static void ScheduleTask()
        {
            // Get the service on the local machine
            using (TaskService ts = new TaskService())
            {               
                // Create a new task definition and assign properties
                TaskDefinition td = ts.NewTask();
                td.RegistrationInfo.Description = "Umesh Does something";
                // Create a trigger that will fire the task at this time every other day
                DailyTrigger d = new DailyTrigger();
                d.DaysInterval = 1; // For daily Execution of Task
                d.StartBoundary = DateTime.Now.Date.AddHours(10);//Executes the Task daily at 10AM
                td.Triggers.Add(d);
                // Create an action that will launch another program or Task whenever the trigger fires
                td.Actions.Add(new ExecAction("C:\\Dev\\BirthDay\\BirthDay\\bin\\Debug\\MyApplication.exe"));
                // Register the task in the root folder
                ts.RootFolder.RegisterTaskDefinition("Umesh", td);
                // Remove the task we just created
                 ts.RootFolder.DeleteTask("Umesh");
            }

        }
    }
}

How to check the status of the Task/Task Details?

1. Go to Run, Type taskschd.msc + Enter

2. Now check the image below, you will get it.

Sunday, 5 July 2015

SQL Server Books

Books on SQL Server

Book1


Book2


SQL Server IF Exists

CheckIf Column Exists in SQL Server Table

Method 1

IFEXISTS(SELECT*FROMsys.columns

WHEREName=N'columnName'ANDOBJECT_ID=OBJECT_ID(N'tableName'))

BEGIN

PRINT'YourColumnExists'

END

For AdventureWorks sample database

IFEXISTS(SELECT*FROMsys.columns

WHERE Name = N'Name' AND OBJECT_ID =OBJECT_ID(N'[HumanResources].

[Department]'))

BEGIN

PRINT'YourColumnExists'

END

Method 2

IFCOL_LENGTH('table_name','column_name')ISNOTNULL

BEGIN

PRINT'YourColumnExists'

END

For AdventureWorks sample database

IFCOL_LENGTH('[HumanResources].[Department]','Name')ISNOTNULL

BEGIN

PRINT'YourColumnExists'

END

Method 3

IFEXISTS(

SELECTTOP1*

FROMINFORMATION_SCHEMA.COLUMNS

WHERE[TABLE_NAME]='TableName'

AND[COLUMN_NAME]='ColumnName'

AND[TABLE_SCHEMA]='SchemaName')

BEGIN

PRINT'YourColumnExists'

END

For AdventureWorks sample database

IFEXISTS(

SELECTTOP1*

FROMINFORMATION_SCHEMA.COLUMNS

WHERE[TABLE_NAME]='Department'

AND[COLUMN_NAME]='Name'

AND[TABLE_SCHEMA]='HumanResources')

BEGIN

PRINT'YourColumnExists'

END