bir şeyler söylemek lazım

blokk…

Follow me on TwitterRSS Beslemeleri

  • Anasayfa
  • Etkinlik Tavkimi
    • DEDAK Etkinlik Takvimi
    • Doğa Yürüyüşleri Takvimi
  • Hakkımda
  • Projeler

Composite Web Control Example

27 May

Posted in Develop

Leave a Comment

This example shows how to create a control named Register that demonstrates the main steps required to implement a composite ASP.NET server control. A composite control uses child controls to create a user interface (UI) and to perform other logic. Since a composite control relies on child controls for its functionality, it is significantly easier to develop a composite control than to implement all of the control’s functionality yourself.

In this example, the Register control uses child controls to create a user interface (UI) for entering user information to register with a Web site. The UI consists of two TextBox controls, one for entering the user’s name and another to enter the user’s e-mail address, and a Button control to submit the information. Register also associates RequiredFieldValidator controls with the two TextBox controls to be sure that the user enters a name and an e-mail address. The Click event of the Button control is raised as the Register control’s Submit event.

The Register control relies on the built-in features of the child controls for its behavior. For example, Register relies on the TextBox controls for handling postback data, the Button control for the postback event, and the RequiredFieldValidator controls for validation.

The code for the Register control is described in the “Code Discussion” section later in this topic. When you examine the code for the Register control, you will notice that most of the code relates to creating and managing the child controls.

// Register.cs
using System;
using System.ComponentModel;
using System.Drawing;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Samples.AspNet.CS.Controls
{
    [
    AspNetHostingPermission(SecurityAction.Demand,
        Level = AspNetHostingPermissionLevel.Minimal),
    AspNetHostingPermission(SecurityAction.InheritanceDemand,
        Level=AspNetHostingPermissionLevel.Minimal),
    DefaultEvent("Submit"),
    DefaultProperty("ButtonText"),
    ToolboxData("<{0}:Register runat="server"> </{0}:Register>"),
    ]
    public class Register : CompositeControl
    {
        private Button submitButton;
        private TextBox nameTextBox;
        private Label nameLabel;
        private TextBox emailTextBox;
        private Label emailLabel;
        private RequiredFieldValidator emailValidator;
        private RequiredFieldValidator nameValidator;

        private static readonly object EventSubmitKey =
            new object();

        // The following properties are delegated to
        // child controls.
        [
        Bindable(true),
        Category("Appearance"),
        DefaultValue(""),
        Description("The text to display on the button.")
        ]
        public string ButtonText
        {
            get
            {
                EnsureChildControls();
                return submitButton.Text;
            }
            set
            {
                EnsureChildControls();
                submitButton.Text = value;
            }
        }

        [
        Bindable(true),
        Category("Default"),
        DefaultValue(""),
        Description("The user name.")
        ]
        public string Name
        {
            get
            {
                EnsureChildControls();
                return nameTextBox.Text;
            }
            set
            {
                EnsureChildControls();
                nameTextBox.Text = value;
            }
        }

        [
        Bindable(true),
        Category("Appearance"),
        DefaultValue(""),
        Description(
            "Error message for the name validator.")
        ]
        public string NameErrorMessage
        {
            get
            {
                EnsureChildControls();
                return nameValidator.ErrorMessage;
            }
            set
            {
                EnsureChildControls();
                nameValidator.ErrorMessage = value;
                nameValidator.ToolTip = value;
            }
        }

        [
        Bindable(true),
        Category("Appearance"),
        DefaultValue(""),
        Description("The text for the name label.")
        ]
        public string NameLabelText
        {
            get
            {
                EnsureChildControls();
                return nameLabel.Text;
            }
            set
            {
                EnsureChildControls();
                nameLabel.Text = value;
            }
        }

        [
        Bindable(true),
        Category("Default"),
        DefaultValue(""),
        Description("The e-mail address.")
        ]
        public string Email
        {
            get
            {
                EnsureChildControls();
                return emailTextBox.Text;
            }
            set
            {
                EnsureChildControls();
                emailTextBox.Text = value;
            }
        }

        [
        Bindable(true),
        Category("Appearance"),
        DefaultValue(""),
        Description(
            "Error message for the e-mail validator.")
        ]
        public string EmailErrorMessage
        {
            get
            {
                EnsureChildControls();
                return emailValidator.ErrorMessage;
            }
            set
            {
                EnsureChildControls();
                emailValidator.ErrorMessage = value;
                emailValidator.ToolTip = value;
            }
        }

        [
        Bindable(true),
        Category("Appearance"),
        DefaultValue(""),
        Description("The text for the e-mail label.")
        ]
        public string EmailLabelText
        {
            get
            {
                EnsureChildControls();
                return emailLabel.Text;
            }
            set
            {
                EnsureChildControls();
                emailLabel.Text = value;

            }
        }

        // The Submit event.
        [
        Category("Action"),
        Description("Raised when the user clicks the button.")
        ]
        public event EventHandler Submit
        {
            add
            {
                Events.AddHandler(EventSubmitKey, value);
            }
            remove
            {
                Events.RemoveHandler(EventSubmitKey, value);
            }
        }

        // The method that raises the Submit event.
        protected virtual void OnSubmit(EventArgs e)
        {
            EventHandler SubmitHandler =
                (EventHandler)Events[EventSubmitKey];
            if (SubmitHandler != null)
            {
                SubmitHandler(this, e);
            }
        }

        // Handles the Click event of the Button and raises
        // the Submit event.
        private void _button_Click(object source, EventArgs e)
        {
            OnSubmit(EventArgs.Empty);
        }

        protected override void RecreateChildControls()
        {
            EnsureChildControls();
        }

        protected override void CreateChildControls()
        {
            Controls.Clear();

            nameLabel = new Label();

            nameTextBox = new TextBox();
            nameTextBox.ID = "nameTextBox";

            nameValidator = new RequiredFieldValidator();
            nameValidator.ID = "validator1";
            nameValidator.ControlToValidate = nameTextBox.ID;
            nameValidator.Text = "Failed validation.";
            nameValidator.Display = ValidatorDisplay.Static;

            emailLabel = new Label();

            emailTextBox = new TextBox();
            emailTextBox.ID = "emailTextBox";

            emailValidator = new RequiredFieldValidator();
            emailValidator.ID = "validator2";
            emailValidator.ControlToValidate =
                emailTextBox.ID;
            emailValidator.Text = "Failed validation.";
            emailValidator.Display = ValidatorDisplay.Static;

            submitButton = new Button();
            submitButton.ID = "button1";
            submitButton.Click
                += new EventHandler(_button_Click);

            this.Controls.Add(nameLabel);
            this.Controls.Add(nameTextBox);
            this.Controls.Add(nameValidator);
            this.Controls.Add(emailLabel);
            this.Controls.Add(emailTextBox);
            this.Controls.Add(emailValidator);
            this.Controls.Add(submitButton);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            AddAttributesToRender(writer);

            writer.AddAttribute(
                HtmlTextWriterAttribute.Cellpadding,
                "1", false);
            writer.RenderBeginTag(HtmlTextWriterTag.Table);

            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            nameLabel.RenderControl(writer);
            writer.RenderEndTag();
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            nameTextBox.RenderControl(writer);
            writer.RenderEndTag();
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            nameValidator.RenderControl(writer);
            writer.RenderEndTag();
            writer.RenderEndTag();

            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            emailLabel.RenderControl(writer);
            writer.RenderEndTag();
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            emailTextBox.RenderControl(writer);
            writer.RenderEndTag();
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            emailValidator.RenderControl(writer);
            writer.RenderEndTag();
            writer.RenderEndTag();

            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.AddAttribute(
                HtmlTextWriterAttribute.Colspan,
                "2", false);
            writer.AddAttribute(
                HtmlTextWriterAttribute.Align,
                "right", false);
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            submitButton.RenderControl(writer);
            writer.RenderEndTag();
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write(" ");
            writer.RenderEndTag();
            writer.RenderEndTag();

            writer.RenderEndTag();
        }
    }
}
.net, asp.net, c#, software, Tips and Tricks

@çıkDeniz Denizbank

22 May

Posted in Develop

Leave a Comment

İşte Yeni Açıkdeniz Internet Şubesinde size sunduğumuz yeniliklerden bazıları;

Kolay kullanım için tasarlanmış İnteraktif İşlem Sayfaları ve Hızlı Arama Fonksiyonu
Arka plan resmi değiştirme özelliği ile Kendi AçıkDeniz’ini yaratma imkanı
Yeni Fonksiyonel Ajanda menüsü
Alıcıya SMS ile Para Transferinin gönderildiği alıcıya anında SMS ile bilgi verebilme imkanı
Kurum Ödemeleri dahil, tüm Finansal İşlemler için ayrı ayrı “Son 20 İşlem” görebilme ve “İşlem Kaydet” özelliği

ve Cuma’nın size eşlik etmesiyle birlikte kullandıkça keşfedeceğiniz ve deneyimleyeceğiniz daha birçok yenilik…

DenizBank

@çıkDeniz

Developed Project, software

Karmate Nayino

22 May

Posted in müzik

Leave a Comment

müzik

Common Table Expressions (CTE) in SQL Server 2005

25 Nis

Posted in Develop

Leave a Comment

Introduction
When crafting a query in SQL, there are often times when we may need to operate over a set of data that doesn’t inherently exist within the system. For example, the database for an eCommerce web application would have the standard tables - Products, Customers, Orders, OrderDetails, and so on – but we may need to run reports on a particular subset of the data or against aggregate data across these tables. Or the reporting queries we need might need to group or filter by results returned by scalar subqueries. Typically, views are used to break down complex queries into digestible chunks or to provide scalar subquery results that can be grouped and filtered. Views, however, are sometimes overkill, as they are permanent objects at the system-level. If we only need to reference this complex query in a single stored procedure or UDF, another option is to use a derived table. Unfortunately, derived tables muddle the readability of the query and must be repeated for each use in a statement.

Common Table Expressions, or CTE, are a new construct introduced in Microsoft SQL Server 2005 that offer a more readable form of the derived table that can be declared once and referenced multiple times in a query. Moreover, CTEs can be recursively defined, allowing a recursive entity to be enumerated without the need for recursive stored procedures. In this article we’ll examine the benefits, uses, and syntax of both recursive and non-recursive CTEs. Read on to learn more!

 

 

A Simple Common Table Expression Example
Before we dive into the syntax or gritty details of CTEs, let’s start by looking at a simple example. I think you’ll agree that even without knowing the syntax of CTEs, they are pretty readable and straightforward (the hallmark of a well-designed programming language construct).

WITH ProductAndCategoryNamesOverTenDollars (ProductName, CategoryName, UnitPrice) AS
(
   SELECT
      p.ProductName,
      c.CategoryName,
      p.UnitPrice
   FROM Products p
      INNER JOIN Categories c ON
         c.CategoryID = p.CategoryID
   WHERE p.UnitPrice > 10.0
)

SELECT *
FROM ProductAndCategoryNamesOverTenDollars
ORDER BY CategoryName ASC, UnitPrice ASC, ProductName ASC

This query creates a CTE named ProductAndCategoryNamesOverTenDollars that returns the name, category name, and price of those products whose unit price exceeds $10.00. Once the CTE has been defined, it must then immediately be used in a query. The query treats the CTE as if were a view or table in the system, returning the three fields defined by the CTE (ProductName, CategoryName, and UnitPrice), ordered alphabetically by category, then by price, and then alphabetically by product name.

In short, a Common Table Expression allows us to define a temporary, view-like construct. We start by (optionally) specifying the columns it returns, then define the query. Following that, the CTE can be used in a SELECT, INSERT, UPDATE, or DELETE statement.

Common Table Expression Syntax
A Common Table Expression contains three core parts:

The CTE name (this is what follows the WITH keyword)
The column list (optional)
The query (appears within parentheses after the AS keyword)
The query using the CTE must be the first query appearing after the CTE. That is, you cannot do the following:


WITH ProductAndCategoryNamesOverTenDollars (ProductName, CategoryName, UnitPrice) AS
(
   SELECT
      p.ProductName,
      c.CategoryName,
      p.UnitPrice
   FROM Products p
      INNER JOIN Categories c ON
         c.CategoryID = p.CategoryID
   WHERE p.UnitPrice > 10.0
)

SELECT *
FROM Products

SELECT *
FROM ProductAndCategoryNamesOverTenDollars
ORDER BY CategoryName ASC, UnitPrice ASC, ProductName ASC

The ProductAndCategoryNamesOverTenDollars CTE only applies to the first query following it. So when the second query is reached, ProductAndCategoryNamesOverTenDollars is undefined, resulting in an “Invalid object name ‘ProductAndCategoryNamesOverTenDollars’” error message.

You can, however, define multiple CTEs after the WITH keyword by separating each CTE with a comma. For example, the following query uses two CTEs. The subsequent SELECT query then uses an INNER JOIN to match together the records from the two CTEs:


WITH CategoryAndNumberOfProducts (CategoryID, CategoryName, NumberOfProducts) AS
(
   SELECT
      CategoryID,
      CategoryName,
      (SELECT COUNT(1) FROM Products p
       WHERE p.CategoryID = c.CategoryID) as NumberOfProducts
   FROM Categories c
),

ProductsOverTenDollars (ProductID, CategoryID, ProductName, UnitPrice) AS
(
   SELECT
      ProductID,
      CategoryID,
      ProductName,
      UnitPrice
   FROM Products p
   WHERE UnitPrice > 10.0
)

SELECT c.CategoryName, c.NumberOfProducts,
      p.ProductName, p.UnitPrice
FROM ProductsOverTenDollars p
   INNER JOIN CategoryAndNumberOfProducts c ON
      p.CategoryID = c.CategoryID
ORDER BY ProductName

Unlike a derived table, CTEs can be defined just once, yet appear multiple times in the subsequent query. To demonstrate this, consider the following example: the Northwind database’s Employees table contains an optional ReportsTo column that, if specified, indicates the employee’s manager. ReportsTo is a self-referencing foreign key, meaning that, if provided, it refers back to another EmployeeID in the Employees table. Imagine that we wanted to display a list of employees including how many other employees they directly managed. This could be done using a simple, CTE-free SELECT statement, but let’s use a CTE for now (for reasons which will become clear soon):


WITH EmployeeSubordinatesReport (EmployeeID, LastName, FirstName, NumberOfSubordinates, ReportsTo) AS
(
   SELECT
      EmployeeID,
      LastName,
      FirstName,
      (SELECT COUNT(1) FROM Employees e2
       WHERE e2.ReportsTo = e.EmployeeID) as NumberOfSubordinates,
      ReportsTo
   FROM Employees e
)

SELECT LastName, FirstName, NumberOfSubordinates
FROM EmployeeSubordinatesReport

This query will return the employees records, showing each employee’s last and first name along with how many other employees they manage. As the figure below shows, only Andrew Fuller and Steven Buchanan are manager material.

Now, imagine that our boss (Andrew Fuller, perhaps) comes charging into our office and demands that the report also lists each employee’s manager’s name and number of subordinates (if the employee has a manager, that is – Mr. Fuller is all to quick to point out that he reports to no one). Adding such functionality is a snap with the CTE – just add it in a LEFT JOIN!


WITH EmployeeSubordinatesReport (EmployeeID, LastName, FirstName, NumberOfSubordinates, ReportsTo) AS
(
   SELECT
      EmployeeID,
      LastName,
      FirstName,
      (SELECT COUNT(1) FROM Employees e2
       WHERE e2.ReportsTo = e.EmployeeID) as NumberOfSubordinates,
      ReportsTo
   FROM Employees e
)

SELECT Employee.LastName, Employee.FirstName, Employee.NumberOfSubordinates,
   Manager.LastName as ManagerLastName, Manager.FirstName as ManagerFirstName, Manager.NumberOfSubordinates as ManagerNumberOfSubordinates
FROM EmployeeSubordinatesReport Employee
   LEFT JOIN EmployeeSubordinatesReport Manager ON
      Employee.ReportsTo = Manager.EmployeeID

With this additional LEFT JOIN, the employee’s manager’s results are returned; if there’s no manager for the employee, NULLs are returned instead.

ipucu, ms sql, Tips and Tricks

DateTime.ToString() Patterns

18 Nis

Posted in Develop

Leave a Comment

All the patterns:

 

 

0	 MM/dd/yyyy	 08/22/2006
1	 dddd, dd MMMM yyyy	 Tuesday, 22 August 2006
2	 dddd, dd MMMM yyyy	 HH:mm Tuesday, 22 August 2006 06:30
3	 dddd, dd MMMM yyyy	 hh:mm tt Tuesday, 22 August 2006 06:30 AM
4	 dddd, dd MMMM yyyy	 H:mm Tuesday, 22 August 2006 6:30
5	 dddd, dd MMMM yyyy	 h:mm tt Tuesday, 22 August 2006 6:30 AM
6	 dddd, dd MMMM yyyy HH:mm:ss	 Tuesday, 22 August 2006 06:30:07
7	 MM/dd/yyyy HH:mm	 08/22/2006 06:30
8	 MM/dd/yyyy hh:mm tt	 08/22/2006 06:30 AM
9	 MM/dd/yyyy H:mm	 08/22/2006 6:30
10	 MM/dd/yyyy h:mm tt	 08/22/2006 6:30 AM
10	 MM/dd/yyyy h:mm tt	 08/22/2006 6:30 AM
10	 MM/dd/yyyy h:mm tt	 08/22/2006 6:30 AM
11	 MM/dd/yyyy HH:mm:ss	08/22/2006 06:30:07
12	 MMMM dd	 August 22
13	 MMMM dd	 August 22
14	 yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK	 2006-08-22T06:30:07.7199222-04:00
15	 yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK	 2006-08-22T06:30:07.7199222-04:00
16	 ddd, dd MMM yyyy HH':'mm':'ss 'GMT'	 Tue, 22 Aug 2006 06:30:07 GMT
17	 ddd, dd MMM yyyy HH':'mm':'ss 'GMT'	 Tue, 22 Aug 2006 06:30:07 GMT
18	 yyyy'-'MM'-'dd'T'HH':'mm':'ss	 2006-08-22T06:30:07
19	 HH:mm	 06:30
20	 hh:mm tt	 06:30 AM
21	 H:mm	 6:30
22	 h:mm tt	 6:30 AM
23	 HH:mm:ss	 06:30:07
24	 yyyy'-'MM'-'dd HH':'mm':'ss'Z'	 2006-08-22 06:30:07Z
25	 dddd, dd MMMM yyyy HH:mm:ss	 Tuesday, 22 August 2006 06:30:07
26	 yyyy MMMM	 2006 August
27	 yyyy MMMM	 2006 August

The patterns for DateTime.ToString ( 'd' ) :
0	 MM/dd/yyyy	 08/22/2006

The patterns for DateTime.ToString ( ‘D’ ) :
0 dddd, dd MMMM yyyy Tuesday, 22 August 2006


The patterns for DateTime.ToString ( 'f' ) :
0	 dddd, dd MMMM yyyy HH:mm	 Tuesday, 22 August 2006 06:30
1	 dddd, dd MMMM yyyy hh:mm	 tt Tuesday, 22 August 2006 06:30 AM
2	 dddd, dd MMMM yyyy H:mm	 Tuesday, 22 August 2006 6:30
3	 dddd, dd MMMM yyyy h:mm	 tt Tuesday, 22 August 2006 6:30 AM
The patterns for DateTime.ToString ( 'F' ) :
0	 dddd, dd MMMM yyyy HH:mm:ss	 Tuesday, 22 August 2006 06:30:07
The patterns for DateTime.ToString ( 'g' ) :
0	 MM/dd/yyyy HH:mm	 08/22/2006 06:30
1	 MM/dd/yyyy hh:mm	 tt 08/22/2006 06:30 AM
2	 MM/dd/yyyy H:mm	 08/22/2006 6:30
3	 MM/dd/yyyy h:mm tt	 08/22/2006 6:30 AM
The patterns for DateTime.ToString ( 'G' ) :
0	 MM/dd/yyyy HH:mm:ss	 08/22/2006 06:30:07
The patterns for DateTime.ToString ( 'm' ) :
0	 MMMM dd	 August 22
The patterns for DateTime.ToString ( 'r' ) :
0	 ddd, dd MMM yyyy HH':'mm':'ss 'GMT'	 Tue, 22 Aug 2006 06:30:07 GMT
The patterns for DateTime.ToString ( 's' ) :
0	 yyyy'-'MM'-'dd'T'HH':'mm':'ss	 2006-08-22T06:30:07
The patterns for DateTime.ToString ( 'u' ) :
0	 yyyy'-'MM'-'dd HH':'mm':'ss'Z'	 2006-08-22 06:30:07Z
The patterns for DateTime.ToString ( 'U' ) :
0	 dddd, dd MMMM yyyy HH:mm:ss	 Tuesday, 22 August 2006 06:30:07
The patterns for DateTime.ToString ( 'y' ) :
0	 yyyy MMMM 2006 August
Building a custom DateTime.ToString Patterns
The following details the meaning of each pattern character. Note the K and z character.

d	Represents the day of the month as a number from 1 through 31. A single-digit day is formatted without a leading zero
dd	Represents the day of the month as a number from 01 through 31. A single-digit day is formatted with a leading zero
ddd	Represents the abbreviated name of the day of the week (Mon, Tues, Wed etc)
dddd	Represents the full name of the day of the week (Monday, Tuesday etc)
h	12-hour clock hour (e.g. 7)
hh	12-hour clock, with a leading 0 (e.g. 07)
H	24-hour clock hour (e.g. 19)
HH	24-hour clock hour, with a leading 0 (e.g. 19)
m	Minutes
mm	Minutes with a leading zero
M	Month number
MM	Month number with leading zero
MMM	Abbreviated Month Name (e.g. Dec)
MMMM	Full month name (e.g. December)
s	Seconds
ss	Seconds with leading zero
t	Abbreviated AM / PM (e.g. A or P)
tt	AM / PM (e.g. AM or PM
y	Year, no leading zero (e.g. 2001 would be 1)
yy	Year, leadin zero (e.g. 2001 would be 01)
yyy	Year, (e.g. 2001 would be 2001)
yyyy	Year, (e.g. 2001 would be 2001)
K	Represents the time zone information of a date and time value (e.g. +05:00)
z	With DateTime values, represents the signed offset of the local operating system's time zone from Coordinated Universal Time (UTC), measured in hours. (e.g. +6)
zz	As z but with leadin zero (e.g. +06)
zzz	With DateTime values, represents the signed offset of the local operating system's time zone from UTC, measured in hours and minutes. (e.g. +06:00)
f	Represents the most significant digit of the seconds fraction; that is, it represents the tenths of a second in a date and time value.
ff	Represents the two most significant digits of the seconds fraction; that is, it represents the hundredths of a second in a date and time value.
fff	Represents the three most significant digits of the seconds fraction; that is, it represents the milliseconds in a date and time value.
ffff	Represents the four most significant digits of the seconds fraction; that is, it represents the ten thousandths of a second in a date and time value. While it is possible to display the ten thousandths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.
fffff	Represents the five most significant digits of the seconds fraction; that is, it represents the hundred thousandths of a second in a date and time value. While it is possible to display the hundred thousandths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.
ffffff	Represents the six most significant digits of the seconds fraction; that is, it represents the millionths of a second in a date and time value. While it is possible to display the millionths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.
fffffff	Represents the seven most significant digits of the seconds fraction; that is, it represents the ten millionths of a second in a date and time value. While it is possible to display the ten millionths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.
F	Represents the most significant digit of the seconds fraction; that is, it represents the tenths of a second in a date and time value. Nothing is displayed if the digit is zero.
:	Represents the time separator defined in the current DateTimeFormatInfo..::.TimeSeparator property. This separator is used to differentiate hours, minutes, and seconds.
/	 Represents the date separator defined in the current DateTimeFormatInfo..::.DateSeparator property. This separator is used to differentiate years, months, and days.
"	 Represents a quoted string (quotation mark). Displays the literal value of any string between two quotation marks ("). Your application should precede each quotation mark with an escape character ().
'	 Represents a quoted string (apostrophe). Displays the literal value of any string between two apostrophe (') characters.
%c	Represents the result associated with a c custom format specifier, when the custom date and time format string consists solely of that custom format specifier. That is, to use the d, f, F, h, m, s, t, y, z, H, or M custom format specifier by itself, the application should specify %d, %f, %F, %h, %m, %s, %t, %y, %z, %H, or %M. For more information about using a single format specifier, see Using Single Custom Format Specifiers.

||\c || Represents the escape character, and displays the character “c” as a literal when that character is preceded by the escape character (\). To insert the backslash character itself in the result string, the application should use two escape characters (“\\”).

Any other character copies any other character to the result string, without affecting formatting. ||

.net, c#
1

Javascript Tarih Toplama Çıkarma (Javascript Date Add and Subtract)

15 Nis

Posted in Develop

Leave a Comment

Javascript ile tarih üzerinde toplama ve çıkarma işlemleri yapılırken bazı aksaklıklar yaşanabilir. Benim karşılaştıklarım hakkında bir kaç bilgi vermek isterim. Belki sizinde işinize yarayacak olur (:

Öncelikle işlemlerinizi UTC Date üzerinden yaparsanız daha sağlıklı sonuçlar almanız muhtemel.

Bir diğer nokta Javascript Ay ve Günleri  array olarak tutmakta ve bu sebeple 0 indexli çalışmaktadır. Ocak ayı için  get yaptığınızda size 0 dönecektir.

Aynı durum gün içinde geçerlidir.

Bununla birlikte tarih toplama ve çıkarma yapıp  yeni tarihi hesaplamaya çalıştığınızda eğer iki tarih içinde Yaz Saati yada Kış Saati değişimine denk geliniyorsa  en son  hesaplamalarda aradaki gün miktarı da küsürlü çıkabilir. Bu durumda round yapmanız yararlı olacaktır.

Son olarak belirteceğim nokta bir tarihin belli bir gün sonrasını bulmak için yapacağınız işlem bir sonraki ayın son gününe denk geliyorsa günü get etmeye çalıştığınızda size tarih bir önceki ayın son gününden bir fazla gelecektir.

Şöyleki;

Kullanıcı tarih olarak 28.01.2011 seçti ve bir başka alanda da 4 gün seçti ve siz fonksiyon olarak 28.01 in dört gün sonrasını bulmaya çalıştığınızda,

işlemler sonucunda size 32.01.2011 olarak dönecektir bunun içinde ayların son günlerini bir dizi olarak saklamanızda yarar vardır.

Bu bahsettiğim durumları aşağıda örnek kod ile açıklamaktayım.

Umarım işinize yarabilir….

function CalculateDates()
{
    var m = [31,28,31,30,31,30,31,31,30,31,30,31];
    var date1 = document.getElementById('txtDate');
    var date2 = document.getElementById('txtDate2');
    var dayTerm = document.getElementById('txtTermDay');
    var termChanged = false;

   if((date1.value != "") && (date2.value != ""))
    {
        var date1Date = Date.parseDate(document.getElementById('date1Date_txtDate').value, '%d.%m.%Y');
        var date2Date = Date.parseDate(document.getElementById('date1date2Date_txtDate').value, '%d.%m.%Y');
        var dayValue = ((date2Date.getTime() - date1Date.getTime()) / (1000*60*60*24));
        dayTerm.value =Math.round(dayValue);
    }
    else if ((dayTerm.value != "") && (date1.value != "") )
    {
        var date1Date = Date.parseDate(date1.value, '%d.%m.%Y');
        var newTime = date1Date.getTime() + dayTerm.value * (1000*60*60*24);
        var newDate = new Date(newTime);
        var day = parseInt(newDate.getUTCDate()) + 1;
        var month = parseInt(newDate.getUTCMonth());
        //control years is leap year
        var year = parseInt(newDate.getYear());
        if(year % 4 == 0){
            m[1]=29;
        }
        var dayString="";
        var monthString="";
        if(m[month]<day)
        {
            dayString= "0";
            monthString = month < 8 ? "0" : "";
            month += 2;
            day = 1;
        }
        else
        {
            dayString = day< 10 ? "0" : "" ;
            monthString =(newDate.getUTCMonth()) < 9 ? "0" : "" ;
            month++;
        }
        date2.value = dayString + day +"."+ monthString + month +"."+newDate.getYear();
    }
    else if ((dayTerm.value != "") && (date2.value != ""))
    {
        var date2Date = Date.parseDate(date2.value, '%d.%m.%Y');
        var newTime = date2Date.getTime() - dayTerm.value * (1000*60*60*24);
        var newDate = new Date(newTime);
        var day = parseInt(newDate.getUTCDate()) + 1;
        var month = parseInt(newDate.getUTCMonth());
        //control years is leap year
        var year = parseInt(newDate.getYear());
        if(year % 4 == 0){
            m[1]=29;
        }
        var dayString="";
        var monthString="";
        if(m[month]<day)
        {
            dayString= "0";
            monthString = month < 8 ? "0" : "";
            month += 2;
            day=1;
        }
        else
        {
            dayString = day< 10 ? "0" : "" ;
            monthString =(newDate.getUTCMonth()) < 9 ? "0" : "" ;   

            month++;
        }
        date1.value = dayString + day+"."+ monthString + month+"."+newDate.getYear();
    }
}   
javascript

jquery customize file upload style

16 Şub

Posted in Develop

Leave a Comment

As websites expand content-sharing and collaboration features, users are electing to upload more and more files—photos, videos, documents, even secure data—via web applications to store them in “cloud”-based systems rather than locally on their computers. The HTML input element with a type="file" attribute gives web developers a native control to handle this file upload functionality. But browsers offer almost no control over how file inputs are presented visually, making it difficult to incorporate them into a uniform interface design.

Today, we’re releasing a jQuery file input plugin that uses progressive enhancement to transform a standard HTML file input into a visually customizable control. With a few lines of CSS and JavaScript, this widget allows you to create a custom-styled file input that leverages all of the accessibility features the native input provides.

This widget is one of the 12 fully-accessible, project-ready, progressive enhancement-driven widgets we created to accompany our book, Designing with Progressive Enhancement. (Purchasers of the book can access all twelve widgets immediately).

A quick demo

Before we get into the mechanics of the custom-styled input control, here’s a demo that highlights key features. The input box and buttons have distinct, custom visual style; and when the user selects a file, the custom input updates to display the file name and an icon representing the file’s extension. To see the feedback in action, browse and choose any file. (FYI: The demo is completely non-functional—i.e., it will not upload files to any server. )

View in a new window

Note: If you click the “view low-bandwidth” link, just remember that you’ll need to click it again to view the enhanced version of this site on future views.

To ensure an accessible experience for the widest audience possible, this demo and all our widgets use our EnhanceJS framework, which tests browsers’ CSS and JavaScript capabilities and applies enhancements only to capable browsers. In practice, browsers that don’t pass receive a basic experience with the fully-fuctional native control; for capable browsers that do pass the test, the script applies advanced CSS and JS enhancements, adds a “View low-bandwidth version” link for users to toggle from a basic to enhanced view, and drops a cookie on change to record the user’s preference. EnhanceJS is used in the demo page, but it is not required to use the widget in your projects. (To learn more about EnhanceJS, check out Introducing EnhanceJS: A smarter, safer way to apply progressive enhancement)

How does this widget actually work?

The approach we’ve used piggybacks on top of the native file input: The widget creates a custom-styled file control using div and span elements, and then uses JavaScript to set the native input‘s opacity to zero and dynamically position it invisibly between the cursor and the custom control. The user actually interacts only with the native input without knowing it. The following infographic demonstrates the concept:

Infographic: the native file input is positioned under the user’s cursor to open the browse dialog.

In addition, the widget script applies custom styling, and parses the filename’s extension to recognize the file format so it can display a file-specific icon (the CSS includes a generic file icon and several specific icons—image, multimedia, zip folder—which are easily customizable).

The best part of this approach is that we get great accessibility support for keyboard users and those with disabilities automatically. Since we’re always using the native file input control, we can leverage all the functionality and accessibility that it provides—the custom file input is really a visual feedback mechanism only. And though the native input is invisible, it’s still fully keyboard-accessible, so there’s no need to add any additional accessibility features or ARIA attributes. (We do, however, add one ARIA attribute to the custom widget to hide it from screen readers, since it’s relevant only to sighted users.)

A tip of the hat

This solution was inspired by the work of Michael McGrady and Shaun Inman, who developed this tricky bit of CSS and JavaScript to position the native file input under the user’s cursor to create custom file inputs. You can find that article here: Styling File Inputs with CSS and the DOM

How do I use it?

To use this script in your page, you’ll need to download and reference both jQuery and jQuery.fileinput.js, as well as the associated CSS and images for the control (download instructions are found below), and call the customFileInput method on any list element on the page. For example, to create a custom input control from a input element with an id of file, find it using jQuery and call the customFileInput method on it:

<code><br /><strong>HTML:</strong><br /><input type="file" name="file" id="file" /><br /><br /><strong>JavaScript (jQuery):</strong><br />$('#file').customFileInput();	<br /></code>

Note: be sure to use jQuery’s $(document).ready event to wait until the DOM is ready before running the script above.

Also, you can disable and enable the control by calling either $('#file').trigger('disable'); or $('#file').trigger('enable'); on the native input. Once disabled, the custom control will be styled to appear disabled as well. If the input is disabled at load, the custom control will naturally inherit that state, so you won’t need to call the “disable” method when you first create the control.

That’s all there is to it!

If you’d like to learn more, we explain in detail how this widget works under the covers and how to apply these principles in different interactions or more complex scenarios in our book, Designing with Progressive Enhancement.

Where can I download it?

If you’ve already purchased Designing with Progressive Enhancement, you can download all twelve widgets by following the instructions at the code examples download page.

For this widget and all others that have been released publicly as open source, download the zip.

If you’re a developer who wants to file a bug or contribute to extended features for any of the publicly-released DWPE widget scripts, we welcome your input. To learn more, check out the project’s Google Code repository: http://code.google.com/p/dwpe/.

 

Alıntıdır

ajax, jquery, Tips and Tricks

Reading CSV (Comma-separated values) Files

9 Oca

Posted in Develop

Leave a Comment

You can read CSV files like simple text files.

Sample Code :

if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string filename = fileDialog.FileName;
char[] delimiter = new char[] { ‘,’ };
txtDosyaAdi.Text = fileDialog.FileName;
int lineCount = 0;
using (StreamReader file = new StreamReader(filename))
{
string line;

data = new DataTable();
DataColumn cl = new DataColumn(MessageEntityClasses.DataGridColumns.From);
data.Columns.Add(cl);
cl = new DataColumn(MessageEntityClasses.DataGridColumns.To);
data.Columns.Add(cl);
cl = new DataColumn(MessageEntityClasses.DataGridColumns.Date);
data.Columns.Add(cl);
cl = new DataColumn(MessageEntityClasses.DataGridColumns.Content);
data.Columns.Add(cl);

while ((line = file.ReadLine()) != null)
{
lineCount++;
if (line.Trim().Length > 0)
{
string[] columns = line.Split(delimiter, StringSplitOptions.None);

DataRow row = data.NewRow();
row[MessageEntityClasses.DataGridColumns.From] = columns[2].Replace(“\”", “”);
row[MessageEntityClasses.DataGridColumns.To] = columns[3].Replace(“\”", “”);
row[MessageEntityClasses.DataGridColumns.Date] = columns[5].Replace(“\”", “”);
row[MessageEntityClasses.DataGridColumns.Content] = columns[7].Replace(“\”", “”);
data.Rows.Add(row);

}
}
}

if (data.Rows.Count > 0)
{
lbTotal.Text = lineCount.ToString();
grdMesajlar.DataSource = data;
}

}

if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string filename = fileDialog.FileName;
char[] delimiter = new char[] { ‘,’ };
txtDosyaAdi.Text = fileDialog.FileName;
int lineCount = 0;
using (StreamReader file = new StreamReader(filename))
{
string line;

data = new DataTable();
DataColumn cl = new DataColumn(MessageEntityClasses.DataGridColumns.From);
data.Columns.Add(cl);
cl = new DataColumn(MessageEntityClasses.DataGridColumns.To);
data.Columns.Add(cl);
cl = new DataColumn(MessageEntityClasses.DataGridColumns.Date);
data.Columns.Add(cl);
cl = new DataColumn(MessageEntityClasses.DataGridColumns.Content);
data.Columns.Add(cl);

while ((line = file.ReadLine()) != null)
{
lineCount++;
if (line.Trim().Length > 0)
{
string[] columns = line.Split(delimiter, StringSplitOptions.None);

DataRow row = data.NewRow();
row[MessageEntityClasses.DataGridColumns.From] = columns[2].Replace(“\”", “”);
row[MessageEntityClasses.DataGridColumns.To] = columns[3].Replace(“\”", “”);
row[MessageEntityClasses.DataGridColumns.Date] = columns[5].Replace(“\”", “”);
row[MessageEntityClasses.DataGridColumns.Content] = columns[7].Replace(“\”", “”);
data.Rows.Add(row);

}
}
}

.net, c#, csv, ipucu, Tips and Tricks, Visual Studio

Windows Servisleri Oluşturma

9 Oca

Posted in Develop

Leave a Comment

Windows servisleri oluşturma C++ programcılarına sunulmuş bir olanaktı.Vb altında bazı 3. parti çözümler kullanılarak da bu işlem gerçekleştirilebiliyordu. Artık Windows servisleri oluşturmak için gerekli herşey .NET Frameworkun  kütüphanesinde System.serviceProcess isim uzayında.Bunun doğal sonucu olarak  .NET altında istediğiniz herhangi bir dilde Windows servisleri geliştirebilirsiniz. Tabiki bu konuyu işlerken benim seçimin Vb olacak.

Windows servisleri kullanıcı müdahelesi gerekmeden, sistem açılışında otomatik olarak çalışabilen uygulamalardır. Windows NT,2000, XP ve sonraki işletim sistemlerinde çalıştırılabilirler.

Bu uygulamamda dosya değişikliklerini takip eden , EventLogta log tutan ve belirlediğimiz klasördeki dosya değişikliklerini belirten  e-mail gönderen bir servis oluşturacağım. Bu tarz bir uygulama yedeklerin alınıp alınmadığını kontrol etmede, ya da örneğin ağ üzerinden teslim edilen dosyaların vaktinde ulaştırılıp ulaştırılmadığını tespit etmek için kullanılabilir.

Windows servisi oluşturmak için yapmamız gereken ilk iş şablonumuzu belirlemek olacak. Bunun için Vs içinden File | New | Projecti seçin. Soldan proje tipini Vb Projesi, sağdan şablon olarak Windows servisini seçin. Proje için şablon oluşturulduktan sonra Solution Explorerda service1.vb dosyasına çift tıklayın ve Properties penceresinden serviceName özelliklerini “VbTestservice” olarak belirleyin. 

service1.vbnin kodlarını inceleyelim;

Imports System.serviceProcess

Projemizin System.serviceProcess isimuzayını kullandığına dikkat edin. Bu isim uzayı windows servislerini kurmada ve çalıştırmada gerekli olan metotları sağlar.

Inherits System.serviceProcess.serviceBase

service1 sınıfı ise serviceBase sınıfından türetiliyor. Bu sınıfı kullarak  servis başladığında, durdurulduğunda, ya da sistem kapatılmak üzere olduğundan bu durumları yakalayıp istediğimiz kodları çalıştırmamıza olanak sağlar.

E-mail kullarak uyarı gönderme:
Servisimizin dosya değişikliklerini istenilen yere ulaştırmada kullanacağı yöntem email göndermek olacak. Hemen hemen herkesin bilgisayarında değişik email servisleri kuruludur ve bu da bize uyarı ve olayları aktarabilmek için gerekli iletişim yapısını sunar. Projemizde bunu gerçekleştirebilmek için .NET Framework kütüphanesindeki MailMessage, MailAttachment ve SmtpMail sınıflarının nesnelerini kullanacağız.

MailMessage sınıfı email oluşturmak için kullanılır.Bu sınıf emaili kime göndereceğimizi, konuyu, emailin önceliğini, ve mesajla birlikte göndereceğimiz eklentileri belirlememizi sağlar.

MailAttachment sınıfı mesajımızla gönderilecek eklentilerin listesini sunar.

SmtpMail sınıfı mesajı gönderecek asıl mekanizmadır. Bu sınıf email göndermek için MailMessage nesnesini parametre olarak alan Send metodunu kullanır.

.NETte email servislerini kullanmak için SMTP (Simple Mail Transfer Protocol) servisinin kurulu olması gerekir. Smtp internette mail göndermek için en yaygın kullanılan protokoldür.Uygulamamızda sisteminizde geçerli bir SMTP servisi kurulu olduğunu varsayacağız.

Geliştireceğimiz servis, email göndermek için System.Web.Mail isim uzayını kullanacak. Bu yüzden projemize, System.Web.dll dosyasına referans ekleyin. Bundan sonra aşağıdaki import deyimini service1 sınıfına ekleyin;

Imports System.Web.Mail

SendMail Yordamını oluşturma:
İlk olarak SendMail isimli, kullanıcıya mail atacak  bir yordam oluşturacağız. service1.vb deki Component Designer generated code bölümünden sonra şu kodları ekleyin:

Private Sub SendMail(ByVal Subject As String, _
ByVal SendTo As String, _
ByVal Message As String, _
Optional ByVal FileName As String = “”)

Dim Mail As New MailMessage
eğer belirtilmişse dosyayı ekle
If FileName <> “” Then
Mail.Attachments.Add(New MailAttachment(FileName))
End If

With Mail
.From = desktek@isimsiz.com
.To = SendTo
.Subject = Subject
.Body = Message
.Priority = MailPriority.High

End With  
SmtpMail.Send(Mail)
End Sub

Bu kodlar sayesinde email nesnemizi oluşturduk , gerekli düzenlemeyi yaptık ve smtpmail.send metoduyla gönderilirken kullanılacak metodu belirledik.

OnStart ve OnStop olaylarının kodlanması:
Servisimiz başladığında (OnStart) ve durduğunda (OnStop) servisin ne zaman başlatılıp ne zaman durdurulduğunu öğrenmek için yöneticiye email göndereceğiz.Bunun için aşağıdaki kodları ekleyin.

Protected Overrides Sub OnStart(ByVal args() As String)
SendMail(“VbTestServisi – Başladı”, “admin@isimsiz.com”, _
“Vb servisi başlıyor.”)
End Sub

Protected Overrides Sub OnStop()
SendMail(“VbTestServisi – Durdu”, “admin@isimsiz.com”, _
“Vb servisi durduruluyor.”)
End Sub

AutoLog Özelliği:
serviceBase sınıfı varsayılan olarak servis hakkında bazı bilgileri (ne zaman başlatıldığını , ne zaman durdurulduğunu, hata oluşursa oluşma zamanı vs…) EventViewera yazar. Bunu servisimizin Autolog özelliğinden değiştirebiliriz. Yine servis özelliklerinden, servisin duraklatılabilirliği, sonladırılabilirliği, kapatılabilirliği gibi değerler true ya da  false olarak belirlenebilir.

Dosya Monitörünü Oluşturma:
Performans açısından düşündüğümüzde yan işlemlerimizi ve ana programımızı ayrı thread lerde (thread i iş parçacığı olarak kullanmak anlam karmaşasına sebep olabilir diye terimi olduğu gibi kullanacağım.) yapmalıyız. Böylelikle ana programımız başka işlemler de yapsa, işletim sisteminden gelen uyarılara cevap verebilecektir. Bu mantığı projemize, kendi thread lerini oluşturan bileşenler kullanarak uygulayabiliriz. Timer ve FileSystemWatcher buna iyi birer örnek oluşturuyorlar. Örneğin timer nesnesi elapsed olayını gerçekleştirdiğinde aynı zamanda yeni bir thread de oluşturur ve bu elapsed olayının içine yerleştirilen kodlar, bu farklı thread içinden çalıştırılır.

Kısa bir açıklama olarak; programı threadlere bölerek daha verimli iş yapabiliriz. Bu marketlerdeki turnikelere benzetilebilir. Ne kadar çok turnike koyarsanız markette o kadar verimli iş yaparsınız.(sadece teoride :) Her thread bir turnike gibi düşünülebilir.

FileSystemWatcher Bileşeni:
FileSystemWathcer dosyalar üzerindeki değişiklikleri algılamak üzere kullanılabilecek bir bileşendir. Belirtilen dosya(lar) üzerinde değişiklik algılandığında ilgili olaylar gerçekleştirilecektir.

Biraz önce belirttiğimiz; gibi bu bileşen de created,changed,deleted veya renamed olaylarını gerçekleştirirken kendi thread lerini oluşturur.

Toolboxın Components bölmesinden FileSystemWatcher bileşenini servisimize ekleyin.Bileşenin bazı özelliklerini inceleyelim:

EnableRaisingEvents: Bileşenin dosya üzerindeki değişikliklere bağlı olarak olayları karşılayacak kodları çağırıp çağırmayacağını belirler. Biz söyleyene kadar herhangi bir olay oluşmasını istemediğimizden bu özelliği False olarak belirleyin. Bu özelliği servisin OnStart olayında True olarak ayarlayacağız.

Path:Bileşenin gözlemyeceği yolu belirtir.Bir projemizde c:\temp klasörünü inceleyeceğiz. c:\temp klasörünü oluşturduktan sonra bu özelliği c:\temp olarak belirleyin.

NotifyFilter:Bileşenin hangi olayları inceleyeceğini belirleyen özelliktir. Projemizde sadece dosyanın son güncellenme tarihinin değiştirilme olayını (dosya kopyalandığında ya da oluşturulduğunda oluşur)inceleyeceğimizden özelliği LastWrite olarak ayarlayın.

Filter:Hangi tür dosyaların inceleneceğini belirler. Projemizde *.txt olarak ayarlayalım.

Bu ayarlamalardan sonra servisimizin OnStart ve OnStop olaylarıını aşağıdaki kodlarla biraz değiştirelim;

OnStart kısmına:

SendMail(“VbTestServisi - Başladı”, “admin@isimsiz.com”, _
“Vb servisi başlıyor.” & AppDomain.GetCurrentThreadId)
FileSystemWatcher1.EnableRaisingEvents = True

OnStop kısmına:

FileSystemWatcher1.EnableRaisingEvents = False
SendMail(“VbTestServisi - Durdu”, “admin@isimsiz.com”, _
“Vb servisi durduruluyor.”)

OnStart olayına iki eklenti yaptık. Biriyle thread ler hakkında söylediklerimizi uygulayarak görmek için app.domain.getcurrentThreadId ile geçerli thread in id sini de maile ekledik. Diğeriyle FileSystemWatcher bileşenin gözlemlemeye başlamasını sağladık.

Aynı şekilde OnStop olayında da bu bileşenin gözlemlemeyi bırakmasını sağladık.Bu sayede bileşenin oluşturduğu thread i de sonlandırmış olduk.

Created Olayı:
Bu adımda FileSystemWatcher bileşenimizin Created olayına bazı kodlar yazacağız. Bu olay incelediğimiz klasöre bir dosya yerleştirildiğinde ya da klasörde dosya oluşturulduğunda tetiklenir. Bu olaya kod yazmak için kod penceresindeyken soldaki listeden FileSystemWatcher1i, sağdan Created olayını seçerek şablonu oluşturun. Bu kısımda StreamReader nesnesini kullanacağımızdan şu import deyimini diğer import deyimlerinin altına ekleyin:

Imports System.IO

Sonra az önce oluşturduğumuz Created olay şablonun Sub… End sub arasına şu kodları yazın:

Dim streamFile As StreamReader
Dim lineData As String
Dim someData As String
Dim linesRead As Integer

Try
streamFile = New StreamReader(e.FullPath)
While linesRead < 5
linesRead += 1
lineData = streamFile.ReadLine
If lineData Is Nothing Then linesRead = 5
someData = someData & lineData
End While
streamReaderı kullanarak dosyadan 5 satır okuyoruz.
Catch eof As IO.EndOfStreamException
Catch eIOExcep As IO.IOException
SendMail(“VbTest service – Dosya okuma hatası”, _
“admin@isimsiz.com”, _
“Dosya: ” & e.FullPath & _
” Hata:” & eIOExcep.Message)
Hata oluşursa oluşan hatayı mail olarak gönderiyoruz.
Finally
streamFile.Close()
End Try
SendMail(“VbTestservice – Dosya mevcut”, _
“admin@isimsiz.com”, _
“Bulunan dosya: ” & e.FullPath & _
“, Thread Id: ” & AppDomain.GetCurrentThreadId & _
Chr(13) & Chr(13) & someData, e.FullPath)
burada elde ettiğimiz satırları mail olarak gönderiyoruz

 

Böylelikle servisimizi tamamlamış olduk. Fakat işimiz henüz bitmedi. Geliştirdiğimiz bu servisi kurmalıyız.

Servis Kurma:
Servisler komut satırından ya da ide içinden çalıştırılamazlar. Tabir yerindeyse Windowsa gömülmelidirler. Bir servisi kurmak için bir install programı ya da bir komut satırı aracı olan InstallUtil.exe yi kullanabiliriz.

Kurulumu gerçekleştirebilmek için projemizin içinde bir Installer sınıfı oluşturmalıyız. Bu sınıf servis kurmak için gerekli işlemleri yapmamızı sağlayacaktır.

service1in dizayn bölümünde sağ tuşa basın ve Add Installerı seçin.

ProjectInstaller isimli yeni bir sınıf projeye eklenecektir. Bu sınıfa iki bileşen eklenmiş olacaktır.Bunlar serviceProcessInstaller1 ve serviceInstaller1. Bu bileşenler servisin adını belirlemede, servisin çalıştırılabileceği hesapları belirlemede ve servisin nasıl başlayacağını belirlemede kullanılır.

serviceProcessInstaller1in Account özelliğini LocalSystem olarak değiştirin.Böylelikle servisin işletim sistemi başladığında kullanıcının sisteme girmesinden bağımsız olarak çalışması sağlanır.

serviceInstaller1in serviceName özelliğini VbTestservice olarak belirleyin. Yine bu bileşenin StartType özelliğinin Manual olduğundan emin olun.Böylelikle servis biz başlatana kadar durgun halde bekleyecekir.

Artık projemizi build edebiliriz.(Control+Shift+B)

Bu ayarları da yaptıktan sonra artık servisimizi sisteme kurabiliriz. Bunun için Visual Studio .NET Command Prompttan servisimizin olduğu projenin bin klasöründe

installutil Windowsservice1.exe yazmanız yeterli.
-Servisi kaldırmak için ise yine aynı yerde installutil Windowsservice1.exe /u komutunu vermeniz yeterli.

Yapmamız gereken son bir işlem kaldı: servisimizi başlatmak. Bunun için Denetim Masası | Yönetimsel Araçlar | Servisler den oluşturduğumuz servisin üstüne sağ tıklayın ve açılan menüden başlat komutunu verin. Hepsi bu kadar. Artık servisimiz çalışıyor..

Böylelikle baştan sona bir windows servisinin nasıl oluşturulduğunu irdelemiş olduk. Gerisi hayal sizin gücünüze kalmış…

 

Alıntıdır

.net, vb.net, Visual Studio

Usage of Xpath in jQuery

9 Oca

Posted in Develop

Leave a Comment

Introduction

XML is a well-supported Internet standard for encoding structured data in a way that can be easily decoded by practically any programming language and even read or written by humans using standard text editors. Many applications, especially modern standards-compliant Web browsers, can deal directly with XML data.

XPath (the XML Path Language) is a powerful query language for selecting nodes in an XML document. Version 1.0 of the XPath standard is widely implemented in a wide range of languages such as Java™, C#, and JavaScript.

jQuery is a de-facto standard cross-browser JavaScript library for selecting and manipulating nodes in an XHTML document (and in XML documents loaded through Ajax). It has been adopted by a large number of prominent companies including Google, IBM®, Microsoft®, and Twitter. It’s current version 1.4 was released as I was writing this article; so I upgraded immediately to take advantage of the promised more speed. Note that the jQuery examples in the article should work unmodified with jQuery 1.3.2, the previous version.

 

Frequently used acronyms

  • Ajax: Asynchronous JavaScript + XML
  • API: Application Programming Interface
  • DOM: Document Object Model
  • W3C: World Wide Web Consortium
  • XHTML: Extensible Hypertext Markup Language
  • XML: Extensible Markup Language
  • XSLT: Extensible Stylesheet Language Transformations

Why use jQuery when XPath exists in JavaScript?

If XPath is a W3C standard, and implementations exist in JavaScript, why bother using jQuery instead?

XPath is a generalized XML standard, while jQuery is a lightweight library designed to deal with the intricacies of cross-browser compatibility so you don’t have to worry about which browser your users are running. It’s flexible enough to work within the browser’s DOM using standard JavaScript idioms, and it provides additional features that make Web application development much less painful, such as powerful Ajax and animation support.

You should, however, always use the right tool for the job at hand; knowing more about these two tools will definitely help you pick the right technology for your next project.

 

The example

Throughout this article, you’ll refer back to a handy sample XML document, which you can find here in Listing 1. This list of books includes various bits of information such as author, a couple of entirely fictional prices and the title.

Listing 1. A sample XML document (book.xml)

<?xml version="1.0" encoding="utf-8"?><catalog>    <book format="trade">        <name>Jennifer Government</name>        <author>Max Barry</author>        <price curr="CAD">15.00</price>        <price curr="USD">12.00</price>    </book><br /><br />    <book format="textbook">        <name>Unity Game Development Essentials</name>        <author>Will Goldstone</author>        <price curr="CAD">52.00</price>        <price curr="USD">45.00</price>    </book><br /><br />    <book format="textbook">        <name>UNIX Visual QuickPro</name>        <author>Chris Herborth</author>        <price curr="CAD">15.00</price>        <price curr="USD">10.00</price>    </book></catalog>

 

Note that I have no affiliation with the authors and/or publishers, except for the obvious one there. The prices are entirely made up and you should check your favorite book store for actual pricing.

 

 

XPath assumptions

For the XPath code in this article, you’re going to make these assumptions:

  • You’ve loaded the book.xml file (from Listing 1) into a format that your XPath implementation can use.
  • You’re starting your searches with an object representing the root of the document. That is, the object that has the <catalog> element as its child. You’ll call this root because it’s the root of the XML document hierarchy.

Because there are so many XPath implementations on so many different platforms, you’ll focus on the XPath statements themselves and use a pseudocode similar to JavaScript to show them in context; check the class library of your favorite development platform for information about loading XML documents and the specific XML node objects you have available.

 

 

jQuery assumptions

The jQuery code in this article makes these assumptions:

  • You’re using the latest (version 1.4.0) jQuery code (see Resources for a link).
  • You’ve loaded the book.xml file through the jQuery.get() or jQuery.post() method and have stored the resulting XML document in a variable named root (to be the same as your XPath examples).

Some sample code for doing this is in Listing 2.

Listing 2. Loading the XML sample with jQuery

<?xml version="1.0" encoding="utf-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"                "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8"/><title>Book Catalog</title><script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script><script type="text/javascript">// <![CDATA[var root = null;<br /><br />$(document).ready( function(){    $.get( "http://localhost/~chrish/books.xml",         function( data ) {            root = data;<br /><br />            $("p#status").text( "Loaded." );        } );} );// ]]></script></head><br /><br /><body><p id="status">Loading book.xml...</p></body></html>

 

In the $(document).ready() function, you use the jQuery get() method to load books.xml from the local Web server, store the resulting document object in the root variable, and set the text of the paragraph with the status ID to indicate that the XML is done loading. For more information about jQuery, check the list of related links in Resources at the end of the article.

 

Selecting nodes

The fundamental purpose of both XPath and jQuery is to select nodes from a document. Once you select a node (or a collection of nodes), you can find the data you’re looking for and manipulate the document when you need to.

XPath is designed to return exactly the nodes you’ve asked for; it’s generally very specific. jQuery, on the other hand, makes it very easy to operate on large collections of nodes, so sometimes you’ll have to be careful to narrow down the matches before you start to work through the nodes.

Selecting a node by name

When you search for a specific node, you often know its name, or the name of its parent element.

To find a specific element, you use its name as in Listing 3.

Listing 3. Selecting nodes by name

/* Find all <book> elements through XPath: */var result = root.find( "//book" );<br /><br />/* Find all <book> elements through jQuery: */var result = $(root).find( "book" );

 

The XPath statement to select all of the <book> elements (//book) uses two forward slashes (//) to specify that all matching nodes, starting from the current node (root in the example), are to be found. This is the default behavior of jQuery, so you don’t need to include anything else. In both cases, the result will be all three <book> elements from Listing 1.

You can often narrow the search results by specifying a path of elements; the results will be matching nodes from the end of the path (see Listing 4).

Listing 4. Selecting nodes by path—these don’t behave the same

/* Be more specific (XPath): */var result = root.find( "/catalog//book" );<br /><br />/* Be more specific (jQuery): */var result = $(root).find( "catalog book" );

 

Starting from the root element (/), this XPath statement will look for the first <catalog> element, and then return all of the <book> elements from that first <catalog>. The jQuery statement behaves a little differently; it will return all <book> elements from all <catalog> elements (see Listing 5). With the example book.xml file, the result is the same set of nodes, but what if you wanted to get all of the <author> elements from the <book> elements? You’d start the XPath expression with two forward slashes (//) like you did in Listing 3.

Listing 5. Pulling out embedded nodes by path—these examples behave the same

/* Get all authors from all books (XPath): */var result = root.find( "//book//author" );<br /><br />/* Get all authors from all books (jQuery): */var result = $(root).find( "book author" );

 

To make jQuery return the <book> elements from the first <catalog>, like the XPath sample in Listing 4, you have to instruct it to use the first <catalog> it finds (see Listing 6).

Listing 6. Matching the books in the first catalog—these examples behave the same

/* All books from the first catalog (XPath): */var result = root.find( "/catalog//book" );<br /><br />/* All books from the first catalog (jQuery): */var result = $(root).find( "catalog:first book" );

 

Finding the last occurrence of an element, such as the last list item in a bulleted list, or the last option in a selection list, is also a common operation. To properly append something to the end of the list, you’ll need to know the location of that end (see Listing 7).

Listing 7. Finding the last book in the catalog

/* The last book from the first catalog (XPath): */var result = root.find( "/catalog/book[last()]" );<br /><br />/* The last book from the first catalog (jQuery): */var result = $(root).find( "catalog:first book:last" );

 

In both cases, you get the last <book> element from the first <catalog> element, which is what you were looking for. In the XPath example, the last() function returns the index of the last matched element, which you use in square brackets.

 

Selecting any node

Sometimes you don’t know the name of the element you’re looking for, or you need to find an element that might be inside of several different elements. In both XPath and jQuery, you can use an asterisk (*) to match any element (see Listing 8).

Listing 8. The any element

/* Find all authors in all elements inside of <catalog> (XPath): */var result = root.find( "/catalog//*//author" );<br /><br />/* Find all authors in all elements inside of <catalog> (jQuery): */var result = $(root).find( "catalog:first * author" );

 

Note that I’ve used :first in the jQuery sample to make it work exactly like the XPath version.

 

Selecting a node by attribute

Similar elements often have unique attributes, such as the id attribute used in XHTML elements to give them a unique reference ID (see Listing 9). Sometimes you don’t care as much about the specific element as you do about it having an attribute with a specific value.

Listing 9. Find those pesky textbooks

/* Find all books that are textbooks (XPath): */var result = root.find( "//book[@format='textbook']" );<br /><br />/* Find all books that are textbooks (jQuery): */var result = $(root).find( "book[format='textbook']" );

 

Both examples will return all <book> elements that have a format attribute set to textbook (there are two in the book.xml file from Listing 1). XPath’s syntax uses an at sign (@ ) to match attributes (jQuery just encloses them in square brackets) and you need to include two forward slashes (//) to match all <book> elements, but the two queries are very similar and straightforward.

jQuery includes a couple of shortcuts for the two most commonly matched-against attributes (id and class) in XHTML. In XPath, you’ll have to write them out explicitly (see Listing 10).

Listing 10. Matching XHTML based on the id and class attributes

/* Find the "status" <p>, then the highlighted elements (XPath) */var result1 = xhtml_root.find( "//p[@id='status']" );var result2 = xhtml_root.find( "//*[@class='highlight']" );<br /><br />/* Find the "status" <p>, then the highlighted elements (jQuery) */var result1 = $( "p#status" );var result2 = $( ".highlight" );

 

Assuming that your XHTML document is valid (and it is, right?), the ID matching queries will only return one element, because IDs must be unique in a valid XML document.

If you’re a fan of Cascading Style Sheets (CSS), you might notice that the jQuery selectors are pretty much the same as CSS selectors. This is handy, because you only need to remember one standard for finding the elements you want through jQuery and for styling them with CSS.

Multiple selectors

Both XPath and jQuery let you combine more than one selector to retrieve every node that matches any of the queries (that is, you’ll get the union of the results). In XPath, you’ll combine statements with the vertical bar (|) character, while in jQuery you’ll use a comma (,) (see Listing 11).

Listing 11. Finding the results of multiple selectors

/* Find all book names and all authors (XPath) */var result = root.find("//name|//author" );<br /><br />/* Find all book names and all authors (jQuery) */var result = $(root).find( "name,author" );

 

In both cases, the result will be a list of all <name> and <author> elements from anywhere in the document. In Figure 1, see the XPath result using AquaPath (for more about AquaPath, a tool for Mac OS X Tiger, see Resources).

 

Figure 1. XPath result with highlighted name and author tags for all books in the book.xml file


Screen capture of XPath result with highlighted name and author tags for all books in the book.xml file

 

 

Traversing nodes

In addition to selecting nodes, you often need to traverse the structure of a document, either to find related data or to perform complex manipulations. XPath and jQuery have you covered when you need to get around in your documents.

Given what you’ve learned previously, you can use these traversal methods to help find ancestors (that is, elements that contain the current element) or descendants (elements contained by the current element).

For example, Listing 12 allows you to find the <catalog> that contains the last <book> you’ve already found.

Listing 12. What catalog lists the last book?

/* Find the catalog for the last book you know about (XPath) */var result = root.find( "//book[last()]/ancestor::catalog" );<br /><br />/* Find the catalog for the last book you know about (jQuery) */var result = $(root).find( "book:last" ).closest( "catalog" );

 

Figure 2 shows the result.

Figure 2. The catalog ancestor of the last book

Screen capture of highlighted catalog tag for the catalog ancestor of the last book in book.xml

One thing to note is that the jQuery closest() method works more like XPath’s ancestor-or-self; it will include the current node if it matches. In this case, it won’t, but it’s something to keep in mind if you can nest elements with the same name, or if you’re matching on attributes.

If you need to go the other way and find elements that might be deeply nested from the one you have, you can do that too (see Listing 13).

 

Listing 13. Find the prices listed in the catalog

/* Find the prices of everything in the catalog. (XPath) */var result = root.find( "//catalog/descendant::price" );<br /><br />/* Find the prices of everything in the catalog. (jQuery) */var result = $(root).find( "catalog price" );

 

Like ancestor in XPath, descendant has a descendant-or-self for those special cases where the selected node might match what you’re looking for (see Figure 3).

Figure 3. All the prices, selected

Screen capture with highlighted price tags for books listed in book.xml

 

 

Simulating advanced XPath features

XPath specifies a number of useful features that aren’t really necessary in jQuery; after all, jQuery is running in the browser where it can take full advantage of JavaScript, while XPath is often used in more restricted environments, such as XSLT processing.

Of course, that won’t stop you from implementing these features in JavaScript if you want to use them.

You can easily count the number of results from your query (see Listing 14).

Listing 14. How many nodes match the selector?

/* How many price entries do you have? (XPath) */var result = root.find( "count(//price)" );<br /><br />/* How many price entries do you have? (jQuery) */var result = $(root).find( "price" ).length;

 

Sometimes you only need to know if a node contains a string or not (see Listing 15).

Listing 15. Does the third <author> have Chris in it?

/* Does the third <author> have "Chris" in its contents? (XPath) */var result = root.find( "contains(//book[3]/author,'Chris')" );<br /><br />/* Does the third <author> have "Chris" in its contents? (jQuery) */var result = $(root).find( "book:eq(2) author:contains('Chris')" ).length > 0

 

A very important difference to note in Listing 15 is that XPath’s indexes start at 1, instead of starting with 0. In jQuery, you have to use :eq(2) to get the third result.

XPath also has a sum() function, which will take the contents of the matching nodes, convert them to numeric values, and return the sum of those values. You have to simulate this with a short function when using jQuery (see Listing 16).

Listing 16. Summing the contents of some nodes

/* Sum the Canadian prices (XPath) */var result = root.find( "sum(//price[@curr='CAD'])" );<br /><br />/* Sum the Canadian prices (jQuery) */function sum( root, selector ) {    var x = 0;    $(root).find( selector ).map( function() {        if( this.text ) {            // Internet Explorer-only            return x += ( this.text * 1 );        }<br /><br />        // Firefox and W3C-compliant browsers        return x += ( this.textContent * 1 );    } );    return x;}<br /><br />var result = sum( root, "price[curr='CAD']" );

 

The map() method in jQuery runs the specified function for each of the result nodes. Note that you have to do a little trickery to get at the contents of the result nodes, too. Be sure to test this sort of JavaScript on all of your favorite browsers.

You should now be well on your way to understanding when and how to use XPath 1.0 and jQuery 1.4 for similar tasks.

 

 

Summary

XPath and jQuery have powerful querying semantics for selecting nodes from well-formed XML documents, including XHTML pages. Although their syntax is different, using one or the other to select important or interesting nodes based on element names or attribute values from a document is relatively easy.

Both XPath and jQuery support straightforward traversal semantics for matching element nodes in relation to the currently matched element. In addition, because jQuery is running in a full JavaScript interpreter, you can simulate some advanced features from XPath with a little bit of coding.

 

Resources

Learn

  • Process XML in the browser using jQuery (Uche Ogbuji, developerWorks, December 2009): Find out how to process XML directly in the browser with jQuery.

     

  • The Java XPath API: Querying XML from Java programs (Elliotte Rusty Harold, developerWorks, August 2008): Learn about the Java XPath API.
  • Get started with XPath (Bertrand Portier, developerWorks, May 2004): Learn what XPath is, the syntax and semantics of the XPath language, how to use XPath location paths, how to use XPath expressions, how to use XPath functions, and how XPath relates to XSLT.
  • Locate specific sections of your XML documents with XPath, Part 1 (Brett McLaughlin, developerWorks, June 2008): In Part 1 of this tutorial, explore details of the XPath specification, which allows you to specify particular sections of an XML document using a directory-like syntax.
  • Locate specific sections of your XML documents with XPath, Part 2 (Brett McLaughlin, developerWorks, June 2008): Focus on using predicates and predicate matching in your XPaths in Part 2 of this tutorial.
  • Simplify your Ajax development with jQuery (Jesse Skinner, developerWorks, April 2007): Learn about the jQuery philosophy, discover its features and functions, perform some common Ajax tasks, and find out how to extend jQuery with plug-ins.
  • XML Path Language (XPath): Create expressions relating to portions of an XML document (developerWorks, February 2007): Find out more about XPath.
  • XPath tutorial from w3schools.com: Learn how to use XPath to find what you need in your XML documents.
  • jQuery Tutorials page: Cover the fundamentals of the jQuery library and more in-depth topics such as learning how to use jQuery in your XHTML pages in these tutorials.
  • The XML FAQ: Explore another excellent source of XML information, the XML FAQ edited by Peter Flynn.
  • XML DOM tutorial from W3schools.com: Find out what XML-based interfaces are available to the browser (and which browsers support them).
  • More articles by this author (Chris Herborth, developerWorks, March 2006-current): Read articles about XML and other technologies.
  • XML area on developerWorks: Get the resources you need to advance your skills in the XML arena.
  • IBM XML certification: Find out how you can become an IBM-Certified Developer in XML and related technologies.
  • XML technical library: See the developerWorks XML Zone for a wide range of technical articles and tips, tutorials, standards, and IBM Redbooks.
  • developerWorks technical events and webcasts: Stay current with technology in these sessions.
  • developerWorks on Twitter: Join today to follow developerworks’s tweets.
  • developerWorks podcasts: Listen to interesting interviews and discussions for software developers.

Get products and technologies

  • jQuery version 1.4.0: Download jQuery and speed up your Web development with a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions.

     

  • AquaPath: Try AquaPath, a free Cocoa-based developer tool for Mac OS X Tiger, to evaluate XPath 2.0 expressions against any XML document and view the result sequence in a dynamic, intuitive tree representation.
  • IBM product evaluation versions: Download or explore the online trials in the IBM SOA Sandbox and get your hands on application development tools and middleware products from DB2®, Lotus®, Rational®, Tivoli®, and WebSphere®.

 

 

ipucu, javascript, jquery, Tips and Tricks, xml, xpath
12345»...Last »
  • Öz geçmiş

    • Türkçe CV (doc)
    • Türkçe CV (pdf)
  • Fotoğraf Albümü

    • Something About Myself
    • Doğa Yürüyüşleri
    • Bozdağ
    • Mahmut Dağı
    • Kızlar Sivrisi
    • Eğridir Dedegöl
    • Spil Dağı
    • Çamiçi Karagöl
    • Ödemiş Zeytinlik
    • Sülüklü Göl
    • Balçova Halkapınar
    • Spil Dağı 16.01.2011
    • Bozdağ Gece Yürüyüşü 23.07.2011
  • Kartpostal Duvarı

    • All Collection
    • Send Post Cards
    • Received Post Cards
    • Son yorumlar
    • Popüler yazılar
    • Arşivler
    • Etiketler
    • Kategoriler
    • deneme (3)
    • Genel (11)
      • müzik (2)
      • Sinema (1)
    • Hasan Sabbah (1)
    • ipucu (3)
    • şiir (4)
    • Sıradan (3)
    • software (17)
      • Develop (12)
      • Developed Project (1)
      • ipucu (3)
      • jquery (6)
    • words (15)
      • can dündar (8)
      • şiir (3)
        • Ömer Hayyam (3)
    şiir .net ajax asp.net c# can dündar csv Developed Project ipucu javascript jquery müzik ms sql Rubai Sıradan sinema software Tips and Tricks vb.net Visual Studio words xml xpath
    • Mayıs 2011 (3)
    • Nisan 2011 (3)
    • Şubat 2011 (1)
    • Ocak 2011 (8)
    • Aralık 2010 (6)
    • Kasım 2010 (1)
    • Ekim 2010 (4)
    • Haziran 2010 (1)
    • Mayıs 2010 (4)
    • Nisan 2010 (3)
    • Mart 2010 (5)
    • Şubat 2010 (1)
    • Ocak 2010 (11)
    • Aralık 2009 (3)
    • Ölmeyi öğrendiğinde yaşamayı da öğrenmişsin demektir! (0)
    • AJAX Refresh Problem IE Not Refreshing (0)
    • Merhaba dünya! (0)
    • Yeniliğe Doğru (0)
    • vururken güneş (0)
    • T-SQL : Kayıt varsa güncelle, yoksa ekle durumu için iki farklı yöntem (0)
    • AutoComplete Combo Box (0)
    • Teşekkürler Dünya (0)
    • Öyle bir hayat yaşıyorumki (0)
    • Windows Servislerinin Debug Edilmesi (0)
  • Son twitter mesajlarım

    Loading tweets...
    Beni Twitter'da takip edin!
  • Kullanıcı girişi






    • Şifrenizi hatırlamıyor musunuz?
  • Bağlantılar

    • Cüneyt Yeşilkaya
    • Kökten Ulaş Birant
    • Özlem Bilgin
    • Sadri Gülnaroğlu
Mystique theme by digitalnature. Modified by Rajesh and Nidheeshdas | Powered by WordPress
RSS Beslemeleri XHTML 1.1 Üst