code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
Imports System
Imports System.Data
Imports System.Data.OleDb
Imports DTO
Imports BUS
Public Class frmLoaiVe
Dim vtclick As Integer
Private Sub frmLoaiVe_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cbxTuyenXe.DataSource = TuyenBus.LayDanhSachTuyen()
cbxTuyenXe.DisplayMember = "TenTuyen"
cbxTuyenXe.ValueMember = "MaTuyen"
dgvLoaiVe.DataSource = LoaiVeBus.LayDanhSachLoaiVe()
End Sub
Public Function LayLoaiVeTuTextboxs() As LoaiVeDto
Dim loaive As New LoaiVeDto
If txtMaLoaiVe.Text <> "" Then
loaive.MaLoai = txtMaLoaiVe.Text
End If
loaive.MaTuyen = cbxTuyenXe.SelectedValue
If txtGiaVe.Text <> "" Then
loaive.GiaVe = txtGiaVe.Text
End If
Return loaive
End Function
Public Function LayLoaiVe_DataGridView(ByVal vtdong As Integer) As LoaiVeDto
Dim loaive As New LoaiVeDto
Try
loaive.MaLoai = dgvLoaiVe.Rows(vtdong).Cells("MaLoaiVe").Value
loaive.MaTuyen = dgvLoaiVe.Rows(vtdong).Cells("MaTuyen").Value
loaive.GiaVe = dgvLoaiVe.Rows(vtdong).Cells("GiaVe").Value
Catch ex As Exception
End Try
Return loaive
End Function
Public Sub HienThiLenTextboxs(ByVal loaive As LoaiVeDto)
txtGiaVe.Text = loaive.GiaVe
txtMaLoaiVe.Text = loaive.MaLoai
cbxTuyenXe.SelectedValue = loaive.MaTuyen
End Sub
Public Sub ResetTextboxs()
txtMaLoaiVe.Text = ""
txtGiaVe.Text = ""
End Sub
Private Sub btnThemLoaiVe_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThemLoaiVe.Click
cbxTuyenXe.Enabled = True
ResetTextboxs()
btnCapNhapThem.Visible = True
btnThemLoaiVe.Visible = False
btnHuy.Enabled = True
btnCapNhatLoaiVe.Enabled = False
btnXoaLoaiVe.Enabled = False
End Sub
Private Sub btnHuy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHuy.Click
cbxTuyenXe.Enabled = False
btnThemLoaiVe.Visible = True
btnCapNhapThem.Visible = True
btnHuy.Enabled = False
btnCapNhatLoaiVe.Enabled = True
btnXoaLoaiVe.Enabled = True
End Sub
Private Sub btnCapNhapThem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCapNhapThem.Click
Dim kq As Integer = LoaiVeBus.ThemLoaiVe(Me.LayLoaiVeTuTextboxs())
If (kq = 0) Then
MessageBox.Show("Mã loại vé đã có trong dữ liệu!!!", "THÔNG BÁO")
Else
dgvLoaiVe.DataSource = LoaiVeBus.LayDanhSachLoaiVe()
dgvLoaiVe.Rows(0).Selected = False
dgvLoaiVe.Rows(dgvLoaiVe.Rows.Count - 2).Selected = True
Dim loaive As LoaiVeDto = LayLoaiVe_DataGridView(dgvLoaiVe.Rows.Count - 2)
HienThiLenTextboxs(loaive)
End If
End Sub
Private Sub dgvLoaiVe_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles dgvLoaiVe.MouseClick
vtclick = dgvLoaiVe.CurrentRow.Index
Dim loaive As LoaiVeDto = LayLoaiVe_DataGridView(vtclick)
HienThiLenTextboxs(loaive)
End Sub
Private Sub btnXoaLoaiVe_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXoaLoaiVe.Click
If vtclick = dgvLoaiVe.Rows.Count - 1 Then
MessageBox.Show("Chọn dòng có dữ liệu cần xóa!!!", "THÔNG BÁO")
Exit Sub
End If
Dim maCanXoa As Integer = dgvLoaiVe.Rows(vtclick).Cells("MaLoaiVe").Value
LoaiVeBus.XoaLoaiVe(maCanXoa)
dgvLoaiVe.DataSource = LoaiVeBus.LayDanhSachLoaiVe()
Dim loaive As LoaiVeDto = LayLoaiVe_DataGridView(0)
HienThiLenTextboxs(loaive)
End Sub
Private Sub btnCapNhatLoaiVe_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCapNhatLoaiVe.Click
Dim loaive As LoaiVeDto = LayLoaiVeTuTextboxs()
LoaiVeBus.CapNhatLoaiVe(loaive)
dgvLoaiVe.DataSource = LoaiVeBus.LayDanhSachLoaiVe()
HienThiLenTextboxs(loaive)
End Sub
Private Sub btnThoat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThoat.Click
Close()
End Sub
End Class | 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/QuanLyXe/GiaoDien/frmLoaiVe.vb | Visual Basic .NET | gpl2 | 4,476 |
Public Class frmMain
Dim kqDangNhap As Boolean = False
Private Sub KT_DangNhap_DangXuat()
frmDangNhap.ShowDialog()
kqDangNhap = frmDangNhap.kqDangNhap
If kqDangNhap Then
mntChucNang.Enabled = True
mntQuanLy.Enabled = True
ttpDangNhap.Visible = False
ttpDangXuat.Visible = True
Else
'.....
End If
End Sub
Private Sub DangXuat()
mntChucNang.Enabled = False
mntQuanLy.Enabled = False
ttpDangNhap.Visible = True
ttpDangXuat.Visible = False
End Sub
Private Sub ttpDangNhap_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ttpDangNhap.Click
KT_DangNhap_DangXuat()
End Sub
Private Sub ttpDangXuat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ttpDangXuat.Click
DangXuat()
End Sub
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
KT_DangNhap_DangXuat()
End Sub
Private Sub XeToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles XeToolStripMenuItem.Click
frmQuanLyXE.MdiParent = Me
frmQuanLyXE.Show()
End Sub
Private Sub GánXeVàoTuyếnToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GánXeVàoTuyếnToolStripMenuItem.Click
frmGanXe.MdiParent = Me
frmGanXe.Show()
End Sub
Private Sub BánVeToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BánVeToolStripMenuItem.Click
frmBanVe.MdiParent = Me
frmBanVe.Show()
End Sub
Private Sub CậpNhậtGiáVéToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CậpNhậtGiáVéToolStripMenuItem.Click
frmLoaiVe.MdiParent = Me
frmLoaiVe.Show()
End Sub
Private Sub TuyếnXeToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TuyếnXeToolStripMenuItem.Click
frmTuyenXe.MdiParent = Me
frmTuyenXe.Show()
End Sub
Private Sub LịchGánToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LịchGánToolStripMenuItem.Click
frmQuanLyLichGan.MdiParent = Me
frmQuanLyLichGan.Show()
End Sub
Private Sub LặpLịchTuyếnToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
frmLapLich.MdiParent = Me
frmLapLich.Show()
End Sub
Private Sub ThoátToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ThoátToolStripMenuItem.Click
Close()
End Sub
Private Sub ThôngTinCáNhânToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ThôngTinCáNhânToolStripMenuItem1.Click
frmQuanLyNhanVien.MdiParent = Me
frmQuanLyNhanVien.Show()
End Sub
End Class | 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/QuanLyXe/GiaoDien/frmMain.vb | Visual Basic .NET | gpl2 | 3,144 |
Imports System.Data.OleDb
Imports BUS
Imports DTO
Public Class frmGanXe
Private Sub frmGanXe_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cbxTuyenXe.DataSource = TuyenBus.LayDanhSachTuyen()
cbxTuyenXe.DisplayMember = "TenTuyen"
cbxTuyenXe.ValueMember = "MaTuyen"
' cbxTuyenXe.Text = ""
'cbxNgayKhoiHanh.Text = ""
'cbxNgayKhoiHanh.ValueMember = "NgayKhoiHanh"
' cbxGioKhoiHanh.Text = ""
' cbxGioKhoiHanh.ValueMember = "ThoiDiemKhoiHanh"
End Sub
Private Sub cbxTuyenXe_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbxTuyenXe.SelectedIndexChanged, cbxTuyenXe.TextChanged
cbxNgayKhoiHanh.Text = ""
cbxTuyenXe.ValueMember = "MaTuyen"
Dim maTuyen As Long = cbxTuyenXe.SelectedValue
cbxNgayKhoiHanh.DataSource = XL_Chung.TimNgayKhoiHanh(maTuyen)
cbxNgayKhoiHanh.DisplayMember = "NgayKhoiHanh"
cbxVe.DataSource = LoaiVeBus.LayDanhSachLoaiVeTheoMaTuyen(maTuyen)
cbxVe.DisplayMember = "GiaVe"
cbxVe.ValueMember = "MaLoaiVe"
End Sub
Private Sub cbxNgayKhoiHanh_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbxNgayKhoiHanh.SelectedIndexChanged, cbxNgayKhoiHanh.TextChanged
cbxGioKhoiHanh.Text = ""
cbxTuyenXe.ValueMember = "MaTuyen"
cbxNgayKhoiHanh.ValueMember = "NgayKhoiHanh"
Dim maTuyen As Long = cbxTuyenXe.SelectedValue
Dim ngayKH As Date = cbxNgayKhoiHanh.SelectedValue
cbxGioKhoiHanh.DataSource = XL_Chung.TimThoiDiemKhoiHanh(maTuyen, ngayKH)
cbxGioKhoiHanh.DisplayMember = "ThoiDiemKhoiHanh"
End Sub
Private Sub HienThiDanhSachXeRanh()
cbxNgayKhoiHanh.ValueMember = "NgayKhoiHanh"
Dim NgayKhoiHanh As Date = cbxNgayKhoiHanh.SelectedValue
cbxGioKhoiHanh.ValueMember = "ThoiDiemKhoiHanh"
Dim ThoiDiemKhoiHanh As String = cbxGioKhoiHanh.SelectedValue
dgvDanhSachXeRanh.DataSource = LichGanBus.DanhSachXeDangRanh(NgayKhoiHanh, ThoiDiemKhoiHanh)
End Sub
Private Sub cbxGioKhoiHanh_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbxGioKhoiHanh.SelectedIndexChanged
If cbxGioKhoiHanh.Text <> "" Then
HienThiDanhSachXeRanh()
End If
End Sub
Private Sub btnGanXe_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGanXe.Click
Dim lg As New LichGanDto
cbxTuyenXe.ValueMember = "MaTuyen"
lg.MaTuyen = cbxTuyenXe.SelectedValue
cbxNgayKhoiHanh.ValueMember = "NgayKhoiHanh"
lg.NgayKhoiHanh = cbxNgayKhoiHanh.SelectedValue
cbxGioKhoiHanh.ValueMember = "ThoiDiemKhoiHanh"
lg.ThoiDiemKhoiHanh = cbxGioKhoiHanh.SelectedValue
If cbxTuyenXe.SelectedValue Is Nothing Then
MessageBox.Show("Chọn tuyến!!!", "THÔNG BÁO")
Exit Sub
ElseIf cbxNgayKhoiHanh.SelectedValue Is Nothing Then
MessageBox.Show("Chọn ngày!!!", "THÔNG BÁO")
Exit Sub
ElseIf cbxGioKhoiHanh.SelectedValue Is Nothing Then
MessageBox.Show("Chọn giờ!!!", "THÔNG BÁO")
Exit Sub
End If
Dim vitri As Integer
Try
vitri = dgvDanhSachXeRanh.CurrentRow.Index
If vitri = dgvDanhSachXeRanh.Rows.Count - 1 Then
End If
lg.MaXe = dgvDanhSachXeRanh.Rows(vitri).Cells("MaXe").Value
Catch ex As Exception
MessageBox.Show("Chọn xe cần gán!!!", "THÔNG BÁO")
Exit Sub
End Try
Dim TinhTrangLap = False
If ckbThuHai.Checked = True Or ckbThuBa.Checked = True Or ckbThuTu.Checked = True _
Or ckbThuNam.Checked = True Or ckbThuSau.Checked = True _
Or ckbThuBay.Checked = True Or ckbChuNhat.Checked = True Then
TinhTrangLap = True
End If
'lg.MaNV = MaNhanVien ???
Dim kq As Integer = LichGanBus.ThemLichGan(lg)
If kq <> 0 Then
Dim maLichGanVuaThem As Long = LichGanBus.LayMaLichGanVuaThem()
If TinhTrangLap Then
'Thêm vào bảng lịch gán lặp
Dim lglap As New LichGanLapDto
lglap.MaLichGan = maLichGanVuaThem
lglap.ThuHai = ckbThuHai.Checked
lglap.ThuBa = ckbThuBa.Checked
lglap.ThuTu = ckbThuTu.Checked
lglap.ThuNam = ckbThuNam.Checked
lglap.ThuSau = ckbThuSau.Checked
lglap.ThuBay = ckbThuBay.Checked
lglap.ChuNhat = ckbChuNhat.Checked
LichGanLapBus.ThemMotLichGanLap(lglap)
End If
ckbThuHai.Checked = False
ckbThuBa.Checked = False
ckbThuTu.Checked = False
ckbThuNam.Checked = False
ckbThuSau.Checked = False
ckbThuBay.Checked = False
ckbChuNhat.Checked = False
'Tạo danh sách vé
Dim soChoNgoi As Integer = dgvDanhSachXeRanh.Rows(vitri).Cells("SoChoNgoi").Value
Dim ve As New VeDto
ve.MaLich = maLichGanVuaThem
ve.LoaiVe = cbxVe.SelectedValue
For i As Integer = 1 To soChoNgoi
ve.MaGhe = i
VeBus.ThemVe(ve)
Next
MessageBox.Show("Đã gán xe vào tuyến!!!", "THÔNG BÁO")
HienThiDanhSachXeRanh()
End If
End Sub
Private Sub btnDong_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDong.Click
Close()
End Sub
End Class | 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/QuanLyXe/GiaoDien/frmGanXe.vb | Visual Basic .NET | gpl2 | 5,927 |
Public Module KT_ThongTinNguoiDung
Dim Loi As String = ""
'Kiểm tra tên đăng nhập có hợp lệ ko
Public Function KT_TenDangNhap(ByVal ten As String) As String
If (ten.Length < 4) Or (ten.Length > 15) Then
Loi = "Tên đăng nhập phải từ 4 - 15 ký số"
Return Loi
Else
If KT_Chuoi(ten) = False Then
Loi = "Các ký tự phải là 0-9, a-z, A-Z"
Return Loi
Else
Dim so As Integer = Convert.ToInt32(ten(0))
If so >= 48 And so <= 57 Then
Loi = "Tên đăng nhập không được bắt đầu là số"
Return Loi
End If
End If
End If
Return Loi
End Function
Public Function KT_MatKhau(ByVal mk As String) As String
Loi = ""
If (mk.Length < 6) Or (mk.Length > 15) Then
Loi = "Mật khẩu phải từ 4 - 15 ký số"
Return Loi
ElseIf KT_Chuoi(mk) = False Then
Loi = "Các ký tự phải là 0-9, a-z, A-Z"
Return Loi
End If
Return Loi
End Function
'Kiểm tra 1 ký tự có nằm trong [0, 9], [a, z], [A, Z]
Public Function KT_KyTu(ByVal c As Char) As Boolean
Dim so As Integer = Convert.ToInt32(c)
Select Case so
Case 48 To 57 'c thuộc [0, 9]
Return True
Case 65 To 92 'c thuộc [A, Z]
Return True
Case 97 To 122 'c thuộc [a, z]
Return True
Case Else
Return False
End Select
'Return False
End Function
'Kiểm tra 1 chuỗi có hợp lệ ko
Public Function KT_Chuoi(ByVal s As String) As Boolean
For i As Integer = 0 To s.Length - 1
If KT_KyTu(s(i)) = False Then
Return False
End If
Next
Return True
End Function
End Module
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/QuanLyXe/GiaoDien/KT_ThongTinNguoiDung.vb | Visual Basic .NET | gpl2 | 2,075 |
Imports System.Data.OleDb
Imports BUS
Imports DTO
Public Class frmQuanLyXE
Dim dtXE As DataTable
'Dim adapterXE As OleDbDataAdapter
Dim vtClick As Integer = 0
Private Sub QuanLyXE_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Dim kt As String = XL_Chung.KiemTraKetNoi_CSDL_CoDuocKhong()
'If kt <> "" Then
' MessageBox.Show(kt)
'Else
dgvXe.DataSource = XeBus.LayDanhSachXe()
' Try
Dim xe As XeDto = LayXeTu_DataGridView(0)
HienThiThongTinXE(xe)
ResetTextboxs()
'Catch ex As Exception
' End Try
'End If
End Sub
''' <summary>
''' '
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Public Function KT_NhapLieu_Them() As String
Dim str As String = ""
If txtMaXe.Text <> "" AndAlso Not IsNumeric(txtMaXe.Text) Then
str = "Mã xe là số!!!"
txtMaXe.Focus()
ElseIf txtSoXe.Text = "" Then
str = "Số xe không được rỗng!!!"
txtSoXe.Focus()
ElseIf txtHieuXe.Text = "" Then
str = "Hiệu xe không được rỗng!!!"
txtHieuXe.Focus()
ElseIf txtDoiXe.Text = "" Or Not IsNumeric(txtDoiXe.Text) Then
str = "Đời xe không rỗng và phải là số!!!"
txtDoiXe.Focus()
ElseIf txtSoChoNgoi.Text = "" Or Not IsNumeric(txtSoChoNgoi.Text) Then
str = "Số chỗ ngồi không rỗng và phải là số!!!"
txtSoChoNgoi.Focus()
End If
Return str
End Function
Public Function LayXeTuTextboxs() As XeDto
Dim xe As New XeDto
If IsNumeric(txtMaXe.Text) Then
xe.MaXe = txtMaXe.Text
End If
xe.SoXe = txtSoXe.Text
xe.HieuXe = txtHieuXe.Text
If IsNumeric(txtDoiXe.Text) Then
xe.DoiXe = txtDoiXe.Text
End If
If IsNumeric(txtSoChoNgoi.Text) Then
xe.SoChoNgoi = txtSoChoNgoi.Text
End If
Return xe
End Function
Public Function LayXeTu_DataGridView(ByVal vtdong As Integer) As XeDto
Dim xe As New XeDto
Try
xe.MaXe = dgvXe.Rows(vtdong).Cells("MaXe").Value
xe.SoXe = dgvXe.Rows(vtdong).Cells("SoXe").Value
xe.HieuXe = dgvXe.Rows(vtdong).Cells("HieuXe").Value
xe.DoiXe = dgvXe.Rows(vtdong).Cells("DoiXe").Value
xe.SoChoNgoi = dgvXe.Rows(vtdong).Cells("SoChoNgoi").Value
Catch ex As Exception
End Try
Return xe
End Function
Public Sub HienThiThongTinXE(ByVal xe As XeDto)
txtMaXe.Text = xe.MaXe
txtSoXe.Text = xe.SoXe
txtHieuXe.Text = xe.HieuXe
txtDoiXe.Text = xe.DoiXe
txtSoChoNgoi.Text = xe.SoChoNgoi
End Sub
Public Sub ResetTextboxs()
txtMaXe.Text = ""
txtSoXe.Text = ""
txtHieuXe.Text = ""
txtDoiXe.Text = ""
txtSoChoNgoi.Text = ""
End Sub
Private Sub btnTimXe_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTimXe.Click
dgvXe.DataSource = XeBus.TimXe(Me.LayXeTuTextboxs())
End Sub
Private Sub btnThemXe_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThemXe.Click
ResetTextboxs()
btnThemXe.Visible = False
btnCapNhatThem.Visible = True
btnThemXe.Visible = False
btnHuy.Enabled = True
btnCapNhatXe.Enabled = False
btnXoaXe.Enabled = False
End Sub
Private Sub btnHuy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHuy.Click
btnThemXe.Visible = True
btnCapNhatThem.Visible = False
btnHuy.Enabled = False
btnCapNhatXe.Enabled = True
btnXoaXe.Enabled = True
dgvXe.DataSource = XeBus.LayDanhSachXe()
Try
Dim xe As XeDto = LayXeTu_DataGridView(0)
HienThiThongTinXE(xe)
Catch ex As Exception
End Try
End Sub
Private Sub btnCapNhatThem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCapNhatThem.Click
Dim ktNhapLieu As String = KT_NhapLieu_Them()
If (ktNhapLieu <> "") Then
MessageBox.Show(ktNhapLieu, "THÔNG BÁO")
Exit Sub
End If
Dim kq As Integer = XeBus.ThemXe(Me.LayXeTuTextboxs())
If (kq = 0) Then
MessageBox.Show("Số xe đã có trong dữ liệu!!!", "THÔNG BÁO")
Else
dgvXe.DataSource = XeBus.LayDanhSachXe()
dgvXe.Rows(0).Selected = False
dgvXe.Rows(dgvXe.Rows.Count - 2).Selected = True
Dim xe As XeDto = LayXeTu_DataGridView(dgvXe.Rows.Count - 2)
HienThiThongTinXE(xe)
End If
End Sub
Private Sub btnXoaXe_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXoaXe.Click
If vtClick = dgvXe.Rows.Count - 1 Then
MessageBox.Show("Chọn dòng có dữ liệu cần xóa!!!", "THÔNG BÁO")
Exit Sub
End If
Dim ma As Integer = dgvXe.Rows(vtClick).Cells("MaXE").Value
Dim kq As Integer = XeBus.XoaXe(ma)
dgvXe.DataSource = XeBus.LayDanhSachXe()
Dim xe As XeDto = LayXeTu_DataGridView(0)
HienThiThongTinXE(xe)
End Sub
Private Sub btnCapNhatXe_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCapNhatXe.Click
Dim ktNhapLieu As String = KT_NhapLieu_Them()
If (ktNhapLieu <> "") Then
MessageBox.Show(ktNhapLieu, "THÔNG BÁO")
Exit Sub
End If
Dim kq As Integer = XeBus.CapNhatXe(Me.LayXeTuTextboxs())
If (kq = 0) Then
MessageBox.Show("Dữ liệu không thay đổi!!!", "THÔNG BÁO")
Else
dgvXe.DataSource = XeBus.LayDanhSachXe()
dgvXe.Rows(0).Selected = False
dgvXe.Rows(vtClick).Selected = True
Dim xe As XeDto = LayXeTu_DataGridView(vtClick)
HienThiThongTinXE(xe)
End If
End Sub
Private Sub dgvXe_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles dgvXe.MouseClick
' Try
vtClick = dgvXe.CurrentRow.Index()
If vtClick = dgvXe.Rows.Count - 1 Then
ResetTextboxs()
Exit Sub
End If
Dim xe As XeDto = LayXeTu_DataGridView(vtClick)
HienThiThongTinXE(xe)
' Catch ex As Exception
' End Try
End Sub
Private Sub btnThoat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThoat.Click
Close()
End Sub
Private Sub Label5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label5.Click
End Sub
End Class
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/QuanLyXe/GiaoDien/frmQuanLyXE.vb | Visual Basic .NET | gpl2 | 7,116 |
Imports System
Imports System.Data
Imports System.Data.OleDb
Imports DTO
Imports BUS
Public Class frmQuanLyLichGan
Dim tbIndex As Integer = 0
Dim vitriClick As Integer
Private Sub frmQuanLyLichGan_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dgvLichLap.DataSource = LichGanLapBus.LayDanhSachXeDuocLap()
dgvLichGan.DataSource = LichGanBus.LayDanhSachLichGan()
End Sub
Public Sub HienThi()
Try
vitriClick = dgvLichLap.CurrentRow.Index
Dim maLichGan As Long
maLichGan = dgvLichLap.Rows(vitriClick).Cells("MaLichGan").Value
Dim dt As DataTable = LichGanLapBus.LayLichGanLap(maLichGan)
ckbThuHai.Checked = dt.Rows(0).Item("ThuHai")
ckbThuBa.Checked = dt.Rows(0).Item("ThuBa")
ckbThuTu.Checked = dt.Rows(0).Item("ThuTu")
ckbThuNam.Checked = dt.Rows(0).Item("ThuNam")
ckbThuSau.Checked = dt.Rows(0).Item("ThuSau")
ckbThuBay.Checked = dt.Rows(0).Item("ThuBay")
ckbChuNhat.Checked = dt.Rows(0).Item("ChuNhat")
Catch ex As Exception
ckbThuHai.Checked = False
ckbThuBa.Checked = False
ckbThuTu.Checked = False
ckbThuNam.Checked = False
ckbThuSau.Checked = False
ckbThuBay.Checked = False
ckbChuNhat.Checked = False
Exit Sub
End Try
End Sub
Private Sub dgvLichLap_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles dgvLichLap.MouseClick
HienThi()
End Sub
Private Sub btnCapNhatLichLap_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCapNhatLichLap.Click
Dim lglap As New LichGanLapDto
Dim flag As Boolean = False
lglap.MaLichGan = dgvLichLap.Rows(vitriClick).Cells("MaLichGan").Value
If ckbThuHai.Checked = True Or ckbThuBa.Checked = True Or ckbThuTu.Checked = True _
Or ckbThuNam.Checked = True Or ckbThuSau.Checked = True _
Or ckbThuBay.Checked = True Or ckbChuNhat.Checked = True Then
flag = True
End If
If flag = False Then
If (MessageBox.Show("Sẽ xóa lịch gán nếu không có lặp!", "THÔNG BÁO", MessageBoxButtons.OKCancel) = Windows.Forms.DialogResult.Cancel) Then
Exit Sub
End If
LichGanLapBus.XoaMotLichGanLap(lglap.MaLichGan)
End If
lglap.ThuHai = ckbThuHai.Checked
lglap.ThuBa = ckbThuBa.Checked
lglap.ThuTu = ckbThuTu.Checked
lglap.ThuNam = ckbThuNam.Checked
lglap.ThuSau = ckbThuSau.Checked
lglap.ThuBay = ckbThuBay.Checked
lglap.ChuNhat = ckbChuNhat.Checked
LichGanLapBus.CapNhatMotLichGanLap(lglap)
dgvLichLap.DataSource = LichGanLapBus.LayDanhSachXeDuocLap()
End Sub
Private Sub dgvLichLap_DataSourceChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dgvLichLap.DataSourceChanged
HienThi()
End Sub
Private Sub btnXoaLichLap_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXoaLichLap.Click
If (MessageBox.Show("Bạn thật sự muốn xóa!", "THÔNG BÁO", MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.No) Then
Exit Sub
End If
Dim MaLichGan As Long = dgvLichLap.Rows(vitriClick).Cells("MaLichGan").Value
LichGanLapBus.XoaMotLichGanLap(MaLichGan)
dgvLichLap.DataSource = LichGanLapBus.LayDanhSachXeDuocLap()
HienThi()
End Sub
Private Sub btnXoaLichGan_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXoaLichGan.Click
Try
Dim vt As Integer = dgvLichLap.CurrentRow.Index
Dim MaLichGan As Long = dgvLichGan.Rows(vt).Cells("MaLichGan").Value
LichGanBus.XoaMotLichGan(MaLichGan)
dgvLichGan.DataSource = LichGanBus.LayDanhSachLichGan()
'Xóa trong bảng lặp lặp
LichGanLapBus.XoaMotLichGanLap(MaLichGan)
dgvLichLap.DataSource = LichGanLapBus.LayDanhSachXeDuocLap()
HienThi()
Catch ex As Exception
End Try
End Sub
Private Sub tctrlHienThi_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tctrlHienThi.SelectedIndexChanged
End Sub
Private Sub btnThoat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThoat.Click
Close()
End Sub
End Class | 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/QuanLyXe/GiaoDien/frmQuanLyLichGan.vb | Visual Basic .NET | gpl2 | 4,778 |
<?xml version="1.0" encoding="utf-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl='urn:schemas-microsoft-com:xslt'>
<xsl:key name="ProjectKey" match="Event" use="@Project" />
<xsl:template match="Events" mode="createProjects">
<projects>
<xsl:for-each select="Event">
<!--xsl:sort select="@Project" order="descending"/-->
<xsl:if test="(1=position()) or (preceding-sibling::*[1]/@Project != @Project)">
<xsl:variable name="ProjectName" select="@Project"/>
<project>
<xsl:attribute name="name">
<xsl:value-of select="@Project"/>
</xsl:attribute>
<xsl:if test="@Project=''">
<xsl:attribute name="solution">
<xsl:value-of select="@Solution"/>
</xsl:attribute>
</xsl:if>
<xsl:for-each select="key('ProjectKey', $ProjectName)">
<!--xsl:sort select="@Source" /-->
<xsl:if test="(1=position()) or (preceding-sibling::*[1]/@Source != @Source)">
<source>
<xsl:attribute name="name">
<xsl:value-of select="@Source"/>
</xsl:attribute>
<xsl:variable name="Source">
<xsl:value-of select="@Source"/>
</xsl:variable>
<xsl:for-each select="key('ProjectKey', $ProjectName)[ @Source = $Source ]">
<event>
<xsl:attribute name="error-level">
<xsl:value-of select="@ErrorLevel"/>
</xsl:attribute>
<xsl:attribute name="description">
<xsl:value-of select="@Description"/>
</xsl:attribute>
</event>
</xsl:for-each>
</source>
</xsl:if>
</xsl:for-each>
</project>
</xsl:if>
</xsl:for-each>
</projects>
</xsl:template>
<xsl:template match="projects">
<xsl:for-each select="project">
<xsl:sort select="@Name" order="ascending"/>
<h2>
<xsl:if test="@solution"><a _locID="Solution">Solution</a>: <xsl:value-of select="@solution"/></xsl:if>
<xsl:if test="not(@solution)"><a _locID="Project">Project</a>: <xsl:value-of select="@name"/>
<xsl:for-each select="source">
<xsl:variable name="Hyperlink" select="@name"/>
<xsl:for-each select="event[@error-level='4']">
 <A class="note"><xsl:attribute name="HREF"><xsl:value-of select="$Hyperlink"/></xsl:attribute><xsl:value-of select="@description"/></A>
</xsl:for-each>
</xsl:for-each>
</xsl:if>
</h2>
<table cellpadding="2" cellspacing="0" width="98%" border="1" bordercolor="white" class="infotable">
<tr>
<td nowrap="1" class="header" _locID="Filename">Filename</td>
<td nowrap="1" class="header" _locID="Status">Status</td>
<td nowrap="1" class="header" _locID="Errors">Errors</td>
<td nowrap="1" class="header" _locID="Warnings">Warnings</td>
</tr>
<xsl:for-each select="source">
<xsl:sort select="@name" order="ascending"/>
<xsl:variable name="source-id" select="generate-id(.)"/>
<xsl:if test="count(event)!=count(event[@error-level='4'])">
<tr class="row">
<td class="content">
<A HREF="javascript:"><xsl:attribute name="onClick">javascript:document.images['<xsl:value-of select="$source-id"/>'].click()</xsl:attribute><IMG border="0" _locID="IMG.alt" _locAttrData="alt" alt="expand/collapse section" class="expandable" height="11" onclick="changepic()" src="_UpgradeReport_Files/UpgradeReport_Plus.gif" width="9" ><xsl:attribute name="name"><xsl:value-of select="$source-id"/></xsl:attribute><xsl:attribute name="child">src<xsl:value-of select="$source-id"/></xsl:attribute></IMG></A> <xsl:value-of select="@name"/>
</td>
<td class="content">
<xsl:if test="count(event[@error-level='3'])=1">
<xsl:for-each select="event[@error-level='3']">
<xsl:if test="@description='Converted'"><a _locID="Converted1">Converted</a></xsl:if>
<xsl:if test="@description!='Converted'"><xsl:value-of select="@description"/></xsl:if>
</xsl:for-each>
</xsl:if>
<xsl:if test="count(event[@error-level='3'])!=1 and count(event[@error-level='3' and @description='Converted'])!=0"><a _locID="Converted2">Converted</a>
</xsl:if>
</td>
<td class="content"><xsl:value-of select="count(event[@error-level='2'])"/></td>
<td class="content"><xsl:value-of select="count(event[@error-level='1'])"/></td>
</tr>
<tr class="collapsed" bgcolor="#ffffff">
<xsl:attribute name="id">src<xsl:value-of select="$source-id"/></xsl:attribute>
<td colspan="7">
<table width="97%" border="1" bordercolor="#dcdcdc" rules="cols" class="issuetable">
<tr>
<td colspan="7" class="issuetitle" _locID="ConversionIssues">Conversion Report - <xsl:value-of select="@name"/>:</td>
</tr>
<xsl:for-each select="event[@error-level!='3']">
<xsl:if test="@error-level!='4'">
<tr>
<td class="issuenone" style="border-bottom:solid 1 lightgray">
<xsl:value-of select="@description"/>
</td>
</tr>
</xsl:if>
</xsl:for-each>
</table>
</td>
</tr>
</xsl:if>
</xsl:for-each>
<tr valign="top">
<td class="foot">
<xsl:if test="count(source)!=1">
<xsl:value-of select="count(source)"/><a _locID="file1"> files</a>
</xsl:if>
<xsl:if test="count(source)=1">
<a _locID="file2">1 file</a>
</xsl:if>
</td>
<td class="foot">
<a _locID="Converted3">Converted</a>: <xsl:value-of select="count(source/event[@error-level='3' and @description='Converted'])"/><BR />
<a _locID="NotConverted">Not converted</a>: <xsl:value-of select="count(source) - count(source/event[@error-level='3' and @description='Converted'])"/>
</td>
<td class="foot"><xsl:value-of select="count(source/event[@error-level='2'])"/></td>
<td class="foot"><xsl:value-of select="count(source/event[@error-level='1'])"/></td>
</tr>
</table>
</xsl:for-each>
</xsl:template>
<xsl:template match="Property">
<xsl:if test="@Name!='Date' and @Name!='Time' and @Name!='LogNumber' and @Name!='Solution'">
<tr><td nowrap="1"><b><xsl:value-of select="@Name"/>: </b><xsl:value-of select="@Value"/></td></tr>
</xsl:if>
</xsl:template>
<xsl:template match="UpgradeLog">
<html>
<head>
<META HTTP-EQUIV="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="_UpgradeReport_Files\UpgradeReport.css" />
<title _locID="ConversionReport0">Conversion Report 
<xsl:if test="Properties/Property[@Name='LogNumber']">
<xsl:value-of select="Properties/Property[@Name='LogNumber']/@Value"/>
</xsl:if>
</title>
<script language="javascript">
function outliner () {
oMe = window.event.srcElement
//get child element
var child = document.all[event.srcElement.getAttribute("child",false)];
//if child element exists, expand or collapse it.
if (null != child)
child.className = child.className == "collapsed" ? "expanded" : "collapsed";
}
function changepic() {
uMe = window.event.srcElement;
var check = uMe.src.toLowerCase();
if (check.lastIndexOf("upgradereport_plus.gif") != -1)
{
uMe.src = "_UpgradeReport_Files/UpgradeReport_Minus.gif"
}
else
{
uMe.src = "_UpgradeReport_Files/UpgradeReport_Plus.gif"
}
}
</script>
</head>
<body topmargin="0" leftmargin="0" rightmargin="0" onclick="outliner();">
<h1 _locID="ConversionReport">Conversion Report - <xsl:value-of select="Properties/Property[@Name='Solution']/@Value"/></h1>
<p><span class="note">
<b _locID="TimeOfConversion">Time of Conversion:</b>  <xsl:value-of select="Properties/Property[@Name='Date']/@Value"/>  <xsl:value-of select="Properties/Property[@Name='Time']/@Value"/><br/>
</span></p>
<xsl:variable name="SortedEvents">
<Events>
<xsl:for-each select="Event">
<xsl:sort select="@Project" order="ascending"/>
<xsl:sort select="@Source" order="ascending"/>
<xsl:sort select="@ErrorLevel" order="ascending"/>
<Event>
<xsl:attribute name="Project"><xsl:value-of select="@Project"/> </xsl:attribute>
<xsl:attribute name="Solution"><xsl:value-of select="/UpgradeLog/Properties/Property[@Name='Solution']/@Value"/> </xsl:attribute>
<xsl:attribute name="Source"><xsl:value-of select="@Source"/> </xsl:attribute>
<xsl:attribute name="ErrorLevel"><xsl:value-of select="@ErrorLevel"/> </xsl:attribute>
<xsl:attribute name="Description"><xsl:value-of select="@Description"/> </xsl:attribute>
</Event>
</xsl:for-each>
</Events>
</xsl:variable>
<xsl:variable name="Projects">
<xsl:apply-templates select="msxsl:node-set($SortedEvents)/*" mode="createProjects"/>
</xsl:variable>
<xsl:apply-templates select="msxsl:node-set($Projects)/*"/>
<p></p><p>
<table class="note">
<tr>
<td nowrap="1">
<b _locID="ConversionSettings">Conversion Settings</b>
</td>
</tr>
<xsl:apply-templates select="Properties"/>
</table></p>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/QuanLyXe/_UpgradeReport_Files/UpgradeReport.xslt | XSLT | gpl2 | 12,579 |
BODY
{
BACKGROUND-COLOR: white;
FONT-FAMILY: "Verdana", sans-serif;
FONT-SIZE: 100%;
MARGIN-LEFT: 0px;
MARGIN-TOP: 0px
}
P
{
FONT-FAMILY: "Verdana", sans-serif;
FONT-SIZE: 70%;
LINE-HEIGHT: 12pt;
MARGIN-BOTTOM: 0px;
MARGIN-LEFT: 10px;
MARGIN-TOP: 10px
}
.note
{
BACKGROUND-COLOR: #ffffff;
COLOR: #336699;
FONT-FAMILY: "Verdana", sans-serif;
FONT-SIZE: 100%;
MARGIN-BOTTOM: 0px;
MARGIN-LEFT: 0px;
MARGIN-TOP: 0px;
PADDING-RIGHT: 10px
}
.infotable
{
BACKGROUND-COLOR: #f0f0e0;
BORDER-BOTTOM: #ffffff 0px solid;
BORDER-COLLAPSE: collapse;
BORDER-LEFT: #ffffff 0px solid;
BORDER-RIGHT: #ffffff 0px solid;
BORDER-TOP: #ffffff 0px solid;
FONT-SIZE: 70%;
MARGIN-LEFT: 10px
}
.issuetable
{
BACKGROUND-COLOR: #ffffe8;
BORDER-COLLAPSE: collapse;
COLOR: #000000;
FONT-SIZE: 100%;
MARGIN-BOTTOM: 10px;
MARGIN-LEFT: 13px;
MARGIN-TOP: 0px
}
.issuetitle
{
BACKGROUND-COLOR: #ffffff;
BORDER-BOTTOM: #dcdcdc 1px solid;
BORDER-TOP: #dcdcdc 1px;
COLOR: #003366;
FONT-WEIGHT: normal
}
.header
{
BACKGROUND-COLOR: #cecf9c;
BORDER-BOTTOM: #ffffff 1px solid;
BORDER-LEFT: #ffffff 1px solid;
BORDER-RIGHT: #ffffff 1px solid;
BORDER-TOP: #ffffff 1px solid;
COLOR: #000000;
FONT-WEIGHT: bold
}
.issuehdr
{
BACKGROUND-COLOR: #E0EBF5;
BORDER-BOTTOM: #dcdcdc 1px solid;
BORDER-TOP: #dcdcdc 1px solid;
COLOR: #000000;
FONT-WEIGHT: normal
}
.issuenone
{
BACKGROUND-COLOR: #ffffff;
BORDER-BOTTOM: 0px;
BORDER-LEFT: 0px;
BORDER-RIGHT: 0px;
BORDER-TOP: 0px;
COLOR: #000000;
FONT-WEIGHT: normal
}
.content
{
BACKGROUND-COLOR: #e7e7ce;
BORDER-BOTTOM: #ffffff 1px solid;
BORDER-LEFT: #ffffff 1px solid;
BORDER-RIGHT: #ffffff 1px solid;
BORDER-TOP: #ffffff 1px solid;
PADDING-LEFT: 3px
}
.issuecontent
{
BACKGROUND-COLOR: #ffffff;
BORDER-BOTTOM: #dcdcdc 1px solid;
BORDER-TOP: #dcdcdc 1px solid;
PADDING-LEFT: 3px
}
A:link
{
COLOR: #cc6633;
TEXT-DECORATION: underline
}
A:visited
{
COLOR: #cc6633;
}
A:active
{
COLOR: #cc6633;
}
A:hover
{
COLOR: #cc3300;
TEXT-DECORATION: underline
}
H1
{
BACKGROUND-COLOR: #003366;
BORDER-BOTTOM: #336699 6px solid;
COLOR: #ffffff;
FONT-SIZE: 130%;
FONT-WEIGHT: normal;
MARGIN: 0em 0em 0em -20px;
PADDING-BOTTOM: 8px;
PADDING-LEFT: 30px;
PADDING-TOP: 16px
}
H2
{
COLOR: #000000;
FONT-SIZE: 80%;
FONT-WEIGHT: bold;
MARGIN-BOTTOM: 3px;
MARGIN-LEFT: 10px;
MARGIN-TOP: 20px;
PADDING-LEFT: 0px
}
H3
{
COLOR: #000000;
FONT-SIZE: 80%;
FONT-WEIGHT: bold;
MARGIN-BOTTOM: -5px;
MARGIN-LEFT: 10px;
MARGIN-TOP: 20px
}
H4
{
COLOR: #000000;
FONT-SIZE: 70%;
FONT-WEIGHT: bold;
MARGIN-BOTTOM: 0px;
MARGIN-TOP: 15px;
PADDING-BOTTOM: 0px
}
UL
{
COLOR: #000000;
FONT-SIZE: 70%;
LIST-STYLE: square;
MARGIN-BOTTOM: 0pt;
MARGIN-TOP: 0pt
}
OL
{
COLOR: #000000;
FONT-SIZE: 70%;
LIST-STYLE: square;
MARGIN-BOTTOM: 0pt;
MARGIN-TOP: 0pt
}
LI
{
LIST-STYLE: square;
MARGIN-LEFT: 0px
}
.expandable
{
CURSOR: hand
}
.expanded
{
color: black
}
.collapsed
{
DISPLAY: none
}
.foot
{
BACKGROUND-COLOR: #ffffff;
BORDER-BOTTOM: #cecf9c 1px solid;
BORDER-TOP: #cecf9c 2px solid
}
.settings
{
MARGIN-LEFT: 25PX;
}
.help
{
TEXT-ALIGN: right;
margin-right: 10px;
}
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/QuanLyXe/_UpgradeReport_Files/UpgradeReport.css | CSS | gpl2 | 3,348 |
Imports System.Data
Imports System.Data.OleDb
Imports DTO
Public Class TuyenDao
Dim provider As New DataProvider
Public Function LayDanhSachTuyen() As DataTable
Dim sql As String = "SELECT * FROM TuyenXe"
Dim dtTUYENXE As DataTable
dtTUYENXE = provider.ThucThiCauTruyVan(sql)
Return dtTUYENXE
End Function
Public Function TimTuyen(ByVal tuyen As TuyenDto) As DataTable
Dim sql As String = "SELECT * FROM TuyenXe WHERE 1"
'If tuyen.MaTuyenXe <> 0 Then
' sql += " and MaTuyen =" & tuyen.MaTuyenXe & " "
'End If
If tuyen.TenTuyenXe <> "" Then
sql += " and TenTuyen = '" & tuyen.TenTuyenXe & "' "
End If
If tuyen.DiaDiemDi <> "" Then
sql += " and DiaDiemDi = '" & tuyen.DiaDiemDi & "' "
End If
If tuyen.DiaDiemDen <> "" Then
sql += " and DiaDiemDen = '" & tuyen.DiaDiemDen & "' "
End If
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function TimTuyenTheoMaTuyen(ByVal maTuyen As Integer) As DataTable
Dim sql As String = "SELECT * FROM TuyenXe WHERE MaTuyen = " & maTuyen
Dim dtTUYEN As DataTable
dtTUYEN = provider.ThucThiCauTruyVan(sql)
Return dtTUYEN
End Function
Public Function ThemTuyen(ByVal tuyen As TuyenDto) As Integer
Dim sql As String = "INSERT INTO TuyenXe(TenTuyen, DiaDiemDi, DiaDiemDen) VALUES (?, ? ,?)"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@TenTuyen", tuyen.TenTuyenXe))
dsParameter.Add(New OleDbParameter("@DiaDiemDi", tuyen.DiaDiemDi))
dsParameter.Add(New OleDbParameter("@DiaDiemDen", tuyen.DiaDiemDen))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function CapNhatTuyen(ByVal tuyen As TuyenDto) As Integer
Dim sql As String = "UPDATE TuyenXe SET TenTuyen = ?, DiaDiemDi = ?, DiaDiemDen = ? WHERE MaTuyen = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@TenTuyen", tuyen.TenTuyenXe))
dsParameter.Add(New OleDbParameter("@DiaDiemDi", tuyen.DiaDiemDi))
dsParameter.Add(New OleDbParameter("@DiaDiemDen", tuyen.DiaDiemDen))
dsParameter.Add(New OleDbParameter("@MaTuyenXe", tuyen.MaTuyenXe))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function XoaTuyen(ByVal maCanXoa As Long) As Integer
Dim sql As String = "DELETE FROM TuyenXe WHERE MaTuyen = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaTuyen", maCanXoa))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function CapNhatXuongCSDL(ByVal tenBang As String, ByVal dt As DataTable) As Integer
Return provider.CapNhatXuongCSDL(tenBang, dt)
End Function
End Class
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/QuanLyXe/DAO/TuyenDao.vb | Visual Basic .NET | gpl2 | 3,049 |
Imports System.Data
Imports System.Data.OleDb
Imports DTO
Public Class NhanVienDao
Dim provider As New DataProvider
Public Function LayNguoiDangNhap(ByVal tenDangNhap As String, ByVal matKhau As String) As Integer
Dim sql As String = "SELECT count(*) FROM NhanVien WHERE TenDangNhap = '" & tenDangNhap & "' AND MatKhau = '" & matKhau & "'"
Dim row As Integer = provider.ThucThiCauTruyVan(sql).Rows.Count
Try
If row > 0 Then
sql = "SELECT LoaiNhanVien FROM NhanVien Where TenDangNhap = '" & tenDangNhap & "' and MatKhau = '" & matKhau & "'"
Dim loaiND As Integer = provider.ThucThiCauTruyVan(sql).Rows(0).Item(0)
If loaiND = 1 Then
Return 1
Else
Return 0
End If
End If
Catch ex As Exception
Return -1
End Try
End Function
Public Function LayNguoiDung(ByVal tenDangNhap As String, ByVal matKhau As String) As DataTable
Dim sql As String = "SELECT MaNhanVien, LoaiNhanVien FROM NhanVien WHERE TenDangNhap = '" & tenDangNhap & "' AND MatKhau = '" & matKhau & "'"
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function LayNguoiDungTheoMa(ByVal maNhanVien As Long) As DataTable
Dim sql As String = "SELECT * FROM NhanVien WHERE MaNhanVien = " & maNhanVien
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function LayQuyen() As DataTable
Dim sql As String = "SELECT pc.MaNhanVien,nv.TenDangNhap,pc.MaQuyen FROM NhanVien nv,PhanQuyen pc"
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function LayNguoiDung() As DataTable
Dim sql As String = "SELECT * FROM Quyen"
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function LayDanhSachNguoiDung() As DataTable
Dim sql As String = "SELECT MaNhanVien,MatKhau,TenDangNhap,HoTen,NgaySinh,IIF(Phai=1,'Nữ','Nam') AS Phai,DiaChi,DienThoai,loaiNhanVien FROM NhanVien "
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function ThemNhanVien(ByVal nhanVien As NhanVienDto) As Integer
Dim sql As String = "insert into NhanVien (TenDangNhap,MatKhau,HoTen,NgaySinh,Phai,DiaChi,DienThoai,LoaiNhanVien) values (?,?,?,?,?,?,?,?)"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@TenDangNhap", nhanVien.TenDangNhap))
dsParameter.Add(New OleDbParameter("@MatKhau", nhanVien.MatKhau))
dsParameter.Add(New OleDbParameter("@HoTen", nhanVien.HoTen))
dsParameter.Add(New OleDbParameter("@NgaySinh", nhanVien.NgaySinh))
dsParameter.Add(New OleDbParameter("@Phai", nhanVien.GioiTinh))
dsParameter.Add(New OleDbParameter("@DiaChi", nhanVien.DiaChi))
dsParameter.Add(New OleDbParameter("@DienThoai", nhanVien.DienThoai))
dsParameter.Add(New OleDbParameter("@LoaiNhanVien", nhanVien.LoaiNhanVien))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function CapNhatNhanVien(ByVal nhanVien As NhanVienDto) As Integer
Dim sql As String = "UPDATE NhanVien SET TenDangNhap = ?, MatKhau = ?, HoTen = ?, NgaySinh = ?, Phai = ?, DiaChi = ?,DienThoai = ?, LoaiNhanVien = ? WHERE MaNhanVien = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@TenDangNhap", nhanVien.TenDangNhap))
dsParameter.Add(New OleDbParameter("@MatKhau", nhanVien.MatKhau))
dsParameter.Add(New OleDbParameter("@HoTen", nhanVien.HoTen))
dsParameter.Add(New OleDbParameter("@NgaySinh", nhanVien.NgaySinh))
dsParameter.Add(New OleDbParameter("@Phai", nhanVien.GioiTinh))
dsParameter.Add(New OleDbParameter("@DiaChi", nhanVien.DiaChi))
dsParameter.Add(New OleDbParameter("@DienThoai", nhanVien.DienThoai))
dsParameter.Add(New OleDbParameter("@LoaiNhanVien", nhanVien.LoaiNhanVien))
dsParameter.Add(New OleDbParameter("@MaNhanVien", nhanVien.MaNhanVien))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function TimKiemNhanVien(ByVal nhanVien As NhanVienDto) As DataTable
Dim sql As String = "select MaNhanVien,MatKhau,TenDangNhap,HoTen,NgaySinh,IIF(Phai=1,'Nữ','Nam') AS Phai,DiaChi,DienThoai,loaiNhanVien from NHANVIEN where 1"
If nhanVien.TenDangNhap <> "" Then
sql += " and TenDangNhap LIKE '%" & nhanVien.TenDangNhap & "%'"
End If
If nhanVien.HoTen <> "" Then
sql += " and HoTen LIKE '%" & nhanVien.HoTen & "%'"
End If
If nhanVien.DienThoai <> "" Then
sql += " and DienThoai LIKE '%" & nhanVien.DienThoai & "%'"
End If
If nhanVien.GioiTinh = 1 Then
sql += " and Phai = " & nhanVien.GioiTinh & ""
End If
If nhanVien.GioiTinh = 0 Then
sql += " and Phai = " & nhanVien.GioiTinh & ""
End If
If nhanVien.LoaiNhanVien = 1 Then
sql += " and LoaiNhanVien = " & nhanVien.LoaiNhanVien & ""
End If
If nhanVien.LoaiNhanVien = 0 Then
sql += " and LoaiNhanVien = " & nhanVien.LoaiNhanVien & ""
End If
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function XoaNhanVien(ByVal nhanVien As NhanVienDto) As String
Dim str As String = ""
Try
Dim con As OleDbConnection = provider.Connect()
Dim sql As String = "delete from NHANVIEN where MaNhanVien = " & nhanVien.MaNhanVien.ToString()
Dim cmd As OleDbCommand = New OleDbCommand(sql, con)
cmd.Parameters.Add("@MaNhanVien", OleDbType.Integer)
cmd.Parameters("@MaNhanVien").Value = nhanVien.MaNhanVien
cmd.ExecuteNonQuery()
con.Close()
Catch ex As Exception
str = ex.Message
End Try
Return str
End Function
End Class
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/QuanLyXe/DAO/NhanVienDao.vb | Visual Basic .NET | gpl2 | 6,156 |
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("DAO")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("DAO")>
<Assembly: AssemblyCopyright("Copyright © 2010")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("1a0f8d74-0b1e-4319-8f9e-0a29d05cb470")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/QuanLyXe/DAO/My Project/AssemblyInfo.vb | Visual Basic .NET | gpl2 | 1,159 |
Imports System.Data
Imports System.Data.OleDb
Imports DAO
Imports DTO
Public Class XL_Chung_dao
Dim provider As New DataProvider
'................
'Tìm ngày khởi hành
Public Function TimNgayKhoiHanh(ByVal maTuyen As Integer) As DataTable
Dim sql As String = "SELECT NgayKhoiHanh FROM LICHTUYENKHONGLAP WHERE MaTuyen = " & maTuyen
sql += " Group by NgayKhoiHanh"
Return provider.ThucThiCauTruyVan(sql)
End Function
'Tìm giờ khởi hành
Public Function TimThoiDiemKhoiHanh(ByVal maTuyen As Integer, ByVal ngayKhoiHanh As Date) As DataTable
Dim sql As String = "SELECT ThoiDiemKhoiHanh FROM LICHTUYENKHONGLAP WHERE MaTuyen = ? and NgayKhoiHanh = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaTuyen", maTuyen))
dsParameter.Add(New OleDbParameter("@NgayKhoiHanh", ngayKhoiHanh))
Return provider.ThucThiCauTruyVan(sql, dsParameter)
End Function
End Class
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/QuanLyXe/DAO/XL_Chung_dao.vb | Visual Basic .NET | gpl2 | 1,034 |
Imports System.Data
Imports System.Data.OleDb
Imports DTO
Public Class LichGanDao
Dim provider As New DataProvider
Public Function LayDanhSachLichGan() As DataTable
Dim sql As String = "SELECT * FROM LichGan"
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function TimLichGanTheoMa(ByVal maCanTim As Integer) As DataTable
Dim sql As String = "SELECT * FROM LichGan WHERE MaLichGan = " & maCanTim
Return provider.ThucThiCauTruyVan(sql)
End Function
'Tìm lịch gán theo mã tuyến, ngày khởi hành, thời điểm và xe
Public Function TimLichGan(ByVal maTuyen As Long, ByVal ngayKhoiHanh As Date, ByVal thoiDiemKhoiHanh As String, ByVal maXe As Long) As DataTable
Dim sql As String = "SELECT * FROM LichGan WHERE MaTuyen = ? and NgayKhoiHanh = ? and ThoiDiemKhoiHanh = ? and MaXe = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaTuyen", maTuyen))
dsParameter.Add(New OleDbParameter("@NgayKhoiHanh", ngayKhoiHanh))
dsParameter.Add(New OleDbParameter("@ThoiDiemKhoiHanh", thoiDiemKhoiHanh))
dsParameter.Add(New OleDbParameter("@MaXe", maXe))
Return provider.ThucThiCauTruyVan(sql, dsParameter)
End Function
Public Function ThemMotLichGan(ByVal lg As LichGanDto) As Integer
Dim sql As String = "INSERT INTO LichGan( MaTuyen, ThoiDiemKhoiHanh, NgayKhoiHanh, MaXe, MaNhanVien) VALUES ( ?, ?, ?, ?, ?)"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaTuyen", lg.MaTuyen))
dsParameter.Add(New OleDbParameter("@ThoiDiemKhoiHanh", lg.ThoiDiemKhoiHanh))
dsParameter.Add(New OleDbParameter("@NgayKhoiHanh", lg.NgayKhoiHanh))
dsParameter.Add(New OleDbParameter("@MaXe", lg.MaXe))
dsParameter.Add(New OleDbParameter("@MaNhanVien", lg.MaNhanVien))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function CapNhatLichGan(ByVal lg As LichGanDto) As Integer
Dim sql As String = "UPDATE LichGan SET MaLichGan = ?, MaTuyen = ?, ThoiDiemKhoiHanh = ?, NgayKhoiHanh = ?, MaXe = ?, MaLap = ? WHERE MaLichGan = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaTuyen", lg.MaTuyen))
dsParameter.Add(New OleDbParameter("@ThoiDiemKhoiHanh", lg.ThoiDiemKhoiHanh))
dsParameter.Add(New OleDbParameter("@NgayKhoiHanh", lg.NgayKhoiHanh))
dsParameter.Add(New OleDbParameter("@MaXe", lg.MaXe))
dsParameter.Add(New OleDbParameter("@MaNhanVien", lg.MaNhanVien))
dsParameter.Add(New OleDbParameter("@MaLichGan", lg.MaLichGan))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function XoaMotLichGan(ByVal maCanXoa As Long) As Integer
Dim sql As String = "DELETE FROM LichGan WHERE MaLichGan = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaLichGan", maCanXoa))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
'Tìm ngày khởi hành
Public Function TimNgayKhoiHanh(ByVal maTuyen As Integer) As DataTable
Dim sql As String = "SELECT NgayKhoiHanh FROM LichGan WHERE MaTuyen = " & maTuyen
sql += " Group by NgayKhoiHanh Order by NgayKhoiHanh"
Return provider.ThucThiCauTruyVan(sql)
End Function
'Tìm giờ khởi hành
Public Function TimThoiDiemKhoiHanh(ByVal maTuyen As Integer, ByVal ngayKhoiHanh As Date) As DataTable
Dim sql As String = "SELECT ThoiDiemKhoiHanh FROM LichGan WHERE MaTuyen = ? and NgayKhoiHanh = ?"
sql += " Group by ThoiDiemKhoiHanh Order by ThoiDiemKhoiHanh"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaTuyen", maTuyen))
dsParameter.Add(New OleDbParameter("@NgayKhoiHanh", ngayKhoiHanh))
Return provider.ThucThiCauTruyVan(sql, dsParameter)
End Function
'Tìm xe đang rảnh theo ngày và thời điểm khởi hành
Public Function DanhSachXeDangRanh(ByVal ngayKhoiHanh As Date, ByVal ThoiDiemKhoiHanh As String) As DataTable
Dim sql As String = "Select * From XE Where MaXe not in("
sql += " Select lg.MaXe From LichGan lg Where lg.NgayKhoiHanh = ? and lg.ThoiDiemKhoiHanh = ? )"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@NgayKhoiHanh", ngayKhoiHanh))
dsParameter.Add(New OleDbParameter("@ThoiDiemKhoiHanh", ThoiDiemKhoiHanh))
Return provider.ThucThiCauTruyVan(sql, dsParameter)
End Function
'Lấy mã lịch gán vừa thêm vào
Public Function LayMaLichGanVuaThem() As Long
Dim sql As String = "Select max(MaLichGan)as MaLichGan From LichGan"
Dim dt As DataTable = provider.ThucThiCauTruyVan(sql)
Return dt.Rows(0).Item(0)
End Function
'Bán vé...
'Tìm xe theo tuyến, thời điểm
Public Function DanhSachXe_TheoTuyen_ThoiDiem(ByVal maTuyen As Long, ByVal ngayKhoiHanh As Date, ByVal ThoiDiemKhoiHanh As String) As DataTable
Dim sql As String = "SELECT x.MaXe, x.SoXe, x.SoChoNgoi FROM XE x, LichGan lg"
sql += " WHERE lg.MaXe = x.MaXe and lg.MaTuyen = ? and lg.NgayKhoiHanh = ? and lg.ThoiDiemKhoiHanh = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaTuyen", maTuyen))
dsParameter.Add(New OleDbParameter("@NgayKhoiHanh", ngayKhoiHanh))
dsParameter.Add(New OleDbParameter("@ThoiDiemKhoiHanh", ThoiDiemKhoiHanh))
Return provider.ThucThiCauTruyVan(sql, dsParameter)
End Function
End Class
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/QuanLyXe/DAO/LichGanDao.vb | Visual Basic .NET | gpl2 | 5,899 |
Imports System.Data
Imports System.Data.OleDb
Imports DTO
Public Class XeDao
Dim provider As New DataProvider
Public Function LayDanhSachXe() As DataTable
Dim sql As String = "SELECT * FROM Xe"
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function TimXe(ByVal xe As XeDto) As DataTable
Dim sql As String = "SELECT * FROM Xe WHERE 1 "
'If xe.MaXe <> 0 Then
' sql += " and MaXe =" & xe.MaXe
'End If
If xe.SoXe <> "" Then
sql += " and SoXe like '" & xe.SoXe & "%' "
End If
If xe.HieuXe <> "" Then
sql += " and HieuXe like'" & xe.HieuXe & "%' "
End If
If xe.DoiXe <> 0 Then
sql += " and DoiXe =" & xe.DoiXe
End If
If xe.SoChoNgoi <> 0 Then
sql += " and SoChoNgoi = " & xe.SoChoNgoi
End If
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function TimXeTheoMaXe(ByVal maXe As Integer) As DataTable
Dim sql As String = "SELECT * FROM Xe WHERE MaXe = " & maXe
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function LaySoChoNgoi_TheoMaXe(ByVal maXe As Integer) As Integer
Dim soChoNgoi As Integer = 0
Dim dt As DataTable = TimXeTheoMaXe(maXe)
If dt.Rows.Count > 0 Then
soChoNgoi = dt.Rows(0).Item("SoChoNgoi")
End If
Return soChoNgoi
End Function
Public Function ThemXe(ByVal xe As XeDto) As Integer
Dim sql As String = "INSERT INTO XE(SoXe, HieuXe, DoiXe, SoChoNgoi) VALUES (?, ?, ?, ?)"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@SoXe", xe.SoXe))
dsParameter.Add(New OleDbParameter("@HieuXe", xe.HieuXe))
dsParameter.Add(New OleDbParameter("@DoiXe", xe.DoiXe))
dsParameter.Add(New OleDbParameter("@SoChoNgoi", xe.SoChoNgoi))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function CapNhatXe(ByVal xe As XeDto) As Integer
Dim sql As String = "UPDATE XE SET SoXe = ?, HieuXe = ?, DoiXe = ?, SoChoNgoi = ? WHERE MaXe = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@SoXe", xe.SoXe))
dsParameter.Add(New OleDbParameter("@HieuXe", xe.HieuXe))
dsParameter.Add(New OleDbParameter("@DoiXe", xe.DoiXe))
dsParameter.Add(New OleDbParameter("@SoChoNgoi", xe.SoChoNgoi))
dsParameter.Add(New OleDbParameter("@MaXe", xe.MaXe))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function XoaXe(ByVal maCanXoa As Long) As Integer
Dim sql As String = "DELETE FROM XE WHERE MaXe = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaXe", maCanXoa))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
End Class
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/QuanLyXe/DAO/XeDao.vb | Visual Basic .NET | gpl2 | 3,076 |
Public Class CHUNG
Dim provider As New DataProvider
Public Function LayDanhSach() As DataTable
Dim sql As String = "SELECT tx.TenTuyen,td.thoidiemkhoihanh,td.ngaykhoihanh,td.malap,ll.thulap,td.manhanvien FROM TuyenXe tx, ThoiDiem_KhoiHanh td, LichLap ll "
sql += "where tx.matuyen = td.matuyen and ll.malap = td.maLap"
Dim dtBang As DataTable
dtBang = provider.ThucThiCauTruyVan(sql)
Return dtBang
End Function
End Class
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/QuanLyXe/DAO/ChungDao.vb | Visual Basic .NET | gpl2 | 492 |
Imports System.Data
Imports System.Data.OleDb
Imports DTO
Public Class LichKhoiHanhDao
Dim provider As New DataProvider
Public Function LayDanhSachLichLap() As DataTable
Dim sql As String = "SELECT * FROM LichLap"
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function TimLichLap(ByVal lichLap As LichKhoiHanhDto) As DataTable
Dim sql As String = "SELECT * FROM LichLap WHERE 1"
If lichLap.MaLap <> 0 Then
sql += " and MaLap =" & lichLap.MaLap & " "
End If
If lichLap.ThuLap <> "" Then
sql += " and ThuLap = '" & lichLap.ThuLap & "' "
End If
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function TimTuyenTheoMaLap(ByVal maLap As Integer) As DataTable
Dim sql As String = "SELECT * FROM LichLap WHERE maLap = " & maLap
Dim dtLichLap As DataTable
dtLichLap = provider.ThucThiCauTruyVan(sql)
Return dtLichLap
End Function
Public Function ThemLichLap(ByVal lichLap As LichKhoiHanhDto) As Integer
Dim sql As String = "INSERT INTO LichLap(ThuLap) VALUES (?)"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@ThuLap", lichLap.ThuLap))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function CapNhatLichLap(ByVal lichLap As LichKhoiHanhDto) As Integer
Dim sql As String = "UPDATE LichLap SET ThuLap = ? WHERE MaLap = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@ThuLap", lichLap.ThuLap))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function XoaLichLap(ByVal maLap As Long) As Integer
Dim sql As String = "DELETE FROM LichLap WHERE MaLap = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaLap", maLap))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function CapNhatXuongCSDL(ByVal tenBang As String, ByVal dt As DataTable) As Integer
Return provider.CapNhatXuongCSDL(tenBang, dt)
End Function
End Class
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/QuanLyXe/DAO/LichKhoiHanhDao.vb | Visual Basic .NET | gpl2 | 2,294 |
Imports System.Data
Imports System.Data.OleDb
Imports DTO
Public Class LichTuyenLapDao
Dim provider As New DataProvider
Public Function LayDanhSachLichTuyenLap() As DataTable
Dim sql As String = "SELECT matuyen ,thoidiemkhoihanh FROM LichTuyenLap "
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function LayDanhSachLichTuyenLapThu() As DataTable
Dim sql As String = "SELECT DISTINCT maTuyen,thuhai,thuba,thutu,thunam,thusau,thubay,chunhat FROM LichTuyenLap "
Return provider.ThucThiCauTruyVan(sql)
End Function
'Public Function LayDanhSachLichTuyenLapThu(ByVal maTuyen As Integer) As DataTable
' Dim sql As String = "SELECT thuhai,thuba,thutu,thunam,thusau,thubay,chunhat FROM LichTuyenLap where matuyen = " & maTuyen
' Return provider.ThucThiCauTruyVan(sql)
'End Function
Public Function ThemThoiDiemKhoiHanh(ByVal thoiDiem As LichTuyenDto) As Integer
Dim sql As String = "INSERT INTO LichTuyenLap(MaTuyen,ThoiDiemKhoiHanh,ThuHai,ThuBa,ThuTu,ThuNam,ThuSau,ThuBay,ChuNhat,MaNhanVien) VALUES(?,?,?,?,?,?,?,?,?,?)"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaTuyen", thoiDiem.MaTuyen))
dsParameter.Add(New OleDbParameter("@ThoiDiemKhoiHanh", thoiDiem.ThoiDiemKhoiHanh))
dsParameter.Add(New OleDbParameter("@ThuHai", thoiDiem.ThuHai))
dsParameter.Add(New OleDbParameter("@ThuBa", thoiDiem.ThuBa))
dsParameter.Add(New OleDbParameter("@ThuTu", thoiDiem.ThuTu))
dsParameter.Add(New OleDbParameter("@ThuNam", thoiDiem.ThuNam))
dsParameter.Add(New OleDbParameter("@ThuSau", thoiDiem.ThuSau))
dsParameter.Add(New OleDbParameter("@ThuBay", thoiDiem.ThuBay))
dsParameter.Add(New OleDbParameter("@ChuNhat", thoiDiem.ChuNhat))
dsParameter.Add(New OleDbParameter("@MaNhanVien", thoiDiem.MaNhanVien))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function CapNhatThoiDiemKhoiHanh(ByRef data As DataTable) As Integer
Dim dataAdapter As New OleDbDataAdapter()
Dim con As OleDbConnection = provider.Connect()
Dim sqlInsert As String = "INSERT INTO LichTuyenLap(MaTuyen,ThoiDiemKhoiHanh) VALUES(@MaTuyen,@ThoiDiemKhoiHanh)"
Dim commandInsert As New OleDbCommand(sqlInsert, con)
commandInsert.Parameters.Add(New OleDbParameter("@MaTuyen", OleDbType.Integer, 4, "MaTuyen"))
commandInsert.Parameters.Add(New OleDbParameter("@ThoiDiemKhoiHanh", OleDbType.VarChar, 10, "ThoiDiemKhoiHanh"))
dataAdapter.InsertCommand = commandInsert
Dim sqlDelete As String = "Delete From LichTuyenLap Where MaTuyen=@MaTuyen And ThoiDiemKhoiHanh=@ThoiDiemKhoiHanh"
Dim commandDelete As New OleDbCommand(sqlDelete, con)
commandDelete.Parameters.Add(New OleDbParameter("@MaTuyen", OleDbType.Integer, 4, "MaTuyen"))
commandDelete.Parameters.Add(New OleDbParameter("@ThoiDiemKhoiHanh", OleDbType.VarChar, 10, "ThoiDiemKhoiHanh"))
dataAdapter.DeleteCommand = commandDelete
Return dataAdapter.Update(data)
End Function
Public Function CapNhatThuLap(ByVal row As DataRow)
Dim sql As String = "UPDATE LichTuyenLap SET ThuHai=?,ThuBa=?,ThuTu=?,ThuNam=?,ThuSau=?,ThuBay=?,ChuNhat=? Where MaTuyen=?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@ThuHai", row("ThuHai")))
dsParameter.Add(New OleDbParameter("@ThuBa", row("ThuBa")))
dsParameter.Add(New OleDbParameter("@ThuTu", row("ThuTu")))
dsParameter.Add(New OleDbParameter("@ThuNam", row("ThuNam")))
dsParameter.Add(New OleDbParameter("@ThuSau", row("ThuSau")))
dsParameter.Add(New OleDbParameter("@ThuBay", row("ThuBay")))
dsParameter.Add(New OleDbParameter("@ChuNhat", row("ChuNhat")))
dsParameter.Add(New OleDbParameter("@MaTuyen", row("MaTuyen")))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function XoaThoiDiemKhoiHanh(ByVal row As DataRow)
Dim sql = "DELETE FROM LichTuyenLap WHERE MaTuyen = ? and ThoiDiemKhoiHanh = ? "
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaTuyen", row("MaTuyen")))
dsParameter.Add(New OleDbParameter("@ThoiDiemKhoiHanh", row("ThoiDiemKhoiHanh")))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
End Class
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/QuanLyXe/DAO/LichTuyenLapDao.vb | Visual Basic .NET | gpl2 | 4,610 |
Imports System.Data
Imports System.Data.OleDb
Imports DTO
Public Class VeDao
Dim provider As New DataProvider
Public Function LayDanhSachVe() As DataTable
Dim sql As String = "SELECT * FROM Ve"
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function TimVeTheoMaLichGan(ByVal MaLichGan As Integer) As DataTable
Dim sql As String = "SELECT v.MaLichGan as MaLich, v.MaGhe, v.TinhTrang, lv.GiaVe, lv.MaLoaiVe FROM Ve v, LoaiVe lv WHERE v.MaLoaiVe = lv.MaLoaiVe and v.MaLichGan = " & MaLichGan
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function TimVe(ByVal ve As VeDto) As DataTable
Dim sql As String = "SELECT * FROM Ve WHERE 1 "
If ve.MaGhe <> 0 Then
sql += " and MaGhe =" & ve.MaGhe
End If
If ve.MaLich <> 0 Then
sql += " and MaLich = " & ve.MaLich
End If
sql += " and TinhTrang = " & ve.TinhTrang
If ve.LoaiVe <> 0 Then
sql += " and LoaiVe =" & ve.LoaiVe
End If
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function ThemVe(ByVal ve As VeDto) As Integer
Dim sql As String = "INSERT INTO VE(MaGhe, MaLichGan, TinhTrang, MaLoaiVe) VALUES (?, ?, ?, ?)"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaGhe", ve.MaGhe))
dsParameter.Add(New OleDbParameter("@MaLich", ve.MaLich))
dsParameter.Add(New OleDbParameter("@TinhTrang", ve.TinhTrang))
dsParameter.Add(New OleDbParameter("@MaLoaiVe", ve.LoaiVe))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function CapNhatVe(ByVal ve As VeDto) As Integer
Dim sql As String = "UPDATE VE SET TinhTrang = ?, MaLoaiVe = ? WHERE MaGhe = ? and MaLichGan = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@TinhTrang", ve.TinhTrang))
dsParameter.Add(New OleDbParameter("@MaLoaiVe", ve.LoaiVe))
dsParameter.Add(New OleDbParameter("@MaGhe", ve.MaGhe))
dsParameter.Add(New OleDbParameter("@MaLichGan", ve.MaLich))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function XoaVe(ByVal maCanXoa As Long) As Integer
'.......
End Function
End Class
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/QuanLyXe/DAO/VeDao.vb | Visual Basic .NET | gpl2 | 2,445 |
Imports System.Data
Imports System.Data.OleDb
Imports DTO
Public Class LoaiVeDao
Dim provider As New DataProvider
Public Function LayDanhSachLoaiVe() As DataTable
Dim sql As String = "SELECT * FROM LOAIVE"
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function LayDanhSachLoaiVeTheoMaTuyen(ByVal maTuyen As Integer) As DataTable
Dim sql As String = "SELECT * FROM LOAIVE WHERE MaTuyen = " & maTuyen
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function ThemLoaiVe(ByVal loaive As LoaiVeDto) As Integer
Dim sql As String = "INSERT INTO LOAIVE(MaTuyen, GiaVe) VALUES (?, ?)"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaTuyen", loaive.MaTuyen))
dsParameter.Add(New OleDbParameter("@GiaVe", loaive.GiaVe))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function CapNhatLoaiVe(ByVal loaive As LoaiVeDto) As Integer
Dim sql As String = "UPDATE LOAIVE SET GiaVe = ? WHERE MaLoaiVe = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@GiaVe", loaive.GiaVe))
dsParameter.Add(New OleDbParameter("@MaLoaiVe", loaive.MaLoai))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function XoaLoaiVe(ByVal maCanXoa As Long) As Integer
Dim sql As String = "DELETE FROM LOAIVE WHERE MaLoaiVe = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaLoai", maCanXoa))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
End Class
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/QuanLyXe/DAO/LoaiVeDao.vb | Visual Basic .NET | gpl2 | 1,774 |
Imports System.Data
Imports System.Data.OleDb
Imports DTO
Public Class LichGanLapDao
Dim provider As New DataProvider
Public Function LayDanhSachXeDuocLap() As DataTable
Dim sql As String = "Select lg.MaLichGan, tx.TenTuyen, lg.ThoiDiemKhoiHanh, lg.MaXe"
sql += " From LichGanLap ll, LichGan lg, TUYENXE tx Where ll.MaLichGan = lg.MaLichGan and tx.MaTuyen = lg.MaTuyen"
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function LayLichGanLap(ByVal maLichGan As Long) As DataTable
Dim sql As String = "Select * From LichGanLap Where MaLichGan = " & maLichGan
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function ThemMotLichGanLap(ByVal lgLap As LichGanLapDto) As Integer
Dim sql As String = "INSERT INTO LichGanLap(MaLichGan, ThuHai,ThuBa,ThuTu,ThuNam,ThuSau,ThuBay,ChuNhat) VALUES(?,?,?,?,?,?,?,?)"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaLichGan", lgLap.MaLichGan))
dsParameter.Add(New OleDbParameter("@ThuHai", lgLap.ThuHai))
dsParameter.Add(New OleDbParameter("@ThuBa", lgLap.ThuBa))
dsParameter.Add(New OleDbParameter("@ThuTu", lgLap.ThuTu))
dsParameter.Add(New OleDbParameter("@ThuNam", lgLap.ThuNam))
dsParameter.Add(New OleDbParameter("@ThuSau", lgLap.ThuSau))
dsParameter.Add(New OleDbParameter("@ThuBay", lgLap.ThuBay))
dsParameter.Add(New OleDbParameter("@ChuNhat", lgLap.ChuNhat))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function CapNhatMotLichGanLap(ByVal lgLap As LichGanLapDto) As Integer
Dim sql As String = "UPDATE LichGanLap SET ThuHai = ?, ThuBa = ?,ThuTu = ?,ThuNam = ?,ThuSau = ?,ThuBay = ?,ChuNhat = ?"
sql += " WHERE MaLichGan = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@ThuHai", lgLap.ThuHai))
dsParameter.Add(New OleDbParameter("@ThuBa", lgLap.ThuBa))
dsParameter.Add(New OleDbParameter("@ThuTu", lgLap.ThuTu))
dsParameter.Add(New OleDbParameter("@ThuNam", lgLap.ThuNam))
dsParameter.Add(New OleDbParameter("@ThuSau", lgLap.ThuSau))
dsParameter.Add(New OleDbParameter("@ThuBay", lgLap.ThuBay))
dsParameter.Add(New OleDbParameter("@ChuNhat", lgLap.ChuNhat))
dsParameter.Add(New OleDbParameter("@MaLichGan", lgLap.MaLichGan))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function XoaMotLichGanLap(ByVal maLichGan) As Integer
Dim sql As String = "DELETE FROM LichGanLap WHERE MaLichGan = " & maLichGan
Return provider.ThucThiTruyVan(sql)
End Function
End Class
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/QuanLyXe/DAO/LichGanLapDao.vb | Visual Basic .NET | gpl2 | 2,816 |
Imports System.Data
Imports System.Data.OleDb
Imports DTO
Public Class LichTuyenKhongLapDao
Dim provider As New DataProvider
Public Function LayDanhSachLichTuyenKhongLap() As DataTable
Dim sql As String = "SELECT MaTuyen,NgayKhoiHanh FROM LichTuyenKhongLap"
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function LayDanhSachLichTuyenKhongLapThoiDiem() As DataTable
Dim sql As String = "SELECT MaTuyen,NgayKhoiHanh,ThoiDiemKhoiHanh FROM LichTuyenKhongLap"
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function ThemThoiDiemKhoiHanh(ByVal thoiDiem As LichTuyenKhongLapDto) As Integer
Dim sql As String = "INSERT INTO LichTuyenKhongLap(MaTuyen,ThoiDiemKhoiHanh,NgayKhoiHanh,MaNhanVien) VALUES(?,?,?,?)"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaTuyen", thoiDiem.MaTuyen))
dsParameter.Add(New OleDbParameter("@ThoiDiemKhoiHanh", thoiDiem.ThoiDiemKhoiHanh))
dsParameter.Add(New OleDbParameter("@NgayKhoiHanh", thoiDiem.NgayKhoiHanh))
dsParameter.Add(New OleDbParameter("@MaNhanVien", thoiDiem.MaNhanVien))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function CapNhatThoiDiemKhoiHanh(ByRef data As DataTable) As Integer
Dim dataAdapter As New OleDbDataAdapter()
Dim con As OleDbConnection = provider.Connect()
Dim sqlInsert As String = "INSERT INTO LichTuyenKhongLap (MaTuyen,NgayKhoiHanh,ThoiDiemKhoiHanh) VALUES(?,?,?)"
Dim commandInsert As New OleDbCommand(sqlInsert, con)
commandInsert.Parameters.Add(New OleDbParameter("@MaTuyen", OleDbType.Integer, 4, "MaTuyen"))
commandInsert.Parameters.Add(New OleDbParameter("@NgayKhoiHanh", OleDbType.Date, 10, "NgayKhoiHanh"))
commandInsert.Parameters.Add(New OleDbParameter("@ThoiDiemKhoiHanh", OleDbType.VarChar, 10, "ThoiDiemKhoiHanh"))
dataAdapter.InsertCommand = commandInsert
Dim sqlDelete As String = "Delete From LichTuyenKhongLap Where MaTuyen=? And NgayKhoiHanh=? and ThoiDiemKhoiHanh=? "
Dim commandDelete As New OleDbCommand(sqlDelete, con)
commandDelete.Parameters.Add(New OleDbParameter("@MaTuyen", OleDbType.Integer, 4, "MaTuyen"))
commandDelete.Parameters.Add(New OleDbParameter("@NgayKhoiHanh", OleDbType.Date, 10, "NgayKhoiHanh"))
commandDelete.Parameters.Add(New OleDbParameter("@ThoiDiemKhoiHanh", OleDbType.VarChar, 10, "ThoiDiemKhoiHanh"))
dataAdapter.DeleteCommand = commandDelete
Return dataAdapter.Update(data)
End Function
End Class
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/QuanLyXe/DAO/LichTuyenKhongLapDao.vb | Visual Basic .NET | gpl2 | 2,712 |
Imports System
Imports System.Data.OleDb
Imports System.Data
Imports System.Collections
Public Class DataProvider
Public Shared ReadOnly Property ConnectionString() As String
Get
Return "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=QuanLyXE.mdb;Persist Security Info=True"
End Get
End Property
Private conn As OleDbConnection
Public Function Connect() As OleDbConnection
If conn Is Nothing Then
conn = New OleDbConnection(ConnectionString)
End If
If (conn.State <> ConnectionState.Open) Then
Try
conn.Open()
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End If
Return conn
End Function
Public Sub DisConnect()
If Not (conn Is Nothing) AndAlso conn.State = ConnectionState.Open Then
conn.Close()
End If
End Sub
Public Function ThucThiCauTruyVan(ByVal sql As String) As DataTable
Try
Return ThucThiCauTruyVan(sql, Nothing)
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Function
Public Function ThucThiCauTruyVan(ByVal sql As String, ByVal dsParameter As List(Of OleDbParameter)) As DataTable
Try
Connect()
Dim command As OleDbCommand
Dim dt As DataTable = New DataTable
command = New OleDbCommand(sql, conn)
If dsParameter IsNot Nothing Then
command.Parameters.AddRange(dsParameter.ToArray())
End If
Dim adapter As New OleDbDataAdapter(command)
adapter.Fill(dt)
Return dt
Catch ex As Exception
Throw New Exception(ex.Message)
Finally '??? dung lam gi?
DisConnect()
End Try
End Function
Public Function ThucThiTruyVan(ByVal sql As String) As Integer
Try
Connect()
Dim command As OleDbCommand
command = New OleDbCommand(sql, conn)
Return command.ExecuteNonQuery()
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Function
Public Function ThucThiTruyVanThuong(ByVal sql As String, ByVal dsParameter As List(Of OleDbParameter)) As Integer
Try
Connect()
Dim command As OleDbCommand
command = New OleDbCommand(sql, conn)
If dsParameter IsNot Nothing Then
command.Parameters.AddRange(dsParameter.ToArray())
End If
Return command.ExecuteNonQuery()
Catch ex As Exception
'Throw New Exception(ex.Message)
Finally
DisConnect()
End Try
End Function
'Hàm này dùng để đưa dữ liệu từ datatable vào bảng có tên 'tenbang'
Public Function CapNhatXuongCSDL(ByVal tenBang As String, ByVal dt As DataTable) As Integer
Dim kq As Integer = 0
Try
Connect()
Dim command As New OleDbCommand("Select * From " & tenBang, conn)
Dim adapter As New OleDbDataAdapter()
adapter.SelectCommand = command
Dim cmb As New OleDbCommandBuilder(adapter)
kq = adapter.Update(dt)
Return kq
Catch ex As Exception
Throw New Exception(ex.Message)
Finally
DisConnect()
End Try
End Function
End Class | 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/QuanLyXe/DAO/DataProvider.vb | Visual Basic .NET | gpl2 | 3,625 |
Imports System.Data.OleDb
Imports BUS
Imports DTO
Public Class frmQuanLyNhanVien
Dim vtClick As Integer = 0
Dim dtNHANVIEN As DataTable
Dim flagInsert As Boolean
Private Sub frmQuanLy_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cbxLoaiNguoiDung.SelectedIndex = 0
Try
If sessionNhanVien.LoaiNhanVien = 0 Then
dgvNhanVien.DataSource = NhanVienBus.LayNguoiDungTheoMa(sessionNhanVien.MaNhanVien)
Else
dgvNhanVien.DataSource = NhanVienBus.LayDanhSachNguoiDung()
End If
Dim nhanVien As New NhanVienDto
nhanVien = LayNguoiDung_DataGridView(0)
HienThiLenTextboxs(nhanVien)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
If sessionNhanVien.LoaiNhanVien = 0 Then
txtTenDangNhap.Enabled = False
btnThem.Enabled = False
btnXoa.Enabled = False
End If
End Sub
Private Sub btnThem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThem.Click
dgvNhanVien.Rows(0).Selected = False
dgvNhanVien.Rows(dgvNhanVien.Rows.Count - 1).Selected = True
If (dgvNhanVien.Rows(dgvNhanVien.Rows.Count - 1).Selected = True) Then
'ResetTextboxs()
End If
Dim kt As String = KiemTra_NhapLieu_Them()
If (kt <> "") Then
MessageBox.Show(kt, "Thong bao")
Exit Sub
End If
Dim kq As Integer = NhanVienBus.ThemNhanVien(Me.NhapNhanVien())
If (kq = 0) Then
MessageBox.Show("đã có trong dữ liệu", "Thông báo")
Else
dgvNhanVien.DataSource = NhanVienBus.LayDanhSachNguoiDung()
dgvNhanVien.Rows(dgvNhanVien.Rows.Count - 1).Selected = True
Dim nhanVien As NhanVienDto = LayNguoiDung_DataGridView(dgvNhanVien.Rows.Count - 2)
HienThiLenTextboxs(nhanVien)
End If
End Sub
Private Sub btnThoat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThoat.Click
Close()
End Sub
Public Sub ResetTextboxs()
txtMaNhanVien.Text = ""
txtTenDangNhap.Text = ""
txtMatKhau.Text = ""
txtHoTen.Text = ""
txtDiaChi.Text = ""
txtDienThoai.Text = ""
End Sub
Public Sub HienThiLenTextboxs(ByVal nhanVien As NhanVienDto)
txtMaNhanVien.Text = nhanVien.MaNhanVien
txtTenDangNhap.Text = nhanVien.TenDangNhap
txtMatKhau.Text = nhanVien.MatKhau
txtHoTen.Text = nhanVien.HoTen
dtpNgaySinh.Value = nhanVien.NgaySinh.Date
If (nhanVien.GioiTinh = 1) Then
rdbNu.Checked = True
Else
rdbNam.Checked = True
End If
txtDiaChi.Text = nhanVien.DiaChi
txtDienThoai.Text = nhanVien.DienThoai
cbxLoaiNguoiDung.SelectedIndex = nhanVien.LoaiNhanVien
End Sub
Public Sub xl_Button(ByVal b As Boolean)
btnThem.Enabled = b
btnXoa.Enabled = b
btnSua.Enabled = b
btnTim.Enabled = Not b
End Sub
Public Function NhapNhanVien() As NhanVienDto
Dim nhanVien As New NhanVienDto
If IsNumeric(txtMaNhanVien.Text) Then
nhanVien.MaNhanVien = txtMaNhanVien.Text
End If
nhanVien.TenDangNhap = txtTenDangNhap.Text
nhanVien.MatKhau = txtMatKhau.Text
nhanVien.HoTen = txtHoTen.Text
nhanVien.NgaySinh = dtpNgaySinh.Value
If rdbNu.Checked = True Then
nhanVien.GioiTinh = 1
Else
nhanVien.GioiTinh = 0
End If
nhanVien.DiaChi = txtDiaChi.Text
nhanVien.DienThoai = txtDienThoai.Text
nhanVien.LoaiNhanVien = cbxLoaiNguoiDung.SelectedIndex
Return nhanVien
End Function
Private Sub dgvNhanVien_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles dgvNhanVien.MouseClick
vtClick = dgvNhanVien.CurrentRow.Index
If vtClick = dgvNhanVien.Rows.Count - 1 Then
ResetTextboxs()
Exit Sub
End If
Try
Dim nhanVien As NhanVienDto
nhanVien = LayNguoiDung_DataGridView(vtClick)
HienThiLenTextboxs(nhanVien)
Catch ex As Exception
End Try
End Sub
Public Function LayNguoiDung_DataGridView(ByVal vtdong As Integer) As NhanVienDto
Dim nhanVien As New NhanVienDto
nhanVien.MaNhanVien = dgvNhanVien.Rows(vtdong).Cells("MaNhanVien").Value
nhanVien.TenDangNhap = dgvNhanVien.Rows(vtdong).Cells("TenDangNhap").Value
nhanVien.MatKhau = dgvNhanVien.Rows(vtdong).Cells("MatKhau").Value
nhanVien.HoTen = dgvNhanVien.Rows(vtdong).Cells("HoTen").Value
nhanVien.NgaySinh = dgvNhanVien.Rows(vtdong).Cells("NgaySinh").Value
Dim phai As String = dgvNhanVien.Rows(vtdong).Cells("Phai").Value
If (phai = "Nam") Then
nhanVien.GioiTinh = 0
Else
nhanVien.GioiTinh = 1
End If
nhanVien.DiaChi = dgvNhanVien.Rows(vtdong).Cells("DiaChi").Value
nhanVien.DienThoai = dgvNhanVien.Rows(vtdong).Cells("DienThoai").Value
nhanVien.LoaiNhanVien = dgvNhanVien.Rows(vtdong).Cells("LoaiNhanVien").Value
Return nhanVien
End Function
Public Function KiemTra_NhapLieu_Them() As String
Dim str As String = ""
If KT_TenDangNhap(txtTenDangNhap.Text) <> "" Then
str = KT_TenDangNhap(txtTenDangNhap.Text)
txtTenDangNhap.Focus()
Return str
ElseIf KT_MatKhau(txtMatKhau.Text) <> "" Then
str = KT_MatKhau(txtMatKhau.Text)
txtMatKhau.Focus()
Return str
ElseIf txtHoTen.Text = "" Then
str = "Ho ten khong duoc rong !!"
txtHoTen.Focus()
Return str
ElseIf txtDienThoai.Text = "" Then
' str = "Điện thoại không được rỗng !!"
'txtDienThoai.Focus()
'Return str
ElseIf txtDiaChi.Text = "" Then
str = "Địa chỉ không được rỗng !!"
txtDiaChi.Focus()
Return str
End If
Return str
End Function
Private Sub dgvNhanVien_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dgvNhanVien.SelectionChanged
vtClick = dgvNhanVien.CurrentRow.Index
If vtClick = dgvNhanVien.Rows.Count - 1 Then
'ResetTextboxs()
Exit Sub
End If
Try
Dim nhanVien As NhanVienDto
nhanVien = LayNguoiDung_DataGridView(vtClick)
HienThiLenTextboxs(nhanVien)
Catch ex As Exception
End Try
End Sub
Private Sub btnTim_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTim.Click
Dim nhanVien As New NhanVienDto
nhanVien.TenDangNhap = txtTenDangNhap.Text
nhanVien.HoTen = txtHoTen.Text
nhanVien.DienThoai = txtDienThoai.Text
If rdbNam.Checked = True Then
nhanVien.GioiTinh = 0
ElseIf rdbNu.Checked = True Then
nhanVien.GioiTinh = 1
End If
dgvNhanVien.DataSource = NhanVienBus.TimKiemNhanVien(nhanVien)
End Sub
Private Sub btnXoa_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXoa.Click
If vtClick = 0 Then
ResetTextboxs()
End If
If vtClick = dgvNhanVien.Rows.Count - 1 Then
MessageBox.Show("Chọn dòng có dữ liệu cần xoá !!", "Thông báo")
Exit Sub
End If
Dim nhanVien As New NhanVienDto
nhanVien.MaNhanVien = dgvNhanVien.Rows(vtClick).Cells("MaNhanVien").Value
NhanVienBus.XoaNhanVien(nhanVien)
dgvNhanVien.DataSource = NhanVienBus.LayDanhSachNguoiDung()
nhanVien = LayNguoiDung_DataGridView(0)
HienThiLenTextboxs(nhanVien)
End Sub
Private Sub btnSua_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSua.Click
If vtClick = dgvNhanVien.Rows.Count - 1 Then
MessageBox.Show("Chọn dòng dữ liệu cần sửa !!", "Thông báo")
Exit Sub
End If
Dim nhanVien As New NhanVienDto
nhanVien = NhapNhanVien()
NhanVienBus.CapNhatNhanVien(nhanVien)
If sessionNhanVien.LoaiNhanVien = 0 Then
dgvNhanVien.DataSource = NhanVienBus.LayNguoiDungTheoMa(sessionNhanVien.MaNhanVien)
Else
dgvNhanVien.DataSource = NhanVienBus.LayDanhSachNguoiDung()
End If
nhanVien = LayNguoiDung_DataGridView(0)
HienThiLenTextboxs(nhanVien)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
txtHoTen.Text = ""
txtDiaChi.Text = ""
txtDienThoai.Text = ""
txtMaNhanVien.Text = ""
txtMatKhau.Text = ""
txtTenDangNhap.Text = ""
dtpNgaySinh.Text = ""
rdbNam.Text = ""
rdbNu.Text = ""
End Sub
End Class | 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/GiaoDien/frmQuanLyNhanVien.vb | Visual Basic .NET | gpl2 | 9,455 |
Public Class sessionNhanVien
Shared _maNhanVien As Long
Shared _loaiNhanVien As Integer
Public Shared Property MaNhanVien() As Long
Get
Return _maNhanVien
End Get
Set(ByVal value As Long)
_maNhanVien = value
End Set
End Property
Public Shared Property LoaiNhanVien() As Integer
Get
Return _loaiNhanVien
End Get
Set(ByVal value As Integer)
_loaiNhanVien = value
End Set
End Property
End Class
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/GiaoDien/sessionNhanVien.vb | Visual Basic .NET | gpl2 | 555 |
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("GiaoDien")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("GiaoDien")>
<Assembly: AssemblyCopyright("Copyright © 2010")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("06b73687-555f-488a-8489-25e993fd1587")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/GiaoDien/My Project/AssemblyInfo.vb | Visual Basic .NET | gpl2 | 1,169 |
Imports System.Data.OleDb
Imports BUS
Imports DTO
Public Class frmBanVe
Private Sub frmBanVe_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cbxTuyenXe.DataSource = TuyenBus.LayDanhSachTuyen()
cbxTuyenXe.DisplayMember = "TenTuyen"
cbxTuyenXe.ValueMember = "MaTuyen"
End Sub
Private Sub cbxTuyenXe_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbxTuyenXe.SelectedIndexChanged
cbxNgayKhoiHanh.Text = ""
cbxTuyenXe.ValueMember = "MaTuyen"
Dim maTuyen As Long = cbxTuyenXe.SelectedValue
cbxNgayKhoiHanh.DataSource = LichGanBus.TimNgayKhoiHanh(maTuyen)
cbxNgayKhoiHanh.DisplayMember = "NgayKhoiHanh"
End Sub
Private Sub cbxNgayKhoiHanh_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbxNgayKhoiHanh.SelectedIndexChanged, cbxNgayKhoiHanh.TextChanged
cbxGioKhoiHanh.Text = ""
cbxTuyenXe.ValueMember = "MaTuyen"
cbxNgayKhoiHanh.ValueMember = "NgayKhoiHanh"
Dim maTuyen As Long = cbxTuyenXe.SelectedValue
Dim ngayKH As Date = cbxNgayKhoiHanh.SelectedValue
cbxGioKhoiHanh.DataSource = LichGanBus.TimThoiDiemKhoiHanh(maTuyen, ngayKH)
cbxGioKhoiHanh.DisplayMember = "ThoiDiemKhoiHanh"
cbxGioKhoiHanh.ValueMember = "ThoiDiemKhoiHanh"
End Sub
Private Sub cbxGioKhoiHanh_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbxGioKhoiHanh.SelectedIndexChanged, cbxGioKhoiHanh.TextChanged
cbxTuyenXe.ValueMember = "MaTuyen"
cbxNgayKhoiHanh.ValueMember = "NgayKhoiHanh"
cbxGioKhoiHanh.ValueMember = "ThoiDiemKhoiHanh"
Dim maTuyen As Long = cbxTuyenXe.SelectedValue
Dim ngayKH As Date = cbxNgayKhoiHanh.SelectedValue
Dim thoiDiemKH As String = cbxGioKhoiHanh.SelectedValue
dgvXe.DataSource = LichGanBus.DanhSachXe_TheoTuyen_ThoiDiem(maTuyen, ngayKH, thoiDiemKH)
End Sub
Private Sub HienThiVe()
cbxTuyenXe.ValueMember = "MaTuyen"
cbxNgayKhoiHanh.ValueMember = "NgayKhoiHanh"
cbxGioKhoiHanh.ValueMember = "ThoiDiemKhoiHanh"
Dim maTuyen As Long = cbxTuyenXe.SelectedValue
Dim ngayKH As Date = cbxNgayKhoiHanh.SelectedValue
Dim thoiDiemKH As String = cbxGioKhoiHanh.SelectedValue
Dim vitri, MaXe As Integer
Try
vitri = dgvXe.CurrentRow.Index
MaXe = dgvXe.Rows(vitri).Cells("MaXe").Value
Catch ex As Exception
End Try
Dim maLichGan As Long
Try
Dim dt As DataTable = LichGanBus.TimLichGan(maTuyen, ngayKH, thoiDiemKH, MaXe)
maLichGan = dt.Rows(0).Item("MaLichGan")
Catch ex As Exception
'.......
End Try
dgvVe.DataSource = VeBus.TimVeTheoMaLichGan(maLichGan)
End Sub
Private Sub dgvXe_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles dgvXe.MouseClick
HienThiVe()
End Sub
Private Sub dgvXe_DataSourceChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dgvXe.DataSourceChanged
HienThiVe()
End Sub
Dim vitriClick As Integer
Private Sub dgvVe_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles dgvVe.MouseClick
Try
vitriClick = dgvVe.CurrentRow.Index
Catch ex As Exception
End Try
End Sub
Dim ve As New VeDto
Private Sub btnBanVe_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBanVe.Click
Dim maGhe As Integer
Dim maLichGan As Long
Dim tinhTrang As Boolean
If vitriClick = dgvVe.Rows.Count - 1 Then
MessageBox.Show("Chọn dòng có dữ liệu!!!", "THÔNG BÁO")
Exit Sub
End If
Try
maGhe = dgvVe.Rows(vitriClick).Cells("MaGhe").Value
maLichGan = dgvVe.Rows(vitriClick).Cells("MaLich").Value
tinhTrang = dgvVe.Rows(vitriClick).Cells("TinhTrang").Value
Catch ex As Exception
MessageBox.Show("Chọn một chỗ ngồi (mã ghế)!", "THÔNG BÁO")
Exit Sub
End Try
If tinhTrang Then
MessageBox.Show("Vé này đã bán!", "THÔNG BÁO")
Exit Sub
End If
ve.MaGhe = maGhe
ve.MaLich = maLichGan
ve.TinhTrang = True
'dgvVe.Columns("MaLoaiVe").Visible = False
ve.LoaiVe = dgvVe.Rows(vitriClick).Cells("MaLoaiVe").Value
VeBus.CapNhatVe(ve)
HienThiVe()
dgvVe.Rows(0).Selected = False
dgvVe.Rows(vitriClick).Selected = True
btnHuy.Enabled = True
End Sub
Private Sub btnHuy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHuy.Click
ve.TinhTrang = False
VeBus.CapNhatVe(ve)
HienThiVe()
dgvVe.Rows(0).Selected = False
dgvVe.Rows(vitriClick).Selected = True
btnHuy.Enabled = False
End Sub
Private Sub btnDong_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDong.Click
Close()
End Sub
End Class | 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/GiaoDien/frmBanVe.vb | Visual Basic .NET | gpl2 | 5,416 |
Imports System.Data.OleDb
Imports BUS
Imports DTO
Public Class frmQuyen
Dim dataset As DataSet
Dim quyenBindingSource As BindingSource
Dim quyenNguoiDungBindingSource As BindingSource
Private Sub frmQuyen_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
LoadData()
BindingSource()
End Sub
Public Sub LoadData()
dataset = New DataSet
dataset.Tables.Add(NhanVienBus.LayNguoiDung())
dataset.Tables.Add(NhanVienBus.LayQuyen())
dataset.Tables(0).TableName = "NguoiDung"
dataset.Tables(1).TableName = "Quyen"
quyenBindingSource.DataSource = dataset
quyenBindingSource.DataMember = "Quyen"
dataset.Relations.Add("QuyenNguoiDung", dataset.Tables(0).Columns("Maquyen"), dataset.Tables(1).Columns("MaQuyen"))
quyenNguoiDungBindingSource.DataSource = quyenBindingSource
quyenNguoiDungBindingSource.DataMember = "QuyenNguoiDung"
End Sub
Public Sub BindingSource()
dgvQuyen.DataSource = quyenBindingSource
dgvNguoiDung.DataSource = quyenNguoiDungBindingSource
End Sub
End Class | 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/GiaoDien/frmQuyen.vb | Visual Basic .NET | gpl2 | 1,222 |
Imports System.Data.OleDb
Imports BUS
Imports DTO
Public Class frmDangNhap
Public kqDangNhap As Boolean = False
Public Function KT_DangNhap() As Boolean
Dim tenDangNhap As String = txtTenDangNhap.Text
Dim matKhau As String = txtMatKhau.Text
Dim loaiNhanVien As Integer = NhanVienBus.LayNguoiDangNhap(tenDangNhap, matKhau)
Dim dt As DataTable = NhanVienBus.LayNguoiDung(tenDangNhap, matKhau)
If (dt.Rows.Count = 0) Then
Return False
End If
sessionNhanVien.MaNhanVien = dt.Rows(0).Item("MaNhanVien")
sessionNhanVien.LoaiNhanVien = dt.Rows(0).Item("LoaiNhanVien")
Return True
'Try
' If loaiNhanVien <> -1 Then
' ' MessageBox.Show("Đăng nhập thành công !", "Thông báo", MessageBoxButtons.OK)
' Return True
' End If
'Catch ex As Exception
' '.....
'End Try
'Return False
End Function
Private Sub btnDangNhap_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDangNhap.Click
kqDangNhap = KT_DangNhap()
If kqDangNhap Then
Close()
Else
txtMatKhau.Text = ""
MsgBox("Bạn Đã Nhập Sai. Xin Vui Lòng Kiểm Tra Lai.........^^_^^...HeHe...^^_^^", vbOKOnly + vbCritical)
End If
MsgBox("Chúc Mùng Bạn Đã Đăng Nhập Thành Công Vào Chương Trình Của Tôi..... @_@.....Thank You...@_@...")
End Sub
Private Sub btnThoat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThoat.Click
Me.Close()
End Sub
Private Sub frmDangNhap_FormClosed(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
txtTenDangNhap.Text = ""
txtMatKhau.Text = ""
End Sub
End Class | 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/GiaoDien/frmDangNhap.vb | Visual Basic .NET | gpl2 | 1,994 |
Imports System.Data.OleDb
Imports BUS
Imports DTO
Public Class frmLapLich
Dim datasrrc As DataSet
Dim tuyenBindingSource As New BindingSource
Dim tuyenLichLapBindingSource As New BindingSource
Dim tuyenThuLapBindingSource As New BindingSource
Friend WithEvents tuyenNgayKhongLapBindingSource As New BindingSource
Dim tuyenThoiDiemKhongLapBindingSource As New BindingSource
Private Sub LICHLAP_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
LoadData()
BindingData()
End Sub
Private Sub btnThem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThem.Click
Try
If xl_kiemtraThem() = True Then
Dim row As DataRowView = tuyenLichLapBindingSource.AddNew()
row.Row.SetField(1, txtGio.Text + ":" + txtPhut.Text)
End If
Catch ex As Exception
End Try
End Sub
Private Sub btnCapNhat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCapNhat.Click
If (tuyenThuLapBindingSource.Position = -1) Then
Dim row As DataRowView = tuyenThuLapBindingSource.AddNew()
row.Row.SetField("ThuHai", cbxThuHai.Checked)
row.Row.SetField("ThuBa", cbxThuBa.Checked)
row.Row.SetField("ThuTu", cbxThuTu.Checked)
row.Row.SetField("ThuNam", cbxThuNam.Checked)
row.Row.SetField("ThuSau", cbxThuSau.Checked)
row.Row.SetField("ThuBay", cbxThuBay.Checked)
row.Row.SetField("ChuNhat", cbxChuNhat.Checked)
End If
EndEdit()
LichTuyenBus.CapNhatThoiDiemKhoiHanh(datasrrc.Tables(1))
LichTuyenBus.CapNhatThuLap(CType(tuyenThuLapBindingSource.Current, DataRowView).Row)
datasrrc.Tables(2).AcceptChanges()
RefreshBindingCheckBox()
End Sub
Private Sub btnHuy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHuy.Click
CancelEdit()
End Sub
Private Sub btnThemThoiDiem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThemThoiDiem.Click
Try
If xl_kiemtraThemKhongLap() = True Then
If (tuyenNgayKhongLapBindingSource.Position = -1) Then
Return
End If
Dim row As DataRowView = tuyenThoiDiemKhongLapBindingSource.AddNew()
row.Row.SetField("ThoiDiemKhoiHanh", txtGioKhongLap.Text + ":" + txtPhutKhongLap.Text)
Dim dt As DataRowView = tuyenNgayKhongLapBindingSource.Current
row.Row.SetField("MaTuyen", dt.Row.Field(Of Integer)("MaTuyen"))
row.Row.SetField("NgayKhoiHanh", dt.Row.Field(Of Date)("NgayKhoiHanh"))
tuyenThoiDiemKhongLapBindingSource.EndEdit()
End If
Catch ex As Exception
End Try
End Sub
Private Sub btnThemNgay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThemNgay.Click
If xl_kiemtraNgayKhoiHanh() = True Then
Dim row As DataRowView = tuyenNgayKhongLapBindingSource.AddNew()
row.Row.SetField("NgayKhoiHanh", dtpNgayKhoiHanh.Value)
tuyenNgayKhongLapBindingSource.EndEdit()
datasrrc.Tables(3).AcceptChanges()
End If
End Sub
Private Sub btnCapNhatThoiDiem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCapNhatThoiDiem.Click
EndEdit()
LichTuyenBus.CapNhatThoiDiemKhoiHanhKhongLap(datasrrc.Tables(4))
End Sub
Private Sub dgvDanhSachLichLap_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvDanhSachLichLap.CellContentClick
If (dgvDanhSachLichLap.Columns(e.ColumnIndex).Name = "colXoa") Then
tuyenLichLapBindingSource.RemoveAt(e.RowIndex)
End If
End Sub
Private Sub NgayKhoiHanh_PositionChanged(ByVal sender As System.Object, ByVal e As EventArgs) Handles tuyenNgayKhongLapBindingSource.CurrentItemChanged
If (tuyenNgayKhongLapBindingSource.Position = -1) Then
Return
End If
Dim rowView As DataRowView = tuyenNgayKhongLapBindingSource.Current
If (rowView.Row.ItemArray.Length > 3) Then
Return
End If
Dim filter As String = String.Format("NgayKhoiHanh = #{1:MM/dd/yyyy}# AND MaTuyen= {0}", _
rowView.Row.Field(Of Integer)("MaTuyen"), _
rowView.Row.Field(Of Date)("NgayKhoiHanh"))
tuyenThoiDiemKhongLapBindingSource.Filter = filter
datasrrc.Tables(4).DefaultView.RowFilter = ""
End Sub
Sub ClearBindingCheckBox()
cbxThuHai.DataBindings.Clear()
cbxThuBa.DataBindings.Clear()
cbxThuTu.DataBindings.Clear()
cbxThuNam.DataBindings.Clear()
cbxThuSau.DataBindings.Clear()
cbxThuBay.DataBindings.Clear()
cbxChuNhat.DataBindings.Clear()
End Sub
Sub RefreshBindingCheckBox()
ClearBindingCheckBox()
cbxThuHai.DataBindings.Add("Checked", tuyenThuLapBindingSource, "ThuHai")
cbxThuBa.DataBindings.Add("Checked", tuyenThuLapBindingSource, "ThuBa")
cbxThuTu.DataBindings.Add("Checked", tuyenThuLapBindingSource, "ThuTu")
cbxThuNam.DataBindings.Add("Checked", tuyenThuLapBindingSource, "ThuNam")
cbxThuSau.DataBindings.Add("Checked", tuyenThuLapBindingSource, "ThuSau")
cbxThuBay.DataBindings.Add("Checked", tuyenThuLapBindingSource, "ThuBay")
cbxChuNhat.DataBindings.Add("Checked", tuyenThuLapBindingSource, "ChuNhat")
End Sub
Public Sub LoadData()
datasrrc = New DataSet
datasrrc.Tables.Add(TuyenBus.LayDanhSachTuyen())
datasrrc.Tables.Add(LichTuyenBus.LayDanhSachLichTuyen())
datasrrc.Tables.Add(LichTuyenBus.LayDanhSachLichTuyenLapThu())
datasrrc.Tables.Add(LichTuyenBus.LayDanhSachLichTuyenKhongLap())
datasrrc.Tables.Add(LichTuyenBus.LayDanhSachLichTuyenKhongLapThoiDiem())
datasrrc.Tables(0).TableName = "Tuyen"
datasrrc.Tables(1).TableName = "LichLap"
datasrrc.Tables(2).TableName = "ThuLap"
datasrrc.Tables(3).TableName = "TuyenKhongLap"
datasrrc.Tables(4).TableName = "ThoiDiemKhongLap"
tuyenBindingSource.DataSource = datasrrc
tuyenBindingSource.DataMember = "Tuyen"
'Tuyến lập
datasrrc.Relations.Add("TuyenLichLap", datasrrc.Tables(0).Columns("MaTuyen"), datasrrc.Tables(1).Columns("MaTuyen"))
datasrrc.Relations.Add("TuyenThuLap", datasrrc.Tables(0).Columns("MaTuyen"), datasrrc.Tables(2).Columns("MaTuyen"))
tuyenLichLapBindingSource.DataSource = tuyenBindingSource
tuyenLichLapBindingSource.DataMember = "TuyenLichLap"
tuyenThuLapBindingSource.DataSource = tuyenBindingSource
tuyenThuLapBindingSource.DataMember = "TuyenThuLap"
'Tuyến không lập
datasrrc.Relations.Add("TuyenLichKhongLap", datasrrc.Tables(0).Columns("MaTuyen"), datasrrc.Tables(3).Columns("MaTuyen"))
tuyenNgayKhongLapBindingSource.DataSource = tuyenBindingSource
tuyenNgayKhongLapBindingSource.DataMember = "TuyenLichKhongLap"
tuyenThoiDiemKhongLapBindingSource.DataSource = datasrrc
tuyenThoiDiemKhongLapBindingSource.DataMember = "ThoiDiemKhongLap"
End Sub
Public Sub BindingData()
cbxTenTuyen.DataSource = tuyenBindingSource
cbxTenTuyen.DisplayMember = "TenTuyen"
cbxTenTuyen.ValueMember = "MaTuyen"
dgvDanhSachLichLap.DataSource = tuyenLichLapBindingSource
dgvNgayKhoiHanh.DataSource = tuyenNgayKhongLapBindingSource
dgvDanhSachLichKhongLap.DataSource = tuyenThoiDiemKhongLapBindingSource
cbxThuHai.DataBindings.Add("Checked", tuyenThuLapBindingSource, "ThuHai")
cbxThuBa.DataBindings.Add("Checked", tuyenThuLapBindingSource, "ThuBa")
cbxThuTu.DataBindings.Add("Checked", tuyenThuLapBindingSource, "ThuTu")
cbxThuNam.DataBindings.Add("Checked", tuyenThuLapBindingSource, "ThuNam")
cbxThuSau.DataBindings.Add("Checked", tuyenThuLapBindingSource, "ThuSau")
cbxThuBay.DataBindings.Add("Checked", tuyenThuLapBindingSource, "ThuBay")
cbxChuNhat.DataBindings.Add("Checked", tuyenThuLapBindingSource, "ChuNhat")
End Sub
Public Function xl_kiemtraThem() As Boolean
Dim temp As String = txtGio.Text & ":" & txtPhut.Text
If txtGio.Text = "" Or Not IsNumeric(txtGio.Text) Then
txtGio.Focus()
MessageBox.Show("Giờ không hợp lệ!", "Thông báo")
Return False
ElseIf CType(txtGio.Text, Integer) < 0 Or CType(txtGio.Text, Integer) > 24 Then
txtGio.Focus()
MessageBox.Show("24 Giờ không hợp lệ!", "Thông báo")
Return False
ElseIf txtPhut.Text = "" Or Not IsNumeric(txtPhut.Text) Then
txtPhut.Focus()
MessageBox.Show("Phút Không hợp lệ !", "Thông báo")
Return False
ElseIf CType(txtPhut.Text, Integer) < 0 Or CType(txtPhut.Text, Integer) > 60 Then
txtPhut.Focus()
MessageBox.Show("60 phút không hợp lệ!", "Thông báo")
Return False
Else
For i As Integer = 0 To dgvDanhSachLichLap.Rows.Count - 1
If temp = dgvDanhSachLichLap.Rows(i).Cells(2).Value Then
MessageBox.Show("Thời điểm hợp lệ !", "Thông báo")
Return False
End If
Next
End If
Return True
End Function
Public Function xl_kiemtraNgayKhoiHanh() As Boolean
Dim ngayKhoiHanh As Date = dtpNgayKhoiHanh.Value
For i As Integer = 0 To dgvNgayKhoiHanh.Rows.Count - 1
If ngayKhoiHanh = CType(dgvNgayKhoiHanh.Rows(i).Cells(1).Value, Date) Then
MessageBox.Show("Ngày khởi hành không lệ !", "Thông báo")
Return False
End If
Next
Return True
End Function
Public Function xl_kiemtraThemKhongLap() As Boolean
Dim temp As String = txtGioKhongLap.Text & ":" & txtPhutKhongLap.Text
If txtGioKhongLap.Text = "" Or Not IsNumeric(txtGioKhongLap.Text) Then
txtGioKhongLap.Focus()
MessageBox.Show("Giờ không hợp lệ!", "Thông báo")
Return False
ElseIf CType(txtGioKhongLap.Text, Integer) < 0 Or CType(txtGioKhongLap.Text, Integer) > 24 Then
txtGioKhongLap.Focus()
MessageBox.Show("24 Giờ không hợp lệ!", "Thông báo")
Return False
ElseIf txtPhutKhongLap.Text = "" Or Not IsNumeric(txtPhutKhongLap.Text) Then
txtPhutKhongLap.Focus()
MessageBox.Show("Phút Không hợp lệ !", "Thông báo")
Return False
ElseIf CType(txtPhutKhongLap.Text, Integer) < 0 Or CType(txtPhutKhongLap.Text, Integer) > 60 Then
txtPhutKhongLap.Focus()
MessageBox.Show("60 phút không hợp lệ!", "Thông báo")
Return False
Else
For i As Integer = 0 To dgvDanhSachLichKhongLap.Rows.Count - 1
If temp = dgvDanhSachLichKhongLap.Rows(i).Cells(3).Value Then
MessageBox.Show("Thời điểm hợp lệ !", "Thông báo")
Return False
End If
Next
Return True
End If
Return True
End Function
Private Sub EndEdit()
tuyenLichLapBindingSource.EndEdit()
tuyenThuLapBindingSource.EndEdit()
tuyenNgayKhongLapBindingSource.EndEdit()
tuyenThoiDiemKhongLapBindingSource.EndEdit()
End Sub
Private Sub CancelEdit()
tuyenLichLapBindingSource.CancelEdit()
tuyenThuLapBindingSource.CancelEdit()
tuyenNgayKhongLapBindingSource.CancelEdit()
tuyenThoiDiemKhongLapBindingSource.CancelEdit()
End Sub
Private Sub btnHuyThoiDiem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHuyThoiDiem.Click
tuyenThoiDiemKhongLapBindingSource.CancelEdit()
tuyenNgayKhongLapBindingSource.CancelEdit()
End Sub
Private Sub dgvDanhSachLichKhongLap_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvDanhSachLichKhongLap.CellContentClick
If (dgvDanhSachLichKhongLap.Columns(e.ColumnIndex).Name = "colXoaThoiDiem") Then
tuyenThoiDiemKhongLapBindingSource.RemoveAt(e.RowIndex)
End If
End Sub
End Class
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/GiaoDien/frmLapLich.vb | Visual Basic .NET | gpl2 | 13,072 |
Imports System.Data.OleDb
Imports BUS
Imports DTO
Public Class frmTuyenXe
Dim dtTUYEN As DataTable
Dim vtClick As Integer = 0
Private Sub TuyenXe_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
dgvTuyen.DataSource = TuyenBus.LayDanhSachTuyen()
Dim tuyen As TuyenDto = LayTuyenTu_DataGridView(0)
HienThiThongTinTUYEN(tuyen)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Public Function KT_NhapLieu_Them() As String
Dim str As String = ""
If txtMaTuyen.Text <> "" AndAlso Not IsNumeric(txtMaTuyen.Text) Then
str = "Mã tuyến là số!!!"
txtMaTuyen.Focus()
ElseIf txtTenTuyen.Text = "" Then
str = "Tên tuyến không được rỗng!!!"
txtTenTuyen.Focus()
ElseIf txtDiaDiemDi.Text = "" Then
str = "Diem diem di không được rỗng!!!"
txtDiaDiemDi.Focus()
ElseIf txtDiaDiemDen.Text = "" Then
str = "Diem diem den không được rỗng!!!"
txtDiaDiemDen.Focus()
End If
Return str
End Function
Public Function LayTuyenTuTextboxs() As TuyenDto
Dim tuyen As New TuyenDto
If IsNumeric(txtMaTuyen.Text) Then
tuyen.MaTuyenXe = txtMaTuyen.Text
End If
tuyen.TenTuyenXe = txtTenTuyen.Text
tuyen.DiaDiemDi = txtDiaDiemDi.Text
tuyen.DiaDiemDen = txtDiaDiemDen.Text
Return tuyen
End Function
Public Function LayTuyenTu_DataGridView(ByVal vtdong As Integer) As TuyenDto
Dim tuyen As New TuyenDto
tuyen.MaTuyenXe = dgvTuyen.Rows(vtdong).Cells("MaTuyen").Value
tuyen.TenTuyenXe = dgvTuyen.Rows(vtdong).Cells("TenTuyen").Value
tuyen.DiaDiemDi = dgvTuyen.Rows(vtdong).Cells("DiaDiemDi").Value
tuyen.DiaDiemDen = dgvTuyen.Rows(vtdong).Cells("DiaDiemDen").Value
Return tuyen
End Function
Public Sub HienThiThongTinTUYEN(ByVal tuyen As TuyenDto)
txtMaTuyen.Text = tuyen.MaTuyenXe
txtTenTuyen.Text = tuyen.TenTuyenXe
txtDiaDiemDi.Text = tuyen.DiaDiemDi
txtDiaDiemDen.Text = tuyen.DiaDiemDen
End Sub
Public Sub ResetTextboxs()
txtMaTuyen.Text = ""
txtTenTuyen.Text = ""
txtDiaDiemDi.Text = ""
txtDiaDiemDen.Text = ""
End Sub
Private Sub btnTimTuyen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTimTuyen.Click
dgvTuyen.DataSource = TuyenBus.TimTuyen(Me.LayTuyenTuTextboxs())
End Sub
Private Sub btnThemTuyen_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThemTuyen.Click
Dim ktNhapLieu As String = KT_NhapLieu_Them()
If (ktNhapLieu <> "") Then
MessageBox.Show(ktNhapLieu, "THÔNG BÁO")
Exit Sub
End If
Dim kq As Integer = TuyenBus.ThemTuyen(Me.LayTuyenTuTextboxs())
If (kq = 0) Then
MessageBox.Show("Tên tuyến xe đã có trong dữ liệu!!!", "THÔNG BÁO")
Else
dgvTuyen.DataSource = TuyenBus.LayDanhSachTuyen()
dgvTuyen.Rows(0).Selected = False
dgvTuyen.Rows(dgvTuyen.Rows.Count - 2).Selected = True
Dim tuyen As TuyenDto = LayTuyenTu_DataGridView(dgvTuyen.Rows.Count - 2)
HienThiThongTinTUYEN(tuyen)
End If
End Sub
Private Sub btnXoaTuyen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXoaTuyen.Click
If vtClick = dgvTuyen.Rows.Count - 1 Then
MessageBox.Show("Chọn dòng có dữ liệu cần xóa!!!", "THÔNG BÁO")
Exit Sub
End If
Dim ma As Integer = dgvTuyen.Rows(vtClick).Cells("MaTuyen").Value
Dim kq As Integer = TuyenBus.XoaTuyen(ma)
dgvTuyen.DataSource = TuyenBus.LayDanhSachTuyen()
Dim tuyen As TuyenDto = LayTuyenTu_DataGridView(0)
HienThiThongTinTuyen(tuyen)
End Sub
Private Sub btnCapNhaTuyen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCapNhaTuyen.Click
Dim ktNhapLieu As String = KT_NhapLieu_Them()
If (ktNhapLieu <> "") Then
MessageBox.Show(ktNhapLieu, "THÔNG BÁO")
Exit Sub
End If
Dim kq As Integer = TuyenBus.CapNhatTuyen(Me.LayTuyenTuTextboxs())
If (kq = 0) Then
MessageBox.Show("Ten Tuyen đã có trong dữ liệu!!!", "THÔNG BÁO")
Else
dgvTuyen.DataSource = TuyenBus.LayDanhSachTuyen()
dgvTuyen.Rows(0).Selected = False
dgvTuyen.Rows(vtClick).Selected = True
Dim tuyen As TuyenDto = LayTuyenTu_DataGridView(vtClick)
HienThiThongTinTUYEN(tuyen)
End If
End Sub
Private Sub dgvTuyen_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles dgvTuyen.MouseClick
vtClick = dgvTuyen.CurrentRow.Index()
If vtClick = dgvTuyen.Rows.Count - 1 Then
ResetTextboxs()
Exit Sub
End If
Dim tuyen As TuyenDto = LayTuyenTu_DataGridView(vtClick)
HienThiThongTinTUYEN(tuyen)
End Sub
Private Sub btnThoat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThoat.Click
Close()
End Sub
End Class | 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/GiaoDien/frmTuyenXe.vb | Visual Basic .NET | gpl2 | 5,577 |
Imports System
Imports System.Data
Imports System.Data.OleDb
Imports DTO
Imports BUS
Public Class frmLoaiVe
Dim vtclick As Integer
Private Sub frmLoaiVe_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cbxTuyenXe.DataSource = TuyenBus.LayDanhSachTuyen()
cbxTuyenXe.DisplayMember = "TenTuyen"
cbxTuyenXe.ValueMember = "MaTuyen"
dgvLoaiVe.DataSource = LoaiVeBus.LayDanhSachLoaiVe()
End Sub
Public Function LayLoaiVeTuTextboxs() As LoaiVeDto
Dim loaive As New LoaiVeDto
If txtMaLoaiVe.Text <> "" Then
loaive.MaLoai = txtMaLoaiVe.Text
End If
loaive.MaTuyen = cbxTuyenXe.SelectedValue
If txtGiaVe.Text <> "" Then
loaive.GiaVe = txtGiaVe.Text
End If
Return loaive
End Function
Public Function LayLoaiVe_DataGridView(ByVal vtdong As Integer) As LoaiVeDto
Dim loaive As New LoaiVeDto
Try
loaive.MaLoai = dgvLoaiVe.Rows(vtdong).Cells("MaLoaiVe").Value
loaive.MaTuyen = dgvLoaiVe.Rows(vtdong).Cells("MaTuyen").Value
loaive.GiaVe = dgvLoaiVe.Rows(vtdong).Cells("GiaVe").Value
Catch ex As Exception
End Try
Return loaive
End Function
Public Sub HienThiLenTextboxs(ByVal loaive As LoaiVeDto)
txtGiaVe.Text = loaive.GiaVe
txtMaLoaiVe.Text = loaive.MaLoai
cbxTuyenXe.SelectedValue = loaive.MaTuyen
End Sub
Public Sub ResetTextboxs()
txtMaLoaiVe.Text = ""
txtGiaVe.Text = ""
End Sub
Private Sub btnThemLoaiVe_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThemLoaiVe.Click
cbxTuyenXe.Enabled = True
ResetTextboxs()
btnCapNhapThem.Visible = True
btnThemLoaiVe.Visible = False
btnHuy.Enabled = True
btnCapNhatLoaiVe.Enabled = False
btnXoaLoaiVe.Enabled = False
End Sub
Private Sub btnHuy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHuy.Click
cbxTuyenXe.Enabled = False
btnThemLoaiVe.Visible = True
btnCapNhapThem.Visible = True
btnHuy.Enabled = False
btnCapNhatLoaiVe.Enabled = True
btnXoaLoaiVe.Enabled = True
End Sub
Private Sub btnCapNhapThem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCapNhapThem.Click
Dim kq As Integer = LoaiVeBus.ThemLoaiVe(Me.LayLoaiVeTuTextboxs())
If (kq = 0) Then
MessageBox.Show("Mã loại vé đã có trong dữ liệu!!!", "THÔNG BÁO")
Else
dgvLoaiVe.DataSource = LoaiVeBus.LayDanhSachLoaiVe()
dgvLoaiVe.Rows(0).Selected = False
dgvLoaiVe.Rows(dgvLoaiVe.Rows.Count - 2).Selected = True
Dim loaive As LoaiVeDto = LayLoaiVe_DataGridView(dgvLoaiVe.Rows.Count - 2)
HienThiLenTextboxs(loaive)
End If
End Sub
Private Sub dgvLoaiVe_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles dgvLoaiVe.MouseClick
vtclick = dgvLoaiVe.CurrentRow.Index
Dim loaive As LoaiVeDto = LayLoaiVe_DataGridView(vtclick)
HienThiLenTextboxs(loaive)
End Sub
Private Sub btnXoaLoaiVe_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXoaLoaiVe.Click
If vtclick = dgvLoaiVe.Rows.Count - 1 Then
MessageBox.Show("Chọn dòng có dữ liệu cần xóa!!!", "THÔNG BÁO")
Exit Sub
End If
Dim maCanXoa As Integer = dgvLoaiVe.Rows(vtclick).Cells("MaLoaiVe").Value
LoaiVeBus.XoaLoaiVe(maCanXoa)
dgvLoaiVe.DataSource = LoaiVeBus.LayDanhSachLoaiVe()
Dim loaive As LoaiVeDto = LayLoaiVe_DataGridView(0)
HienThiLenTextboxs(loaive)
End Sub
Private Sub btnCapNhatLoaiVe_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCapNhatLoaiVe.Click
Dim loaive As LoaiVeDto = LayLoaiVeTuTextboxs()
LoaiVeBus.CapNhatLoaiVe(loaive)
dgvLoaiVe.DataSource = LoaiVeBus.LayDanhSachLoaiVe()
HienThiLenTextboxs(loaive)
End Sub
Private Sub btnThoat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThoat.Click
Close()
End Sub
End Class | 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/GiaoDien/frmLoaiVe.vb | Visual Basic .NET | gpl2 | 4,476 |
Public Class frmMain
Dim kqDangNhap As Boolean = False
Private Sub KT_DangNhap_DangXuat()
frmDangNhap.ShowDialog()
kqDangNhap = frmDangNhap.kqDangNhap
If kqDangNhap Then
mntChucNang.Enabled = True
mntQuanLy.Enabled = True
ttpDangNhap.Visible = False
ttpDangXuat.Visible = True
Else
'.....
End If
End Sub
Private Sub DangXuat()
mntChucNang.Enabled = False
mntQuanLy.Enabled = False
ttpDangNhap.Visible = True
ttpDangXuat.Visible = False
End Sub
Private Sub ttpDangNhap_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ttpDangNhap.Click
KT_DangNhap_DangXuat()
End Sub
Private Sub ttpDangXuat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ttpDangXuat.Click
DangXuat()
End Sub
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
KT_DangNhap_DangXuat()
End Sub
Private Sub XeToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles XeToolStripMenuItem.Click
frmQuanLyXE.MdiParent = Me
frmQuanLyXE.Show()
End Sub
Private Sub GánXeVàoTuyếnToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GánXeVàoTuyếnToolStripMenuItem.Click
frmGanXe.MdiParent = Me
frmGanXe.Show()
End Sub
Private Sub BánVeToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BánVeToolStripMenuItem.Click
frmBanVe.MdiParent = Me
frmBanVe.Show()
End Sub
Private Sub CậpNhậtGiáVéToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CậpNhậtGiáVéToolStripMenuItem.Click
frmLoaiVe.MdiParent = Me
frmLoaiVe.Show()
End Sub
Private Sub TuyếnXeToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TuyếnXeToolStripMenuItem.Click
frmTuyenXe.MdiParent = Me
frmTuyenXe.Show()
End Sub
Private Sub LịchGánToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LịchGánToolStripMenuItem.Click
frmQuanLyLichGan.MdiParent = Me
frmQuanLyLichGan.Show()
End Sub
Private Sub LặpLịchTuyếnToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
frmLapLich.MdiParent = Me
frmLapLich.Show()
End Sub
Private Sub ThoátToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ThoátToolStripMenuItem.Click
Close()
End Sub
Private Sub ThôngTinCáNhânToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ThôngTinCáNhânToolStripMenuItem1.Click
frmQuanLyNhanVien.MdiParent = Me
frmQuanLyNhanVien.Show()
End Sub
End Class | 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/GiaoDien/frmMain.vb | Visual Basic .NET | gpl2 | 3,144 |
Imports System.Data.OleDb
Imports BUS
Imports DTO
Public Class frmGanXe
Private Sub frmGanXe_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cbxTuyenXe.DataSource = TuyenBus.LayDanhSachTuyen()
cbxTuyenXe.DisplayMember = "TenTuyen"
cbxTuyenXe.ValueMember = "MaTuyen"
' cbxTuyenXe.Text = ""
'cbxNgayKhoiHanh.Text = ""
'cbxNgayKhoiHanh.ValueMember = "NgayKhoiHanh"
' cbxGioKhoiHanh.Text = ""
' cbxGioKhoiHanh.ValueMember = "ThoiDiemKhoiHanh"
End Sub
Private Sub cbxTuyenXe_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbxTuyenXe.SelectedIndexChanged, cbxTuyenXe.TextChanged
cbxNgayKhoiHanh.Text = ""
cbxTuyenXe.ValueMember = "MaTuyen"
Dim maTuyen As Long = cbxTuyenXe.SelectedValue
cbxNgayKhoiHanh.DataSource = XL_Chung.TimNgayKhoiHanh(maTuyen)
cbxNgayKhoiHanh.DisplayMember = "NgayKhoiHanh"
cbxVe.DataSource = LoaiVeBus.LayDanhSachLoaiVeTheoMaTuyen(maTuyen)
cbxVe.DisplayMember = "GiaVe"
cbxVe.ValueMember = "MaLoaiVe"
End Sub
Private Sub cbxNgayKhoiHanh_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbxNgayKhoiHanh.SelectedIndexChanged, cbxNgayKhoiHanh.TextChanged
cbxGioKhoiHanh.Text = ""
cbxTuyenXe.ValueMember = "MaTuyen"
cbxNgayKhoiHanh.ValueMember = "NgayKhoiHanh"
Dim maTuyen As Long = cbxTuyenXe.SelectedValue
Dim ngayKH As Date = cbxNgayKhoiHanh.SelectedValue
cbxGioKhoiHanh.DataSource = XL_Chung.TimThoiDiemKhoiHanh(maTuyen, ngayKH)
cbxGioKhoiHanh.DisplayMember = "ThoiDiemKhoiHanh"
End Sub
Private Sub HienThiDanhSachXeRanh()
cbxNgayKhoiHanh.ValueMember = "NgayKhoiHanh"
Dim NgayKhoiHanh As Date = cbxNgayKhoiHanh.SelectedValue
cbxGioKhoiHanh.ValueMember = "ThoiDiemKhoiHanh"
Dim ThoiDiemKhoiHanh As String = cbxGioKhoiHanh.SelectedValue
dgvDanhSachXeRanh.DataSource = LichGanBus.DanhSachXeDangRanh(NgayKhoiHanh, ThoiDiemKhoiHanh)
End Sub
Private Sub cbxGioKhoiHanh_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbxGioKhoiHanh.SelectedIndexChanged
If cbxGioKhoiHanh.Text <> "" Then
HienThiDanhSachXeRanh()
End If
End Sub
Private Sub btnGanXe_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGanXe.Click
Dim lg As New LichGanDto
cbxTuyenXe.ValueMember = "MaTuyen"
lg.MaTuyen = cbxTuyenXe.SelectedValue
cbxNgayKhoiHanh.ValueMember = "NgayKhoiHanh"
lg.NgayKhoiHanh = cbxNgayKhoiHanh.SelectedValue
cbxGioKhoiHanh.ValueMember = "ThoiDiemKhoiHanh"
lg.ThoiDiemKhoiHanh = cbxGioKhoiHanh.SelectedValue
If cbxTuyenXe.SelectedValue Is Nothing Then
MessageBox.Show("Chọn tuyến!!!", "THÔNG BÁO")
Exit Sub
ElseIf cbxNgayKhoiHanh.SelectedValue Is Nothing Then
MessageBox.Show("Chọn ngày!!!", "THÔNG BÁO")
Exit Sub
ElseIf cbxGioKhoiHanh.SelectedValue Is Nothing Then
MessageBox.Show("Chọn giờ!!!", "THÔNG BÁO")
Exit Sub
End If
Dim vitri As Integer
Try
vitri = dgvDanhSachXeRanh.CurrentRow.Index
If vitri = dgvDanhSachXeRanh.Rows.Count - 1 Then
End If
lg.MaXe = dgvDanhSachXeRanh.Rows(vitri).Cells("MaXe").Value
Catch ex As Exception
MessageBox.Show("Chọn xe cần gán!!!", "THÔNG BÁO")
Exit Sub
End Try
Dim TinhTrangLap = False
If ckbThuHai.Checked = True Or ckbThuBa.Checked = True Or ckbThuTu.Checked = True _
Or ckbThuNam.Checked = True Or ckbThuSau.Checked = True _
Or ckbThuBay.Checked = True Or ckbChuNhat.Checked = True Then
TinhTrangLap = True
End If
'lg.MaNV = MaNhanVien ???
Dim kq As Integer = LichGanBus.ThemLichGan(lg)
If kq <> 0 Then
Dim maLichGanVuaThem As Long = LichGanBus.LayMaLichGanVuaThem()
If TinhTrangLap Then
'Thêm vào bảng lịch gán lặp
Dim lglap As New LichGanLapDto
lglap.MaLichGan = maLichGanVuaThem
lglap.ThuHai = ckbThuHai.Checked
lglap.ThuBa = ckbThuBa.Checked
lglap.ThuTu = ckbThuTu.Checked
lglap.ThuNam = ckbThuNam.Checked
lglap.ThuSau = ckbThuSau.Checked
lglap.ThuBay = ckbThuBay.Checked
lglap.ChuNhat = ckbChuNhat.Checked
LichGanLapBus.ThemMotLichGanLap(lglap)
End If
ckbThuHai.Checked = False
ckbThuBa.Checked = False
ckbThuTu.Checked = False
ckbThuNam.Checked = False
ckbThuSau.Checked = False
ckbThuBay.Checked = False
ckbChuNhat.Checked = False
'Tạo danh sách vé
Dim soChoNgoi As Integer = dgvDanhSachXeRanh.Rows(vitri).Cells("SoChoNgoi").Value
Dim ve As New VeDto
ve.MaLich = maLichGanVuaThem
ve.LoaiVe = cbxVe.SelectedValue
For i As Integer = 1 To soChoNgoi
ve.MaGhe = i
VeBus.ThemVe(ve)
Next
MessageBox.Show("Đã gán xe vào tuyến!!!", "THÔNG BÁO")
HienThiDanhSachXeRanh()
End If
End Sub
Private Sub btnDong_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDong.Click
Close()
End Sub
End Class | 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/GiaoDien/frmGanXe.vb | Visual Basic .NET | gpl2 | 5,927 |
Public Module KT_ThongTinNguoiDung
Dim Loi As String = ""
'Kiểm tra tên đăng nhập có hợp lệ ko
Public Function KT_TenDangNhap(ByVal ten As String) As String
If (ten.Length < 4) Or (ten.Length > 15) Then
Loi = "Tên đăng nhập phải từ 4 - 15 ký số"
Return Loi
Else
If KT_Chuoi(ten) = False Then
Loi = "Các ký tự phải là 0-9, a-z, A-Z"
Return Loi
Else
Dim so As Integer = Convert.ToInt32(ten(0))
If so >= 48 And so <= 57 Then
Loi = "Tên đăng nhập không được bắt đầu là số"
Return Loi
End If
End If
End If
Return Loi
End Function
Public Function KT_MatKhau(ByVal mk As String) As String
Loi = ""
If (mk.Length < 6) Or (mk.Length > 15) Then
Loi = "Mật khẩu phải từ 4 - 15 ký số"
Return Loi
ElseIf KT_Chuoi(mk) = False Then
Loi = "Các ký tự phải là 0-9, a-z, A-Z"
Return Loi
End If
Return Loi
End Function
'Kiểm tra 1 ký tự có nằm trong [0, 9], [a, z], [A, Z]
Public Function KT_KyTu(ByVal c As Char) As Boolean
Dim so As Integer = Convert.ToInt32(c)
Select Case so
Case 48 To 57 'c thuộc [0, 9]
Return True
Case 65 To 92 'c thuộc [A, Z]
Return True
Case 97 To 122 'c thuộc [a, z]
Return True
Case Else
Return False
End Select
'Return False
End Function
'Kiểm tra 1 chuỗi có hợp lệ ko
Public Function KT_Chuoi(ByVal s As String) As Boolean
For i As Integer = 0 To s.Length - 1
If KT_KyTu(s(i)) = False Then
Return False
End If
Next
Return True
End Function
End Module
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/GiaoDien/KT_ThongTinNguoiDung.vb | Visual Basic .NET | gpl2 | 2,075 |
Imports System.Data.OleDb
Imports BUS
Imports DTO
Public Class frmQuanLyXE
Dim dtXE As DataTable
'Dim adapterXE As OleDbDataAdapter
Dim vtClick As Integer = 0
Private Sub QuanLyXE_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Dim kt As String = XL_Chung.KiemTraKetNoi_CSDL_CoDuocKhong()
'If kt <> "" Then
' MessageBox.Show(kt)
'Else
dgvXe.DataSource = XeBus.LayDanhSachXe()
' Try
Dim xe As XeDto = LayXeTu_DataGridView(0)
HienThiThongTinXE(xe)
ResetTextboxs()
'Catch ex As Exception
' End Try
'End If
End Sub
''' <summary>
''' '
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Public Function KT_NhapLieu_Them() As String
Dim str As String = ""
If txtMaXe.Text <> "" AndAlso Not IsNumeric(txtMaXe.Text) Then
str = "Mã xe là số!!!"
txtMaXe.Focus()
ElseIf txtSoXe.Text = "" Then
str = "Số xe không được rỗng!!!"
txtSoXe.Focus()
ElseIf txtHieuXe.Text = "" Then
str = "Hiệu xe không được rỗng!!!"
txtHieuXe.Focus()
ElseIf txtDoiXe.Text = "" Or Not IsNumeric(txtDoiXe.Text) Then
str = "Đời xe không rỗng và phải là số!!!"
txtDoiXe.Focus()
ElseIf txtSoChoNgoi.Text = "" Or Not IsNumeric(txtSoChoNgoi.Text) Then
str = "Số chỗ ngồi không rỗng và phải là số!!!"
txtSoChoNgoi.Focus()
End If
Return str
End Function
Public Function LayXeTuTextboxs() As XeDto
Dim xe As New XeDto
If IsNumeric(txtMaXe.Text) Then
xe.MaXe = txtMaXe.Text
End If
xe.SoXe = txtSoXe.Text
xe.HieuXe = txtHieuXe.Text
If IsNumeric(txtDoiXe.Text) Then
xe.DoiXe = txtDoiXe.Text
End If
If IsNumeric(txtSoChoNgoi.Text) Then
xe.SoChoNgoi = txtSoChoNgoi.Text
End If
Return xe
End Function
Public Function LayXeTu_DataGridView(ByVal vtdong As Integer) As XeDto
Dim xe As New XeDto
Try
xe.MaXe = dgvXe.Rows(vtdong).Cells("MaXe").Value
xe.SoXe = dgvXe.Rows(vtdong).Cells("SoXe").Value
xe.HieuXe = dgvXe.Rows(vtdong).Cells("HieuXe").Value
xe.DoiXe = dgvXe.Rows(vtdong).Cells("DoiXe").Value
xe.SoChoNgoi = dgvXe.Rows(vtdong).Cells("SoChoNgoi").Value
Catch ex As Exception
End Try
Return xe
End Function
Public Sub HienThiThongTinXE(ByVal xe As XeDto)
txtMaXe.Text = xe.MaXe
txtSoXe.Text = xe.SoXe
txtHieuXe.Text = xe.HieuXe
txtDoiXe.Text = xe.DoiXe
txtSoChoNgoi.Text = xe.SoChoNgoi
End Sub
Public Sub ResetTextboxs()
txtMaXe.Text = ""
txtSoXe.Text = ""
txtHieuXe.Text = ""
txtDoiXe.Text = ""
txtSoChoNgoi.Text = ""
End Sub
Private Sub btnTimXe_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTimXe.Click
dgvXe.DataSource = XeBus.TimXe(Me.LayXeTuTextboxs())
End Sub
Private Sub btnThemXe_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThemXe.Click
ResetTextboxs()
btnThemXe.Visible = False
btnCapNhatThem.Visible = True
btnThemXe.Visible = False
btnHuy.Enabled = True
btnCapNhatXe.Enabled = False
btnXoaXe.Enabled = False
End Sub
Private Sub btnHuy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHuy.Click
btnThemXe.Visible = True
btnCapNhatThem.Visible = False
btnHuy.Enabled = False
btnCapNhatXe.Enabled = True
btnXoaXe.Enabled = True
dgvXe.DataSource = XeBus.LayDanhSachXe()
Try
Dim xe As XeDto = LayXeTu_DataGridView(0)
HienThiThongTinXE(xe)
Catch ex As Exception
End Try
End Sub
Private Sub btnCapNhatThem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCapNhatThem.Click
Dim ktNhapLieu As String = KT_NhapLieu_Them()
If (ktNhapLieu <> "") Then
MessageBox.Show(ktNhapLieu, "THÔNG BÁO")
Exit Sub
End If
Dim kq As Integer = XeBus.ThemXe(Me.LayXeTuTextboxs())
If (kq = 0) Then
MessageBox.Show("Số xe đã có trong dữ liệu!!!", "THÔNG BÁO")
Else
dgvXe.DataSource = XeBus.LayDanhSachXe()
dgvXe.Rows(0).Selected = False
dgvXe.Rows(dgvXe.Rows.Count - 2).Selected = True
Dim xe As XeDto = LayXeTu_DataGridView(dgvXe.Rows.Count - 2)
HienThiThongTinXE(xe)
End If
End Sub
Private Sub btnXoaXe_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXoaXe.Click
If vtClick = dgvXe.Rows.Count - 1 Then
MessageBox.Show("Chọn dòng có dữ liệu cần xóa!!!", "THÔNG BÁO")
Exit Sub
End If
Dim ma As Integer = dgvXe.Rows(vtClick).Cells("MaXE").Value
Dim kq As Integer = XeBus.XoaXe(ma)
dgvXe.DataSource = XeBus.LayDanhSachXe()
Dim xe As XeDto = LayXeTu_DataGridView(0)
HienThiThongTinXE(xe)
End Sub
Private Sub btnCapNhatXe_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCapNhatXe.Click
Dim ktNhapLieu As String = KT_NhapLieu_Them()
If (ktNhapLieu <> "") Then
MessageBox.Show(ktNhapLieu, "THÔNG BÁO")
Exit Sub
End If
Dim kq As Integer = XeBus.CapNhatXe(Me.LayXeTuTextboxs())
If (kq = 0) Then
MessageBox.Show("Dữ liệu không thay đổi!!!", "THÔNG BÁO")
Else
dgvXe.DataSource = XeBus.LayDanhSachXe()
dgvXe.Rows(0).Selected = False
dgvXe.Rows(vtClick).Selected = True
Dim xe As XeDto = LayXeTu_DataGridView(vtClick)
HienThiThongTinXE(xe)
End If
End Sub
Private Sub dgvXe_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles dgvXe.MouseClick
' Try
vtClick = dgvXe.CurrentRow.Index()
If vtClick = dgvXe.Rows.Count - 1 Then
ResetTextboxs()
Exit Sub
End If
Dim xe As XeDto = LayXeTu_DataGridView(vtClick)
HienThiThongTinXE(xe)
' Catch ex As Exception
' End Try
End Sub
Private Sub btnThoat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThoat.Click
Close()
End Sub
Private Sub Label5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label5.Click
End Sub
End Class
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/GiaoDien/frmQuanLyXE.vb | Visual Basic .NET | gpl2 | 7,116 |
Imports System
Imports System.Data
Imports System.Data.OleDb
Imports DTO
Imports BUS
Public Class frmQuanLyLichGan
Dim tbIndex As Integer = 0
Dim vitriClick As Integer
Private Sub frmQuanLyLichGan_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dgvLichLap.DataSource = LichGanLapBus.LayDanhSachXeDuocLap()
dgvLichGan.DataSource = LichGanBus.LayDanhSachLichGan()
End Sub
Public Sub HienThi()
Try
vitriClick = dgvLichLap.CurrentRow.Index
Dim maLichGan As Long
maLichGan = dgvLichLap.Rows(vitriClick).Cells("MaLichGan").Value
Dim dt As DataTable = LichGanLapBus.LayLichGanLap(maLichGan)
ckbThuHai.Checked = dt.Rows(0).Item("ThuHai")
ckbThuBa.Checked = dt.Rows(0).Item("ThuBa")
ckbThuTu.Checked = dt.Rows(0).Item("ThuTu")
ckbThuNam.Checked = dt.Rows(0).Item("ThuNam")
ckbThuSau.Checked = dt.Rows(0).Item("ThuSau")
ckbThuBay.Checked = dt.Rows(0).Item("ThuBay")
ckbChuNhat.Checked = dt.Rows(0).Item("ChuNhat")
Catch ex As Exception
ckbThuHai.Checked = False
ckbThuBa.Checked = False
ckbThuTu.Checked = False
ckbThuNam.Checked = False
ckbThuSau.Checked = False
ckbThuBay.Checked = False
ckbChuNhat.Checked = False
Exit Sub
End Try
End Sub
Private Sub dgvLichLap_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles dgvLichLap.MouseClick
HienThi()
End Sub
Private Sub btnCapNhatLichLap_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCapNhatLichLap.Click
Dim lglap As New LichGanLapDto
Dim flag As Boolean = False
lglap.MaLichGan = dgvLichLap.Rows(vitriClick).Cells("MaLichGan").Value
If ckbThuHai.Checked = True Or ckbThuBa.Checked = True Or ckbThuTu.Checked = True _
Or ckbThuNam.Checked = True Or ckbThuSau.Checked = True _
Or ckbThuBay.Checked = True Or ckbChuNhat.Checked = True Then
flag = True
End If
If flag = False Then
If (MessageBox.Show("Sẽ xóa lịch gán nếu không có lặp!", "THÔNG BÁO", MessageBoxButtons.OKCancel) = Windows.Forms.DialogResult.Cancel) Then
Exit Sub
End If
LichGanLapBus.XoaMotLichGanLap(lglap.MaLichGan)
End If
lglap.ThuHai = ckbThuHai.Checked
lglap.ThuBa = ckbThuBa.Checked
lglap.ThuTu = ckbThuTu.Checked
lglap.ThuNam = ckbThuNam.Checked
lglap.ThuSau = ckbThuSau.Checked
lglap.ThuBay = ckbThuBay.Checked
lglap.ChuNhat = ckbChuNhat.Checked
LichGanLapBus.CapNhatMotLichGanLap(lglap)
dgvLichLap.DataSource = LichGanLapBus.LayDanhSachXeDuocLap()
End Sub
Private Sub dgvLichLap_DataSourceChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dgvLichLap.DataSourceChanged
HienThi()
End Sub
Private Sub btnXoaLichLap_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXoaLichLap.Click
If (MessageBox.Show("Bạn thật sự muốn xóa!", "THÔNG BÁO", MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.No) Then
Exit Sub
End If
Dim MaLichGan As Long = dgvLichLap.Rows(vitriClick).Cells("MaLichGan").Value
LichGanLapBus.XoaMotLichGanLap(MaLichGan)
dgvLichLap.DataSource = LichGanLapBus.LayDanhSachXeDuocLap()
HienThi()
End Sub
Private Sub btnXoaLichGan_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXoaLichGan.Click
Try
Dim vt As Integer = dgvLichLap.CurrentRow.Index
Dim MaLichGan As Long = dgvLichGan.Rows(vt).Cells("MaLichGan").Value
LichGanBus.XoaMotLichGan(MaLichGan)
dgvLichGan.DataSource = LichGanBus.LayDanhSachLichGan()
'Xóa trong bảng lặp lặp
LichGanLapBus.XoaMotLichGanLap(MaLichGan)
dgvLichLap.DataSource = LichGanLapBus.LayDanhSachXeDuocLap()
HienThi()
Catch ex As Exception
End Try
End Sub
Private Sub tctrlHienThi_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tctrlHienThi.SelectedIndexChanged
End Sub
Private Sub btnThoat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThoat.Click
Close()
End Sub
End Class | 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/GiaoDien/frmQuanLyLichGan.vb | Visual Basic .NET | gpl2 | 4,778 |
<?xml version="1.0" encoding="utf-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl='urn:schemas-microsoft-com:xslt'>
<xsl:key name="ProjectKey" match="Event" use="@Project" />
<xsl:template match="Events" mode="createProjects">
<projects>
<xsl:for-each select="Event">
<!--xsl:sort select="@Project" order="descending"/-->
<xsl:if test="(1=position()) or (preceding-sibling::*[1]/@Project != @Project)">
<xsl:variable name="ProjectName" select="@Project"/>
<project>
<xsl:attribute name="name">
<xsl:value-of select="@Project"/>
</xsl:attribute>
<xsl:if test="@Project=''">
<xsl:attribute name="solution">
<xsl:value-of select="@Solution"/>
</xsl:attribute>
</xsl:if>
<xsl:for-each select="key('ProjectKey', $ProjectName)">
<!--xsl:sort select="@Source" /-->
<xsl:if test="(1=position()) or (preceding-sibling::*[1]/@Source != @Source)">
<source>
<xsl:attribute name="name">
<xsl:value-of select="@Source"/>
</xsl:attribute>
<xsl:variable name="Source">
<xsl:value-of select="@Source"/>
</xsl:variable>
<xsl:for-each select="key('ProjectKey', $ProjectName)[ @Source = $Source ]">
<event>
<xsl:attribute name="error-level">
<xsl:value-of select="@ErrorLevel"/>
</xsl:attribute>
<xsl:attribute name="description">
<xsl:value-of select="@Description"/>
</xsl:attribute>
</event>
</xsl:for-each>
</source>
</xsl:if>
</xsl:for-each>
</project>
</xsl:if>
</xsl:for-each>
</projects>
</xsl:template>
<xsl:template match="projects">
<xsl:for-each select="project">
<xsl:sort select="@Name" order="ascending"/>
<h2>
<xsl:if test="@solution"><a _locID="Solution">Solution</a>: <xsl:value-of select="@solution"/></xsl:if>
<xsl:if test="not(@solution)"><a _locID="Project">Project</a>: <xsl:value-of select="@name"/>
<xsl:for-each select="source">
<xsl:variable name="Hyperlink" select="@name"/>
<xsl:for-each select="event[@error-level='4']">
 <A class="note"><xsl:attribute name="HREF"><xsl:value-of select="$Hyperlink"/></xsl:attribute><xsl:value-of select="@description"/></A>
</xsl:for-each>
</xsl:for-each>
</xsl:if>
</h2>
<table cellpadding="2" cellspacing="0" width="98%" border="1" bordercolor="white" class="infotable">
<tr>
<td nowrap="1" class="header" _locID="Filename">Filename</td>
<td nowrap="1" class="header" _locID="Status">Status</td>
<td nowrap="1" class="header" _locID="Errors">Errors</td>
<td nowrap="1" class="header" _locID="Warnings">Warnings</td>
</tr>
<xsl:for-each select="source">
<xsl:sort select="@name" order="ascending"/>
<xsl:variable name="source-id" select="generate-id(.)"/>
<xsl:if test="count(event)!=count(event[@error-level='4'])">
<tr class="row">
<td class="content">
<A HREF="javascript:"><xsl:attribute name="onClick">javascript:document.images['<xsl:value-of select="$source-id"/>'].click()</xsl:attribute><IMG border="0" _locID="IMG.alt" _locAttrData="alt" alt="expand/collapse section" class="expandable" height="11" onclick="changepic()" src="_UpgradeReport_Files/UpgradeReport_Plus.gif" width="9" ><xsl:attribute name="name"><xsl:value-of select="$source-id"/></xsl:attribute><xsl:attribute name="child">src<xsl:value-of select="$source-id"/></xsl:attribute></IMG></A> <xsl:value-of select="@name"/>
</td>
<td class="content">
<xsl:if test="count(event[@error-level='3'])=1">
<xsl:for-each select="event[@error-level='3']">
<xsl:if test="@description='Converted'"><a _locID="Converted1">Converted</a></xsl:if>
<xsl:if test="@description!='Converted'"><xsl:value-of select="@description"/></xsl:if>
</xsl:for-each>
</xsl:if>
<xsl:if test="count(event[@error-level='3'])!=1 and count(event[@error-level='3' and @description='Converted'])!=0"><a _locID="Converted2">Converted</a>
</xsl:if>
</td>
<td class="content"><xsl:value-of select="count(event[@error-level='2'])"/></td>
<td class="content"><xsl:value-of select="count(event[@error-level='1'])"/></td>
</tr>
<tr class="collapsed" bgcolor="#ffffff">
<xsl:attribute name="id">src<xsl:value-of select="$source-id"/></xsl:attribute>
<td colspan="7">
<table width="97%" border="1" bordercolor="#dcdcdc" rules="cols" class="issuetable">
<tr>
<td colspan="7" class="issuetitle" _locID="ConversionIssues">Conversion Report - <xsl:value-of select="@name"/>:</td>
</tr>
<xsl:for-each select="event[@error-level!='3']">
<xsl:if test="@error-level!='4'">
<tr>
<td class="issuenone" style="border-bottom:solid 1 lightgray">
<xsl:value-of select="@description"/>
</td>
</tr>
</xsl:if>
</xsl:for-each>
</table>
</td>
</tr>
</xsl:if>
</xsl:for-each>
<tr valign="top">
<td class="foot">
<xsl:if test="count(source)!=1">
<xsl:value-of select="count(source)"/><a _locID="file1"> files</a>
</xsl:if>
<xsl:if test="count(source)=1">
<a _locID="file2">1 file</a>
</xsl:if>
</td>
<td class="foot">
<a _locID="Converted3">Converted</a>: <xsl:value-of select="count(source/event[@error-level='3' and @description='Converted'])"/><BR />
<a _locID="NotConverted">Not converted</a>: <xsl:value-of select="count(source) - count(source/event[@error-level='3' and @description='Converted'])"/>
</td>
<td class="foot"><xsl:value-of select="count(source/event[@error-level='2'])"/></td>
<td class="foot"><xsl:value-of select="count(source/event[@error-level='1'])"/></td>
</tr>
</table>
</xsl:for-each>
</xsl:template>
<xsl:template match="Property">
<xsl:if test="@Name!='Date' and @Name!='Time' and @Name!='LogNumber' and @Name!='Solution'">
<tr><td nowrap="1"><b><xsl:value-of select="@Name"/>: </b><xsl:value-of select="@Value"/></td></tr>
</xsl:if>
</xsl:template>
<xsl:template match="UpgradeLog">
<html>
<head>
<META HTTP-EQUIV="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="_UpgradeReport_Files\UpgradeReport.css" />
<title _locID="ConversionReport0">Conversion Report 
<xsl:if test="Properties/Property[@Name='LogNumber']">
<xsl:value-of select="Properties/Property[@Name='LogNumber']/@Value"/>
</xsl:if>
</title>
<script language="javascript">
function outliner () {
oMe = window.event.srcElement
//get child element
var child = document.all[event.srcElement.getAttribute("child",false)];
//if child element exists, expand or collapse it.
if (null != child)
child.className = child.className == "collapsed" ? "expanded" : "collapsed";
}
function changepic() {
uMe = window.event.srcElement;
var check = uMe.src.toLowerCase();
if (check.lastIndexOf("upgradereport_plus.gif") != -1)
{
uMe.src = "_UpgradeReport_Files/UpgradeReport_Minus.gif"
}
else
{
uMe.src = "_UpgradeReport_Files/UpgradeReport_Plus.gif"
}
}
</script>
</head>
<body topmargin="0" leftmargin="0" rightmargin="0" onclick="outliner();">
<h1 _locID="ConversionReport">Conversion Report - <xsl:value-of select="Properties/Property[@Name='Solution']/@Value"/></h1>
<p><span class="note">
<b _locID="TimeOfConversion">Time of Conversion:</b>  <xsl:value-of select="Properties/Property[@Name='Date']/@Value"/>  <xsl:value-of select="Properties/Property[@Name='Time']/@Value"/><br/>
</span></p>
<xsl:variable name="SortedEvents">
<Events>
<xsl:for-each select="Event">
<xsl:sort select="@Project" order="ascending"/>
<xsl:sort select="@Source" order="ascending"/>
<xsl:sort select="@ErrorLevel" order="ascending"/>
<Event>
<xsl:attribute name="Project"><xsl:value-of select="@Project"/> </xsl:attribute>
<xsl:attribute name="Solution"><xsl:value-of select="/UpgradeLog/Properties/Property[@Name='Solution']/@Value"/> </xsl:attribute>
<xsl:attribute name="Source"><xsl:value-of select="@Source"/> </xsl:attribute>
<xsl:attribute name="ErrorLevel"><xsl:value-of select="@ErrorLevel"/> </xsl:attribute>
<xsl:attribute name="Description"><xsl:value-of select="@Description"/> </xsl:attribute>
</Event>
</xsl:for-each>
</Events>
</xsl:variable>
<xsl:variable name="Projects">
<xsl:apply-templates select="msxsl:node-set($SortedEvents)/*" mode="createProjects"/>
</xsl:variable>
<xsl:apply-templates select="msxsl:node-set($Projects)/*"/>
<p></p><p>
<table class="note">
<tr>
<td nowrap="1">
<b _locID="ConversionSettings">Conversion Settings</b>
</td>
</tr>
<xsl:apply-templates select="Properties"/>
</table></p>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/_UpgradeReport_Files/UpgradeReport.xslt | XSLT | gpl2 | 12,579 |
BODY
{
BACKGROUND-COLOR: white;
FONT-FAMILY: "Verdana", sans-serif;
FONT-SIZE: 100%;
MARGIN-LEFT: 0px;
MARGIN-TOP: 0px
}
P
{
FONT-FAMILY: "Verdana", sans-serif;
FONT-SIZE: 70%;
LINE-HEIGHT: 12pt;
MARGIN-BOTTOM: 0px;
MARGIN-LEFT: 10px;
MARGIN-TOP: 10px
}
.note
{
BACKGROUND-COLOR: #ffffff;
COLOR: #336699;
FONT-FAMILY: "Verdana", sans-serif;
FONT-SIZE: 100%;
MARGIN-BOTTOM: 0px;
MARGIN-LEFT: 0px;
MARGIN-TOP: 0px;
PADDING-RIGHT: 10px
}
.infotable
{
BACKGROUND-COLOR: #f0f0e0;
BORDER-BOTTOM: #ffffff 0px solid;
BORDER-COLLAPSE: collapse;
BORDER-LEFT: #ffffff 0px solid;
BORDER-RIGHT: #ffffff 0px solid;
BORDER-TOP: #ffffff 0px solid;
FONT-SIZE: 70%;
MARGIN-LEFT: 10px
}
.issuetable
{
BACKGROUND-COLOR: #ffffe8;
BORDER-COLLAPSE: collapse;
COLOR: #000000;
FONT-SIZE: 100%;
MARGIN-BOTTOM: 10px;
MARGIN-LEFT: 13px;
MARGIN-TOP: 0px
}
.issuetitle
{
BACKGROUND-COLOR: #ffffff;
BORDER-BOTTOM: #dcdcdc 1px solid;
BORDER-TOP: #dcdcdc 1px;
COLOR: #003366;
FONT-WEIGHT: normal
}
.header
{
BACKGROUND-COLOR: #cecf9c;
BORDER-BOTTOM: #ffffff 1px solid;
BORDER-LEFT: #ffffff 1px solid;
BORDER-RIGHT: #ffffff 1px solid;
BORDER-TOP: #ffffff 1px solid;
COLOR: #000000;
FONT-WEIGHT: bold
}
.issuehdr
{
BACKGROUND-COLOR: #E0EBF5;
BORDER-BOTTOM: #dcdcdc 1px solid;
BORDER-TOP: #dcdcdc 1px solid;
COLOR: #000000;
FONT-WEIGHT: normal
}
.issuenone
{
BACKGROUND-COLOR: #ffffff;
BORDER-BOTTOM: 0px;
BORDER-LEFT: 0px;
BORDER-RIGHT: 0px;
BORDER-TOP: 0px;
COLOR: #000000;
FONT-WEIGHT: normal
}
.content
{
BACKGROUND-COLOR: #e7e7ce;
BORDER-BOTTOM: #ffffff 1px solid;
BORDER-LEFT: #ffffff 1px solid;
BORDER-RIGHT: #ffffff 1px solid;
BORDER-TOP: #ffffff 1px solid;
PADDING-LEFT: 3px
}
.issuecontent
{
BACKGROUND-COLOR: #ffffff;
BORDER-BOTTOM: #dcdcdc 1px solid;
BORDER-TOP: #dcdcdc 1px solid;
PADDING-LEFT: 3px
}
A:link
{
COLOR: #cc6633;
TEXT-DECORATION: underline
}
A:visited
{
COLOR: #cc6633;
}
A:active
{
COLOR: #cc6633;
}
A:hover
{
COLOR: #cc3300;
TEXT-DECORATION: underline
}
H1
{
BACKGROUND-COLOR: #003366;
BORDER-BOTTOM: #336699 6px solid;
COLOR: #ffffff;
FONT-SIZE: 130%;
FONT-WEIGHT: normal;
MARGIN: 0em 0em 0em -20px;
PADDING-BOTTOM: 8px;
PADDING-LEFT: 30px;
PADDING-TOP: 16px
}
H2
{
COLOR: #000000;
FONT-SIZE: 80%;
FONT-WEIGHT: bold;
MARGIN-BOTTOM: 3px;
MARGIN-LEFT: 10px;
MARGIN-TOP: 20px;
PADDING-LEFT: 0px
}
H3
{
COLOR: #000000;
FONT-SIZE: 80%;
FONT-WEIGHT: bold;
MARGIN-BOTTOM: -5px;
MARGIN-LEFT: 10px;
MARGIN-TOP: 20px
}
H4
{
COLOR: #000000;
FONT-SIZE: 70%;
FONT-WEIGHT: bold;
MARGIN-BOTTOM: 0px;
MARGIN-TOP: 15px;
PADDING-BOTTOM: 0px
}
UL
{
COLOR: #000000;
FONT-SIZE: 70%;
LIST-STYLE: square;
MARGIN-BOTTOM: 0pt;
MARGIN-TOP: 0pt
}
OL
{
COLOR: #000000;
FONT-SIZE: 70%;
LIST-STYLE: square;
MARGIN-BOTTOM: 0pt;
MARGIN-TOP: 0pt
}
LI
{
LIST-STYLE: square;
MARGIN-LEFT: 0px
}
.expandable
{
CURSOR: hand
}
.expanded
{
color: black
}
.collapsed
{
DISPLAY: none
}
.foot
{
BACKGROUND-COLOR: #ffffff;
BORDER-BOTTOM: #cecf9c 1px solid;
BORDER-TOP: #cecf9c 2px solid
}
.settings
{
MARGIN-LEFT: 25PX;
}
.help
{
TEXT-ALIGN: right;
margin-right: 10px;
}
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/_UpgradeReport_Files/UpgradeReport.css | CSS | gpl2 | 3,348 |
Imports System.Data
Imports System.Data.OleDb
Imports DTO
Public Class TuyenDao
Dim provider As New DataProvider
Public Function LayDanhSachTuyen() As DataTable
Dim sql As String = "SELECT * FROM TuyenXe"
Dim dtTUYENXE As DataTable
dtTUYENXE = provider.ThucThiCauTruyVan(sql)
Return dtTUYENXE
End Function
Public Function TimTuyen(ByVal tuyen As TuyenDto) As DataTable
Dim sql As String = "SELECT * FROM TuyenXe WHERE 1"
'If tuyen.MaTuyenXe <> 0 Then
' sql += " and MaTuyen =" & tuyen.MaTuyenXe & " "
'End If
If tuyen.TenTuyenXe <> "" Then
sql += " and TenTuyen = '" & tuyen.TenTuyenXe & "' "
End If
If tuyen.DiaDiemDi <> "" Then
sql += " and DiaDiemDi = '" & tuyen.DiaDiemDi & "' "
End If
If tuyen.DiaDiemDen <> "" Then
sql += " and DiaDiemDen = '" & tuyen.DiaDiemDen & "' "
End If
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function TimTuyenTheoMaTuyen(ByVal maTuyen As Integer) As DataTable
Dim sql As String = "SELECT * FROM TuyenXe WHERE MaTuyen = " & maTuyen
Dim dtTUYEN As DataTable
dtTUYEN = provider.ThucThiCauTruyVan(sql)
Return dtTUYEN
End Function
Public Function ThemTuyen(ByVal tuyen As TuyenDto) As Integer
Dim sql As String = "INSERT INTO TuyenXe(TenTuyen, DiaDiemDi, DiaDiemDen) VALUES (?, ? ,?)"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@TenTuyen", tuyen.TenTuyenXe))
dsParameter.Add(New OleDbParameter("@DiaDiemDi", tuyen.DiaDiemDi))
dsParameter.Add(New OleDbParameter("@DiaDiemDen", tuyen.DiaDiemDen))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function CapNhatTuyen(ByVal tuyen As TuyenDto) As Integer
Dim sql As String = "UPDATE TuyenXe SET TenTuyen = ?, DiaDiemDi = ?, DiaDiemDen = ? WHERE MaTuyen = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@TenTuyen", tuyen.TenTuyenXe))
dsParameter.Add(New OleDbParameter("@DiaDiemDi", tuyen.DiaDiemDi))
dsParameter.Add(New OleDbParameter("@DiaDiemDen", tuyen.DiaDiemDen))
dsParameter.Add(New OleDbParameter("@MaTuyenXe", tuyen.MaTuyenXe))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function XoaTuyen(ByVal maCanXoa As Long) As Integer
Dim sql As String = "DELETE FROM TuyenXe WHERE MaTuyen = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaTuyen", maCanXoa))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function CapNhatXuongCSDL(ByVal tenBang As String, ByVal dt As DataTable) As Integer
Return provider.CapNhatXuongCSDL(tenBang, dt)
End Function
End Class
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/DAO/TuyenDao.vb | Visual Basic .NET | gpl2 | 3,049 |
Imports System.Data
Imports System.Data.OleDb
Imports DTO
Public Class NhanVienDao
Dim provider As New DataProvider
Public Function LayNguoiDangNhap(ByVal tenDangNhap As String, ByVal matKhau As String) As Integer
Dim sql As String = "SELECT count(*) FROM NhanVien WHERE TenDangNhap = '" & tenDangNhap & "' AND MatKhau = '" & matKhau & "'"
Dim row As Integer = provider.ThucThiCauTruyVan(sql).Rows.Count
Try
If row > 0 Then
sql = "SELECT LoaiNhanVien FROM NhanVien Where TenDangNhap = '" & tenDangNhap & "' and MatKhau = '" & matKhau & "'"
Dim loaiND As Integer = provider.ThucThiCauTruyVan(sql).Rows(0).Item(0)
If loaiND = 1 Then
Return 1
Else
Return 0
End If
End If
Catch ex As Exception
Return -1
End Try
End Function
Public Function LayNguoiDung(ByVal tenDangNhap As String, ByVal matKhau As String) As DataTable
Dim sql As String = "SELECT MaNhanVien, LoaiNhanVien FROM NhanVien WHERE TenDangNhap = '" & tenDangNhap & "' AND MatKhau = '" & matKhau & "'"
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function LayNguoiDungTheoMa(ByVal maNhanVien As Long) As DataTable
Dim sql As String = "SELECT * FROM NhanVien WHERE MaNhanVien = " & maNhanVien
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function LayQuyen() As DataTable
Dim sql As String = "SELECT pc.MaNhanVien,nv.TenDangNhap,pc.MaQuyen FROM NhanVien nv,PhanQuyen pc"
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function LayNguoiDung() As DataTable
Dim sql As String = "SELECT * FROM Quyen"
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function LayDanhSachNguoiDung() As DataTable
Dim sql As String = "SELECT MaNhanVien,MatKhau,TenDangNhap,HoTen,NgaySinh,IIF(Phai=1,'Nữ','Nam') AS Phai,DiaChi,DienThoai,loaiNhanVien FROM NhanVien "
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function ThemNhanVien(ByVal nhanVien As NhanVienDto) As Integer
Dim sql As String = "insert into NhanVien (TenDangNhap,MatKhau,HoTen,NgaySinh,Phai,DiaChi,DienThoai,LoaiNhanVien) values (?,?,?,?,?,?,?,?)"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@TenDangNhap", nhanVien.TenDangNhap))
dsParameter.Add(New OleDbParameter("@MatKhau", nhanVien.MatKhau))
dsParameter.Add(New OleDbParameter("@HoTen", nhanVien.HoTen))
dsParameter.Add(New OleDbParameter("@NgaySinh", nhanVien.NgaySinh))
dsParameter.Add(New OleDbParameter("@Phai", nhanVien.GioiTinh))
dsParameter.Add(New OleDbParameter("@DiaChi", nhanVien.DiaChi))
dsParameter.Add(New OleDbParameter("@DienThoai", nhanVien.DienThoai))
dsParameter.Add(New OleDbParameter("@LoaiNhanVien", nhanVien.LoaiNhanVien))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function CapNhatNhanVien(ByVal nhanVien As NhanVienDto) As Integer
Dim sql As String = "UPDATE NhanVien SET TenDangNhap = ?, MatKhau = ?, HoTen = ?, NgaySinh = ?, Phai = ?, DiaChi = ?,DienThoai = ?, LoaiNhanVien = ? WHERE MaNhanVien = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@TenDangNhap", nhanVien.TenDangNhap))
dsParameter.Add(New OleDbParameter("@MatKhau", nhanVien.MatKhau))
dsParameter.Add(New OleDbParameter("@HoTen", nhanVien.HoTen))
dsParameter.Add(New OleDbParameter("@NgaySinh", nhanVien.NgaySinh))
dsParameter.Add(New OleDbParameter("@Phai", nhanVien.GioiTinh))
dsParameter.Add(New OleDbParameter("@DiaChi", nhanVien.DiaChi))
dsParameter.Add(New OleDbParameter("@DienThoai", nhanVien.DienThoai))
dsParameter.Add(New OleDbParameter("@LoaiNhanVien", nhanVien.LoaiNhanVien))
dsParameter.Add(New OleDbParameter("@MaNhanVien", nhanVien.MaNhanVien))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function TimKiemNhanVien(ByVal nhanVien As NhanVienDto) As DataTable
Dim sql As String = "select MaNhanVien,MatKhau,TenDangNhap,HoTen,NgaySinh,IIF(Phai=1,'Nữ','Nam') AS Phai,DiaChi,DienThoai,loaiNhanVien from NHANVIEN where 1"
If nhanVien.TenDangNhap <> "" Then
sql += " and TenDangNhap LIKE '%" & nhanVien.TenDangNhap & "%'"
End If
If nhanVien.HoTen <> "" Then
sql += " and HoTen LIKE '%" & nhanVien.HoTen & "%'"
End If
If nhanVien.DienThoai <> "" Then
sql += " and DienThoai LIKE '%" & nhanVien.DienThoai & "%'"
End If
If nhanVien.GioiTinh = 1 Then
sql += " and Phai = " & nhanVien.GioiTinh & ""
End If
If nhanVien.GioiTinh = 0 Then
sql += " and Phai = " & nhanVien.GioiTinh & ""
End If
If nhanVien.LoaiNhanVien = 1 Then
sql += " and LoaiNhanVien = " & nhanVien.LoaiNhanVien & ""
End If
If nhanVien.LoaiNhanVien = 0 Then
sql += " and LoaiNhanVien = " & nhanVien.LoaiNhanVien & ""
End If
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function XoaNhanVien(ByVal nhanVien As NhanVienDto) As String
Dim str As String = ""
Try
Dim con As OleDbConnection = provider.Connect()
Dim sql As String = "delete from NHANVIEN where MaNhanVien = " & nhanVien.MaNhanVien.ToString()
Dim cmd As OleDbCommand = New OleDbCommand(sql, con)
cmd.Parameters.Add("@MaNhanVien", OleDbType.Integer)
cmd.Parameters("@MaNhanVien").Value = nhanVien.MaNhanVien
cmd.ExecuteNonQuery()
con.Close()
Catch ex As Exception
str = ex.Message
End Try
Return str
End Function
End Class
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/DAO/NhanVienDao.vb | Visual Basic .NET | gpl2 | 6,156 |
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("DAO")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("DAO")>
<Assembly: AssemblyCopyright("Copyright © 2010")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("1a0f8d74-0b1e-4319-8f9e-0a29d05cb470")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/DAO/My Project/AssemblyInfo.vb | Visual Basic .NET | gpl2 | 1,159 |
Imports System.Data
Imports System.Data.OleDb
Imports DAO
Imports DTO
Public Class XL_Chung_dao
Dim provider As New DataProvider
'................
'Tìm ngày khởi hành
Public Function TimNgayKhoiHanh(ByVal maTuyen As Integer) As DataTable
Dim sql As String = "SELECT NgayKhoiHanh FROM LICHTUYENKHONGLAP WHERE MaTuyen = " & maTuyen
sql += " Group by NgayKhoiHanh"
Return provider.ThucThiCauTruyVan(sql)
End Function
'Tìm giờ khởi hành
Public Function TimThoiDiemKhoiHanh(ByVal maTuyen As Integer, ByVal ngayKhoiHanh As Date) As DataTable
Dim sql As String = "SELECT ThoiDiemKhoiHanh FROM LICHTUYENKHONGLAP WHERE MaTuyen = ? and NgayKhoiHanh = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaTuyen", maTuyen))
dsParameter.Add(New OleDbParameter("@NgayKhoiHanh", ngayKhoiHanh))
Return provider.ThucThiCauTruyVan(sql, dsParameter)
End Function
End Class
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/DAO/XL_Chung_dao.vb | Visual Basic .NET | gpl2 | 1,034 |
Imports System.Data
Imports System.Data.OleDb
Imports DTO
Public Class LichGanDao
Dim provider As New DataProvider
Public Function LayDanhSachLichGan() As DataTable
Dim sql As String = "SELECT * FROM LichGan"
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function TimLichGanTheoMa(ByVal maCanTim As Integer) As DataTable
Dim sql As String = "SELECT * FROM LichGan WHERE MaLichGan = " & maCanTim
Return provider.ThucThiCauTruyVan(sql)
End Function
'Tìm lịch gán theo mã tuyến, ngày khởi hành, thời điểm và xe
Public Function TimLichGan(ByVal maTuyen As Long, ByVal ngayKhoiHanh As Date, ByVal thoiDiemKhoiHanh As String, ByVal maXe As Long) As DataTable
Dim sql As String = "SELECT * FROM LichGan WHERE MaTuyen = ? and NgayKhoiHanh = ? and ThoiDiemKhoiHanh = ? and MaXe = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaTuyen", maTuyen))
dsParameter.Add(New OleDbParameter("@NgayKhoiHanh", ngayKhoiHanh))
dsParameter.Add(New OleDbParameter("@ThoiDiemKhoiHanh", thoiDiemKhoiHanh))
dsParameter.Add(New OleDbParameter("@MaXe", maXe))
Return provider.ThucThiCauTruyVan(sql, dsParameter)
End Function
Public Function ThemMotLichGan(ByVal lg As LichGanDto) As Integer
Dim sql As String = "INSERT INTO LichGan( MaTuyen, ThoiDiemKhoiHanh, NgayKhoiHanh, MaXe, MaNhanVien) VALUES ( ?, ?, ?, ?, ?)"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaTuyen", lg.MaTuyen))
dsParameter.Add(New OleDbParameter("@ThoiDiemKhoiHanh", lg.ThoiDiemKhoiHanh))
dsParameter.Add(New OleDbParameter("@NgayKhoiHanh", lg.NgayKhoiHanh))
dsParameter.Add(New OleDbParameter("@MaXe", lg.MaXe))
dsParameter.Add(New OleDbParameter("@MaNhanVien", lg.MaNhanVien))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function CapNhatLichGan(ByVal lg As LichGanDto) As Integer
Dim sql As String = "UPDATE LichGan SET MaLichGan = ?, MaTuyen = ?, ThoiDiemKhoiHanh = ?, NgayKhoiHanh = ?, MaXe = ?, MaLap = ? WHERE MaLichGan = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaTuyen", lg.MaTuyen))
dsParameter.Add(New OleDbParameter("@ThoiDiemKhoiHanh", lg.ThoiDiemKhoiHanh))
dsParameter.Add(New OleDbParameter("@NgayKhoiHanh", lg.NgayKhoiHanh))
dsParameter.Add(New OleDbParameter("@MaXe", lg.MaXe))
dsParameter.Add(New OleDbParameter("@MaNhanVien", lg.MaNhanVien))
dsParameter.Add(New OleDbParameter("@MaLichGan", lg.MaLichGan))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function XoaMotLichGan(ByVal maCanXoa As Long) As Integer
Dim sql As String = "DELETE FROM LichGan WHERE MaLichGan = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaLichGan", maCanXoa))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
'Tìm ngày khởi hành
Public Function TimNgayKhoiHanh(ByVal maTuyen As Integer) As DataTable
Dim sql As String = "SELECT NgayKhoiHanh FROM LichGan WHERE MaTuyen = " & maTuyen
sql += " Group by NgayKhoiHanh Order by NgayKhoiHanh"
Return provider.ThucThiCauTruyVan(sql)
End Function
'Tìm giờ khởi hành
Public Function TimThoiDiemKhoiHanh(ByVal maTuyen As Integer, ByVal ngayKhoiHanh As Date) As DataTable
Dim sql As String = "SELECT ThoiDiemKhoiHanh FROM LichGan WHERE MaTuyen = ? and NgayKhoiHanh = ?"
sql += " Group by ThoiDiemKhoiHanh Order by ThoiDiemKhoiHanh"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaTuyen", maTuyen))
dsParameter.Add(New OleDbParameter("@NgayKhoiHanh", ngayKhoiHanh))
Return provider.ThucThiCauTruyVan(sql, dsParameter)
End Function
'Tìm xe đang rảnh theo ngày và thời điểm khởi hành
Public Function DanhSachXeDangRanh(ByVal ngayKhoiHanh As Date, ByVal ThoiDiemKhoiHanh As String) As DataTable
Dim sql As String = "Select * From XE Where MaXe not in("
sql += " Select lg.MaXe From LichGan lg Where lg.NgayKhoiHanh = ? and lg.ThoiDiemKhoiHanh = ? )"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@NgayKhoiHanh", ngayKhoiHanh))
dsParameter.Add(New OleDbParameter("@ThoiDiemKhoiHanh", ThoiDiemKhoiHanh))
Return provider.ThucThiCauTruyVan(sql, dsParameter)
End Function
'Lấy mã lịch gán vừa thêm vào
Public Function LayMaLichGanVuaThem() As Long
Dim sql As String = "Select max(MaLichGan)as MaLichGan From LichGan"
Dim dt As DataTable = provider.ThucThiCauTruyVan(sql)
Return dt.Rows(0).Item(0)
End Function
'Bán vé...
'Tìm xe theo tuyến, thời điểm
Public Function DanhSachXe_TheoTuyen_ThoiDiem(ByVal maTuyen As Long, ByVal ngayKhoiHanh As Date, ByVal ThoiDiemKhoiHanh As String) As DataTable
Dim sql As String = "SELECT x.MaXe, x.SoXe, x.SoChoNgoi FROM XE x, LichGan lg"
sql += " WHERE lg.MaXe = x.MaXe and lg.MaTuyen = ? and lg.NgayKhoiHanh = ? and lg.ThoiDiemKhoiHanh = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaTuyen", maTuyen))
dsParameter.Add(New OleDbParameter("@NgayKhoiHanh", ngayKhoiHanh))
dsParameter.Add(New OleDbParameter("@ThoiDiemKhoiHanh", ThoiDiemKhoiHanh))
Return provider.ThucThiCauTruyVan(sql, dsParameter)
End Function
End Class
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/DAO/LichGanDao.vb | Visual Basic .NET | gpl2 | 5,899 |
Imports System.Data
Imports System.Data.OleDb
Imports DTO
Public Class XeDao
Dim provider As New DataProvider
Public Function LayDanhSachXe() As DataTable
Dim sql As String = "SELECT * FROM Xe"
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function TimXe(ByVal xe As XeDto) As DataTable
Dim sql As String = "SELECT * FROM Xe WHERE 1 "
'If xe.MaXe <> 0 Then
' sql += " and MaXe =" & xe.MaXe
'End If
If xe.SoXe <> "" Then
sql += " and SoXe like '" & xe.SoXe & "%' "
End If
If xe.HieuXe <> "" Then
sql += " and HieuXe like'" & xe.HieuXe & "%' "
End If
If xe.DoiXe <> 0 Then
sql += " and DoiXe =" & xe.DoiXe
End If
If xe.SoChoNgoi <> 0 Then
sql += " and SoChoNgoi = " & xe.SoChoNgoi
End If
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function TimXeTheoMaXe(ByVal maXe As Integer) As DataTable
Dim sql As String = "SELECT * FROM Xe WHERE MaXe = " & maXe
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function LaySoChoNgoi_TheoMaXe(ByVal maXe As Integer) As Integer
Dim soChoNgoi As Integer = 0
Dim dt As DataTable = TimXeTheoMaXe(maXe)
If dt.Rows.Count > 0 Then
soChoNgoi = dt.Rows(0).Item("SoChoNgoi")
End If
Return soChoNgoi
End Function
Public Function ThemXe(ByVal xe As XeDto) As Integer
Dim sql As String = "INSERT INTO XE(SoXe, HieuXe, DoiXe, SoChoNgoi) VALUES (?, ?, ?, ?)"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@SoXe", xe.SoXe))
dsParameter.Add(New OleDbParameter("@HieuXe", xe.HieuXe))
dsParameter.Add(New OleDbParameter("@DoiXe", xe.DoiXe))
dsParameter.Add(New OleDbParameter("@SoChoNgoi", xe.SoChoNgoi))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function CapNhatXe(ByVal xe As XeDto) As Integer
Dim sql As String = "UPDATE XE SET SoXe = ?, HieuXe = ?, DoiXe = ?, SoChoNgoi = ? WHERE MaXe = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@SoXe", xe.SoXe))
dsParameter.Add(New OleDbParameter("@HieuXe", xe.HieuXe))
dsParameter.Add(New OleDbParameter("@DoiXe", xe.DoiXe))
dsParameter.Add(New OleDbParameter("@SoChoNgoi", xe.SoChoNgoi))
dsParameter.Add(New OleDbParameter("@MaXe", xe.MaXe))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function XoaXe(ByVal maCanXoa As Long) As Integer
Dim sql As String = "DELETE FROM XE WHERE MaXe = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaXe", maCanXoa))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
End Class
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/DAO/XeDao.vb | Visual Basic .NET | gpl2 | 3,076 |
Public Class CHUNG
Dim provider As New DataProvider
Public Function LayDanhSach() As DataTable
Dim sql As String = "SELECT tx.TenTuyen,td.thoidiemkhoihanh,td.ngaykhoihanh,td.malap,ll.thulap,td.manhanvien FROM TuyenXe tx, ThoiDiem_KhoiHanh td, LichLap ll "
sql += "where tx.matuyen = td.matuyen and ll.malap = td.maLap"
Dim dtBang As DataTable
dtBang = provider.ThucThiCauTruyVan(sql)
Return dtBang
End Function
End Class
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/DAO/ChungDao.vb | Visual Basic .NET | gpl2 | 492 |
Imports System.Data
Imports System.Data.OleDb
Imports DTO
Public Class LichKhoiHanhDao
Dim provider As New DataProvider
Public Function LayDanhSachLichLap() As DataTable
Dim sql As String = "SELECT * FROM LichLap"
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function TimLichLap(ByVal lichLap As LichKhoiHanhDto) As DataTable
Dim sql As String = "SELECT * FROM LichLap WHERE 1"
If lichLap.MaLap <> 0 Then
sql += " and MaLap =" & lichLap.MaLap & " "
End If
If lichLap.ThuLap <> "" Then
sql += " and ThuLap = '" & lichLap.ThuLap & "' "
End If
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function TimTuyenTheoMaLap(ByVal maLap As Integer) As DataTable
Dim sql As String = "SELECT * FROM LichLap WHERE maLap = " & maLap
Dim dtLichLap As DataTable
dtLichLap = provider.ThucThiCauTruyVan(sql)
Return dtLichLap
End Function
Public Function ThemLichLap(ByVal lichLap As LichKhoiHanhDto) As Integer
Dim sql As String = "INSERT INTO LichLap(ThuLap) VALUES (?)"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@ThuLap", lichLap.ThuLap))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function CapNhatLichLap(ByVal lichLap As LichKhoiHanhDto) As Integer
Dim sql As String = "UPDATE LichLap SET ThuLap = ? WHERE MaLap = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@ThuLap", lichLap.ThuLap))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function XoaLichLap(ByVal maLap As Long) As Integer
Dim sql As String = "DELETE FROM LichLap WHERE MaLap = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaLap", maLap))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function CapNhatXuongCSDL(ByVal tenBang As String, ByVal dt As DataTable) As Integer
Return provider.CapNhatXuongCSDL(tenBang, dt)
End Function
End Class
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/DAO/LichKhoiHanhDao.vb | Visual Basic .NET | gpl2 | 2,294 |
Imports System.Data
Imports System.Data.OleDb
Imports DTO
Public Class LichTuyenLapDao
Dim provider As New DataProvider
Public Function LayDanhSachLichTuyenLap() As DataTable
Dim sql As String = "SELECT matuyen ,thoidiemkhoihanh FROM LichTuyenLap "
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function LayDanhSachLichTuyenLapThu() As DataTable
Dim sql As String = "SELECT DISTINCT maTuyen,thuhai,thuba,thutu,thunam,thusau,thubay,chunhat FROM LichTuyenLap "
Return provider.ThucThiCauTruyVan(sql)
End Function
'Public Function LayDanhSachLichTuyenLapThu(ByVal maTuyen As Integer) As DataTable
' Dim sql As String = "SELECT thuhai,thuba,thutu,thunam,thusau,thubay,chunhat FROM LichTuyenLap where matuyen = " & maTuyen
' Return provider.ThucThiCauTruyVan(sql)
'End Function
Public Function ThemThoiDiemKhoiHanh(ByVal thoiDiem As LichTuyenDto) As Integer
Dim sql As String = "INSERT INTO LichTuyenLap(MaTuyen,ThoiDiemKhoiHanh,ThuHai,ThuBa,ThuTu,ThuNam,ThuSau,ThuBay,ChuNhat,MaNhanVien) VALUES(?,?,?,?,?,?,?,?,?,?)"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaTuyen", thoiDiem.MaTuyen))
dsParameter.Add(New OleDbParameter("@ThoiDiemKhoiHanh", thoiDiem.ThoiDiemKhoiHanh))
dsParameter.Add(New OleDbParameter("@ThuHai", thoiDiem.ThuHai))
dsParameter.Add(New OleDbParameter("@ThuBa", thoiDiem.ThuBa))
dsParameter.Add(New OleDbParameter("@ThuTu", thoiDiem.ThuTu))
dsParameter.Add(New OleDbParameter("@ThuNam", thoiDiem.ThuNam))
dsParameter.Add(New OleDbParameter("@ThuSau", thoiDiem.ThuSau))
dsParameter.Add(New OleDbParameter("@ThuBay", thoiDiem.ThuBay))
dsParameter.Add(New OleDbParameter("@ChuNhat", thoiDiem.ChuNhat))
dsParameter.Add(New OleDbParameter("@MaNhanVien", thoiDiem.MaNhanVien))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function CapNhatThoiDiemKhoiHanh(ByRef data As DataTable) As Integer
Dim dataAdapter As New OleDbDataAdapter()
Dim con As OleDbConnection = provider.Connect()
Dim sqlInsert As String = "INSERT INTO LichTuyenLap(MaTuyen,ThoiDiemKhoiHanh) VALUES(@MaTuyen,@ThoiDiemKhoiHanh)"
Dim commandInsert As New OleDbCommand(sqlInsert, con)
commandInsert.Parameters.Add(New OleDbParameter("@MaTuyen", OleDbType.Integer, 4, "MaTuyen"))
commandInsert.Parameters.Add(New OleDbParameter("@ThoiDiemKhoiHanh", OleDbType.VarChar, 10, "ThoiDiemKhoiHanh"))
dataAdapter.InsertCommand = commandInsert
Dim sqlDelete As String = "Delete From LichTuyenLap Where MaTuyen=@MaTuyen And ThoiDiemKhoiHanh=@ThoiDiemKhoiHanh"
Dim commandDelete As New OleDbCommand(sqlDelete, con)
commandDelete.Parameters.Add(New OleDbParameter("@MaTuyen", OleDbType.Integer, 4, "MaTuyen"))
commandDelete.Parameters.Add(New OleDbParameter("@ThoiDiemKhoiHanh", OleDbType.VarChar, 10, "ThoiDiemKhoiHanh"))
dataAdapter.DeleteCommand = commandDelete
Return dataAdapter.Update(data)
End Function
Public Function CapNhatThuLap(ByVal row As DataRow)
Dim sql As String = "UPDATE LichTuyenLap SET ThuHai=?,ThuBa=?,ThuTu=?,ThuNam=?,ThuSau=?,ThuBay=?,ChuNhat=? Where MaTuyen=?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@ThuHai", row("ThuHai")))
dsParameter.Add(New OleDbParameter("@ThuBa", row("ThuBa")))
dsParameter.Add(New OleDbParameter("@ThuTu", row("ThuTu")))
dsParameter.Add(New OleDbParameter("@ThuNam", row("ThuNam")))
dsParameter.Add(New OleDbParameter("@ThuSau", row("ThuSau")))
dsParameter.Add(New OleDbParameter("@ThuBay", row("ThuBay")))
dsParameter.Add(New OleDbParameter("@ChuNhat", row("ChuNhat")))
dsParameter.Add(New OleDbParameter("@MaTuyen", row("MaTuyen")))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function XoaThoiDiemKhoiHanh(ByVal row As DataRow)
Dim sql = "DELETE FROM LichTuyenLap WHERE MaTuyen = ? and ThoiDiemKhoiHanh = ? "
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaTuyen", row("MaTuyen")))
dsParameter.Add(New OleDbParameter("@ThoiDiemKhoiHanh", row("ThoiDiemKhoiHanh")))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
End Class
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/DAO/LichTuyenLapDao.vb | Visual Basic .NET | gpl2 | 4,610 |
Imports System.Data
Imports System.Data.OleDb
Imports DTO
Public Class VeDao
Dim provider As New DataProvider
Public Function LayDanhSachVe() As DataTable
Dim sql As String = "SELECT * FROM Ve"
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function TimVeTheoMaLichGan(ByVal MaLichGan As Integer) As DataTable
Dim sql As String = "SELECT v.MaLichGan as MaLich, v.MaGhe, v.TinhTrang, lv.GiaVe, lv.MaLoaiVe FROM Ve v, LoaiVe lv WHERE v.MaLoaiVe = lv.MaLoaiVe and v.MaLichGan = " & MaLichGan
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function TimVe(ByVal ve As VeDto) As DataTable
Dim sql As String = "SELECT * FROM Ve WHERE 1 "
If ve.MaGhe <> 0 Then
sql += " and MaGhe =" & ve.MaGhe
End If
If ve.MaLich <> 0 Then
sql += " and MaLich = " & ve.MaLich
End If
sql += " and TinhTrang = " & ve.TinhTrang
If ve.LoaiVe <> 0 Then
sql += " and LoaiVe =" & ve.LoaiVe
End If
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function ThemVe(ByVal ve As VeDto) As Integer
Dim sql As String = "INSERT INTO VE(MaGhe, MaLichGan, TinhTrang, MaLoaiVe) VALUES (?, ?, ?, ?)"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaGhe", ve.MaGhe))
dsParameter.Add(New OleDbParameter("@MaLich", ve.MaLich))
dsParameter.Add(New OleDbParameter("@TinhTrang", ve.TinhTrang))
dsParameter.Add(New OleDbParameter("@MaLoaiVe", ve.LoaiVe))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function CapNhatVe(ByVal ve As VeDto) As Integer
Dim sql As String = "UPDATE VE SET TinhTrang = ?, MaLoaiVe = ? WHERE MaGhe = ? and MaLichGan = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@TinhTrang", ve.TinhTrang))
dsParameter.Add(New OleDbParameter("@MaLoaiVe", ve.LoaiVe))
dsParameter.Add(New OleDbParameter("@MaGhe", ve.MaGhe))
dsParameter.Add(New OleDbParameter("@MaLichGan", ve.MaLich))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function XoaVe(ByVal maCanXoa As Long) As Integer
'.......
End Function
End Class
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/DAO/VeDao.vb | Visual Basic .NET | gpl2 | 2,445 |
Imports System.Data
Imports System.Data.OleDb
Imports DTO
Public Class LoaiVeDao
Dim provider As New DataProvider
Public Function LayDanhSachLoaiVe() As DataTable
Dim sql As String = "SELECT * FROM LOAIVE"
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function LayDanhSachLoaiVeTheoMaTuyen(ByVal maTuyen As Integer) As DataTable
Dim sql As String = "SELECT * FROM LOAIVE WHERE MaTuyen = " & maTuyen
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function ThemLoaiVe(ByVal loaive As LoaiVeDto) As Integer
Dim sql As String = "INSERT INTO LOAIVE(MaTuyen, GiaVe) VALUES (?, ?)"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaTuyen", loaive.MaTuyen))
dsParameter.Add(New OleDbParameter("@GiaVe", loaive.GiaVe))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function CapNhatLoaiVe(ByVal loaive As LoaiVeDto) As Integer
Dim sql As String = "UPDATE LOAIVE SET GiaVe = ? WHERE MaLoaiVe = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@GiaVe", loaive.GiaVe))
dsParameter.Add(New OleDbParameter("@MaLoaiVe", loaive.MaLoai))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function XoaLoaiVe(ByVal maCanXoa As Long) As Integer
Dim sql As String = "DELETE FROM LOAIVE WHERE MaLoaiVe = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaLoai", maCanXoa))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
End Class
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/DAO/LoaiVeDao.vb | Visual Basic .NET | gpl2 | 1,774 |
Imports System.Data
Imports System.Data.OleDb
Imports DTO
Public Class LichGanLapDao
Dim provider As New DataProvider
Public Function LayDanhSachXeDuocLap() As DataTable
Dim sql As String = "Select lg.MaLichGan, tx.TenTuyen, lg.ThoiDiemKhoiHanh, lg.MaXe"
sql += " From LichGanLap ll, LichGan lg, TUYENXE tx Where ll.MaLichGan = lg.MaLichGan and tx.MaTuyen = lg.MaTuyen"
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function LayLichGanLap(ByVal maLichGan As Long) As DataTable
Dim sql As String = "Select * From LichGanLap Where MaLichGan = " & maLichGan
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function ThemMotLichGanLap(ByVal lgLap As LichGanLapDto) As Integer
Dim sql As String = "INSERT INTO LichGanLap(MaLichGan, ThuHai,ThuBa,ThuTu,ThuNam,ThuSau,ThuBay,ChuNhat) VALUES(?,?,?,?,?,?,?,?)"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaLichGan", lgLap.MaLichGan))
dsParameter.Add(New OleDbParameter("@ThuHai", lgLap.ThuHai))
dsParameter.Add(New OleDbParameter("@ThuBa", lgLap.ThuBa))
dsParameter.Add(New OleDbParameter("@ThuTu", lgLap.ThuTu))
dsParameter.Add(New OleDbParameter("@ThuNam", lgLap.ThuNam))
dsParameter.Add(New OleDbParameter("@ThuSau", lgLap.ThuSau))
dsParameter.Add(New OleDbParameter("@ThuBay", lgLap.ThuBay))
dsParameter.Add(New OleDbParameter("@ChuNhat", lgLap.ChuNhat))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function CapNhatMotLichGanLap(ByVal lgLap As LichGanLapDto) As Integer
Dim sql As String = "UPDATE LichGanLap SET ThuHai = ?, ThuBa = ?,ThuTu = ?,ThuNam = ?,ThuSau = ?,ThuBay = ?,ChuNhat = ?"
sql += " WHERE MaLichGan = ?"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@ThuHai", lgLap.ThuHai))
dsParameter.Add(New OleDbParameter("@ThuBa", lgLap.ThuBa))
dsParameter.Add(New OleDbParameter("@ThuTu", lgLap.ThuTu))
dsParameter.Add(New OleDbParameter("@ThuNam", lgLap.ThuNam))
dsParameter.Add(New OleDbParameter("@ThuSau", lgLap.ThuSau))
dsParameter.Add(New OleDbParameter("@ThuBay", lgLap.ThuBay))
dsParameter.Add(New OleDbParameter("@ChuNhat", lgLap.ChuNhat))
dsParameter.Add(New OleDbParameter("@MaLichGan", lgLap.MaLichGan))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function XoaMotLichGanLap(ByVal maLichGan) As Integer
Dim sql As String = "DELETE FROM LichGanLap WHERE MaLichGan = " & maLichGan
Return provider.ThucThiTruyVan(sql)
End Function
End Class
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/DAO/LichGanLapDao.vb | Visual Basic .NET | gpl2 | 2,816 |
Imports System.Data
Imports System.Data.OleDb
Imports DTO
Public Class LichTuyenKhongLapDao
Dim provider As New DataProvider
Public Function LayDanhSachLichTuyenKhongLap() As DataTable
Dim sql As String = "SELECT MaTuyen,NgayKhoiHanh FROM LichTuyenKhongLap"
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function LayDanhSachLichTuyenKhongLapThoiDiem() As DataTable
Dim sql As String = "SELECT MaTuyen,NgayKhoiHanh,ThoiDiemKhoiHanh FROM LichTuyenKhongLap"
Return provider.ThucThiCauTruyVan(sql)
End Function
Public Function ThemThoiDiemKhoiHanh(ByVal thoiDiem As LichTuyenKhongLapDto) As Integer
Dim sql As String = "INSERT INTO LichTuyenKhongLap(MaTuyen,ThoiDiemKhoiHanh,NgayKhoiHanh,MaNhanVien) VALUES(?,?,?,?)"
Dim dsParameter As New List(Of OleDbParameter)
dsParameter.Add(New OleDbParameter("@MaTuyen", thoiDiem.MaTuyen))
dsParameter.Add(New OleDbParameter("@ThoiDiemKhoiHanh", thoiDiem.ThoiDiemKhoiHanh))
dsParameter.Add(New OleDbParameter("@NgayKhoiHanh", thoiDiem.NgayKhoiHanh))
dsParameter.Add(New OleDbParameter("@MaNhanVien", thoiDiem.MaNhanVien))
Return provider.ThucThiTruyVanThuong(sql, dsParameter)
End Function
Public Function CapNhatThoiDiemKhoiHanh(ByRef data As DataTable) As Integer
Dim dataAdapter As New OleDbDataAdapter()
Dim con As OleDbConnection = provider.Connect()
Dim sqlInsert As String = "INSERT INTO LichTuyenKhongLap (MaTuyen,NgayKhoiHanh,ThoiDiemKhoiHanh) VALUES(?,?,?)"
Dim commandInsert As New OleDbCommand(sqlInsert, con)
commandInsert.Parameters.Add(New OleDbParameter("@MaTuyen", OleDbType.Integer, 4, "MaTuyen"))
commandInsert.Parameters.Add(New OleDbParameter("@NgayKhoiHanh", OleDbType.Date, 10, "NgayKhoiHanh"))
commandInsert.Parameters.Add(New OleDbParameter("@ThoiDiemKhoiHanh", OleDbType.VarChar, 10, "ThoiDiemKhoiHanh"))
dataAdapter.InsertCommand = commandInsert
Dim sqlDelete As String = "Delete From LichTuyenKhongLap Where MaTuyen=? And NgayKhoiHanh=? and ThoiDiemKhoiHanh=? "
Dim commandDelete As New OleDbCommand(sqlDelete, con)
commandDelete.Parameters.Add(New OleDbParameter("@MaTuyen", OleDbType.Integer, 4, "MaTuyen"))
commandDelete.Parameters.Add(New OleDbParameter("@NgayKhoiHanh", OleDbType.Date, 10, "NgayKhoiHanh"))
commandDelete.Parameters.Add(New OleDbParameter("@ThoiDiemKhoiHanh", OleDbType.VarChar, 10, "ThoiDiemKhoiHanh"))
dataAdapter.DeleteCommand = commandDelete
Return dataAdapter.Update(data)
End Function
End Class
| 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/DAO/LichTuyenKhongLapDao.vb | Visual Basic .NET | gpl2 | 2,712 |
Imports System
Imports System.Data.OleDb
Imports System.Data
Imports System.Collections
Public Class DataProvider
Public Shared ReadOnly Property ConnectionString() As String
Get
Return "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=QuanLyXE.mdb;Persist Security Info=True"
End Get
End Property
Private conn As OleDbConnection
Public Function Connect() As OleDbConnection
If conn Is Nothing Then
conn = New OleDbConnection(ConnectionString)
End If
If (conn.State <> ConnectionState.Open) Then
Try
conn.Open()
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End If
Return conn
End Function
Public Sub DisConnect()
If Not (conn Is Nothing) AndAlso conn.State = ConnectionState.Open Then
conn.Close()
End If
End Sub
Public Function ThucThiCauTruyVan(ByVal sql As String) As DataTable
Try
Return ThucThiCauTruyVan(sql, Nothing)
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Function
Public Function ThucThiCauTruyVan(ByVal sql As String, ByVal dsParameter As List(Of OleDbParameter)) As DataTable
Try
Connect()
Dim command As OleDbCommand
Dim dt As DataTable = New DataTable
command = New OleDbCommand(sql, conn)
If dsParameter IsNot Nothing Then
command.Parameters.AddRange(dsParameter.ToArray())
End If
Dim adapter As New OleDbDataAdapter(command)
adapter.Fill(dt)
Return dt
Catch ex As Exception
Throw New Exception(ex.Message)
Finally '??? dung lam gi?
DisConnect()
End Try
End Function
Public Function ThucThiTruyVan(ByVal sql As String) As Integer
Try
Connect()
Dim command As OleDbCommand
command = New OleDbCommand(sql, conn)
Return command.ExecuteNonQuery()
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Function
Public Function ThucThiTruyVanThuong(ByVal sql As String, ByVal dsParameter As List(Of OleDbParameter)) As Integer
Try
Connect()
Dim command As OleDbCommand
command = New OleDbCommand(sql, conn)
If dsParameter IsNot Nothing Then
command.Parameters.AddRange(dsParameter.ToArray())
End If
Return command.ExecuteNonQuery()
Catch ex As Exception
'Throw New Exception(ex.Message)
Finally
DisConnect()
End Try
End Function
'Hàm này dùng để đưa dữ liệu từ datatable vào bảng có tên 'tenbang'
Public Function CapNhatXuongCSDL(ByVal tenBang As String, ByVal dt As DataTable) As Integer
Dim kq As Integer = 0
Try
Connect()
Dim command As New OleDbCommand("Select * From " & tenBang, conn)
Dim adapter As New OleDbDataAdapter()
adapter.SelectCommand = command
Dim cmb As New OleDbCommandBuilder(adapter)
kq = adapter.Update(dt)
Return kq
Catch ex As Exception
Throw New Exception(ex.Message)
Finally
DisConnect()
End Try
End Function
End Class | 10650251065124quanlyhocsinh | trunk/QuảnLyXe/QuanLyXe/DAO/DataProvider.vb | Visual Basic .NET | gpl2 | 3,625 |
// Copyright 2012, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.ad.catalog.layouts;
import com.google.ad.catalog.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
/**
* Menu system for different ad layouts.
*
* @author api.eleichtenschl@gmail.com (Eric Leichtenschlag)
*/
public class AdvancedLayouts extends Activity implements OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.advancedlayouts);
}
/** Handles the on click events for each button. */
@Override
public void onClick(View view) {
final int id = view.getId();
Intent intent = null;
switch (id) {
// Uncomment corresponding intent when implementing an example.
case R.id.tabbedView:
intent = new Intent(AdvancedLayouts.this, TabbedViewExample.class);
break;
case R.id.listView:
intent = new Intent(AdvancedLayouts.this, ListViewExample.class);
break;
case R.id.openGLView:
intent = new Intent(AdvancedLayouts.this, OpenGLViewExample.class);
break;
case R.id.scrollView:
intent = new Intent(AdvancedLayouts.this, ScrollViewExample.class);
break;
}
if (intent != null) {
startActivity(intent);
}
}
}
| 10beseukhan-ad-catalog-android | adcatalog/src/com/google/ad/catalog/layouts/AdvancedLayouts.java | Java | asf20 | 2,023 |
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.ad.catalog.layouts;
import com.google.ad.catalog.AdCatalog;
import com.google.ad.catalog.R;
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdView;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
/**
* Example of a ScrollView with an AdMob banner.
*
* @author api.eleichtenschl@gmail.com (Eric Leichtenschlag)
*/
public class ScrollViewExample extends Activity implements AdListener {
private static final String LOGTAG = "ScrollViewExample";
private AdView adView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scrollviewexample);
adView = (AdView) findViewById(R.id.adView);
AdRequest adRequestBanner = new AdRequest();
// Set testing according to our preference.
if (AdCatalog.isTestMode) {
adRequestBanner.addTestDevice(AdRequest.TEST_EMULATOR);
}
adView.setAdListener(this);
adView.loadAd(adRequestBanner);
}
/** Overwrite the onDestroy() method to dispose of banners first. */
@Override
public void onDestroy() {
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
@Override
public void onReceiveAd(Ad ad) {
Log.d(LOGTAG, "I received an ad");
}
@Override
public void onFailedToReceiveAd(Ad ad, AdRequest.ErrorCode error) {
Log.d(LOGTAG, "I failed to receive an ad");
}
@Override
public void onPresentScreen(Ad ad) {
Log.d(LOGTAG, "Presenting screen");
}
@Override
public void onDismissScreen(Ad ad) {
Log.d(LOGTAG, "Dismissing screen");
}
@Override
public void onLeaveApplication(Ad ad) {
Log.d(LOGTAG, "Leaving application");
}
}
| 10beseukhan-ad-catalog-android | adcatalog/src/com/google/ad/catalog/layouts/ScrollViewExample.java | Java | asf20 | 2,441 |
// Copyright 2012, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.ad.catalog.layouts;
import com.google.ad.catalog.AdCatalog;
import com.google.ad.catalog.R;
import com.google.ads.AdRequest;
import com.google.ads.AdView;
import android.app.Activity;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.RelativeLayout;
/**
* Example of an OpenGL view with an AdMob banner.
*
* @author api.eleichtenschl@gmail.com (Eric Leichtenschlag)
*/
public class OpenGLViewExample extends Activity {
private GLSurfaceView glSurfaceView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.openglviewexample);
// Load the AdView with a request.
AdView adView = (AdView) findViewById(R.id.openGLAdView);
AdRequest adRequest = new AdRequest();
if (AdCatalog.isTestMode) {
adRequest.addTestDevice(AdRequest.TEST_EMULATOR);
}
adView.loadAd(adRequest);
// Initialize the GLSurfaceView and add it to the layout above the AdView.
this.glSurfaceView = new GLSurfaceView(this);
this.glSurfaceView.setRenderer(new CubeRenderer(true));
RelativeLayout layout = (RelativeLayout) findViewById(R.id.openGLLayout);
RelativeLayout.LayoutParams params =
new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
params.addRule(RelativeLayout.ABOVE, R.id.openGLAdView);
layout.addView(this.glSurfaceView, params);
}
@Override
protected void onResume() {
// Ideally a game should implement onResume() and onPause()
// to take appropriate action when the activity looses focus.
super.onResume();
this.glSurfaceView.onResume();
}
@Override
protected void onPause() {
// Ideally a game should implement onResume() and onPause()
// to take appropriate action when the activity looses focus.
super.onPause();
this.glSurfaceView.onPause();
}
}
| 10beseukhan-ad-catalog-android | adcatalog/src/com/google/ad/catalog/layouts/OpenGLViewExample.java | Java | asf20 | 2,617 |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.ad.catalog.layouts;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import javax.microedition.khronos.opengles.GL10;
/**
* A vertex shaded cube.
*/
class Cube
{
public Cube()
{
int one = 0x10000;
int vertices[] = {
-one, -one, -one,
one, -one, -one,
one, one, -one,
-one, one, -one,
-one, -one, one,
one, -one, one,
one, one, one,
-one, one, one,
};
int colors[] = {
0, 0, 0, one,
one, 0, 0, one,
one, one, 0, one,
0, one, 0, one,
0, 0, one, one,
one, 0, one, one,
one, one, one, one,
0, one, one, one,
};
byte indices[] = {
0, 4, 5, 0, 5, 1,
1, 5, 6, 1, 6, 2,
2, 6, 7, 2, 7, 3,
3, 7, 4, 3, 4, 0,
4, 7, 6, 4, 6, 5,
3, 0, 1, 3, 1, 2
};
// Buffers to be passed to gl*Pointer() functions
// must be direct, i.e., they must be placed on the
// native heap where the garbage collector cannot
// move them.
//
// Buffers with multi-byte datatypes (e.g., short, int, float)
// must have their byte order set to native order
ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length*4);
vbb.order(ByteOrder.nativeOrder());
mVertexBuffer = vbb.asIntBuffer();
mVertexBuffer.put(vertices);
mVertexBuffer.position(0);
ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length*4);
cbb.order(ByteOrder.nativeOrder());
mColorBuffer = cbb.asIntBuffer();
mColorBuffer.put(colors);
mColorBuffer.position(0);
mIndexBuffer = ByteBuffer.allocateDirect(indices.length);
mIndexBuffer.put(indices);
mIndexBuffer.position(0);
}
public void draw(GL10 gl)
{
gl.glFrontFace(GL10.GL_CW);
gl.glVertexPointer(3, GL10.GL_FIXED, 0, mVertexBuffer);
gl.glColorPointer(4, GL10.GL_FIXED, 0, mColorBuffer);
gl.glDrawElements(GL10.GL_TRIANGLES, 36, GL10.GL_UNSIGNED_BYTE, mIndexBuffer);
}
private IntBuffer mVertexBuffer;
private IntBuffer mColorBuffer;
private ByteBuffer mIndexBuffer;
}
| 10beseukhan-ad-catalog-android | adcatalog/src/com/google/ad/catalog/layouts/Cube.java | Java | asf20 | 3,144 |
// Copyright 2012, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.ad.catalog.layouts;
import com.google.ad.catalog.R;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabContentFactory;
import android.widget.TabHost.TabSpec;
import java.util.HashMap;
/**
* Example of including AdMob ads into a Tabbed View, which references the v4
* support library for the fragment API instead of the deprecated TabActivity
* class. These library classes are included in android-support-v4.jar, which
* is a part of the Android Compatibility Package found in the Extras section
* of the Android SDK Manager.
*
* @author api.eleichtenschl@gmail.com (Eric Leichtenschlag)
*/
public class TabbedViewExample extends FragmentActivity {
private TabHost tabHost;
private TabManager tabManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabviewexample);
this.tabHost = (TabHost) findViewById(android.R.id.tabhost);
this.tabHost.setup();
// Initialize the tabs.
this.tabManager = new TabManager(this, this.tabHost, R.id.realtabcontent);
Bundle args = new Bundle();
args.putInt("layoutResource", R.layout.tabblue);
this.tabManager.addTab(this.tabHost.newTabSpec("Tab1").setIndicator("Tab 1"),
TabFragment.class, args);
args = new Bundle();
args.putInt("layoutResource", R.layout.tabred);
this.tabManager.addTab(this.tabHost.newTabSpec("Tab2").setIndicator("Tab 2"),
TabFragment.class, args);
args = new Bundle();
args.putInt("layoutResource", R.layout.tabgreen);
this.tabManager.addTab(this.tabHost.newTabSpec("Tab3").setIndicator("Tab 3"),
TabFragment.class, args);
// Set the current tab if one exists.
if (savedInstanceState != null) {
this.tabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("tab", this.tabHost.getCurrentTabTag());
}
/**
* This is a helper class that implements a generic mechanism for
* associating fragments with the tabs in a tab host. It relies on a
* trick. Normally a tab host has a simple API for supplying a View or
* Intent that each tab will show. This is not sufficient for switching
* between fragments. So instead we make the content part of the tab host
* 0dp high (it is not shown) and the TabManager supplies its own dummy
* view to show as the tab content. It listens to changes in tabs, and takes
* care of switch to the correct fragment shown in a separate content area
* whenever the selected tab changes.
*/
public static class TabManager implements OnTabChangeListener {
private final FragmentActivity activity;
private final TabHost tabHost;
private final int containerId;
private final HashMap<String, TabInfo> tabInfoMap = new HashMap<String, TabInfo>();
private TabInfo currentTab;
/** Represents the information of a tab. */
static final class TabInfo {
private final String tag;
private final Class<?> clss;
private final Bundle args;
private Fragment fragment;
TabInfo(String tag, Class<?> clss, Bundle args) {
this.tag = tag;
this.clss = clss;
this.args = args;
}
}
/** Creates an empty tab. */
static class DummyTabFactory implements TabContentFactory {
private final Context context;
public DummyTabFactory(Context context) {
this.context = context;
}
@Override
public View createTabContent(String tag) {
View view = new View(this.context);
view.setMinimumWidth(0);
view.setMinimumHeight(0);
return view;
}
}
public TabManager(FragmentActivity activity, TabHost tabHost, int containerId) {
this.activity = activity;
this.tabHost = tabHost;
this.containerId = containerId;
this.tabHost.setOnTabChangedListener(this);
}
public void addTab(TabSpec tabSpec, Class<?> clss, Bundle args) {
tabSpec.setContent(new DummyTabFactory(this.activity));
String tag = tabSpec.getTag();
TabInfo tabInfo = new TabInfo(tag, clss, args);
// Check to see if there is already a fragment for this tab. If so,
// deactivate it, because the initial state is that a tab isn't shown.
tabInfo.fragment = this.activity.getSupportFragmentManager().findFragmentByTag(tag);
if (tabInfo.fragment != null && !tabInfo.fragment.isDetached()) {
FragmentTransaction transaction =
this.activity.getSupportFragmentManager().beginTransaction();
transaction.detach(tabInfo.fragment).commit();
}
this.tabInfoMap.put(tag, tabInfo);
this.tabHost.addTab(tabSpec);
}
@Override
public void onTabChanged(String tabId) {
TabInfo newTab = this.tabInfoMap.get(tabId);
if (this.currentTab != newTab) {
FragmentTransaction transaction =
this.activity.getSupportFragmentManager().beginTransaction();
if (this.currentTab != null && this.currentTab.fragment != null) {
transaction.detach(this.currentTab.fragment);
}
if (newTab != null) {
if (newTab.fragment == null) {
newTab.fragment = Fragment.instantiate(this.activity,
newTab.clss.getName(), newTab.args);
transaction.add(this.containerId, newTab.fragment, newTab.tag);
} else {
transaction.attach(newTab.fragment);
}
}
this.currentTab = newTab;
transaction.commit();
this.activity.getSupportFragmentManager().executePendingTransactions();
}
}
}
/** Fragment for a tab in the Tab View example. */
public static class TabFragment extends Fragment {
private int layoutResource;
static TabFragment newInstance(int resource) {
TabFragment fragment = new TabFragment();
// Supply the layout resource input as an argument.
Bundle args = new Bundle();
args.putInt("layoutResource", resource);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Default to blue tab, if no resource is provided.
this.layoutResource = R.layout.tabblue;
Bundle args = getArguments();
if (args != null && args.getInt("layoutResource") != 0) {
this.layoutResource = args.getInt("layoutResource");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(this.layoutResource, container, false);
}
}
}
| 10beseukhan-ad-catalog-android | adcatalog/src/com/google/ad/catalog/layouts/TabbedViewExample.java | Java | asf20 | 7,746 |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.ad.catalog.layouts;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.opengl.GLSurfaceView;
/**
* Render a pair of tumbling cubes.
*/
class CubeRenderer implements GLSurfaceView.Renderer {
public CubeRenderer(boolean useTranslucentBackground) {
mTranslucentBackground = useTranslucentBackground;
mCube = new Cube();
}
public void onDrawFrame(GL10 gl) {
/*
* Usually, the first thing one might want to do is to clear
* the screen. The most efficient way of doing this is to use
* glClear().
*/
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
/*
* Now we're ready to draw some 3D objects
*/
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
gl.glTranslatef(0, 0, -3.0f);
gl.glRotatef(mAngle, 0, 1, 0);
gl.glRotatef(mAngle*0.25f, 1, 0, 0);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
mCube.draw(gl);
gl.glRotatef(mAngle*2.0f, 0, 1, 1);
gl.glTranslatef(0.5f, 0.5f, 0.5f);
mCube.draw(gl);
mAngle += 1.2f;
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
gl.glViewport(0, 0, width, height);
/*
* Set our projection matrix. This doesn't have to be done
* each time we draw, but usually a new projection needs to
* be set when the viewport is resized.
*/
float ratio = (float) width / height;
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10);
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
/*
* By default, OpenGL enables features that improve quality
* but reduce performance. One might want to tweak that
* especially on software renderer.
*/
gl.glDisable(GL10.GL_DITHER);
/*
* Some one-time OpenGL initialization can be made here
* probably based on features of this particular context
*/
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT,
GL10.GL_FASTEST);
if (mTranslucentBackground) {
gl.glClearColor(0,0,0,0);
} else {
gl.glClearColor(1,1,1,1);
}
gl.glEnable(GL10.GL_CULL_FACE);
gl.glShadeModel(GL10.GL_SMOOTH);
gl.glEnable(GL10.GL_DEPTH_TEST);
}
private boolean mTranslucentBackground;
private Cube mCube;
private float mAngle;
}
| 10beseukhan-ad-catalog-android | adcatalog/src/com/google/ad/catalog/layouts/CubeRenderer.java | Java | asf20 | 3,331 |
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.ad.catalog.layouts;
import com.google.ad.catalog.AdCatalogUtils;
import com.google.ad.catalog.Constants;
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
/**
* Custom list adapter to embed AdMob ads in a ListView at the top
* and bottom of the screen.
*
* @author api.rajpara@gmail.com (Raj Parameswaran)
*/
public class ListViewExampleListAdapter extends BaseAdapter implements AdListener {
private static final String LOGTAG = "ListViewExampleListAdapter";
private final Activity activity;
private final BaseAdapter delegate;
public ListViewExampleListAdapter(Activity activity, BaseAdapter delegate) {
this.activity = activity;
this.delegate = delegate;
}
@Override
public int getCount() {
// Total count includes list items and ads.
return delegate.getCount() + 2;
}
@Override
public Object getItem(int position) {
// Return null if an item is an ad. Otherwise return the delegate item.
if (isItemAnAd(position)) {
return null;
}
return delegate.getItem(getOffsetPosition(position));
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (isItemAnAd(position)) {
if (convertView instanceof AdView) {
Log.d(LOGTAG, "I am reusing an ad");
return convertView;
} else {
Log.d(LOGTAG, "I am creating a new ad");
AdView adView = new AdView(activity, AdSize.SMART_BANNER, Constants.getAdmobId(activity));
adView.loadAd(AdCatalogUtils.createAdRequest());
return adView;
}
} else {
return delegate.getView(getOffsetPosition(position), convertView, parent);
}
}
@Override
public int getViewTypeCount() {
return delegate.getViewTypeCount() + 1;
}
@Override
public int getItemViewType(int position) {
if (isItemAnAd(position)) {
return delegate.getViewTypeCount();
} else {
return delegate.getItemViewType(getOffsetPosition(position));
}
}
@Override
public boolean areAllItemsEnabled() {
return false;
}
@Override
public boolean isEnabled(int position) {
return (!isItemAnAd(position)) && delegate.isEnabled(getOffsetPosition(position));
}
private boolean isItemAnAd(int position) {
// Place an ad at the first and last list view positions.
return (position == 0 || position == (getCount() - 1));
}
@Override
public void onDismissScreen(Ad arg0) {
Log.d(LOGTAG, "Dismissing screen");
}
@Override
public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) {
Log.d(LOGTAG, "I failed to receive an ad");
}
@Override
public void onLeaveApplication(Ad arg0) {
Log.d(LOGTAG, "Leaving application");
}
@Override
public void onPresentScreen(Ad arg0) {
Log.d(LOGTAG, "Presenting screen");
}
@Override
public void onReceiveAd(Ad arg0) {
Log.d(LOGTAG, "I received an ad");
}
private int getOffsetPosition(int position) {
return position - 1;
}
}
| 10beseukhan-ad-catalog-android | adcatalog/src/com/google/ad/catalog/layouts/ListViewExampleListAdapter.java | Java | asf20 | 3,926 |
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.ad.catalog.layouts;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
/**
* Example of a ListView with embedded AdMob ads.
*
* @author api.rajpara@gmail.com (Raj Parameswaran)
*/
public class ListViewExample extends ListActivity {
public static final String[] LIST_ITEMS = {
"Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7",
"Item 8", "Item 9", "Item 10", "Item 11", "Item 12", "Item 13", "Item 14",
"Item 15", "Item 16", "Item 17", "Item 18", "Item 19", "Item 20", "Item 21"
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set list adapter to be the custom ListViewExampleListAdapter.
ListViewExampleListAdapter adapter = new ListViewExampleListAdapter(
this, new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, LIST_ITEMS));
setListAdapter(adapter);
}
@Override
protected void onListItemClick(ListView listView, View view, int position, long id) {
String item = (String) getListAdapter().getItem(position);
// Clicking an item should bring up toast, different from clicking ad.
Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
}
}
| 10beseukhan-ad-catalog-android | adcatalog/src/com/google/ad/catalog/layouts/ListViewExample.java | Java | asf20 | 1,972 |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.ad.catalog;
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.InterstitialAd;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
/**
* This activity features interstitial ads before going to a youtube link.
*
* @author api.eleichtenschl@gmail.com (Eric Leichtenschlag)
*/
public class VideoPreroll extends Activity implements OnClickListener {
private InterstitialAd interstitial;
private VideoHandler videoHandler;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videopreroll);
videoHandler = new VideoHandler();
interstitial = new InterstitialAd(this, Constants.getAdmobId(this));
interstitial.setAdListener(videoHandler);
interstitial.loadAd(AdCatalogUtils.createAdRequest());
}
/** Handles the on click events for each button. */
@Override
public void onClick(View view) {
final int id = view.getId();
switch (id) {
case R.id.earthquake:
videoHandler.setLink(Constants.EARTHQUAKE_LINK);
break;
case R.id.fillInTheBlanks:
videoHandler.setLink(Constants.FILL_IN_THE_BLANKS_LINK);
break;
case R.id.packageTracking:
videoHandler.setLink(Constants.PACKAGE_TRACKING_LINK);
break;
}
if (interstitial.isReady()) {
interstitial.show();
} else {
interstitial.loadAd(AdCatalogUtils.createAdRequest());
videoHandler.playVideo();
}
}
/**
* This handler supports playing a video after an interstitial is displayed.
*
* @author api.eleichtenschl@gmail.com (Eric Leichtenschlag)
*/
class VideoHandler implements AdListener {
private String youtubeLink;
/** Instantiates a new VideoHandler object. */
public VideoHandler() {
youtubeLink = "";
}
/** Sets the YouTube link. */
public void setLink(String link) {
youtubeLink = link;
}
/** Plays the video. */
public void playVideo() {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(youtubeLink)));
}
@Override
public void onReceiveAd(Ad ad) {
Log.d("Video_Handler", "I received an ad");
}
@Override
public void onFailedToReceiveAd(Ad ad, AdRequest.ErrorCode error) {
Log.d("Video_Handler", "I failed to receive an ad");
}
@Override
public void onPresentScreen(Ad ad) {
Log.d("Video_Handler", "Presenting screen");
}
@Override
public void onDismissScreen(Ad ad) {
Log.d("Video_Handler", "Dismissing screen");
playVideo();
}
@Override
public void onLeaveApplication(Ad ad) {
Log.d("Video_Handler", "Leaving application");
}
}
}
| 10beseukhan-ad-catalog-android | adcatalog/src/com/google/ad/catalog/VideoPreroll.java | Java | asf20 | 3,577 |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.ad.catalog;
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdView;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
/**
* Showcases the different banner formats on both phones and tablets. Phones
* will show a standard banner, a medium rectangle, and a smart banner. Tablets
* will show full size banners and leaderboard ads in addition to the three
* formats above.
*
* @author api.eleichtenschl@gmail.com (Eric Leichtenschlag)
*/
public class Banners extends Activity implements OnClickListener, AdListener {
private AdView adViewBanner;
private AdView adViewRect;
private AdView adViewSmartBanner;
private AdView adViewFullSizeBanner;
private AdView adViewLeaderboard;
/** Used to hide the last AdView that was selected. */
private AdView lastVisibleAdView = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.banners);
// Set the ad listener and load an load for each AdView.
AdRequest adRequest = AdCatalogUtils.createAdRequest();
adViewBanner = (AdView) findViewById(R.id.adViewBanner);
adViewBanner.setAdListener(this);
adViewBanner.loadAd(adRequest);
adViewSmartBanner = (AdView) findViewById(R.id.adViewSmart);
adViewSmartBanner.setAdListener(this);
adViewSmartBanner.loadAd(adRequest);
if (AdCatalogUtils.isExtraLargeScreen(this)) {
adViewRect = (AdView) findViewById(R.id.adViewRect);
adViewRect.setAdListener(this);
adViewRect.loadAd(adRequest);
adViewFullSizeBanner = (AdView) findViewById(R.id.adViewFullSize);
adViewFullSizeBanner.setAdListener(this);
adViewFullSizeBanner.loadAd(adRequest);
adViewLeaderboard = (AdView) findViewById(R.id.adViewLeaderboard);
adViewLeaderboard.setAdListener(this);
adViewLeaderboard.loadAd(adRequest);
}
}
/** Handles the on click events for each button. */
@Override
public void onClick(View view) {
if (lastVisibleAdView != null) {
lastVisibleAdView.setVisibility(View.GONE);
}
switch (view.getId()) {
case R.id.standardBanner:
adViewBanner.setVisibility(View.VISIBLE);
lastVisibleAdView = adViewBanner;
break;
case R.id.mediumRectangle:
adViewRect.setVisibility(View.VISIBLE);
lastVisibleAdView = adViewRect;
break;
case R.id.smartBanner:
adViewSmartBanner.setVisibility(View.VISIBLE);
lastVisibleAdView = adViewSmartBanner;
break;
case R.id.fullSize:
adViewFullSizeBanner.setVisibility(View.VISIBLE);
lastVisibleAdView = adViewFullSizeBanner;
break;
case R.id.leaderboard:
adViewLeaderboard.setVisibility(View.VISIBLE);
lastVisibleAdView = adViewLeaderboard;
break;
}
}
/** Overwrite the onDestroy() method to dispose of the banners first. */
@Override
public void onDestroy() {
if (adViewBanner != null) {
adViewBanner.destroy();
}
if (adViewRect != null) {
adViewRect.destroy();
}
if (adViewSmartBanner != null) {
adViewSmartBanner.destroy();
}
if (adViewFullSizeBanner != null) {
adViewFullSizeBanner.destroy();
}
if (adViewLeaderboard != null) {
adViewLeaderboard.destroy();
}
super.onDestroy();
}
@Override
public void onReceiveAd(Ad ad) {
Log.d("Banners_class", "I received an ad");
}
@Override
public void onFailedToReceiveAd(Ad ad, AdRequest.ErrorCode error) {
Log.d("Banners_class", "I failed to receive an ad");
}
@Override
public void onPresentScreen(Ad ad) {
Log.d("Banners_class", "Presenting screen");
}
@Override
public void onDismissScreen(Ad ad) {
Log.d("Banners_class", "Dismissing screen");
}
@Override
public void onLeaveApplication(Ad ad) {
Log.d("Banners_class", "Leaving application");
}
}
| 10beseukhan-ad-catalog-android | adcatalog/src/com/google/ad/catalog/Banners.java | Java | asf20 | 4,740 |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.ad.catalog;
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.InterstitialAd;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;
import android.widget.ViewFlipper;
/**
* This activity demonstrates displaying an interstitial in between page
* swipes. Use case could be displaying a gallery of photos.
*
* @author api.eleichtenschl@gmail.com (Eric Leichtenschlag)
*/
public class PageSwipe extends Activity implements AdListener, OnTouchListener {
private InterstitialAd interstitial;
private float downXValue;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pageswipe);
LinearLayout layout = (LinearLayout) findViewById(R.id.swipe_main);
layout.setOnTouchListener(this);
interstitial = new InterstitialAd(this, Constants.getAdmobId(this));
interstitial.setAdListener(this);
interstitial.loadAd(AdCatalogUtils.createAdRequest());
}
/** Used to detect which direction a user swiped. */
@Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
downXValue = event.getX();
break;
case MotionEvent.ACTION_UP:
float currentX = event.getX();
ViewFlipper viewFlipper = (ViewFlipper) findViewById(R.id.flipper);
if (downXValue < currentX) {
viewFlipper.setInAnimation(view.getContext(), R.anim.push_right_in);
viewFlipper.setOutAnimation(view.getContext(), R.anim.push_right_out);
viewFlipper.showPrevious();
showInterstitial();
} else if (downXValue > currentX) {
viewFlipper.setInAnimation(view.getContext(), R.anim.push_left_in);
viewFlipper.setOutAnimation(view.getContext(), R.anim.push_left_out);
viewFlipper.showNext();
showInterstitial();
}
break;
}
return true;
}
/** Shows the interstitial, or loads a new interstitial if one is not ready. */
public void showInterstitial() {
if (interstitial.isReady()) {
interstitial.show();
} else {
interstitial.loadAd(AdCatalogUtils.createAdRequest());
}
}
@Override
public void onReceiveAd(Ad ad) {
Log.d("PageSwipe_Class", "I received an ad");
}
@Override
public void onFailedToReceiveAd(Ad ad, AdRequest.ErrorCode error) {
Log.d("PageSwipe_Class", "I failed to receive an ad");
}
@Override
public void onPresentScreen(Ad ad) {
Log.d("PageSwipe_Class", "Presenting screen");
}
@Override
public void onDismissScreen(Ad ad) {
Log.d("PageSwipe_Class", "Dismissing screen");
}
@Override
public void onLeaveApplication(Ad ad) {
Log.d("PageSwipe_Class", "Leaving application");
}
}
| 10beseukhan-ad-catalog-android | adcatalog/src/com/google/ad/catalog/PageSwipe.java | Java | asf20 | 3,676 |
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.ad.catalog;
import com.google.ads.AdRequest;
import android.content.Context;
import android.content.res.Configuration;
/**
* Utilities class for some common tasks within Ad Catalog.
*
* @author api.eleichtenschl@gmail.com (Eric Leichtenschlag)
*/
public class AdCatalogUtils {
/**
* Prevent instantiation.
*/
private AdCatalogUtils() {
// Empty.
}
/**
* Determines whether or not the device has an extra large screen.
*
* @param context The Android context.
* @return boolean value indicating if the screen size is extra large.
*/
public static boolean isExtraLargeScreen(Context context) {
int screenSizeMask = context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK;
if (screenSizeMask == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
return true;
} else {
return false;
}
}
/**
* Creates an ad request. It will be a test request if test mode is enabled.
*
* @return An AdRequest to use when loading an ad.
*/
public static AdRequest createAdRequest() {
AdRequest adRequest = new AdRequest();
if (AdCatalog.isTestMode) {
// This call will add the emulator as a test device. To add a physical
// device for testing, pass in your hashed device ID, which can be found
// in the LogCat output when loading an ad on your device.
adRequest.addTestDevice(AdRequest.TEST_EMULATOR);
}
return adRequest;
}
}
| 10beseukhan-ad-catalog-android | adcatalog/src/com/google/ad/catalog/AdCatalogUtils.java | Java | asf20 | 2,101 |
// Copyright 2011, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.ad.catalog;
import android.content.Context;
/**
* This class holds constant values for publisher ID and preferences keys.
*
* @author api.eleichtenschl@gmail.com (Eric Leichtenschlag)
*/
public final class Constants {
/** The AdMob publisher ID. */
private static String admobId = null;
/** Preferences keys. */
public static final String PREFS_NAME = "AdExamplesPrefs";
public static final String PREFS_SPLASH_KEY = "loadSplashInterstitial";
/** Video links. */
public static final String EARTHQUAKE_LINK = "http://www.youtube.com/watch?v=SZ-ZRhxAINA";
public static final String FILL_IN_THE_BLANKS_LINK =
"http://www.youtube.com/watch?v=24Ri7yZhRwM&NR=1";
public static final String PACKAGE_TRACKING_LINK = "http://www.youtube.com/watch?v=jb5crXH2Cb8";
/** Private constructor so that the class cannot be instantiated. */
private Constants() {
// This will never be called.
}
/** Gets the AdMob Id from the context resources. */
public static String getAdmobId(Context context) {
if (admobId == null) {
admobId = context.getResources().getString(R.string.admob_id);
}
return admobId;
}
}
| 10beseukhan-ad-catalog-android | adcatalog/src/com/google/ad/catalog/Constants.java | Java | asf20 | 1,792 |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.ad.catalog;
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.InterstitialAd;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ToggleButton;
/**
* Menu system for different methods of displaying interstitials. Setting the splash
* toggle will load an interstitial next time the application is launched.
*
* @author api.eleichtenschl@gmail.com (Eric Leichtenschlag)
*/
public class Interstitials extends Activity implements OnClickListener, AdListener {
private InterstitialAd interstitial;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.interstitials);
interstitial = new InterstitialAd(this, Constants.getAdmobId(this));
interstitial.setAdListener(this);
final ToggleButton splashToggleButton = (ToggleButton) findViewById(R.id.toggleSplash);
if (splashToggleButton != null) {
// Set the default toggle value from the preferences.
SharedPreferences settings = getSharedPreferences(Constants.PREFS_NAME, 0);
splashToggleButton.setChecked(settings.getBoolean(Constants.PREFS_SPLASH_KEY, false));
}
}
/** Handles the on click events for each button. */
@Override
public void onClick(View view) {
final int id = view.getId();
Intent intent;
switch (id) {
// Basic button click - load a basic interstitial.
case R.id.basic:
interstitial.loadAd(AdCatalogUtils.createAdRequest());
break;
// Game Levels button click - go to Game Levels Activity.
case R.id.gameLevels:
intent = new Intent(Interstitials.this, GameLevels.class);
startActivity(intent);
break;
// Video Preroll button click - go to Video Preroll Activity.
case R.id.videoPreroll:
intent = new Intent(Interstitials.this, VideoPreroll.class);
startActivity(intent);
break;
// Page Swipe button click - go to Page Swipe Activity.
case R.id.pageSwipe:
intent = new Intent(Interstitials.this, PageSwipe.class);
startActivity(intent);
break;
// Splash button click - toggle preference to receive splash screen interstitial.
case R.id.toggleSplash:
ToggleButton splashToggleButton = (ToggleButton) view;
boolean isChecked = splashToggleButton.isChecked();
SharedPreferences settings = getSharedPreferences(Constants.PREFS_NAME, 0);
settings.edit().putBoolean(Constants.PREFS_SPLASH_KEY, isChecked).commit();
Log.i("Interstitials_Class", "Set splash preference to " + isChecked);
break;
}
}
@Override
public void onReceiveAd(Ad ad) {
Log.d("Interstitials_Class", "I received an ad");
if (interstitial.isReady()) {
interstitial.show();
}
}
@Override
public void onFailedToReceiveAd(Ad ad, AdRequest.ErrorCode error) {
Log.d("Interstitials_Class", "I failed to receive an ad");
}
@Override
public void onPresentScreen(Ad ad) {
Log.d("Interstitials_Class", "Presenting screen");
}
@Override
public void onDismissScreen(Ad ad) {
Log.d("Interstitials_Class", "Dismissing screen");
}
@Override
public void onLeaveApplication(Ad ad) {
Log.d("Interstitials_Class", "Leaving application");
}
}
| 10beseukhan-ad-catalog-android | adcatalog/src/com/google/ad/catalog/Interstitials.java | Java | asf20 | 4,198 |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.ad.catalog;
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.InterstitialAd;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ViewFlipper;
/**
* This activity shows an example of how to display an interstitial in between
* game levels.
*
* @author api.eleichtenschl@gmail.com (Eric Leichtenschlag)
*/
public class GameLevels extends Activity implements OnClickListener, AdListener {
private InterstitialAd interstitial;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gamelevels);
// Start loading the interstitial.
interstitial = new InterstitialAd(this, Constants.getAdmobId(this));
interstitial.setAdListener(this);
interstitial.loadAd(AdCatalogUtils.createAdRequest());
}
/** Handles the on click events for each button. */
@Override
public void onClick(View view) {
final int id = view.getId();
switch (id) {
case R.id.gameNextButton:
if (interstitial.isReady()) {
interstitial.show();
} else {
interstitial.loadAd(AdCatalogUtils.createAdRequest());
final ViewFlipper viewFlipper = (ViewFlipper) findViewById(R.id.levelFlipper);
viewFlipper.showNext();
}
break;
}
}
@Override
public void onReceiveAd(Ad ad) {
Log.d("GameLevels_Class", "I received an ad");
}
@Override
public void onFailedToReceiveAd(Ad ad, AdRequest.ErrorCode error) {
Log.d("GameLevels_Class", "I failed to receive an ad");
}
@Override
public void onPresentScreen(Ad ad) {
Log.d("GameLevels_Class", "Presenting screen");
}
@Override
public void onDismissScreen(Ad ad) {
Log.d("GameLevels_Class", "Dismissing screen");
final ViewFlipper viewFlipper = (ViewFlipper) findViewById(R.id.levelFlipper);
viewFlipper.showNext();
}
@Override
public void onLeaveApplication(Ad ad) {
Log.d("GameLevels_Class", "Leaving application");
}
}
| 10beseukhan-ad-catalog-android | adcatalog/src/com/google/ad/catalog/GameLevels.java | Java | asf20 | 2,841 |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.ad.catalog;
import com.google.ad.catalog.layouts.AdvancedLayouts;
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.InterstitialAd;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ToggleButton;
/**
* This is the main activity that loads on when the app is first run. The user
* will be provided with a menu to view banners or interstitials. If the user
* has previously set the splash toggle button, an interstitial will be loaded
* when this activity is created.
*
* @author api.eleichtenschl@gmail.com (Eric Leichtenschlag)
*/
public class AdCatalog extends Activity implements OnClickListener, AdListener {
private InterstitialAd interstitial;
private Button bannerButton;
private Button interstitialButton;
public static boolean isTestMode;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Default to test mode on.
isTestMode = true;
ToggleButton testModeToggle = (ToggleButton) findViewById(R.id.toggleTestMode);
testModeToggle.setChecked(isTestMode);
// Load interstitial if splash interstitial preference was set.
SharedPreferences settings = getSharedPreferences(Constants.PREFS_NAME, 0);
boolean loadSplashInterstitial = settings.getBoolean(Constants.PREFS_SPLASH_KEY, false);
if (loadSplashInterstitial) {
interstitial = new InterstitialAd(this, Constants.getAdmobId(this));
interstitial.setAdListener(this);
interstitial.loadAd(AdCatalogUtils.createAdRequest());
}
}
/** Handles the on click events for each button. */
@Override
public void onClick(View view) {
final int id = view.getId();
Intent intent = null;
switch (id) {
// Banners button click - go to Banners Activity.
case R.id.Banners:
intent = new Intent(AdCatalog.this, Banners.class);
break;
// Interstitials button click - go to Interstitials Activity.
case R.id.Interstitials:
intent = new Intent(AdCatalog.this, Interstitials.class);
break;
// Advanced Layouts button click - go to Advanced Layouts Activity.
case R.id.AdvancedLayouts:
intent = new Intent(AdCatalog.this, AdvancedLayouts.class);
break;
// Test Ads toggle click - change Test Mode preference.
case R.id.toggleTestMode:
isTestMode = !isTestMode;
Log.d("AdCatalog", "Test mode: " + isTestMode);
break;
}
if (intent != null) {
startActivity(intent);
}
}
@Override
public void onReceiveAd(Ad ad) {
Log.d("AdExamples_Class", "I received an ad");
interstitial.show();
}
@Override
public void onFailedToReceiveAd(Ad ad, AdRequest.ErrorCode error) {
Log.d("AdExamples_Class", "I failed to receive an ad");
}
@Override
public void onPresentScreen(Ad ad) {
Log.d("AdExamples_Class", "Presenting screen");
// Deactivate buttons so interstitial returns before they can be clicked.
if (bannerButton != null) {
bannerButton.setEnabled(false);
}
if (interstitialButton != null) {
interstitialButton.setEnabled(false);
}
}
@Override
public void onDismissScreen(Ad ad) {
Log.d("AdExamples_Class", "Dismissing screen");
// Reactivate buttons after interstitial is dismissed.
if (bannerButton != null) {
bannerButton.setEnabled(true);
}
if (interstitialButton != null) {
interstitialButton.setEnabled(true);
}
}
@Override
public void onLeaveApplication(Ad ad) {
Log.d("AdExamples_Class", "Leaving application");
}
}
| 10beseukhan-ad-catalog-android | adcatalog/src/com/google/ad/catalog/AdCatalog.java | Java | asf20 | 4,561 |
<html>
<head>
<title>Madcaps Diagnostics</title>
<style type="text/CSS">
table { width: 600px; }
</style>
</head>
<body>
<a name=Madcaps><table bgcolor=#0000b0><tr><td><br><font size=7 color=white><code><b>M a d c a p s</b></code></font><p></td></tr></table></a>
<a name=diagnostics><table bgcolor=#0000b0><tr><td><br><font size=5 color=white><code><b>d i a g n o s t i c s</b></code></font><p></td></tr></table></a>
<table bgcolor=#e0e0ff><tr><td><font color=black>
<dl><code>g e n e r a t e d 2 0 1 0 / 0 8 / 0 6 0 9 : 5 7 : 3 2</code>
</dl></font></td></tr></table><p>
<a name=tableofcontents><table bgcolor=#d0d0d0><tr><td><br><font size=5 color=white><code><b>t a b l e o f c o n t e n t s</b></code></font><p></td></tr></table></a>
<table bgcolor=white><tr><td><font color=black>
<dl><dd><a href=#hardware><code><b>hardware</b></code></a>
<dd><a href=#operatingsystem><code><b>operating system</b></code></a>
<dd><a href=#displayadapter0><code><b>display adapter 0</b></code></a><code><b>:</b></code> <b></b> <a href=#displayadapter0.textureformats><font size=1>texture formats</font></a> <a href=#displayadapter0.capabilities><font size=1>capabilities</font></a>
<dd><a href=#soundadapter0><code><b>sound adapter 0</b></code></a><code><b>:</b></code> <b>Realtek HD Audio output</b>
<dd><a href=#inputdevice0><code><b>input device 0</b></code></a><code><b>:</b></code> <b>Mouse</b>
<dd><a href=#inputdevice1><code><b>input device 1</b></code></a><code><b>:</b></code> <b>Keyboard</b>
<dd><a href=#dlls><code><b>dlls</b></code></a> <a href=#dlls.directx><font size=1>directx</font></a> <a href=#dlls.crtl><font size=1>crtl</font></a> <a href=#dlls.misc><font size=1>miscellaneous</font></a>
</dl></font></td></tr></table><p>
<a name=hardware><table bgcolor=#0000b0><tr><td><br><font size=5 color=white><code><b>h a r d w a r e</b></code></font><p></td></tr></table></a>
<table bgcolor=#ececff><tr><td><font color=black>
<dl><dt><b>Processor Type</b><dd><code> Intel (or compatible) </code>
<dt><b>Processor Level</b><dd><code> Pentium Pro / Pentium 2 class, Model 17 Stepping 0a </code>
<dt><b>Processor Count</b><dd> 2, <code>0x2</code>
<dt><b>Physical Memory Installed (MB)</b><dd> 1015, <code>0x3f7</code>
</dl></font></td></tr></table><p>
<a name=operatingsystem><table bgcolor=#606060><tr><td><br><font size=5 color=white><code><b>o p e r a t i n g s y s t e m</b></code></font><p></td></tr></table></a>
<table bgcolor=#f0f0f0><tr><td><font color=black>
<font size=5><b>Windows XP or .NET Server</b><p></font>
<dl><dt><b>Computer Name</b><dd><code> GO-361C1F51DBC2 </code>
<dt><b>User Name</b><dd><code> ni </code>
<dt><b>OS Version</b><dd><code> 5.1.2600 </code>
<dt><b>szCSDVersion</b><dd><code> Service Pack 3 </code>
<dt><b>Service Pack Version</b><dd><code> 3.0 </code>
</dl></font></td></tr></table><p>
<a name=displayadapter0><table bgcolor=#0000b0><tr><td><br><font size=5 color=white><code><b>d i s p l a y a d a p t e r 0</b></code></font><p></td></tr></table></a>
<table bgcolor=#ececff><tr><td><font color=black>
<font size=5><b></b><p></font>
<dl><dt><b>VendorId</b><dd> 0, <code>0x0</code>
<dt><b>DeviceId</b><dd> 0, <code>0x0</code>
<dt><b>SubSysId</b><dd> 0, <code>0x0</code>
<dt><b>Revision</b><dd> 0, <code>0x0</code>
</dl><p><table bgcolor=#a0a0e0><tr><td><font size=4 color=white><code><b>d r i v e r</b></code></font></td></tr></table></a><dl>
<dt><b>Driver</b><dd><code> vga.dll </code>
<dt><b>DriverVersion</b><dd> 5.1.2600.0
<dt><b>DeviceIdentifier</b><dd><code> {d7b70ee0-4340-11cf-b063-282aaec2c835} </code>
</dl><p><table bgcolor=#a0a0e0><tr><td><font size=4 color=white><code><b>1 1 s u p p o r t e d m o d e s</b></code></font></td></tr></table></a><dl>
<font size=+1><code>D3DFMT_X8R8G8B8</code></font><blockquote>
<code><b> 640 x 480</b></code>: 1Hz<br>
<code><b> 800 x 600</b></code>: 1Hz<br>
<code><b>1024 x 768</b></code>: 1Hz<br>
<code><b>1280 x 1024</b></code>: 1Hz<br>
<code><b>1600 x 1200</b></code>: 1Hz
</blockquote>
<font size=+1><code>D3DFMT_R5G6B5</code></font><blockquote>
<code><b> 640 x 480</b></code>: 1Hz<br>
<code><b> 800 x 600</b></code>: 1Hz<br>
<code><b>1024 x 768</b></code>: 1Hz<br>
<code><b>1280 x 1024</b></code>: 1Hz<br>
<code><b>1600 x 1200</b></code>: 1Hz<br>
<code><b>1920 x 1440</b></code>: 1Hz</blockquote>
<a name=displayadapter0.textureformats></a></dl><p><table bgcolor=#a0a0e0><tr><td><font size=4 color=white><code><b>t e x t u r e f o r m a t s</b></code></font></td></tr></table></a><dl>
<dt><b>Supported texture formats:</b><dd><blockquote>
<i>no texture formats supported!</i>
</blockquote>
</dl><p><table bgcolor=#a0a0e0><tr><td><font size=4 color=white><code><b>c u b e t e x t u r e f o r m a t s</b></code></font></td></tr></table></a><dl>
<dt><b>Supported cube texture formats:</b><dd><blockquote>
<i>no cube texture formats supported!</i>
</blockquote>
</dl><p><table bgcolor=#a0a0e0><tr><td><font size=4 color=white><code><b>v o l u m e t e x t u r e f o r m a t s</b></code></font></td></tr></table></a><dl>
<dt><b>Supported volume texture formats:</b><dd><blockquote>
<i>no texture formats supported!</i>
</blockquote>
</dl><p><table bgcolor=#a0a0e0><tr><td><font size=4 color=white><code><b>d e p t h / s t e n c i l b u f f e r f o r m a t</b></code></font></td></tr></table></a><dl>
<dt><b>Supported depth/stencil buffer formats:</b><dd><blockquote>
<i>no depth/stencil buffer formats supported!</i>
</blockquote>
</dl><p><table bgcolor=#a0a0e0><tr><td><font size=4 color=white><code><b>m u l t i s a m p l e t y p e s</b></code></font></td></tr></table></a><dl>
<dt><b>Supported multisample types:</b><dd><blockquote>
<code><b>D3DMULTISAMPLE_NONE</b></code> <code>D3DFMT_X8R8G8B8</code> <code>D3DFMT_R5G6B5</code></blockquote>
<a name=displayadapter0.capabilities></a></dl><p><table bgcolor=#a0a0e0><tr><td><font size=4 color=white><code><b>c a p a b i l i t i e s</b></code></font></td></tr></table></a><dl>
<dt><b><code>GetDeviceCaps()</code> status code</b><dd> 2289436778, <code>0x8876086a</code>
</dl></font></td></tr></table><p>
<a name=soundadapter0><table bgcolor=#606060><tr><td><br><font size=5 color=white><code><b>s o u n d a d a p t e r 0</b></code></font><p></td></tr></table></a>
<table bgcolor=#f0f0f0><tr><td><font color=black>
<font size=5><b>Realtek HD Audio output</b><p></font>
<dl><dt><b>dwFlags</b><dd><code> 0xf5f</code> (3935)
<blockquote><code>DSCAPS_PRIMARYMONO</code> (<code>0x1</code>, 1)
<br><code>DSCAPS_PRIMARYSTEREO</code> (<code>0x2</code>, 2)
<br><code>DSCAPS_PRIMARY8BIT</code> (<code>0x4</code>, 4)
<br><code>DSCAPS_PRIMARY16BIT</code> (<code>0x8</code>, 8)
<br><code>DSCAPS_CONTINUOUSRATE</code> (<code>0x10</code>, 16)
<br><code>DSCAPS_CERTIFIED</code> (<code>0x40</code>, 64)
<br><code>DSCAPS_SECONDARYMONO</code> (<code>0x100</code>, 256)
<br><code>DSCAPS_SECONDARYSTEREO</code> (<code>0x200</code>, 512)
<br><code>DSCAPS_SECONDARY8BIT</code> (<code>0x400</code>, 1024)
<br><code>DSCAPS_SECONDARY16BIT</code> (<code>0x800</code>, 2048)
</blockquote>
<dt><b>dwMinSecondarySampleRate</b><dd> 8000, <code>0x1f40</code>
<dt><b>dwMaxSecondarySampleRate</b><dd> 192000, <code>0x2ee00</code>
<dt><b>dwPrimaryBuffers</b><dd> 1, <code>0x1</code>
<dt><b>dwMaxHwMixingAllBuffers</b><dd> 33, <code>0x21</code>
<dt><b>dwMaxHwMixingStaticBuffers</b><dd> 33, <code>0x21</code>
<dt><b>dwMaxHwMixingStreamingBuffers</b><dd> 33, <code>0x21</code>
<dt><b>dwFreeHwMixingAllBuffers</b><dd> 31, <code>0x1f</code>
<dt><b>dwFreeHwMixingStaticBuffers</b><dd> 31, <code>0x1f</code>
<dt><b>dwFreeHwMixingStreamingBuffers</b><dd> 31, <code>0x1f</code>
<dt><b>dwMaxHw3DAllBuffers</b><dd> 33, <code>0x21</code>
<dt><b>dwMaxHw3DStaticBuffers</b><dd> 33, <code>0x21</code>
<dt><b>dwMaxHw3DStreamingBuffers</b><dd> 33, <code>0x21</code>
<dt><b>dwFreeHw3DAllBuffers</b><dd> 31, <code>0x1f</code>
<dt><b>dwFreeHw3DStaticBuffers</b><dd> 31, <code>0x1f</code>
<dt><b>dwFreeHw3DStreamingBuffers</b><dd> 31, <code>0x1f</code>
<dt><b>dwTotalHwMemBytes</b><dd> 0, <code>0x0</code>
<dt><b>dwFreeHwMemBytes</b><dd> 0, <code>0x0</code>
<dt><b>dwMaxContigFreeHwMemBytes</b><dd> 0, <code>0x0</code>
<dt><b>dwUnlockTransferRateHwBuffers</b><dd> 0, <code>0x0</code>
<dt><b>dwPlayCpuOverheadSwBuffers</b><dd> 0, <code>0x0</code>
</dl></font></td></tr></table><p>
<a name=inputdevice0><table bgcolor=#0000b0><tr><td><br><font size=5 color=white><code><b>i n p u t d e v i c e 0</b></code></font><p></td></tr></table></a>
<table bgcolor=#ececff><tr><td><font color=black>
<font size=5><b>Mouse</b><p></font>
<dl><dt><b>tszProductName</b><dd><code> Mouse </code>
<dt><b>guidInstance</b><dd><code> {6f1d2b60-d5a0-11cf-bfc7-444553540000} </code>
<dt><b>guidProduct</b><dd><code> {6f1d2b60-d5a0-11cf-bfc7-444553540000} </code>
<dt><b>dwDevType</b><dd><code> DI8DEVTYPE_MOUSE</code> (18, <code>0x12</code>)
<dt><b>dwDevSubType</b><dd><code> DI8DEVTYPEMOUSE_UNKNOWN</code> (1, <code>0x1</code>)
</dl></font></td></tr></table><p>
<a name=inputdevice1><table bgcolor=#606060><tr><td><br><font size=5 color=white><code><b>i n p u t d e v i c e 1</b></code></font><p></td></tr></table></a>
<table bgcolor=#f0f0f0><tr><td><font color=black>
<font size=5><b>Keyboard</b><p></font>
<dl><dt><b>tszProductName</b><dd><code> Keyboard </code>
<dt><b>guidInstance</b><dd><code> {6f1d2b61-d5a0-11cf-bfc7-444553540000} </code>
<dt><b>guidProduct</b><dd><code> {6f1d2b61-d5a0-11cf-bfc7-444553540000} </code>
<dt><b>dwDevType</b><dd><code> DI8DEVTYPE_KEYBOARD</code> (19, <code>0x13</code>)
<dt><b>dwDevSubType</b><dd><code> DI8DEVTYPEKEYBOARD_PCENH</code> (4, <code>0x4</code>)
</dl></font></td></tr></table><p>
<a name=dlls><table bgcolor=#0000b0><tr><td><br><font size=5 color=white><code><b>d l l s</b></code></font><p></td></tr></table></a>
<table bgcolor=#ececff><tr><td><font color=black>
<dl><a name=dlls.directx></a>
</dl><p><table bgcolor=#a0a0e0><tr><td><font size=4 color=white><code><b>d i r e c t x</b></code></font></td></tr></table></a><dl>
<dt><b>d3d8.dll</b><dd><code> version 5.3.2600.5512, size 1179648 bytes </code>
<dt><b>d3d8d.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>d3d8thk.dll</b><dd><code> version 5.3.2600.5512, size 8192 bytes </code>
<dt><b>d3d9.dll</b><dd><code> version 5.3.2600.5512, size 1689088 bytes </code>
<dt><b>d3d9d.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>d3dim.dll</b><dd><code> version 5.1.2600.0, size 436224 bytes </code>
<dt><b>d3dim700.dll</b><dd><code> version 5.3.2600.5512, size 824320 bytes </code>
<dt><b>d3dpmesh.dll</b><dd><code> version 5.1.2600.0, size 34816 bytes </code>
<dt><b>d3dramp.dll</b><dd><code> version 5.1.2600.0, size 590336 bytes </code>
<dt><b>d3dref.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>d3dref8.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>d3dref9.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>d3drm.dll</b><dd><code> version 5.1.2600.0, size 350208 bytes </code>
<dt><b>d3dx8d.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>d3dx9d.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>d3dxof.dll</b><dd><code> version 5.1.2600.0, size 47616 bytes </code>
<dt><b>ddraw.dll</b><dd><code> version 5.3.2600.5512, size 279552 bytes </code>
<dt><b>ddrawex.dll</b><dd><code> version 5.3.2600.5512, size 27136 bytes </code>
<dt><b>diactfrm.dll</b><dd><code> version 5.1.2600.0, size 394240 bytes </code>
<dt><b>dimap.dll</b><dd><code> version 5.1.2600.0, size 44032 bytes </code>
<dt><b>dinput.dll</b><dd><code> version 5.3.2600.5512, size 158720 bytes </code>
<dt><b>dinput8.dll</b><dd><code> version 5.3.2600.5512, size 181760 bytes </code>
<dt><b>dinput8d.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>directx.cpl</b><dd><code> <i>not found!</i> </code>
<dt><b>dmband.dll</b><dd><code> version 5.3.2600.5512, size 28672 bytes </code>
<dt><b>dmbandd.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>dmcompod.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>dmcompos.dll</b><dd><code> version 5.3.2600.5512, size 61440 bytes </code>
<dt><b>dmime.dll</b><dd><code> version 5.3.2600.5512, size 181248 bytes </code>
<dt><b>dmimed.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>dmloaded.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>dmloader.dll</b><dd><code> version 5.3.2600.5512, size 35840 bytes </code>
<dt><b>dmscripd.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>dmscript.dll</b><dd><code> version 5.3.2600.5512, size 82432 bytes </code>
<dt><b>dmstyle.dll</b><dd><code> version 5.3.2600.5512, size 105984 bytes </code>
<dt><b>dmstyled.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>dmsynth.dll</b><dd><code> version 5.3.2600.5512, size 103424 bytes </code>
<dt><b>dmsynthd.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>dmusic.dll</b><dd><code> version 5.3.2600.5512, size 104448 bytes </code>
<dt><b>dmusicd.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>dplay.dll</b><dd><code> version 5.0.2134.1, size 33040 bytes </code>
<dt><b>dplaysvr.exe</b><dd><code> version 5.3.2600.5512, size 29696 bytes </code>
<dt><b>dplayx.dll</b><dd><code> version 5.3.2600.5512, size 229888 bytes </code>
<dt><b>dpmodemx.dll</b><dd><code> version 5.3.2600.5512, size 23552 bytes </code>
<dt><b>dpnaddr.dll</b><dd><code> version 5.3.2600.5512, size 3072 bytes </code>
<dt><b>dpnet.dll</b><dd><code> version 5.3.2600.5512, size 375296 bytes </code>
<dt><b>dpnetd.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>dpnhpast.dll</b><dd><code> version 5.3.2600.5512, size 35328 bytes </code>
<dt><b>dpnhpastd.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>dpnhupnp.dll</b><dd><code> version 5.3.2600.5512, size 60928 bytes </code>
<dt><b>dpnhupnpd.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>dpnlobby.dll</b><dd><code> version 5.3.2600.5512, size 3072 bytes </code>
<dt><b>dpnsvr.exe</b><dd><code> version 5.3.2600.5512, size 17920 bytes </code>
<dt><b>dpnsvrd.exe</b><dd><code> <i>not found!</i> </code>
<dt><b>dpserial.dll</b><dd><code> version 5.0.2134.1, size 53520 bytes </code>
<dt><b>dpvacm.dll</b><dd><code> version 5.3.2600.5512, size 21504 bytes </code>
<dt><b>dpvacmd.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>dpvoice.dll</b><dd><code> version 5.3.2600.5512, size 212480 bytes </code>
<dt><b>dpvoiced.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>dpvsetup.exe</b><dd><code> version 5.3.2600.5512, size 83456 bytes </code>
<dt><b>dpvvox.dll</b><dd><code> version 5.3.2600.5512, size 116736 bytes </code>
<dt><b>dpvvoxd.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>dpwsock.dll</b><dd><code> version 5.0.2134.1, size 42768 bytes </code>
<dt><b>dpwsockx.dll</b><dd><code> version 5.3.2600.5512, size 57344 bytes </code>
<dt><b>dsdmo.dll</b><dd><code> version 5.3.2600.5512, size 181248 bytes </code>
<dt><b>dsdmoprp.dll</b><dd><code> version 5.3.2600.5512, size 71680 bytes </code>
<dt><b>dsound.dll</b><dd><code> version 5.3.2600.5512, size 367616 bytes </code>
<dt><b>dsound3d.dll</b><dd><code> version 5.3.2600.5512, size 1293824 bytes </code>
<dt><b>dswave.dll</b><dd><code> version 5.3.2600.5512, size 19456 bytes </code>
<dt><b>dswaved.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>dx7vb.dll</b><dd><code> version 5.3.2600.5512, size 619008 bytes </code>
<dt><b>dx8vb.dll</b><dd><code> version 5.3.2600.5512, size 1227264 bytes </code>
<dt><b>dxapi.sys</b><dd><code> version 5.1.2600.0, size 10496 bytes </code>
<dt><b>dxdiagn.dll</b><dd><code> version 5.3.2600.5512, size 2113536 bytes </code>
<dt><b>gcdef.dll</b><dd><code> version 5.1.2600.0, size 76800 bytes </code>
<dt><b>joy.cpl</b><dd><code> version 5.3.2600.5512, size 68608 bytes </code>
<dt><b>Microsoft.DirectX.AudioVideoPlayback.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>Microsoft.DirectX.Diagnostics.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>Microsoft.DirectX.Direct3D.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>Microsoft.DirectX.Direct3DX.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>Microsoft.DirectX.DirectDraw.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>Microsoft.DirectX.DirectInput.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>Microsoft.DirectX.DirectPlay.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>Microsoft.DirectX.DirectSound.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>Microsoft.DirectX.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>pid.dll</b><dd><code> version 5.3.2600.5512, size 35328 bytes </code>
<dt><b>system.dll</b><dd><code> <i>not found!</i> </code>
<a name=dlls.crtl></a>
</dl><p><table bgcolor=#a0a0e0><tr><td><font size=4 color=white><code><b>c r u n - t i m e l i b r a r y</b></code></font></td></tr></table></a><dl>
<dt><b>mfc40.dll</b><dd><code> version 4.1.6140, size 924432 bytes </code>
<dt><b>mfc42.dll</b><dd><code> version 6.02.4131.0, size 1028096 bytes </code>
<dt><b>msvcirt.dll</b><dd><code> version 5.1.2600.5512, size 57344 bytes </code>
<dt><b>msvcirtd.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>msvcp50.dll</b><dd><code> version 5.0.0.7051, size 565760 bytes </code>
<dt><b>msvcp60.dll</b><dd><code> version 6.2.3104.0, size 413696 bytes </code>
<dt><b>msvcp60d.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>msvcrt.dll</b><dd><code> version 6.1.8638.5512, size 343040 bytes </code>
<dt><b>msvcrtd.dll</b><dd><code> <i>not found!</i> </code>
</dl><p><table bgcolor=#a0a0e0><tr><td><font size=4 color=white><code><b>w i n d o w s</b></code></font></td></tr></table></a><dl>
<dt><b>comctl32.dll</b><dd><code> version 6.0.2900.5512, size 617472 bytes </code>
<dt><b>comdlg32.dll</b><dd><code> version 6.0.2900.5512, size 276992 bytes </code>
<dt><b>ctl3d32.dll</b><dd><code> version 2.31.000, size 27136 bytes </code>
<dt><b>gdi32.dll</b><dd><code> version 5.1.2600.5512, size 285184 bytes </code>
<dt><b>kernel32.dll</b><dd><code> version 5.1.2600.5512, size 989696 bytes </code>
<dt><b>user32.dll</b><dd><code> version 5.1.2600.5512, size 578560 bytes </code>
<dt><b>version.dll</b><dd><code> version 5.1.2600.5512, size 18944 bytes </code>
<dt><b>wsock32.dll</b><dd><code> version 5.1.2600.5512, size 22528 bytes </code>
</dl><p><table bgcolor=#a0a0e0><tr><td><font size=4 color=white><code><b>i n t e r n e t e x p l o r e r</b></code></font></td></tr></table></a><dl>
<dt><b>shdocvw.dll</b><dd><code> version 6.0.2900.5512, size 1499136 bytes </code>
<a name=dlls.misc></a>
</dl><p><table bgcolor=#a0a0e0><tr><td><font size=4 color=white><code><b>m i s c e l l a n e o u s</b></code></font></td></tr></table></a><dl>
<dt><b>amstream.dll</b><dd><code> version 6.05.2600.5512, size 70656 bytes </code>
<dt><b>bdaplgin.ax</b><dd><code> <i>not found!</i> </code>
<dt><b>bdasup.sys</b><dd><code> <i>not found!</i> </code>
<dt><b>ccdecode.sys</b><dd><code> <i>not found!</i> </code>
<dt><b>devenum.dll</b><dd><code> version 6.05.2600.5512, size 59904 bytes </code>
<dt><b>dxmasf.dll</b><dd><code> version 6.4.09.1133, size 498742 bytes </code>
<dt><b>encapi.dll</b><dd><code> version 5.3.2600.5512, size 20480 bytes </code>
<dt><b>iac25_32.ax</b><dd><code> version 2.05.53, size 199680 bytes </code>
<dt><b>ipsink.ax</b><dd><code> <i>not found!</i> </code>
<dt><b>ir41_32.ax</b><dd><code> version 4.51.16.03, size 848384 bytes </code>
<dt><b>ir41_qc.dll</b><dd><code> version 4.30.62.2, size 120320 bytes </code>
<dt><b>ir41_qcx.dll</b><dd><code> version 4.30.64.1, size 338432 bytes </code>
<dt><b>ir50_32.dll</b><dd><code> version R.5.10.15.2.55, size 755200 bytes </code>
<dt><b>ir50_qc.dll</b><dd><code> version 5.0.63.48, size 200192 bytes </code>
<dt><b>ir50_qcx.dll</b><dd><code> version 5.0.64.48, size 183808 bytes </code>
<dt><b>ivfsrc.ax</b><dd><code> version 5.10.2.51, size 154624 bytes </code>
<dt><b>ks.sys</b><dd><code> version 5.3.2600.5512, size 141056 bytes </code>
<dt><b>ksproxy.ax</b><dd><code> version 5.3.2600.5512, size 129536 bytes </code>
<dt><b>kstvtune.ax</b><dd><code> <i>not found!</i> </code>
<dt><b>ksuser.dll</b><dd><code> version 5.3.2600.5512, size 4096 bytes </code>
<dt><b>kswdmcap.ax</b><dd><code> <i>not found!</i> </code>
<dt><b>ksxbar.ax</b><dd><code> <i>not found!</i> </code>
<dt><b>mciqtz32.dll</b><dd><code> version 6.05.2600.5512, size 35328 bytes </code>
<dt><b>mpe.sys</b><dd><code> <i>not found!</i> </code>
<dt><b>mpeg2data.ax</b><dd><code> version 6.05.2600.5512, size 118272 bytes </code>
<dt><b>mpg2splt.ax</b><dd><code> version 6.05.2600.5512, size 148992 bytes </code>
<dt><b>msdmo.dll</b><dd><code> version 6.05.2600.5512, size 14336 bytes </code>
<dt><b>msdv.sys</b><dd><code> <i>not found!</i> </code>
<dt><b>msdvbnp.ax</b><dd><code> <i>not found!</i> </code>
<dt><b>mskssrv.sys</b><dd><code> version 5.3.2600.5512, size 7552 bytes </code>
<dt><b>mspclock.sys</b><dd><code> version 5.3.2600.5512, size 5376 bytes </code>
<dt><b>mspqm.sys</b><dd><code> version 5.1.2600.5512, size 4992 bytes </code>
<dt><b>mstee.sys</b><dd><code> <i>not found!</i> </code>
<dt><b>msvidctl.dll</b><dd><code> version 6.5.2600.5512, size 1428992 bytes </code>
<dt><b>mswebdvd.dll</b><dd><code> version 6.5.2600.5512, size 203776 bytes </code>
<dt><b>msyuv.dll</b><dd><code> version 5.3.2600.5512, size 16896 bytes </code>
<dt><b>nabtsfec.sys</b><dd><code> <i>not found!</i> </code>
<dt><b>ndisip.sys</b><dd><code> <i>not found!</i> </code>
<dt><b>psisdecd.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>psisrndr.ax</b><dd><code> <i>not found!</i> </code>
<dt><b>qasf.dll</b><dd><code> version 9.0.0.4503, size 237568 bytes </code>
<dt><b>qcap.dll</b><dd><code> version 6.05.2600.5512, size 192512 bytes </code>
<dt><b>qdv.dll</b><dd><code> version 6.05.2600.5512, size 279040 bytes </code>
<dt><b>qdvd.dll</b><dd><code> version 6.05.2600.5512, size 386048 bytes </code>
<dt><b>qedit.dll</b><dd><code> version 6.05.2600.5512, size 562176 bytes </code>
<dt><b>qedwipes.dll</b><dd><code> version 6.05.2600.5512, size 733696 bytes </code>
<dt><b>quartz.dll</b><dd><code> version 6.05.2600.5512, size 1288192 bytes </code>
<dt><b>slip.sys</b><dd><code> <i>not found!</i> </code>
<dt><b>stream.sys</b><dd><code> version 5.3.2600.5512, size 49408 bytes </code>
<dt><b>streamip.sys</b><dd><code> <i>not found!</i> </code>
<dt><b>strmdll.dll</b><dd><code> version 4.1.0.3936, size 246814 bytes </code>
<dt><b>swenum.sys</b><dd><code> version 5.3.2600.5512, size 4352 bytes </code>
<dt><b>vbisurf.ax</b><dd><code> version 5.3.2600.5512, size 30208 bytes </code>
<dt><b>vfwwdm32.dll</b><dd><code> <i>not found!</i> </code>
<dt><b>wstcodec.sys</b><dd><code> <i>not found!</i> </code>
<dt><b>wstdecod.dll</b><dd><code> version 5.3.2600.5512, size 50688 bytes </code>
</dl></font></td></tr></table><p>
<a name=calculationtook1.25seconds><table bgcolor=#606060><tr><td><br><font size=4 color=white><code><b>c a l c u l a t i o n t o o k 1 . 2 5 s e c o n d s</b></code></font><p></td></tr></table></a>
<table bgcolor=#606060><tr><td><p><font color=white size=-1 face=arial,helvetica><b>Generated by <a href=http://www.midwinter.com/~lch/programming/dx8diagnostics/><font color=white>dx8Diagnostics version 1.2</font></a></b></font></td></tr></table><!--
Nonce:
[d3d:0:{d7b70ee0-4340-11cf-b063-282aaec2c835}][dsound:0:{bd6dd71a-3deb-11d1-b171-00c04fc20001}][dinput:0:{6f1d2b60-d5a0-11cf-bfc7-444553540000}][dinput:1:{6f1d2b61-d5a0-11cf-bfc7-444553540000}]
-->
</body>
</html> | 12130187-project | trunk/dx8diagnostics.html | HTML | bsd | 23,712 |
#pragma config(Sensor, dgtl1, lateralSensor, sensorSONAR_cm)
#pragma config(Sensor, dgtl3, wheelEncoder, sensorQuadEncoder)
#pragma config(Sensor, dgtl5, leftSensor, sensorTouch)
#pragma config(Sensor, dgtl6, rightSensor, sensorTouch)
#pragma config(Sensor, dgtl7, clawSensor, sensorTouch)
#pragma config(Sensor, dgtl8, frontalSensor, sensorSONAR_cm)
#pragma config(Motor, port2, frontMotor, tmotorServoContinuousRotation, openLoop, reversed)
#pragma config(Motor, port3, clawMotor, tmotorServoContinuousRotation, openLoop, reversed)
#pragma config(Motor, port4, upMotor, tmotorServoStandard, openLoop)
#pragma config(Motor, port5, rotationMotor, tmotorServoStandard, openLoop)
//*!!Code automatically generated by 'ROBOTC' configuration wizard !!*//
const int DimGrid = 24;
const int lateralMovement=6;
const int NZZ = DimGrid/(lateralMovement*2);
const int speed = 60;
const int extend = -127;
const int timeMoveUp = 1200;
const int timeRotate = 30;
const int time = 500;
const int time2 = 3000;
const int time3 = 500;
const int timeBackward = 500;
const int timeClaw = 200;
const float length = 7/3.25;
const float width = 5/3.25;
const float C = 1.5;
const int wall = 10;
const int bottleLength = 4;
const int clawSpeed = 50;
const byte ERR = 1;
const int degree = 92;
const int out = 3;
float X,Y,XO,YO;//0:front 1:right 2:down 3:left
byte ORI;
bool turn,move,END,ENDR;
byte map[DimGrid][DimGrid];
task position(){
while(!END){
float ang=0;
SensorValue[wheelEncoder]=0;
while(move&&!turn){
ang=SensorValue[wheelEncoder];
if(ang>100){ang=360-ang;}
SensorValue[wheelEncoder]=0;
switch(ORI){
case 0:Y+=ang/90;break;
case 1:X+=ang/90;break;
case 2:Y-=ang/90;break;
case 3:X-=ang/90;break;
}
wait1Msec(time);
}
wait1Msec(time);
}
}
float sonar(char i){
float s=(i=='f')?SensorValue(frontalSensor):SensorValue(lateralSensor);
if(s>1&&s<20)return s;
else return 100;
}
void add(int x,int y){
if(x<DimGrid&&x>0&&y>0&&y<DimGrid&&map[x][y]<127){map[x][y]++;}
}
task relevation(){
for(int i=0;i<DimGrid;i++)
for(int j=0;j<DimGrid;j++)
map[i][j]=0;
while(!ENDR){
if(sonar('f')<100){
switch(ORI){
case 0:add(X,Y+length); break;
case 1:add(X+length,Y); break;
case 2:add(X,Y-length); break;
case 3:add(X-length,Y); break;
}
}
if(sonar('l')<100){
switch(ORI){
case 3:add(X,Y+width); break;
case 0:add(X+width,Y); break;
case 1:add(X,Y-width); break;
case 2:add(X-width,Y); break;
}
}
}
}
void turnLR2(int dir){//1:right -1:left
if(dir<0){
motor[rotationMotor]=-degree;
wait1Msec(timeMoveUp*1.5);
motor[upMotor]=extend;
wait1Msec(timeMoveUp);
for(int i=-degree;i<degree;i++){
wait1Msec(timeRotate);
motor[rotationMotor]=i;
}
}else{
motor[rotationMotor]=degree;
wait1Msec(timeMoveUp*1.5);
motor[upMotor]=extend;
wait1Msec(timeMoveUp);
for(int i=-degree;i<degree;i++){
wait1Msec(timeRotate);
motor[rotationMotor]=-i;
}
}
motor[upMotor]=-extend;
wait1Msec(timeMoveUp);
motor[rotationMotor]=0;
wait1Msec(timeMoveUp*1.5);
}
void turnLR(int dir){
turn=true;
// turnLR2(dir);
turnLR2(dir);
turn=false;
ORI+=dir;
if(ORI>3){ORI-=4;}
if(ORI<0){ORI+=4;}
}
void moveStraight2(int cel){
float x=X;
float y=Y;
switch(ORI){
case 0:y=Y+cel; break;
case 1:x=X+cel; break;
case 2:y=Y-cel; break;
case 3:x=X-cel; break;
}
while((abs(x-X)>ERR||abs(y-Y)>ERR)){
move=true;
motor[frontMotor]=speed;
}
move=false;
motor[frontMotor]=0;
}
bool moveStraight(int cel,bool keep){
float x=X;
float y=Y;
bool found=false;
bool b;
switch(ORI){
case 0:{y=Y+cel; b=Y>y; break;}
case 1:{x=X+cel; b=X>x; break;}
case 2:{y=Y-cel; b=Y<y; break;}
case 3:{x=X-cel; b=X<x; break;}
}
while(!b&&!found){
move=true;
motor[frontMotor]=speed;
if(sonar('f')<wall){
move = false;
motor[frontMotor]=0;
int obj=0;
for(int i=0;i<100;i++){if(sonar('f')<wall)obj++;}
if(obj>=90&&!keep){
motor[frontMotor]=-speed;
wait1Msec(timeBackward);
motor[frontMotor]=0;
turnLR(-1);
moveStraight2(bottleLength);
turnLR(1);
moveStraight2(bottleLength*2.5);
turnLR(1);
moveStraight2(bottleLength);
turnLR(-1);
}else if(obj>=90){
found=true;
}
}
switch(ORI){
case 0:{b=Y>y; break;}
case 1:{b=X>x; break;}
case 2:{b=Y<y; break;}
case 3:{b=X<x; break;}
}
}
motor[frontMotor]=0;
move=false;
return found;
}
void think(){
float middle=0;
int i=0;
for (int x=0;x<DimGrid;x++)
for (int y=0;y<DimGrid;y++)
if (map[x][y]!=0){
i++;
middle+=map[x][y];
}
middle/=i;
i=0;
XO = 0;
YO = 0;
for (int x=0;x<DimGrid;x++)
for (int y=0;y<DimGrid;y++){
map[x][y]=(map[x][y]>=middle*C)?1:0;
if(map[x][y]==1){
i++;
XO+=x;
YO+=y;
}
}
XO/=i;
YO/=i;
}
void pickUp(){
motor[frontMotor]=-speed;
wait1Msec(timeBackward);
motor[frontMotor]=0;
turnLR(1);
turnLR(1);
motor[clawMotor]=-clawSpeed;
wait1Msec(time3);
while(!SensorValue(clawSensor)){
motor[frontMotor]=-speed;
}
motor[frontMotor]=0;
motor[clawMotor]=clawSpeed;
wait1Msec(time3);
motor[clawMotor]=0;
}
void putDown(){
motor[frontMotor]=speed;
wait1Msec(time3);
motor[frontMotor]=0;
motor[clawMotor]=-clawSpeed;
wait1Msec(timeClaw);
motor[clawMotor]=0;
}
task main(){
X=0;
Y=0;
ORI=0;
turn = false;
END=false;
motor[upMotor]=-extend;
wait1Msec(1000);
StartTask(position);
StartTask(relevation);
int i=0;
while(i<NZZ){
moveStraight(DimGrid+out+((i!=0)?out:0),false);
turnLR(1);
moveStraight(lateralMovement,false);
turnLR(1);
moveStraight(DimGrid+out*2,false);
if(i<NZZ-1){
turnLR(-1);
moveStraight(lateralMovement,false);
turnLR(-1);
}
i++;
}
ENDR=false;
turnLR(1);
moveStraight(DimGrid-lateralMovement,false);
turnLR(1);
think();
wait1Msec(time2);
bool found=false;
i=0;
while(i<NZZ&&!found){
found = moveStraight(DimGrid+out*2,true);
if (!found){
turnLR(1);
moveStraight(lateralMovement,false);
turnLR(1);
found = moveStraight(DimGrid+out*2,true);
if(!found){
turnLR(-1);
moveStraight(lateralMovement,false);
turnLR(-1);
i++;
}
}
}
if (found){
pickUp();
if(X>XO){
switch(ORI){
case 1:turnLR(1);turnLR(1); break;
case 2:turnLR(1); break;
case 0:turnLR(-1); break;
}
moveStraight(X-XO,false);
}else if(X<XO){
switch(ORI){
case 3:turnLR(1);turnLR(1); break;
case 2:turnLR(-1); break;
case 0:turnLR(1); break;
}
moveStraight(XO-X,false);
}
if(Y>YO){
switch(ORI){
case 0:turnLR(1);turnLR(1); break;
case 1:turnLR(1); break;
case 3:turnLR(-1); break;
}
moveStraight(Y-YO,false);
}else if(Y<YO){
switch(ORI){
case 2:turnLR(1);turnLR(1); break;
case 1:turnLR(-1); break;
case 3:turnLR(1); break;
}
moveStraight(YO-Y,false);
}
putDown();
}
ENDR=true;
END=true;
}
| 123123b | FinalProject.c | C | mit | 7,838 |
import logging
logger = logging.getLogger('x90-analyze')
logger.setLevel(logging.DEBUG)
# File Handler
hdlr = logging.FileHandler('logs/run.log')
formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
hdlr.setLevel(logging.DEBUG)
# Stream handler
ch = logging.StreamHandler()
formatter = logging.Formatter('[%(levelname)s] %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)
ch.setLevel(logging.INFO)
def printerror (msg):
logger.error(msg)
def printwarning (msg):
logger.warning(msg)
def printinfo (msg):
logger.info(msg)
| 0x90-analyze | trunk/logger.py | Python | gpl2 | 616 |
import os
import re
import shutil
import commands
import _mysql
import hashlib
import logger
# Analyze project.
def analyze_metrics(project, revision, url, db, folder):
analyze_code_metrics(project, revision, url, db, folder)
analyze_filemetrics(project, revision, url, db, folder)
# Get code metrics:
def analyze_code_metrics(project, revision, url, db, folder):
logger.printinfo("Analyzing code")
phand = os.popen("cloc "+folder)
# read output from the command
while 1:
line = phand.readline()
if line == "": break
# Find the sum of the code calculations with regex.
m = re.search('SUM:.*?(?P<FILES>[0-9]+).*? (?P<BLANK>[0-9]+).*? (?P<COMMENT>[0-9]+).*? (?P<CODE>[0-9]+)', line)
if m is not None:
files = m.group("FILES")
blank = m.group("BLANK")
comment = m.group("COMMENT")
code = m.group("CODE")
db.insertmetric(project, revision, url, files, blank, comment, code)
phand.close()
return
phand.close()
return
# Code metrics by file:
def analyze_filemetrics (project, revision, url, db, folder):
logger.printinfo("Analyzing files")
phand = os.popen("cloc --by-file --sql=1 " + folder)
# read output from the command
while 1:
line = phand.readline()
if line == "": break
m = re.search('\',\ \'(?P<LANG>.*?)\',\ \'(?P<FILE>.*?)\',\ (?P<BLANK>[0-9]+),\ (?P<COMMENT>[0-9]+),\ (?P<CODE>[0-9]+),\ ', line)
if m is not None:
filename = m.group("FILE");
blank = m.group("BLANK");
comment = m.group("COMMENT");
code = m.group("CODE");
lang = m.group("LANG");
db.insertfilemetric(project, revision, url, filename, blank, comment, code, lang)
phand.close()
| 0x90-analyze | trunk/metrics.py | Python | gpl2 | 1,648 |
##
## Ändra databas inställningar
## TOD: Fixa stöd för att genera grafer för enskilda projekt.
##
## usage: R < plot.r --save abiword
#
#
library(RMySQL)
con <- dbConnect(dbDriver("MySQL"), user="root",
password="reload", dbname="x90test")
args <- commandArgs()
name <-args[3]
# Get commits from database.
query <- paste("SELECT date, rev, count(s.rev) as commits FROM log as s where s.project='",name,"' group by date_format(s.date,'%Y%m')
", sep="");
res <- dbGetQuery(con,query)
# Plot activity
png(paste(name,"commits",".png"), width = 320, height = 320, units = "px")
plot(strptime(res$date,"%Y-%m-%d"),res$commits, type="l", xlab="Date", ylab="Commits",
main=paste(name,"count(log.date) per month"))
# Get comment density from database
query <- paste("select date, sum(comment)/sum(code) as totaldensity, log.rev from filemetric, log where log.rev=filemetric.rev and filemetric.project='",name,"' and log.project='",name,"' group by date_format(log.date,'%Y%m') order by date asc", sep="");
results <- dbGetQuery(con,query)
#print(results)
png(paste(name,"density",".png"), width = 320, height = 320, units = "px")
plot(strptime(results$date,"%Y-%m-%d"),results$totaldensity, type="l", xlab="Date", ylab="Density", ylim=c(0,0.8),
main=paste(name,"sum(comment)/sum(code) per month"))
dev.off()
| 0x90-analyze | trunk/graph/plot.r | R | gpl2 | 1,339 |
import _mysql
import logger
import hashlib
class DbHandler:
##
## Ansluter till databas of verifierar att tabellerna finns.
## Om de inte finns, skapa dem..
##
def __init__(self, pSettings):
# Connect to database:
try:
self.db=_mysql.connect(host=pSettings.host, user=pSettings.username, passwd=pSettings.password, db=pSettings.schema)
# Verifiera att tabeller finns.
self.db.query("SELECT * FROM project LIMIT 1")
self.db.use_result();
self.db.query("SELECT * FROM log LIMIT 1")
self.db.use_result();
self.db.query("SELECT * FROM metric LIMIT 1")
self.db.use_result();
return None;
except _mysql.Error, e:
if e.args[0] == 1146:
# Skapa tabell
logger.printerror("No tables found. Create tables first!")
logger.printerror("The SQL code to create tables is in sql/tables.sql")
exit();
if e.args[0] == 2005:
logger.printerror("Fel: Kunde inte ansluta till: "+pHost)
exit();
if e.args[0] == 1045:
logger.printerror("[E] Invalid username/password!"+pHost)
exit();
if e.args[0] == 1049:
logger.printerror("[E] The schema doesnt exists!\r\nCreate it in mysql first.")
exit();
else:
logger.printerror("[E] Error %d: %s" % (e.args[0],e.args[1]))
exit();
# Insert project to database
def insertproject(self, name, type):
try:
self.db.query("insert into project (name, type) VALUES ('"+name+"','"+type+"')")
except _mysql.Error, e:
if e.args[0] == 1062:
logger.printinfo("[!] Projektet "+name+" finns redan, analyzerar det igen!")
else:
logger.printerror("[E] Error %d: %s" % (e.args[0],e.args[1]))
return;
# Insert to scmlog
def insertscmlog(self, project, url, rev, user, date):
# Insert into database and notify user.
try:
self.db.query("insert into log (project, url, rev, user, date) VALUES ('"+project+"','"+url+"','"+rev+"','"+user+"','"+date+"')")
logger.printinfo("New revision "+rev)
except _mysql.Error, e:
if e.args[0] != 1062: # Ignorerar duplicate fel.
print "Error %d: %s" % (e.args[0],e.args[1])
def fetchrevisonstoanalyze(self, project, url):
# Get the first revision each month and check if its been analyzed!
self.db.query("select revs.foundrev as rev, (Select 1 from metric where metric.rev=revs.foundrev and revs.url=metric.url and revs.project=metric.project limit 1) as analyzed from (SELECT log.url,log.project, ( select c.rev from log as c where c.project=log.project and c.date= min(log.date) limit 1) as foundrev FROM `log` where project='"+project+"' and url='"+url+"' group by date_format(date,'%Y%m') order by date desc) as revs")
r = self.db.store_result()
revisions = r.fetch_row(10000)
revs = []
for row in revisions:
revision = row[0]
analyzed = row[1]
if(analyzed is None):
revs.append(revision)
return revs
# Insert metric
def insertmetric(self, project, revision, url, files, blank, comment, code):
self.db.query("insert into metric (files, blank, comment, code, rev, url, project) VALUES ('"
+files+"','"+blank+"','"+comment+"','"+code+"','"+revision+"','"+url+"','"+project+"')");
# Insert filemetric
def insertfilemetric(self, project, revision, url, filename, blank, comment, code, lang):
try:
# Because of the limited key size in mysql, Generate a md5 hash as filename id:
md5name = hashlib.md5( filename ).hexdigest();
self.db.query("insert into filemetric (project, rev,url, file, blank, comment, code, lang, md5) VALUES ('"
+project+"','"+revision+"','"+url+"','"+filename+"','"+blank+"','"+comment
+"','"+code+"','"+lang+"','"+md5name+"')");
except UnboundLocalError, e:
print e
except _mysql.Error, e:
print "Error %d: %s" % (e.args[0],e.args[1])
| 0x90-analyze | trunk/database.py | Python | gpl2 | 3,783 |
##
## Mercurial-analyzer
##
## Todo: skriv om...
from xml.dom import minidom
import logger
## Parses a dom file
def parsedom(file):
try:
dom = minidom.parse(file)
except Exception:
logger.printerror("Failed to parse the xml file " + file);
exit()
return dom
class Project:
name="-noname-"
type="svn"
urls = []
def getprojects (file = 'settings/projects.xml'):
projects = [];
dom = parsedom(file)
logger.printinfo("Parsing project-settings")
try:
for node in dom.getElementsByTagName('project'):
proj = Project();
tmp = [];
for xnode in node.getElementsByTagName("name"):
proj.name = xnode.firstChild.wholeText
for xnode in node.getElementsByTagName("type"):
proj.type = xnode.firstChild.wholeText
for xnode in node.getElementsByTagName("url"):
tmp.append(xnode.firstChild.wholeText);
proj.urls = tmp;
projects.append(proj);
except Exception:
logger.printerror("Malformed xml elements")
exit()
return projects;
class DbSettings:
host=""
username=""
password=""
schema=""
def getdbsettings (file = 'settings/db.xml'):
logger.printinfo("Parsing database-settings")
dom = parsedom(file)
dbsetting = DbSettings()
try:
for node in dom.getElementsByTagName('database'):
for xnode in node.getElementsByTagName("host"):
dbsetting.host = xnode.firstChild.wholeText
for xnode in node.getElementsByTagName("username"):
dbsetting.username = xnode.firstChild.wholeText
for xnode in node.getElementsByTagName("password"):
dbsetting.password = xnode.firstChild.wholeText
for xnode in node.getElementsByTagName("schema"):
dbsetting.schema = xnode.firstChild.wholeText
except Exception:
logger.printerror("Malformed xml elements")
exit()
# Validate, or atleast check that variables have been changed...
if(dbsetting.host==""):
logger.printerror("Missing host")
exit()
if(dbsetting.username==""):
logger.printerror("Missing username")
exit()
if(dbsetting.password==""):
logger.printerror("Missing password")
exit()
if(dbsetting.schema==""):
logger.printerror("Missing schema")
exit()
return dbsetting;
class Type:
name="-noname-"
changelog=""
regex=""
checkout=""
def gettypes (file = 'settings/types.xml'):
types = {};
dom = parsedom(file)
logger.printinfo("Parsing supported vcs info")
try:
for node in dom.getElementsByTagName('type'):
proj = Type();
for xnode in node.getElementsByTagName("name"):
proj.name = xnode.firstChild.wholeText
for xnode in node.getElementsByTagName("changelog"):
proj.changelog = xnode.firstChild.wholeText
for xnode in node.getElementsByTagName("regex"):
proj.regex = xnode.firstChild.wholeText
for xnode in node.getElementsByTagName("checkout"):
proj.checkout = xnode.firstChild.wholeText
types[proj.name]=proj;
except Exception:
logger.printerror("Malformed xml elements")
exit()
return types;
| 0x90-analyze | trunk/settingsreader.py | Python | gpl2 | 2,937 |
import os
import sys
import re
import shutil
import commands
import _mysql
import logger
import metrics
# Find and insert commits to database
def analyze_scmlog(project, url, vcsinfo, db):
logger.printinfo("Getting changelog from vcs")
if os.path.exists ('/tmp/x90analy'):
shutil.rmtree("/tmp/x90analy")
# Checkout first version first to collect activity data.
logger.printinfo("Cloning latest version of repo, to get changeset ")
# prepare cmd
cmd = vcsinfo.changelog.replace("@[url]", url);
cmd = cmd.replace("@[workdir]", "/tmp/x90analy");
phand = os.popen(cmd)
# read and parse output from the command
while 1:
line = phand.readline()
if line == "": break
# Match with regex.
m = re.search(vcsinfo.regex, line)
if m is not None:
rev = m.group("REV")
user = m.group("AUTHOR")
date = m.group("YEAR")+"-"+m.group("MONTH")+"-"+m.group("DAY")
db.insertscmlog(project.name, url, rev, user, date)
phand.close()
# Analyze code of revisions (the last one each month)
def analyze_revisions(project, url, vcsinfo, db):
logger.printinfo("Analyzing code")
revisions = db.fetchrevisonstoanalyze(project.name, url)
for revision in revisions:
logger.printinfo("\t[+] Checking out rev: "+revision)
# prepare cmd
cmd = vcsinfo.checkout.replace("@[rev]", revision);
cmd = cmd.replace("@[workdir]", "/tmp/x90analy");
# check it out!
phand = os.popen(cmd)
while 1:
line = phand.readline()
if line == "": break
phand.close()
metrics.analyze_metrics(project.name, revision, url, db, "/tmp/x90analy")
def analyze_project(project, vcsinfo, db):
logger.printinfo("Analyzing:"+project.name);
# Add project to database.
db.insertproject(project.name, project.type);
for url in project.urls:
# Get revisions:
analyze_scmlog(project, url, vcsinfo, db);
# Analyze revisions:
analyze_revisions(project, url, vcsinfo, db);
| 0x90-analyze | trunk/analyzelib.py | Python | gpl2 | 1,896 |
##
## mercurial-analyzer
##
## Requires: Cloc (sudo apt-get install cloc)
import analyzelib
import settingsreader
from database import DbHandler
import logger
def getType(types, name):
try:
ret = types[name];
return ret
except Exception:
logger.printerror("Missing type "+name)
exit();
logger.printinfo("\t------------------------")
logger.printinfo("\t 0x90-analyzer ")
logger.printinfo("\t------------------------")
# Connect to mysql-db with settings from settings.xml
dbsettings = settingsreader.getdbsettings()
db = DbHandler(dbsettings)
types = settingsreader.gettypes()
# Find and analyze projects from settings.xml
projects = settingsreader.getprojects()
for project in projects:
type = getType(types, project.type);
analyzelib.analyze_project(project, type, db)
logger.printinfo("Done.")
| 0x90-analyze | trunk/analyze.py | Python | gpl2 | 829 |
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To chang e this template file, choose Tools | Templates
* and open the template in the editor.
*/
| 123teste321 | trunk/teste.php | PHP | gpl3 | 197 |
/*------------------------------------------------------------------------------
** Ident: Innovation en Inspiration > Google Android
** Author: rene
** Copyright: (c) Jan 22, 2009 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.tests;
import junit.framework.TestSuite;
import nl.sogeti.android.gpstracker.tests.actions.ExportGPXTest;
import nl.sogeti.android.gpstracker.tests.db.GPStrackingProviderTest;
import nl.sogeti.android.gpstracker.tests.gpsmock.MockGPSLoggerServiceTest;
import nl.sogeti.android.gpstracker.tests.logger.GPSLoggerServiceTest;
import nl.sogeti.android.gpstracker.tests.userinterface.LoggerMapTest;
import android.test.InstrumentationTestRunner;
import android.test.InstrumentationTestSuite;
/**
* Perform unit tests Run on the adb shell:
*
* <pre>
* am instrument -w nl.sogeti.android.gpstracker.tests/.GPStrackingInstrumentation
* </pre>
*
* @version $Id$
* @author rene (c) Jan 22, 2009, Sogeti B.V.
*/
public class GPStrackingInstrumentation extends InstrumentationTestRunner
{
/**
* (non-Javadoc)
* @see android.test.InstrumentationTestRunner#getAllTests()
*/
@Override
public TestSuite getAllTests()
{
TestSuite suite = new InstrumentationTestSuite( this );
suite.setName( "GPS Tracking Testsuite" );
suite.addTestSuite( GPStrackingProviderTest.class );
suite.addTestSuite( MockGPSLoggerServiceTest.class );
suite.addTestSuite( GPSLoggerServiceTest.class );
suite.addTestSuite( ExportGPXTest.class );
suite.addTestSuite( LoggerMapTest.class );
// suite.addTestSuite( OpenGPSTrackerDemo.class ); // The demo recorded for youtube
// suite.addTestSuite( MapStressTest.class ); // The stress test of the map viewer
return suite;
}
/**
* (non-Javadoc)
* @see android.test.InstrumentationTestRunner#getLoader()
*/
@Override
public ClassLoader getLoader()
{
return GPStrackingInstrumentation.class.getClassLoader();
}
}
| 11chauhanpeeyush11-peeyush | OpenGPSTracker/test/src/nl/sogeti/android/gpstracker/tests/GPStrackingInstrumentation.java | Java | gpl3 | 3,313 |
/*------------------------------------------------------------------------------
** Ident: Innovation en Inspiration > Google Android
** Author: rene
** Copyright: (c) Jan 22, 2009 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.tests.utils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.content.Context;
import android.content.res.XmlResourceParser;
import android.util.Log;
/**
* Feeder of GPS-location information
*
* @version $Id$
* @author Maarten van Berkel (maarten.van.berkel@sogeti.nl / +0586)
*/
public class MockGPSLoggerDriver implements Runnable
{
private static final String TAG = "MockGPSLoggerDriver";
private boolean running = true;
private int mTimeout;
private Context mContext;
private TelnetPositionSender sender;
private ArrayList<SimplePosition> positions;
private int mRouteResource;
/**
* Constructor: create a new MockGPSLoggerDriver.
*
* @param context context of the test package
* @param route resource identifier for the xml route
* @param timeout time to idle between waypoints in miliseconds
*/
public MockGPSLoggerDriver(Context context, int route, int timeout)
{
this();
this.mTimeout = timeout;
this.mRouteResource = route;// R.xml.denhaagdenbosch;
this.mContext = context;
}
public MockGPSLoggerDriver()
{
this.sender = new TelnetPositionSender();
}
public int getPositions()
{
return this.positions.size();
}
private void prepareRun( int xmlResource )
{
this.positions = new ArrayList<SimplePosition>();
XmlResourceParser xmlParser = this.mContext.getResources().getXml( xmlResource );
doUglyXMLParsing( this.positions, xmlParser );
xmlParser.close();
}
public void run()
{
prepareRun( this.mRouteResource );
while( this.running && ( this.positions.size() > 0 ) )
{
SimplePosition position = this.positions.remove( 0 );
//String nmeaCommand = createGPGGALocationCommand(position.getLongitude(), position.getLatitude(), 0);
String nmeaCommand = createGPRMCLocationCommand( position.lng, position.lat, 0, 0 );
String checksum = calulateChecksum( nmeaCommand );
this.sender.sendCommand( "geo nmea $" + nmeaCommand + "*" + checksum + "\r\n" );
try
{
Thread.sleep( this.mTimeout );
}
catch( InterruptedException e )
{
Log.w( TAG, "Interrupted" );
}
}
}
public static String calulateChecksum( String nmeaCommand )
{
byte[] chars = null;
try
{
chars = nmeaCommand.getBytes( "ASCII" );
}
catch( UnsupportedEncodingException e )
{
e.printStackTrace();
}
byte xor = 0;
for( int i = 0; i < chars.length; i++ )
{
xor ^= chars[i];
}
return Integer.toHexString( (int) xor ).toUpperCase();
}
public void stop()
{
this.running = false;
}
private void doUglyXMLParsing( ArrayList<SimplePosition> positions, XmlResourceParser xmlParser )
{
int eventType;
try
{
eventType = xmlParser.getEventType();
SimplePosition lastPosition = null;
boolean speed = false;
while( eventType != XmlPullParser.END_DOCUMENT )
{
if( eventType == XmlPullParser.START_TAG )
{
if( xmlParser.getName().equals( "trkpt" ) || xmlParser.getName().equals( "rtept" ) || xmlParser.getName().equals( "wpt" ) )
{
lastPosition = new SimplePosition( xmlParser.getAttributeFloatValue( 0, 12.3456F ), xmlParser.getAttributeFloatValue( 1, 12.3456F ) );
positions.add( lastPosition );
}
if( xmlParser.getName().equals( "speed" ) )
{
speed = true;
}
}
else if( eventType == XmlPullParser.END_TAG )
{
if( xmlParser.getName().equals( "speed" ) )
{
speed = false;
}
}
else if( eventType == XmlPullParser.TEXT )
{
if( lastPosition != null && speed )
{
lastPosition.speed = Float.parseFloat( xmlParser.getText() );
}
}
eventType = xmlParser.next();
}
}
catch( XmlPullParserException e )
{ /* ignore */
}
catch( IOException e )
{/* ignore */
}
}
/**
* Create a NMEA GPRMC sentence
*
* @param longitude
* @param latitude
* @param elevation
* @param speed in mps
* @return
*/
public static String createGPRMCLocationCommand( double longitude, double latitude, double elevation, double speed )
{
speed *= 0.51; // from m/s to knots
final String COMMAND_GPS = "GPRMC," + "%1$02d" + // hh c.get(Calendar.HOUR_OF_DAY)
"%2$02d" + // mm c.get(Calendar.MINUTE)
"%3$02d." + // ss. c.get(Calendar.SECOND)
"%4$03d,A," + // ss, c.get(Calendar.MILLISECOND)
"%5$03d" + // llll latDegree
"%6$09.6f," + // latMinute
"%7$c," + // latDirection (N or S)
"%8$03d" + // longDegree
"%9$09.6f," + // longMinutett
"%10$c," + // longDirection (E or W)
"%14$.2f," + // Speed over ground in knot
"0," + // Track made good in degrees True
"%11$02d" + // dd
"%12$02d" + // mm
"%13$02d," + // yy
"0," + // Magnetic variation degrees (Easterly var. subtracts from true course)
"E," + // East/West
"mode"; // Just as workaround....
Calendar c = Calendar.getInstance();
double absLong = Math.abs( longitude );
int longDegree = (int) Math.floor( absLong );
char longDirection = 'E';
if( longitude < 0 )
{
longDirection = 'W';
}
double longMinute = ( absLong - Math.floor( absLong ) ) * 60;
double absLat = Math.abs( latitude );
int latDegree = (int) Math.floor( absLat );
char latDirection = 'N';
if( latitude < 0 )
{
latDirection = 'S';
}
double latMinute = ( absLat - Math.floor( absLat ) ) * 60;
String command = String.format( COMMAND_GPS, c.get( Calendar.HOUR_OF_DAY ), c.get( Calendar.MINUTE ), c.get( Calendar.SECOND ), c.get( Calendar.MILLISECOND ), latDegree, latMinute,
latDirection, longDegree, longMinute, longDirection, c.get( Calendar.DAY_OF_MONTH ), c.get( Calendar.MONTH ), c.get( Calendar.YEAR ) - 2000 , speed);
return command;
}
public static String createGPGGALocationCommand( double longitude, double latitude, double elevation )
{
final String COMMAND_GPS = "GPGGA," + // $--GGA,
"%1$02d" + // hh c.get(Calendar.HOUR_OF_DAY)
"%2$02d" + // mm c.get(Calendar.MINUTE)
"%3$02d." + // ss. c.get(Calendar.SECOND)
"%4$03d," + // sss, c.get(Calendar.MILLISECOND)
"%5$03d" + // llll latDegree
"%6$09.6f," + // latMinute
"%7$c," + // latDirection
"%8$03d" + // longDegree
"%9$09.6f," + // longMinutett
"%10$c," + // longDirection
"1,05,02.1,00545.5,M,-26.0,M,,";
Calendar c = Calendar.getInstance();
double absLong = Math.abs( longitude );
int longDegree = (int) Math.floor( absLong );
char longDirection = 'E';
if( longitude < 0 )
{
longDirection = 'W';
}
double longMinute = ( absLong - Math.floor( absLong ) ) * 60;
double absLat = Math.abs( latitude );
int latDegree = (int) Math.floor( absLat );
char latDirection = 'N';
if( latitude < 0 )
{
latDirection = 'S';
}
double latMinute = ( absLat - Math.floor( absLat ) ) * 60;
String command = String.format( COMMAND_GPS, c.get( Calendar.HOUR_OF_DAY ), c.get( Calendar.MINUTE ), c.get( Calendar.SECOND ), c.get( Calendar.MILLISECOND ), latDegree, latMinute,
latDirection, longDegree, longMinute, longDirection );
return command;
}
class SimplePosition
{
public float speed;
public double lat, lng;
public SimplePosition(float latitude, float longtitude)
{
this.lat = latitude;
this.lng = longtitude;
}
}
public void sendSMS( String string )
{
this.sender.sendCommand( "sms send 31886606607 " + string + "\r\n" );
}
} | 11chauhanpeeyush11-peeyush | OpenGPSTracker/test/src/nl/sogeti/android/gpstracker/tests/utils/MockGPSLoggerDriver.java | Java | gpl3 | 10,654 |
/*------------------------------------------------------------------------------
** Ident: Innovation en Inspiration > Google Android
** Author: rene
** Copyright: (c) Jan 22, 2009 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.tests.utils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.util.Log;
/**
* Translates SimplePosition objects to a telnet command and sends the commands to a telnet session with an android emulator.
*
* @version $Id$
* @author Bram Pouwelse (c) Jan 22, 2009, Sogeti B.V.
*
*/
public class TelnetPositionSender
{
private static final String TAG = "TelnetPositionSender";
private static final String TELNET_OK_FEEDBACK_MESSAGE = "OK\r\n";
private static String HOST = "10.0.2.2";
private static int PORT = 5554;
private Socket socket;
private OutputStream out;
private InputStream in;
/**
* Constructor
*/
public TelnetPositionSender()
{
}
/**
* Setup a telnet connection to the android emulator
*/
private void createTelnetConnection() {
try {
this.socket = new Socket(HOST, PORT);
this.in = this.socket.getInputStream();
this.out = this.socket.getOutputStream();
Thread.sleep(500); // give the telnet session half a second to
// respond
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
readInput(); // read the input to throw it away the first time :)
}
private void closeConnection()
{
try
{
this.out.close();
this.in.close();
this.socket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
/**
* read the input buffer
* @return
*/
private String readInput() {
StringBuffer sb = new StringBuffer();
try {
byte[] bytes = new byte[this.in.available()];
this.in.read(bytes);
for (byte b : bytes) {
sb.append((char) b);
}
} catch (Exception e) {
System.err.println("Warning: Could not read the input from the telnet session");
}
return sb.toString();
}
/**
* When a new position is received it is sent to the android emulator over the telnet connection.
*
* @param position the position to send
*/
public void sendCommand(String telnetString)
{
createTelnetConnection();
Log.v( TAG, "Sending command: "+telnetString);
byte[] sendArray = telnetString.getBytes();
for (byte b : sendArray)
{
try
{
this.out.write(b);
} catch (IOException e) {
System.out.println("IOException: " + e.getMessage());
}
}
String feedback = readInput();
if (!feedback.equals(TELNET_OK_FEEDBACK_MESSAGE))
{
System.err.println("Warning: no OK mesage message was(" + feedback + ")");
}
closeConnection();
}
} | 11chauhanpeeyush11-peeyush | OpenGPSTracker/test/src/nl/sogeti/android/gpstracker/tests/utils/TelnetPositionSender.java | Java | gpl3 | 4,544 |
/*------------------------------------------------------------------------------
** Ident: Innovation en Inspiration > Google Android
** Author: rene
** Copyright: (c) Jan 22, 2009 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.tests.demo;
import nl.sogeti.android.gpstracker.logger.GPSLoggerServiceManager;
import nl.sogeti.android.gpstracker.tests.utils.MockGPSLoggerDriver;
import nl.sogeti.android.gpstracker.viewer.map.CommonLoggerMap;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.LargeTest;
import android.test.suitebuilder.annotation.SmallTest;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
/**
* @version $Id$
* @author rene (c) Jan 22, 2009, Sogeti B.V.
*/
public class OpenGPSTrackerDemo extends ActivityInstrumentationTestCase2<CommonLoggerMap>
{
private static final int ZOOM_LEVEL = 16;
private static final Class<CommonLoggerMap> CLASS = CommonLoggerMap.class;
private static final String PACKAGE = "nl.sogeti.android.gpstracker";
private CommonLoggerMap mLoggermap;
private GPSLoggerServiceManager mLoggerServiceManager;
private MapView mMapView;
private MockGPSLoggerDriver mSender;
public OpenGPSTrackerDemo()
{
super( PACKAGE, CLASS );
}
@Override
protected void setUp() throws Exception
{
super.setUp();
this.mLoggermap = getActivity();
this.mMapView = (MapView) this.mLoggermap.findViewById( nl.sogeti.android.gpstracker.R.id.myMapView );
this.mSender = new MockGPSLoggerDriver();
}
protected void tearDown() throws Exception
{
this.mLoggerServiceManager.shutdown( getActivity() );
super.tearDown();
}
/**
* Start tracking and allow it to go on for 30 seconds
*
* @throws InterruptedException
*/
@LargeTest
public void testTracking() throws InterruptedException
{
a_introSingelUtrecht30Seconds();
c_startRoute10Seconds();
d_showDrawMethods30seconds();
e_statistics10Seconds();
f_showPrecision30seconds();
g_stopTracking10Seconds();
h_shareTrack30Seconds();
i_finish10Seconds();
}
@SmallTest
public void a_introSingelUtrecht30Seconds() throws InterruptedException
{
this.mMapView.getController().setZoom( ZOOM_LEVEL);
Thread.sleep( 1 * 1000 );
// Browse the Utrecht map
sendMessage( "Selecting a previous recorded track" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "MENU DPAD_RIGHT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "L" );
Thread.sleep( 2 * 1000 );
sendMessage( "The walk around the \"singel\" in Utrecht" );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 2 * 1000 );
Thread.sleep( 2 * 1000 );
sendMessage( "Scrolling about" );
this.mMapView.getController().animateTo( new GeoPoint( 52095829, 5118599 ) );
Thread.sleep( 2 * 1000 );
this.mMapView.getController().animateTo( new GeoPoint( 52096778, 5125090 ) );
Thread.sleep( 2 * 1000 );
this.mMapView.getController().animateTo( new GeoPoint( 52085117, 5128255 ) );
Thread.sleep( 2 * 1000 );
this.mMapView.getController().animateTo( new GeoPoint( 52081517, 5121646 ) );
Thread.sleep( 2 * 1000 );
this.mMapView.getController().animateTo( new GeoPoint( 52093535, 5116711 ) );
Thread.sleep( 2 * 1000 );
this.sendKeys( "G G" );
Thread.sleep( 5 * 1000 );
}
@SmallTest
public void c_startRoute10Seconds() throws InterruptedException
{
sendMessage( "Lets start a new route" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "MENU DPAD_RIGHT DPAD_LEFT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "T" );//Toggle start/stop tracker
Thread.sleep( 1 * 1000 );
this.mMapView.getController().setZoom( ZOOM_LEVEL);
this.sendKeys( "D E M O SPACE R O U T E ENTER" );
Thread.sleep( 5 * 1000 );
sendMessage( "The GPS logger is already running as a background service" );
Thread.sleep( 5 * 1000 );
this.sendKeys( "ENTER" );
this.sendKeys( "T T T T" );
Thread.sleep( 30 * 1000 );
this.sendKeys( "G G" );
}
@SmallTest
public void d_showDrawMethods30seconds() throws InterruptedException
{
sendMessage( "Track drawing color has different options" );
this.mMapView.getController().setZoom( ZOOM_LEVEL );
this.sendKeys( "MENU DPAD_RIGHT DPAD_RIGHT DPAD_RIGHT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "S" );
Thread.sleep( 3 * 1000 );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "DPAD_UP DPAD_UP DPAD_UP DPAD_UP" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "BACK" );
sendMessage( "Plain green" );
Thread.sleep( 15 * 1000 );
this.sendKeys( "MENU DPAD_RIGHT DPAD_RIGHT DPAD_RIGHT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "S" );
Thread.sleep( 3 * 1000 );
this.sendKeys( "MENU" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "DPAD_UP DPAD_UP DPAD_UP DPAD_UP" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_DOWN" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_DOWN" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_DOWN" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_DOWN DPAD_DOWN" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_UP");
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "BACK" );
sendMessage( "Average speeds drawn" );
Thread.sleep( 15 * 1000 );
}
@SmallTest
public void e_statistics10Seconds() throws InterruptedException
{
// Show of the statistics screen
sendMessage( "Lets look at some statistics" );
this.sendKeys( "MENU DPAD_RIGHT DPAD_RIGHT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "E" );
Thread.sleep( 2 * 1000 );
sendMessage( "Shows the basics on time, speed and distance" );
Thread.sleep( 10 * 1000 );
this.sendKeys( "BACK" );
}
@SmallTest
public void f_showPrecision30seconds() throws InterruptedException
{
this.mMapView.getController().setZoom( ZOOM_LEVEL );
sendMessage( "There are options on the precision of tracking" );
this.sendKeys( "MENU DPAD_RIGHT DPAD_RIGHT DPAD_RIGHT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "S" );
Thread.sleep( 3 * 1000 );
this.sendKeys( "DPAD_DOWN DPAD_DOWN" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "DPAD_UP DPAD_UP" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_DOWN DPAD_DOWN" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_UP" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "BACK" );
sendMessage( "Course will drain the battery the least" );
Thread.sleep( 5 * 1000 );
sendMessage( "Fine will store the best track" );
Thread.sleep( 10 * 1000 );
}
@SmallTest
public void g_stopTracking10Seconds() throws InterruptedException
{
this.mMapView.getController().setZoom( ZOOM_LEVEL );
Thread.sleep( 5 * 1000 );
// Stop tracking
sendMessage( "Stopping tracking" );
this.sendKeys( "MENU DPAD_RIGHT DPAD_LEFT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "T" );
Thread.sleep( 2 * 1000 );
sendMessage( "Is the track stored?" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "MENU DPAD_RIGHT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "L" );
this.sendKeys( "DPAD_DOWN DPAD_DOWN" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 2 * 1000 );
}
private void h_shareTrack30Seconds()
{
// TODO Auto-generated method stub
}
@SmallTest
public void i_finish10Seconds() throws InterruptedException
{
this.mMapView.getController().setZoom( ZOOM_LEVEL );
this.sendKeys( "G G" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "G G" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "G G" );
sendMessage( "Thank you for watching this demo." );
Thread.sleep( 10 * 1000 );
Thread.sleep( 5 * 1000 );
}
private void sendMessage( String string )
{
this.mSender.sendSMS( string );
}
}
| 11chauhanpeeyush11-peeyush | OpenGPSTracker/test/src/nl/sogeti/android/gpstracker/tests/demo/OpenGPSTrackerDemo.java | Java | gpl3 | 10,188 |
<html><head></head><body>
<p>
Open GPS Tracker is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
</p><p>
Open GPS Tracker is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
</p><p>
You should have received a copy of the GNU General Public License along with Open GPS Tracker. If not, see <a href="http://www.gnu.org/licenses/">http://www.gnu.org/licenses/</a>.
</p>
</body></html> | 11chauhanpeeyush11-peeyush | OpenGPSTracker/application/assets/license_short.html | HTML | gpl3 | 729 |
</html><head></head>
<body>
<div class="section-copyrights">
<h3>Copyright (c) 2008 Google Inc.</h3>
<h4>Apache License Version 2.0</h4>
<ul>
<li>UnicodeReader.java</li>
</ul>
<hr/>
<h3>Copyright (c) 2005-2008, The Android Open Source Project</h3>
<h4>Apache License Version 2.0</h4>
<ul>
<li>compass_arrow.png</li>
<li>compass_base.png</li>
<li>ic_maps_indicator_current_position.png</li>
<li>ic_media_play_mirrored.png</li>
<li>ic_media_play.png</li>
<li>ic_menu_info_details.png</li>
<li>ic_menu_mapmode.png</li>
<li>ic_menu_movie.png</li>
<li>ic_menu_picture.png</li>
<li>ic_menu_preferences.png</li>
<li>ic_menu_show_list.png</li>
<li>ic_menu_view.png</li>
<li>icon.png</li>
<li>speedindexbar.png</li>
<li>stip.gif</li>
<li>stip2.gif</li>
</ul>
<hr/>
<h3>Copyright 1999-2011 The Apache Software Foundation</h3>
<h4>Apache License Version 2.0</h4>
<ul>
<li>Apache HttpComponents Client</li>
<li>Apache HttpComponents Core</li>
<li>Apache HttpComponents Mime</li>
</ul>
<hr/>
<h3>Copyright (c) 2009 Matthias Kaeppler</h3>
<h4>Apache License Version 2.0</h4>
<ul>
<li>OAuth Signpost</li>
</ul>
<hr/>
</div>
<div class="section-content"><p>Apache License<br></br>Version 2.0, January 2004<br></br>
<a href="http://www.apache.org/licenses/">http://www.apache.org/licenses/</a> </p>
<p>TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION</p>
<p><strong><a name="definitions">1. Definitions</a></strong>.</p>
<p>"License" shall mean the terms and conditions for use, reproduction, and
distribution as defined by Sections 1 through 9 of this document.</p>
<p>"Licensor" shall mean the copyright owner or entity authorized by the
copyright owner that is granting the License.</p>
<p>"Legal Entity" shall mean the union of the acting entity and all other
entities that control, are controlled by, or are under common control with
that entity. For the purposes of this definition, "control" means (i) the
power, direct or indirect, to cause the direction or management of such
entity, whether by contract or otherwise, or (ii) ownership of fifty
percent (50%) or more of the outstanding shares, or (iii) beneficial
ownership of such entity.</p>
<p>"You" (or "Your") shall mean an individual or Legal Entity exercising
permissions granted by this License.</p>
<p>"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation source,
and configuration files.</p>
<p>"Object" form shall mean any form resulting from mechanical transformation
or translation of a Source form, including but not limited to compiled
object code, generated documentation, and conversions to other media types.</p>
<p>"Work" shall mean the work of authorship, whether in Source or Object form,
made available under the License, as indicated by a copyright notice that
is included in or attached to the work (an example is provided in the
Appendix below).</p>
<p>"Derivative Works" shall mean any work, whether in Source or Object form,
that is based on (or derived from) the Work and for which the editorial
revisions, annotations, elaborations, or other modifications represent, as
a whole, an original work of authorship. For the purposes of this License,
Derivative Works shall not include works that remain separable from, or
merely link (or bind by name) to the interfaces of, the Work and Derivative
Works thereof.</p>
<p>"Contribution" shall mean any work of authorship, including the original
version of the Work and any modifications or additions to that Work or
Derivative Works thereof, that is intentionally submitted to Licensor for
inclusion in the Work by the copyright owner or by an individual or Legal
Entity authorized to submit on behalf of the copyright owner. For the
purposes of this definition, "submitted" means any form of electronic,
verbal, or written communication sent to the Licensor or its
representatives, including but not limited to communication on electronic
mailing lists, source code control systems, and issue tracking systems that
are managed by, or on behalf of, the Licensor for the purpose of discussing
and improving the Work, but excluding communication that is conspicuously
marked or otherwise designated in writing by the copyright owner as "Not a
Contribution."</p>
<p>"Contributor" shall mean Licensor and any individual or Legal Entity on
behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.</p>
<p><strong><a name="copyright">2. Grant of Copyright License</a></strong>. Subject to the
terms and conditions of this License, each Contributor hereby grants to You
a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of, publicly
display, publicly perform, sublicense, and distribute the Work and such
Derivative Works in Source or Object form.</p>
<p><strong><a name="patent">3. Grant of Patent License</a></strong>. Subject to the terms
and conditions of this License, each Contributor hereby grants to You a
perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made, use,
offer to sell, sell, import, and otherwise transfer the Work, where such
license applies only to those patent claims licensable by such Contributor
that are necessarily infringed by their Contribution(s) alone or by
combination of their Contribution(s) with the Work to which such
Contribution(s) was submitted. If You institute patent litigation against
any entity (including a cross-claim or counterclaim in a lawsuit) alleging
that the Work or a Contribution incorporated within the Work constitutes
direct or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate as of the
date such litigation is filed.</p>
<p><strong><a name="redistribution">4. Redistribution</a></strong>. You may reproduce and
distribute copies of the Work or Derivative Works thereof in any medium,
with or without modifications, and in Source or Object form, provided that
You meet the following conditions:</p>
<ol>
<li>
<p>You must give any other recipients of the Work or Derivative Works a
copy of this License; and</p>
</li>
<li>
<p>You must cause any modified files to carry prominent notices stating
that You changed the files; and</p>
</li>
<li>
<p>You must retain, in the Source form of any Derivative Works that You
distribute, all copyright, patent, trademark, and attribution notices from
the Source form of the Work, excluding those notices that do not pertain to
any part of the Derivative Works; and</p>
</li>
<li>
<p>If the Work includes a "NOTICE" text file as part of its distribution,
then any Derivative Works that You distribute must include a readable copy
of the attribution notices contained within such NOTICE file, excluding
those notices that do not pertain to any part of the Derivative Works, in
at least one of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or documentation,
if provided along with the Derivative Works; or, within a display generated
by the Derivative Works, if and wherever such third-party notices normally
appear. The contents of the NOTICE file are for informational purposes only
and do not modify the License. You may add Your own attribution notices
within Derivative Works that You distribute, alongside or as an addendum to
the NOTICE text from the Work, provided that such additional attribution
notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may
provide additional or different license terms and conditions for use,
reproduction, or distribution of Your modifications, or for any such
Derivative Works as a whole, provided Your use, reproduction, and
distribution of the Work otherwise complies with the conditions stated in
this License.</p>
</li>
</ol>
<p><strong><a name="contributions">5. Submission of Contributions</a></strong>. Unless You
explicitly state otherwise, any Contribution intentionally submitted for
inclusion in the Work by You to the Licensor shall be under the terms and
conditions of this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify the
terms of any separate license agreement you may have executed with Licensor
regarding such Contributions.</p>
<p><strong><a name="trademarks">6. Trademarks</a></strong>. This License does not grant
permission to use the trade names, trademarks, service marks, or product
names of the Licensor, except as required for reasonable and customary use
in describing the origin of the Work and reproducing the content of the
NOTICE file.</p>
<p><strong><a name="no-warranty">7. Disclaimer of Warranty</a></strong>. Unless required by
applicable law or agreed to in writing, Licensor provides the Work (and
each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including,
without limitation, any warranties or conditions of TITLE,
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You
are solely responsible for determining the appropriateness of using or
redistributing the Work and assume any risks associated with Your exercise
of permissions under this License.</p>
<p><strong><a name="no-liability">8. Limitation of Liability</a></strong>. In no event and
under no legal theory, whether in tort (including negligence), contract, or
otherwise, unless required by applicable law (such as deliberate and
grossly negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a result
of this License or out of the use or inability to use the Work (including
but not limited to damages for loss of goodwill, work stoppage, computer
failure or malfunction, or any and all other commercial damages or losses),
even if such Contributor has been advised of the possibility of such
damages.</p>
<p><strong><a name="additional">9. Accepting Warranty or Additional Liability</a></strong>.
While redistributing the Work or Derivative Works thereof, You may choose
to offer, and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this License.
However, in accepting such obligations, You may act only on Your own behalf
and on Your sole responsibility, not on behalf of any other Contributor,
and only if You agree to indemnify, defend, and hold each Contributor
harmless for any liability incurred by, or claims asserted against, such
Contributor by reason of your accepting any such warranty or additional
liability.</p>
<p>END OF TERMS AND CONDITIONS</p>
</body></html> | 11chauhanpeeyush11-peeyush | OpenGPSTracker/application/assets/notices.html | HTML | gpl3 | 10,965 |
</html><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> </head>
<body>
<h4>Translations</h4>
Translations hosted by <a href="http://www.getlocalization.com/">Get Localization</a>.
<ul>
<li>Chinese: 安智网汉化, NetDragon Websoft</li>
<li>Danish: Martin Larsen</li>
<li>Dutch: René de Groot, zwets</li>
<li>English: René de Groot</li>
<li>French: Paul Meier, mvl87, Fabrice Veniard</li>
<li>Finnish: Jani Pesonen</li>
<li>German: Werner Bogula, SkryBav, doopdoop</li>
<li>Hindi: vibin_nair</li>
<li>Italian: Paul Meier</li>
<li>Polish: Marcin Kost, Michał Podbielski, Wojciech Maj</li>
<li>Russian: Yuri Zaitsev </li>
<li>Spanish: Alfonso Montero López, Diego</li>
<li>Swedish: Jesper Falk</li>
</ul>
<h4>Code</h4>
Code hosted by <a href="http://code.google.com/p/open-gpstracker/">Google Code</a>.
<ul>
<li>Application: René de Groot</li>
<li>Start at boot: Tom Van Braeckel</li>
</ul>
<h4>Images</h4>
<ul>
<li>Bubbles icons: ICONS etc. MySiteMyWay</li>
</ul>
</body></html> | 11chauhanpeeyush11-peeyush | OpenGPSTracker/application/assets/contributions.html | HTML | gpl3 | 1,021 |
/*------------------------------------------------------------------------------
** Ident: Sogeti Smart Mobile Solutions
** Author: rene
** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.db;
import java.util.Date;
import nl.sogeti.android.gpstracker.db.GPStracking.Media;
import nl.sogeti.android.gpstracker.db.GPStracking.MediaColumns;
import nl.sogeti.android.gpstracker.db.GPStracking.MetaData;
import nl.sogeti.android.gpstracker.db.GPStracking.Segments;
import nl.sogeti.android.gpstracker.db.GPStracking.Tracks;
import nl.sogeti.android.gpstracker.db.GPStracking.TracksColumns;
import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints;
import nl.sogeti.android.gpstracker.db.GPStracking.WaypointsColumns;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.location.Location;
import android.net.Uri;
import android.util.Log;
/**
* Class to hold bare-metal database operations exposed as functionality blocks
* To be used by database adapters, like a content provider, that implement a
* required functionality set
*
* @version $Id$
* @author rene (c) Jan 22, 2009, Sogeti B.V.
*/
public class DatabaseHelper extends SQLiteOpenHelper
{
private Context mContext;
private final static String TAG = "OGT.DatabaseHelper";
public DatabaseHelper(Context context)
{
super(context, GPStracking.DATABASE_NAME, null, GPStracking.DATABASE_VERSION);
this.mContext = context;
}
/*
* (non-Javadoc)
* @see
* android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite
* .SQLiteDatabase)
*/
@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(Waypoints.CREATE_STATEMENT);
db.execSQL(Segments.CREATE_STATMENT);
db.execSQL(Tracks.CREATE_STATEMENT);
db.execSQL(Media.CREATE_STATEMENT);
db.execSQL(MetaData.CREATE_STATEMENT);
}
/**
* Will update version 1 through 5 to version 8
*
* @see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase,
* int, int)
* @see GPStracking.DATABASE_VERSION
*/
@Override
public void onUpgrade(SQLiteDatabase db, int current, int targetVersion)
{
Log.i(TAG, "Upgrading db from " + current + " to " + targetVersion);
if (current <= 5) // From 1-5 to 6 (these before are the same before)
{
current = 6;
}
if (current == 6) // From 6 to 7 ( no changes )
{
current = 7;
}
if (current == 7) // From 7 to 8 ( more waypoints data )
{
for (String statement : Waypoints.UPGRADE_STATEMENT_7_TO_8)
{
db.execSQL(statement);
}
current = 8;
}
if (current == 8) // From 8 to 9 ( media Uri data )
{
db.execSQL(Media.CREATE_STATEMENT);
current = 9;
}
if (current == 9) // From 9 to 10 ( metadata )
{
db.execSQL(MetaData.CREATE_STATEMENT);
current = 10;
}
}
public void vacuum()
{
new Thread()
{
@Override
public void run()
{
SQLiteDatabase sqldb = getWritableDatabase();
sqldb.execSQL("VACUUM");
}
}.start();
}
int bulkInsertWaypoint(long trackId, long segmentId, ContentValues[] valuesArray)
{
if (trackId < 0 || segmentId < 0)
{
throw new IllegalArgumentException("Track and segments may not the less then 0.");
}
int inserted = 0;
SQLiteDatabase sqldb = getWritableDatabase();
sqldb.beginTransaction();
try
{
for (ContentValues args : valuesArray)
{
args.put(Waypoints.SEGMENT, segmentId);
long id = sqldb.insert(Waypoints.TABLE, null, args);
if (id >= 0)
{
inserted++;
}
}
sqldb.setTransactionSuccessful();
}
finally
{
if (sqldb.inTransaction())
{
sqldb.endTransaction();
}
}
return inserted;
}
/**
* Creates a waypoint under the current track segment with the current time
* on which the waypoint is reached
*
* @param track track
* @param segment segment
* @param latitude latitude
* @param longitude longitude
* @param time time
* @param speed the measured speed
* @return
*/
long insertWaypoint(long trackId, long segmentId, Location location)
{
if (trackId < 0 || segmentId < 0)
{
throw new IllegalArgumentException("Track and segments may not the less then 0.");
}
SQLiteDatabase sqldb = getWritableDatabase();
ContentValues args = new ContentValues();
args.put(WaypointsColumns.SEGMENT, segmentId);
args.put(WaypointsColumns.TIME, location.getTime());
args.put(WaypointsColumns.LATITUDE, location.getLatitude());
args.put(WaypointsColumns.LONGITUDE, location.getLongitude());
args.put(WaypointsColumns.SPEED, location.getSpeed());
args.put(WaypointsColumns.ACCURACY, location.getAccuracy());
args.put(WaypointsColumns.ALTITUDE, location.getAltitude());
args.put(WaypointsColumns.BEARING, location.getBearing());
long waypointId = sqldb.insert(Waypoints.TABLE, null, args);
ContentResolver resolver = this.mContext.getContentResolver();
Uri notifyUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments/" + segmentId + "/waypoints");
resolver.notifyChange(notifyUri, null);
// Log.d( TAG, "Waypoint stored: "+notifyUri);
return waypointId;
}
/**
* Insert a URI for a given waypoint/segment/track in the media table
*
* @param trackId
* @param segmentId
* @param waypointId
* @param mediaUri
* @return
*/
long insertMedia(long trackId, long segmentId, long waypointId, String mediaUri)
{
if (trackId < 0 || segmentId < 0 || waypointId < 0)
{
throw new IllegalArgumentException("Track, segments and waypoint may not the less then 0.");
}
SQLiteDatabase sqldb = getWritableDatabase();
ContentValues args = new ContentValues();
args.put(MediaColumns.TRACK, trackId);
args.put(MediaColumns.SEGMENT, segmentId);
args.put(MediaColumns.WAYPOINT, waypointId);
args.put(MediaColumns.URI, mediaUri);
// Log.d( TAG, "Media stored in the datebase: "+mediaUri );
long mediaId = sqldb.insert(Media.TABLE, null, args);
ContentResolver resolver = this.mContext.getContentResolver();
Uri notifyUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments/" + segmentId + "/waypoints/" + waypointId + "/media");
resolver.notifyChange(notifyUri, null);
// Log.d( TAG, "Notify: "+notifyUri );
resolver.notifyChange(Media.CONTENT_URI, null);
// Log.d( TAG, "Notify: "+Media.CONTENT_URI );
return mediaId;
}
/**
* Insert a key/value pair as meta-data for a track and optionally narrow the
* scope by segment or segment/waypoint
*
* @param trackId
* @param segmentId
* @param waypointId
* @param key
* @param value
* @return
*/
long insertOrUpdateMetaData(long trackId, long segmentId, long waypointId, String key, String value)
{
long metaDataId = -1;
if (trackId < 0 && key != null && value != null)
{
throw new IllegalArgumentException("Track, key and value must be provided");
}
if (waypointId >= 0 && segmentId < 0)
{
throw new IllegalArgumentException("Waypoint must have segment");
}
ContentValues args = new ContentValues();
args.put(MetaData.TRACK, trackId);
args.put(MetaData.SEGMENT, segmentId);
args.put(MetaData.WAYPOINT, waypointId);
args.put(MetaData.KEY, key);
args.put(MetaData.VALUE, value);
String whereClause = MetaData.TRACK + " = ? AND " + MetaData.SEGMENT + " = ? AND " + MetaData.WAYPOINT + " = ? AND " + MetaData.KEY + " = ?";
String[] whereArgs = new String[] { Long.toString(trackId), Long.toString(segmentId), Long.toString(waypointId), key };
SQLiteDatabase sqldb = getWritableDatabase();
int updated = sqldb.update(MetaData.TABLE, args, whereClause, whereArgs);
if (updated == 0)
{
metaDataId = sqldb.insert(MetaData.TABLE, null, args);
}
else
{
Cursor c = null;
try
{
c = sqldb.query(MetaData.TABLE, new String[] { MetaData._ID }, whereClause, whereArgs, null, null, null);
if( c.moveToFirst() )
{
metaDataId = c.getLong(0);
}
}
finally
{
if (c != null)
{
c.close();
}
}
}
ContentResolver resolver = this.mContext.getContentResolver();
Uri notifyUri;
if (segmentId >= 0 && waypointId >= 0)
{
notifyUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments/" + segmentId + "/waypoints/" + waypointId + "/metadata");
}
else if (segmentId >= 0)
{
notifyUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments/" + segmentId + "/metadata");
}
else
{
notifyUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/metadata");
}
resolver.notifyChange(notifyUri, null);
resolver.notifyChange(MetaData.CONTENT_URI, null);
return metaDataId;
}
/**
* Deletes a single track and all underlying segments, waypoints, media and
* metadata
*
* @param trackId
* @return
*/
int deleteTrack(long trackId)
{
SQLiteDatabase sqldb = getWritableDatabase();
int affected = 0;
Cursor cursor = null;
long segmentId = -1;
long metadataId = -1;
try
{
sqldb.beginTransaction();
// Iterate on each segement to delete each
cursor = sqldb.query(Segments.TABLE, new String[] { Segments._ID }, Segments.TRACK + "= ?", new String[] { String.valueOf(trackId) }, null, null,
null, null);
if (cursor.moveToFirst())
{
do
{
segmentId = cursor.getLong(0);
affected += deleteSegment(sqldb, trackId, segmentId);
}
while (cursor.moveToNext());
}
else
{
Log.e(TAG, "Did not find the last active segment");
}
// Delete the track
affected += sqldb.delete(Tracks.TABLE, Tracks._ID + "= ?", new String[] { String.valueOf(trackId) });
// Delete remaining meta-data
affected += sqldb.delete(MetaData.TABLE, MetaData.TRACK + "= ?", new String[] { String.valueOf(trackId) });
cursor = sqldb.query(MetaData.TABLE, new String[] { MetaData._ID }, MetaData.TRACK + "= ?", new String[] { String.valueOf(trackId) }, null, null,
null, null);
if (cursor.moveToFirst())
{
do
{
metadataId = cursor.getLong(0);
affected += deleteMetaData(metadataId);
}
while (cursor.moveToNext());
}
sqldb.setTransactionSuccessful();
}
finally
{
if (cursor != null)
{
cursor.close();
}
if (sqldb.inTransaction())
{
sqldb.endTransaction();
}
}
ContentResolver resolver = this.mContext.getContentResolver();
resolver.notifyChange(Tracks.CONTENT_URI, null);
resolver.notifyChange(ContentUris.withAppendedId(Tracks.CONTENT_URI, trackId), null);
return affected;
}
/**
* @param mediaId
* @return
*/
int deleteMedia(long mediaId)
{
SQLiteDatabase sqldb = getWritableDatabase();
Cursor cursor = null;
long trackId = -1;
long segmentId = -1;
long waypointId = -1;
try
{
cursor = sqldb.query(Media.TABLE, new String[] { Media.TRACK, Media.SEGMENT, Media.WAYPOINT }, Media._ID + "= ?",
new String[] { String.valueOf(mediaId) }, null, null, null, null);
if (cursor.moveToFirst())
{
trackId = cursor.getLong(0);
segmentId = cursor.getLong(0);
waypointId = cursor.getLong(0);
}
else
{
Log.e(TAG, "Did not find the media element to delete");
}
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
int affected = sqldb.delete(Media.TABLE, Media._ID + "= ?", new String[] { String.valueOf(mediaId) });
ContentResolver resolver = this.mContext.getContentResolver();
Uri notifyUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments/" + segmentId + "/waypoints/" + waypointId + "/media");
resolver.notifyChange(notifyUri, null);
notifyUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments/" + segmentId + "/media");
resolver.notifyChange(notifyUri, null);
notifyUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/media");
resolver.notifyChange(notifyUri, null);
resolver.notifyChange(ContentUris.withAppendedId(Media.CONTENT_URI, mediaId), null);
return affected;
}
int deleteMetaData(long metadataId)
{
SQLiteDatabase sqldb = getWritableDatabase();
Cursor cursor = null;
long trackId = -1;
long segmentId = -1;
long waypointId = -1;
try
{
cursor = sqldb.query(MetaData.TABLE, new String[] { MetaData.TRACK, MetaData.SEGMENT, MetaData.WAYPOINT }, MetaData._ID + "= ?",
new String[] { String.valueOf(metadataId) }, null, null, null, null);
if (cursor.moveToFirst())
{
trackId = cursor.getLong(0);
segmentId = cursor.getLong(0);
waypointId = cursor.getLong(0);
}
else
{
Log.e(TAG, "Did not find the media element to delete");
}
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
int affected = sqldb.delete(MetaData.TABLE, MetaData._ID + "= ?", new String[] { String.valueOf(metadataId) });
ContentResolver resolver = this.mContext.getContentResolver();
Uri notifyUri;
if (trackId >= 0 && segmentId >= 0 && waypointId >= 0)
{
notifyUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments/" + segmentId + "/waypoints/" + waypointId + "/media");
resolver.notifyChange(notifyUri, null);
}
if (trackId >= 0 && segmentId >= 0)
{
notifyUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments/" + segmentId + "/media");
resolver.notifyChange(notifyUri, null);
}
notifyUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/media");
resolver.notifyChange(notifyUri, null);
resolver.notifyChange(ContentUris.withAppendedId(Media.CONTENT_URI, metadataId), null);
return affected;
}
/**
* Delete a segment and all member waypoints
*
* @param sqldb The SQLiteDatabase in question
* @param trackId The track id of this delete
* @param segmentId The segment that needs deleting
* @return
*/
int deleteSegment(SQLiteDatabase sqldb, long trackId, long segmentId)
{
int affected = sqldb.delete(Segments.TABLE, Segments._ID + "= ?", new String[] { String.valueOf(segmentId) });
// Delete all waypoints from segments
affected += sqldb.delete(Waypoints.TABLE, Waypoints.SEGMENT + "= ?", new String[] { String.valueOf(segmentId) });
// Delete all media from segment
affected += sqldb.delete(Media.TABLE, Media.TRACK + "= ? AND " + Media.SEGMENT + "= ?",
new String[] { String.valueOf(trackId), String.valueOf(segmentId) });
// Delete meta-data
affected += sqldb.delete(MetaData.TABLE, MetaData.TRACK + "= ? AND " + MetaData.SEGMENT + "= ?",
new String[] { String.valueOf(trackId), String.valueOf(segmentId) });
ContentResolver resolver = this.mContext.getContentResolver();
resolver.notifyChange(Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments/" + segmentId), null);
resolver.notifyChange(Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments"), null);
return affected;
}
int updateTrack(long trackId, String name)
{
int updates;
String whereclause = Tracks._ID + " = " + trackId;
ContentValues args = new ContentValues();
args.put(Tracks.NAME, name);
// Execute the query.
SQLiteDatabase mDb = getWritableDatabase();
updates = mDb.update(Tracks.TABLE, args, whereclause, null);
ContentResolver resolver = this.mContext.getContentResolver();
Uri notifyUri = ContentUris.withAppendedId(Tracks.CONTENT_URI, trackId);
resolver.notifyChange(notifyUri, null);
return updates;
}
/**
* Insert a key/value pair as meta-data for a track and optionally narrow the
* scope by segment or segment/waypoint
*
* @param trackId
* @param segmentId
* @param waypointId
* @param key
* @param value
* @return
*/
int updateMetaData(long trackId, long segmentId, long waypointId, long metadataId, String selection, String[] selectionArgs, String value)
{
{
if ((metadataId < 0 && trackId < 0))
{
throw new IllegalArgumentException("Track or meta-data id be provided");
}
if (trackId >= 0 && (selection == null || !selection.contains("?") || selectionArgs.length != 1))
{
throw new IllegalArgumentException("A where clause selection must be provided to select the correct KEY");
}
if (trackId >= 0 && waypointId >= 0 && segmentId < 0)
{
throw new IllegalArgumentException("Waypoint must have segment");
}
SQLiteDatabase sqldb = getWritableDatabase();
String[] whereParams;
String whereclause;
if (metadataId >= 0)
{
whereclause = MetaData._ID + " = ? ";
whereParams = new String[] { Long.toString(metadataId) };
}
else
{
whereclause = MetaData.TRACK + " = ? AND " + MetaData.SEGMENT + " = ? AND " + MetaData.WAYPOINT + " = ? AND " + MetaData.KEY + " = ? ";
whereParams = new String[] { Long.toString(trackId), Long.toString(segmentId), Long.toString(waypointId), selectionArgs[0] };
}
ContentValues args = new ContentValues();
args.put(MetaData.VALUE, value);
int updates = sqldb.update(MetaData.TABLE, args, whereclause, whereParams);
ContentResolver resolver = this.mContext.getContentResolver();
Uri notifyUri;
if (trackId >= 0 && segmentId >= 0 && waypointId >= 0)
{
notifyUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments/" + segmentId + "/waypoints/" + waypointId + "/metadata");
}
else if (trackId >= 0 && segmentId >= 0)
{
notifyUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments/" + segmentId + "/metadata");
}
else if (trackId >= 0)
{
notifyUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/metadata");
}
else
{
notifyUri = Uri.withAppendedPath(MetaData.CONTENT_URI, "" + metadataId);
}
resolver.notifyChange(notifyUri, null);
resolver.notifyChange(MetaData.CONTENT_URI, null);
return updates;
}
}
/**
* Move to a fresh track with a new first segment for this track
*
* @return
*/
long toNextTrack(String name)
{
long currentTime = new Date().getTime();
ContentValues args = new ContentValues();
args.put(TracksColumns.NAME, name);
args.put(TracksColumns.CREATION_TIME, currentTime);
SQLiteDatabase sqldb = getWritableDatabase();
long trackId = sqldb.insert(Tracks.TABLE, null, args);
ContentResolver resolver = this.mContext.getContentResolver();
resolver.notifyChange(Tracks.CONTENT_URI, null);
return trackId;
}
/**
* Moves to a fresh segment to which waypoints can be connected
*
* @return
*/
long toNextSegment(long trackId)
{
SQLiteDatabase sqldb = getWritableDatabase();
ContentValues args = new ContentValues();
args.put(Segments.TRACK, trackId);
long segmentId = sqldb.insert(Segments.TABLE, null, args);
ContentResolver resolver = this.mContext.getContentResolver();
resolver.notifyChange(Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments"), null);
return segmentId;
}
}
| 11chauhanpeeyush11-peeyush | OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/db/DatabaseHelper.java | Java | gpl3 | 22,575 |
/*------------------------------------------------------------------------------
** Ident: Sogeti Smart Mobile Solutions
** Author: rene
** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.db;
import android.content.ContentUris;
import android.net.Uri;
import android.net.Uri.Builder;
import android.provider.BaseColumns;
/**
* The GPStracking provider stores all static information about GPStracking.
*
* @version $Id$
* @author rene (c) Jan 22, 2009, Sogeti B.V.
*/
public final class GPStracking
{
/** The authority of this provider: nl.sogeti.android.gpstracker */
public static final String AUTHORITY = "nl.sogeti.android.gpstracker";
/** The content:// style Uri for this provider, content://nl.sogeti.android.gpstracker */
public static final Uri CONTENT_URI = Uri.parse( "content://" + GPStracking.AUTHORITY );
/** The name of the database file */
static final String DATABASE_NAME = "GPSLOG.db";
/** The version of the database schema */
static final int DATABASE_VERSION = 10;
/**
* This table contains tracks.
*
* @author rene
*/
public static final class Tracks extends TracksColumns implements android.provider.BaseColumns
{
/** The MIME type of a CONTENT_URI subdirectory of a single track. */
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nl.sogeti.android.track";
/** The MIME type of CONTENT_URI providing a directory of tracks. */
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nl.sogeti.android.track";
/** The content:// style URL for this provider, content://nl.sogeti.android.gpstracker/tracks */
public static final Uri CONTENT_URI = Uri.parse( "content://" + GPStracking.AUTHORITY + "/" + Tracks.TABLE );
/** The name of this table */
public static final String TABLE = "tracks";
static final String CREATE_STATEMENT =
"CREATE TABLE " + Tracks.TABLE + "(" + " " + Tracks._ID + " " + Tracks._ID_TYPE +
"," + " " + Tracks.NAME + " " + Tracks.NAME_TYPE +
"," + " " + Tracks.CREATION_TIME + " " + Tracks.CREATION_TIME_TYPE +
");";
}
/**
* This table contains segments.
*
* @author rene
*/
public static final class Segments extends SegmentsColumns implements android.provider.BaseColumns
{
/** The MIME type of a CONTENT_URI subdirectory of a single segment. */
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nl.sogeti.android.segment";
/** The MIME type of CONTENT_URI providing a directory of segments. */
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nl.sogeti.android.segment";
/** The name of this table, segments */
public static final String TABLE = "segments";
static final String CREATE_STATMENT =
"CREATE TABLE " + Segments.TABLE + "(" + " " + Segments._ID + " " + Segments._ID_TYPE +
"," + " " + Segments.TRACK + " " + Segments.TRACK_TYPE +
");";
}
/**
* This table contains waypoints.
*
* @author rene
*/
public static final class Waypoints extends WaypointsColumns implements android.provider.BaseColumns
{
/** The MIME type of a CONTENT_URI subdirectory of a single waypoint. */
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nl.sogeti.android.waypoint";
/** The MIME type of CONTENT_URI providing a directory of waypoints. */
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nl.sogeti.android.waypoint";
/** The name of this table, waypoints */
public static final String TABLE = "waypoints";
static final String CREATE_STATEMENT = "CREATE TABLE " + Waypoints.TABLE +
"(" + " " + BaseColumns._ID + " " + WaypointsColumns._ID_TYPE +
"," + " " + WaypointsColumns.LATITUDE + " " + WaypointsColumns.LATITUDE_TYPE +
"," + " " + WaypointsColumns.LONGITUDE + " " + WaypointsColumns.LONGITUDE_TYPE +
"," + " " + WaypointsColumns.TIME + " " + WaypointsColumns.TIME_TYPE +
"," + " " + WaypointsColumns.SPEED + " " + WaypointsColumns.SPEED +
"," + " " + WaypointsColumns.SEGMENT + " " + WaypointsColumns.SEGMENT_TYPE +
"," + " " + WaypointsColumns.ACCURACY + " " + WaypointsColumns.ACCURACY_TYPE +
"," + " " + WaypointsColumns.ALTITUDE + " " + WaypointsColumns.ALTITUDE_TYPE +
"," + " " + WaypointsColumns.BEARING + " " + WaypointsColumns.BEARING_TYPE +
");";
static final String[] UPGRADE_STATEMENT_7_TO_8 =
{
"ALTER TABLE " + Waypoints.TABLE + " ADD COLUMN " + WaypointsColumns.ACCURACY + " " + WaypointsColumns.ACCURACY_TYPE +";",
"ALTER TABLE " + Waypoints.TABLE + " ADD COLUMN " + WaypointsColumns.ALTITUDE + " " + WaypointsColumns.ALTITUDE_TYPE +";",
"ALTER TABLE " + Waypoints.TABLE + " ADD COLUMN " + WaypointsColumns.BEARING + " " + WaypointsColumns.BEARING_TYPE +";"
};
/**
* Build a waypoint Uri like:
* content://nl.sogeti.android.gpstracker/tracks/2/segments/1/waypoints/52
* using the provided identifiers
*
* @param trackId
* @param segmentId
* @param waypointId
*
* @return
*/
public static Uri buildUri(long trackId, long segmentId, long waypointId)
{
Builder builder = Tracks.CONTENT_URI.buildUpon();
ContentUris.appendId(builder, trackId);
builder.appendPath(Segments.TABLE);
ContentUris.appendId(builder, segmentId);
builder.appendPath(Waypoints.TABLE);
ContentUris.appendId(builder, waypointId);
return builder.build();
}
}
/**
* This table contains media URI's.
*
* @author rene
*/
public static final class Media extends MediaColumns implements android.provider.BaseColumns
{
/** The MIME type of a CONTENT_URI subdirectory of a single media entry. */
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nl.sogeti.android.media";
/** The MIME type of CONTENT_URI providing a directory of media entry. */
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nl.sogeti.android.media";
/** The name of this table */
public static final String TABLE = "media";
static final String CREATE_STATEMENT = "CREATE TABLE " + Media.TABLE +
"(" + " " + BaseColumns._ID + " " + MediaColumns._ID_TYPE +
"," + " " + MediaColumns.TRACK + " " + MediaColumns.TRACK_TYPE +
"," + " " + MediaColumns.SEGMENT + " " + MediaColumns.SEGMENT_TYPE +
"," + " " + MediaColumns.WAYPOINT + " " + MediaColumns.WAYPOINT_TYPE +
"," + " " + MediaColumns.URI + " " + MediaColumns.URI_TYPE +
");";
public static final Uri CONTENT_URI = Uri.parse( "content://" + GPStracking.AUTHORITY + "/" + Media.TABLE );
}
/**
* This table contains media URI's.
*
* @author rene
*/
public static final class MetaData extends MetaDataColumns implements android.provider.BaseColumns
{
/** The MIME type of a CONTENT_URI subdirectory of a single metadata entry. */
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nl.sogeti.android.metadata";
/** The MIME type of CONTENT_URI providing a directory of media entry. */
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nl.sogeti.android.metadata";
/** The name of this table */
public static final String TABLE = "metadata";
static final String CREATE_STATEMENT = "CREATE TABLE " + MetaData.TABLE +
"(" + " " + BaseColumns._ID + " " + MetaDataColumns._ID_TYPE +
"," + " " + MetaDataColumns.TRACK + " " + MetaDataColumns.TRACK_TYPE +
"," + " " + MetaDataColumns.SEGMENT + " " + MetaDataColumns.SEGMENT_TYPE +
"," + " " + MetaDataColumns.WAYPOINT + " " + MetaDataColumns.WAYPOINT_TYPE +
"," + " " + MetaDataColumns.KEY + " " + MetaDataColumns.KEY_TYPE +
"," + " " + MetaDataColumns.VALUE + " " + MetaDataColumns.VALUE_TYPE +
");";
/**
* content://nl.sogeti.android.gpstracker/metadata
*/
public static final Uri CONTENT_URI = Uri.parse( "content://" + GPStracking.AUTHORITY + "/" + MetaData.TABLE );
}
/**
* Columns from the tracks table.
*
* @author rene
*/
public static class TracksColumns
{
public static final String NAME = "name";
public static final String CREATION_TIME = "creationtime";
static final String CREATION_TIME_TYPE = "INTEGER NOT NULL";
static final String NAME_TYPE = "TEXT";
static final String _ID_TYPE = "INTEGER PRIMARY KEY AUTOINCREMENT";
}
/**
* Columns from the segments table.
*
* @author rene
*/
public static class SegmentsColumns
{
/** The track _id to which this segment belongs */
public static final String TRACK = "track";
static final String TRACK_TYPE = "INTEGER NOT NULL";
static final String _ID_TYPE = "INTEGER PRIMARY KEY AUTOINCREMENT";
}
/**
* Columns from the waypoints table.
*
* @author rene
*/
public static class WaypointsColumns
{
/** The latitude */
public static final String LATITUDE = "latitude";
/** The longitude */
public static final String LONGITUDE = "longitude";
/** The recorded time */
public static final String TIME = "time";
/** The speed in meters per second */
public static final String SPEED = "speed";
/** The segment _id to which this segment belongs */
public static final String SEGMENT = "tracksegment";
/** The accuracy of the fix */
public static final String ACCURACY = "accuracy";
/** The altitude */
public static final String ALTITUDE = "altitude";
/** the bearing of the fix */
public static final String BEARING = "bearing";
static final String LATITUDE_TYPE = "REAL NOT NULL";
static final String LONGITUDE_TYPE = "REAL NOT NULL";
static final String TIME_TYPE = "INTEGER NOT NULL";
static final String SPEED_TYPE = "REAL NOT NULL";
static final String SEGMENT_TYPE = "INTEGER NOT NULL";
static final String ACCURACY_TYPE = "REAL";
static final String ALTITUDE_TYPE = "REAL";
static final String BEARING_TYPE = "REAL";
static final String _ID_TYPE = "INTEGER PRIMARY KEY AUTOINCREMENT";
}
/**
* Columns from the media table.
*
* @author rene
*/
public static class MediaColumns
{
/** The track _id to which this segment belongs */
public static final String TRACK = "track";
static final String TRACK_TYPE = "INTEGER NOT NULL";
public static final String SEGMENT = "segment";
static final String SEGMENT_TYPE = "INTEGER NOT NULL";
public static final String WAYPOINT = "waypoint";
static final String WAYPOINT_TYPE = "INTEGER NOT NULL";
public static final String URI = "uri";
static final String URI_TYPE = "TEXT";
static final String _ID_TYPE = "INTEGER PRIMARY KEY AUTOINCREMENT";
}
/**
* Columns from the media table.
*
* @author rene
*/
public static class MetaDataColumns
{
/** The track _id to which this segment belongs */
public static final String TRACK = "track";
static final String TRACK_TYPE = "INTEGER NOT NULL";
public static final String SEGMENT = "segment";
static final String SEGMENT_TYPE = "INTEGER";
public static final String WAYPOINT = "waypoint";
static final String WAYPOINT_TYPE = "INTEGER";
public static final String KEY = "key";
static final String KEY_TYPE = "TEXT NOT NULL";
public static final String VALUE = "value";
static final String VALUE_TYPE = "TEXT NOT NULL";
static final String _ID_TYPE = "INTEGER PRIMARY KEY AUTOINCREMENT";
}
}
| 11chauhanpeeyush11-peeyush | OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/db/GPStracking.java | Java | gpl3 | 13,886 |
/*------------------------------------------------------------------------------
** Ident: Sogeti Smart Mobile Solutions
** Author: rene
** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.db;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import nl.sogeti.android.gpstracker.db.GPStracking.Media;
import nl.sogeti.android.gpstracker.db.GPStracking.MetaData;
import nl.sogeti.android.gpstracker.db.GPStracking.Segments;
import nl.sogeti.android.gpstracker.db.GPStracking.Tracks;
import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints;
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.location.Location;
import android.net.Uri;
import android.provider.LiveFolders;
import android.util.Log;
/**
* Goal of this Content Provider is to make the GPS Tracking information uniformly
* available to this application and even other applications. The GPS-tracking
* database can hold, tracks, segments or waypoints
* <p>
* A track is an actual route taken from start to finish. All the GPS locations
* collected are waypoints. Waypoints taken in sequence without loss of GPS-signal
* are considered connected and are grouped in segments. A route is build up out of
* 1 or more segments.
* <p>
* For example:<br>
* <code>content://nl.sogeti.android.gpstracker/tracks</code>
* is the URI that returns all the stored tracks or starts a new track on insert
* <p>
* <code>content://nl.sogeti.android.gpstracker/tracks/2</code>
* is the URI string that would return a single result row, the track with ID = 23.
* <p>
* <code>content://nl.sogeti.android.gpstracker/tracks/2/segments</code> is the URI that returns
* all the stored segments of a track with ID = 2 or starts a new segment on insert
* <p>
* <code>content://nl.sogeti.android.gpstracker/tracks/2/waypoints</code> is the URI that returns
* all the stored waypoints of a track with ID = 2
* <p>
* <code>content://nl.sogeti.android.gpstracker/tracks/2/segments</code> is the URI that returns
* all the stored segments of a track with ID = 2
* <p>
* <code>content://nl.sogeti.android.gpstracker/tracks/2/segments/3</code> is
* the URI string that would return a single result row, the segment with ID = 3 of a track with ID = 2 .
* <p>
* <code>content://nl.sogeti.android.gpstracker/tracks/2/segments/1/waypoints</code> is the URI that
* returns all the waypoints of a segment 1 of track 2.
* <p>
* <code>content://nl.sogeti.android.gpstracker/tracks/2/segments/1/waypoints/52</code> is the URI string that
* would return a single result row, the waypoint with ID = 52
* <p>
* Media is stored under a waypoint and may be queried as:<br>
* <code>content://nl.sogeti.android.gpstracker/tracks/2/segments/3/waypoints/22/media</code>
* <p>
*
*
* All media for a segment can be queried with:<br>
* <code>content://nl.sogeti.android.gpstracker/tracks/2/segments/3/media</code>
* <p>
* All media for a track can be queried with:<br>
* <code>content://nl.sogeti.android.gpstracker/tracks/2/media</code>
*
* <p>
* The whole set of collected media may be queried as:<br>
* <code>content://nl.sogeti.android.gpstracker/media</code>
* <p>
* A single media is stored with an ID, for instance ID = 12:<br>
* <code>content://nl.sogeti.android.gpstracker/media/12</code>
* <p>
* The whole set of collected media may be queried as:<br>
* <code>content://nl.sogeti.android.gpstracker/media</code>
* <p>
*
*
* Meta-data regarding a single waypoint may be queried as:<br>
* <code>content://nl.sogeti.android.gpstracker/tracks/2/segments/3/waypoints/22/metadata</code>
* <p>
* Meta-data regarding a single segment as whole may be queried as:<br>
* <code>content://nl.sogeti.android.gpstracker/tracks/2/segments/3/metadata</code>
* Note: This does not include meta-data of waypoints.
* <p>
* Meta-data regarding a single track as a whole may be queried as:<br>
* <code>content://nl.sogeti.android.gpstracker/tracks/2/metadata</code>
* Note: This does not include meta-data of waypoints or segments.
*
* @version $Id$
* @author rene (c) Jan 22, 2009, Sogeti B.V.
*/
public class GPStrackingProvider extends ContentProvider
{
private static final String TAG = "OGT.GPStrackingProvider";
/* Action types as numbers for using the UriMatcher */
private static final int TRACKS = 1;
private static final int TRACK_ID = 2;
private static final int TRACK_MEDIA = 3;
private static final int TRACK_WAYPOINTS = 4;
private static final int SEGMENTS = 5;
private static final int SEGMENT_ID = 6;
private static final int SEGMENT_MEDIA = 7;
private static final int WAYPOINTS = 8;
private static final int WAYPOINT_ID = 9;
private static final int WAYPOINT_MEDIA = 10;
private static final int SEARCH_SUGGEST_ID = 11;
private static final int LIVE_FOLDERS = 12;
private static final int MEDIA = 13;
private static final int MEDIA_ID = 14;
private static final int TRACK_METADATA = 15;
private static final int SEGMENT_METADATA = 16;
private static final int WAYPOINT_METADATA = 17;
private static final int METADATA = 18;
private static final int METADATA_ID = 19;
private static final String[] SUGGEST_PROJECTION =
new String[]
{
Tracks._ID,
Tracks.NAME+" AS "+SearchManager.SUGGEST_COLUMN_TEXT_1,
"datetime("+Tracks.CREATION_TIME+"/1000, 'unixepoch') as "+SearchManager.SUGGEST_COLUMN_TEXT_2,
Tracks._ID+" AS "+SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID
};
private static final String[] LIVE_PROJECTION =
new String[]
{
Tracks._ID+" AS "+LiveFolders._ID,
Tracks.NAME+" AS "+ LiveFolders.NAME,
"datetime("+Tracks.CREATION_TIME+"/1000, 'unixepoch') as "+LiveFolders.DESCRIPTION
};
private static UriMatcher sURIMatcher = new UriMatcher( UriMatcher.NO_MATCH );
/**
* Although it is documented that in addURI(null, path, 0) "path" should be an absolute path this does not seem to work. A relative path gets the jobs done and matches an absolute path.
*/
static
{
GPStrackingProvider.sURIMatcher = new UriMatcher( UriMatcher.NO_MATCH );
GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "tracks", GPStrackingProvider.TRACKS );
GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "tracks/#", GPStrackingProvider.TRACK_ID );
GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "tracks/#/media", GPStrackingProvider.TRACK_MEDIA );
GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "tracks/#/metadata", GPStrackingProvider.TRACK_METADATA );
GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "tracks/#/waypoints", GPStrackingProvider.TRACK_WAYPOINTS );
GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "tracks/#/segments", GPStrackingProvider.SEGMENTS );
GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "tracks/#/segments/#", GPStrackingProvider.SEGMENT_ID );
GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "tracks/#/segments/#/media", GPStrackingProvider.SEGMENT_MEDIA );
GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "tracks/#/segments/#/metadata", GPStrackingProvider.SEGMENT_METADATA );
GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "tracks/#/segments/#/waypoints", GPStrackingProvider.WAYPOINTS );
GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "tracks/#/segments/#/waypoints/#", GPStrackingProvider.WAYPOINT_ID );
GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "tracks/#/segments/#/waypoints/#/media", GPStrackingProvider.WAYPOINT_MEDIA );
GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "tracks/#/segments/#/waypoints/#/metadata", GPStrackingProvider.WAYPOINT_METADATA );
GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "media", GPStrackingProvider.MEDIA );
GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "media/#", GPStrackingProvider.MEDIA_ID );
GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "metadata", GPStrackingProvider.METADATA );
GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "metadata/#", GPStrackingProvider.METADATA_ID );
GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "live_folders/tracks", GPStrackingProvider.LIVE_FOLDERS );
GPStrackingProvider.sURIMatcher.addURI( GPStracking.AUTHORITY, "search_suggest_query", GPStrackingProvider.SEARCH_SUGGEST_ID );
}
private DatabaseHelper mDbHelper;
/**
* (non-Javadoc)
* @see android.content.ContentProvider#onCreate()
*/
@Override
public boolean onCreate()
{
if (this.mDbHelper == null)
{
this.mDbHelper = new DatabaseHelper( getContext() );
}
return true;
}
/**
* (non-Javadoc)
* @see android.content.ContentProvider#getType(android.net.Uri)
*/
@Override
public String getType( Uri uri )
{
int match = GPStrackingProvider.sURIMatcher.match( uri );
String mime = null;
switch (match)
{
case TRACKS:
mime = Tracks.CONTENT_TYPE;
break;
case TRACK_ID:
mime = Tracks.CONTENT_ITEM_TYPE;
break;
case SEGMENTS:
mime = Segments.CONTENT_TYPE;
break;
case SEGMENT_ID:
mime = Segments.CONTENT_ITEM_TYPE;
break;
case WAYPOINTS:
mime = Waypoints.CONTENT_TYPE;
break;
case WAYPOINT_ID:
mime = Waypoints.CONTENT_ITEM_TYPE;
break;
case MEDIA_ID:
case TRACK_MEDIA:
case SEGMENT_MEDIA:
case WAYPOINT_MEDIA:
mime = Media.CONTENT_ITEM_TYPE;
break;
case METADATA_ID:
case TRACK_METADATA:
case SEGMENT_METADATA:
case WAYPOINT_METADATA:
mime = MetaData.CONTENT_ITEM_TYPE;
break;
case UriMatcher.NO_MATCH:
default:
Log.w(TAG, "There is not MIME type defined for URI "+uri);
break;
}
return mime;
}
/**
* (non-Javadoc)
* @see android.content.ContentProvider#insert(android.net.Uri, android.content.ContentValues)
*/
@Override
public Uri insert( Uri uri, ContentValues values )
{
//Log.d( TAG, "insert on "+uri );
Uri insertedUri = null;
int match = GPStrackingProvider.sURIMatcher.match( uri );
List<String> pathSegments = null;
long trackId = -1;
long segmentId = -1;
long waypointId = -1;
long mediaId = -1;
String key;
String value;
switch (match)
{
case WAYPOINTS:
pathSegments = uri.getPathSegments();
trackId = Long.parseLong( pathSegments.get( 1 ) );
segmentId = Long.parseLong( pathSegments.get( 3 ) );
Location loc = new Location( TAG );
Double latitude = values.getAsDouble( Waypoints.LATITUDE );
Double longitude = values.getAsDouble( Waypoints.LONGITUDE );
Long time = values.getAsLong( Waypoints.TIME );
Float speed = values.getAsFloat( Waypoints.SPEED );
if( time == null )
{
time = System.currentTimeMillis();
}
if( speed == null )
{
speed = 0f;
}
loc.setLatitude( latitude );
loc.setLongitude( longitude );
loc.setTime( time );
loc.setSpeed( speed );
if( values.containsKey( Waypoints.ACCURACY ) )
{
loc.setAccuracy( values.getAsFloat( Waypoints.ACCURACY ) );
}
if( values.containsKey( Waypoints.ALTITUDE ) )
{
loc.setAltitude( values.getAsDouble( Waypoints.ALTITUDE ) );
}
if( values.containsKey( Waypoints.BEARING ) )
{
loc.setBearing( values.getAsFloat( Waypoints.BEARING ) );
}
waypointId = this.mDbHelper.insertWaypoint(
trackId,
segmentId,
loc );
// Log.d( TAG, "Have inserted to segment "+segmentId+" with waypoint "+waypointId );
insertedUri = ContentUris.withAppendedId( uri, waypointId );
break;
case WAYPOINT_MEDIA:
pathSegments = uri.getPathSegments();
trackId = Long.parseLong( pathSegments.get( 1 ) );
segmentId = Long.parseLong( pathSegments.get( 3 ) );
waypointId = Long.parseLong( pathSegments.get( 5 ) );
String mediaUri = values.getAsString( Media.URI );
mediaId = this.mDbHelper.insertMedia( trackId, segmentId, waypointId, mediaUri );
insertedUri = ContentUris.withAppendedId( Media.CONTENT_URI, mediaId );
break;
case SEGMENTS:
pathSegments = uri.getPathSegments();
trackId = Integer.parseInt( pathSegments.get( 1 ) );
segmentId = this.mDbHelper.toNextSegment( trackId );
insertedUri = ContentUris.withAppendedId( uri, segmentId );
break;
case TRACKS:
String name = ( values == null ) ? "" : values.getAsString( Tracks.NAME );
trackId = this.mDbHelper.toNextTrack( name );
insertedUri = ContentUris.withAppendedId( uri, trackId );
break;
case TRACK_METADATA:
pathSegments = uri.getPathSegments();
trackId = Long.parseLong( pathSegments.get( 1 ) );
key = values.getAsString( MetaData.KEY );
value = values.getAsString( MetaData.VALUE );
mediaId = this.mDbHelper.insertOrUpdateMetaData( trackId, -1L, -1L, key, value );
insertedUri = ContentUris.withAppendedId( MetaData.CONTENT_URI, mediaId );
break;
case SEGMENT_METADATA:
pathSegments = uri.getPathSegments();
trackId = Long.parseLong( pathSegments.get( 1 ) );
segmentId = Long.parseLong( pathSegments.get( 3 ) );
key = values.getAsString( MetaData.KEY );
value = values.getAsString( MetaData.VALUE );
mediaId = this.mDbHelper.insertOrUpdateMetaData( trackId, segmentId, -1L, key, value );
insertedUri = ContentUris.withAppendedId( MetaData.CONTENT_URI, mediaId );
break;
case WAYPOINT_METADATA:
pathSegments = uri.getPathSegments();
trackId = Long.parseLong( pathSegments.get( 1 ) );
segmentId = Long.parseLong( pathSegments.get( 3 ) );
waypointId = Long.parseLong( pathSegments.get( 5 ) );
key = values.getAsString( MetaData.KEY );
value = values.getAsString( MetaData.VALUE );
mediaId = this.mDbHelper.insertOrUpdateMetaData( trackId, segmentId, waypointId, key, value );
insertedUri = ContentUris.withAppendedId( MetaData.CONTENT_URI, mediaId );
break;
default:
Log.e( GPStrackingProvider.TAG, "Unable to match the insert URI: " + uri.toString() );
insertedUri = null;
break;
}
return insertedUri;
}
/**
* (non-Javadoc)
* @see android.content.ContentProvider#query(android.net.Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String)
*/
@Override
public Cursor query( Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder )
{
// Log.d( TAG, "Query on Uri:"+uri );
int match = GPStrackingProvider.sURIMatcher.match( uri );
String tableName = null;
String innerSelection = "1";
String[] innerSelectionArgs = new String[]{};
String sortorder = sortOrder;
List<String> pathSegments = uri.getPathSegments();
switch (match)
{
case TRACKS:
tableName = Tracks.TABLE;
break;
case TRACK_ID:
tableName = Tracks.TABLE;
innerSelection = Tracks._ID + " = ? ";
innerSelectionArgs = new String[]{ pathSegments.get( 1 ) };
break;
case SEGMENTS:
tableName = Segments.TABLE;
innerSelection = Segments.TRACK + " = ? ";
innerSelectionArgs = new String[]{ pathSegments.get( 1 ) };
break;
case SEGMENT_ID:
tableName = Segments.TABLE;
innerSelection = Segments.TRACK + " = ? and " + Segments._ID + " = ? ";
innerSelectionArgs = new String[]{ pathSegments.get( 1 ), pathSegments.get( 3 ) };
break;
case WAYPOINTS:
tableName = Waypoints.TABLE;
innerSelection = Waypoints.SEGMENT + " = ? ";
innerSelectionArgs = new String[]{ pathSegments.get( 3 ) };
break;
case WAYPOINT_ID:
tableName = Waypoints.TABLE;
innerSelection = Waypoints.SEGMENT + " = ? and " + Waypoints._ID + " = ? ";
innerSelectionArgs = new String[]{ pathSegments.get( 3 ), pathSegments.get( 5 ) };
break;
case TRACK_WAYPOINTS:
tableName = Waypoints.TABLE + " INNER JOIN " + Segments.TABLE + " ON "+ Segments.TABLE+"."+Segments._ID +"=="+ Waypoints.SEGMENT;
innerSelection = Segments.TRACK + " = ? ";
innerSelectionArgs = new String[]{ pathSegments.get( 1 ) };
break;
case GPStrackingProvider.MEDIA:
tableName = Media.TABLE;
break;
case GPStrackingProvider.MEDIA_ID:
tableName = Media.TABLE;
innerSelection = Media._ID + " = ? ";
innerSelectionArgs = new String[]{ pathSegments.get( 1 ) };
break;
case TRACK_MEDIA:
tableName = Media.TABLE;
innerSelection = Media.TRACK + " = ? ";
innerSelectionArgs = new String[]{ pathSegments.get( 1 ) };
break;
case SEGMENT_MEDIA:
tableName = Media.TABLE;
innerSelection = Media.TRACK + " = ? and " + Media.SEGMENT + " = ? ";
innerSelectionArgs = new String[]{ pathSegments.get( 1 ), pathSegments.get( 3 ) };
break;
case WAYPOINT_MEDIA:
tableName = Media.TABLE;
innerSelection = Media.TRACK + " = ? and " + Media.SEGMENT + " = ? and " + Media.WAYPOINT + " = ? ";
innerSelectionArgs = new String[]{ pathSegments.get( 1 ),pathSegments.get( 3 ), pathSegments.get( 5 )};
break;
case TRACK_METADATA:
tableName = MetaData.TABLE;
innerSelection = MetaData.TRACK + " = ? and " + MetaData.SEGMENT + " = ? and " + MetaData.WAYPOINT + " = ? ";
innerSelectionArgs = new String[]{ pathSegments.get( 1 ), "-1", "-1" };
break;
case SEGMENT_METADATA:
tableName = MetaData.TABLE;
innerSelection = MetaData.TRACK + " = ? and " + MetaData.SEGMENT + " = ? and " + MetaData.WAYPOINT + " = ? ";
innerSelectionArgs = new String[]{pathSegments.get( 1 ), pathSegments.get( 3 ), "-1" };
break;
case WAYPOINT_METADATA:
tableName = MetaData.TABLE;
innerSelection = MetaData.TRACK + " = ? and " + MetaData.SEGMENT + " = ? and " + MetaData.WAYPOINT + " = ? ";
innerSelectionArgs = new String[]{ pathSegments.get( 1 ), pathSegments.get( 3 ), pathSegments.get( 5 ) };
break;
case GPStrackingProvider.METADATA:
tableName = MetaData.TABLE;
break;
case GPStrackingProvider.METADATA_ID:
tableName = MetaData.TABLE;
innerSelection = MetaData._ID + " = ? ";
innerSelectionArgs = new String[]{ pathSegments.get( 1 ) };
break;
case SEARCH_SUGGEST_ID:
tableName = Tracks.TABLE;
if( selectionArgs[0] == null || selectionArgs[0].equals( "" ) )
{
selection = null;
selectionArgs = null;
sortorder = Tracks.CREATION_TIME+" desc";
}
else
{
selectionArgs[0] = "%" +selectionArgs[0]+ "%";
}
projection = SUGGEST_PROJECTION;
break;
case LIVE_FOLDERS:
tableName = Tracks.TABLE;
projection = LIVE_PROJECTION;
sortorder = Tracks.CREATION_TIME+" desc";
break;
default:
Log.e( GPStrackingProvider.TAG, "Unable to come to an action in the query uri: " + uri.toString() );
return null;
}
// SQLiteQueryBuilder is a helper class that creates the
// proper SQL syntax for us.
SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
// Set the table we're querying.
qBuilder.setTables( tableName );
if( selection == null )
{
selection = innerSelection;
}
else
{
selection = "( "+ innerSelection + " ) and " + selection;
}
LinkedList<String> allArgs = new LinkedList<String>();
if( selectionArgs == null )
{
allArgs.addAll(Arrays.asList(innerSelectionArgs));
}
else
{
allArgs.addAll(Arrays.asList(innerSelectionArgs));
allArgs.addAll(Arrays.asList(selectionArgs));
}
selectionArgs = allArgs.toArray(innerSelectionArgs);
// Make the query.
SQLiteDatabase mDb = this.mDbHelper.getWritableDatabase();
Cursor c = qBuilder.query( mDb, projection, selection, selectionArgs, null, null, sortorder );
c.setNotificationUri( getContext().getContentResolver(), uri );
return c;
}
/**
* (non-Javadoc)
* @see android.content.ContentProvider#update(android.net.Uri, android.content.ContentValues, java.lang.String, java.lang.String[])
*/
@Override
public int update( Uri uri, ContentValues givenValues, String selection, String[] selectionArgs )
{
int updates = -1 ;
long trackId;
long segmentId;
long waypointId;
long metaDataId;
List<String> pathSegments;
int match = GPStrackingProvider.sURIMatcher.match( uri );
String value;
switch (match)
{
case TRACK_ID:
trackId = new Long( uri.getLastPathSegment() ).longValue();
String name = givenValues.getAsString( Tracks.NAME );
updates = mDbHelper.updateTrack(trackId, name);
break;
case TRACK_METADATA:
pathSegments = uri.getPathSegments();
trackId = Long.parseLong( pathSegments.get( 1 ) );
value = givenValues.getAsString( MetaData.VALUE );
updates = mDbHelper.updateMetaData( trackId, -1L, -1L, -1L, selection, selectionArgs, value);
break;
case SEGMENT_METADATA:
pathSegments = uri.getPathSegments();
trackId = Long.parseLong( pathSegments.get( 1 ) );
segmentId = Long.parseLong( pathSegments.get( 3 ) );
value = givenValues.getAsString( MetaData.VALUE );
updates = mDbHelper.updateMetaData( trackId, segmentId, -1L, -1L, selection, selectionArgs, value);
break;
case WAYPOINT_METADATA:
pathSegments = uri.getPathSegments();
trackId = Long.parseLong( pathSegments.get( 1 ) );
segmentId = Long.parseLong( pathSegments.get( 3 ) );
waypointId = Long.parseLong( pathSegments.get( 5 ) );
value = givenValues.getAsString( MetaData.VALUE );
updates = mDbHelper.updateMetaData( trackId, segmentId, waypointId, -1L, selection, selectionArgs, value);
break;
case METADATA_ID:
pathSegments = uri.getPathSegments();
metaDataId = Long.parseLong( pathSegments.get( 1 ) );
value = givenValues.getAsString( MetaData.VALUE );
updates = mDbHelper.updateMetaData( -1L, -1L, -1L, metaDataId, selection, selectionArgs, value);
break;
default:
Log.e( GPStrackingProvider.TAG, "Unable to come to an action in the query uri" + uri.toString() );
return -1;
}
return updates;
}
/**
* (non-Javadoc)
* @see android.content.ContentProvider#delete(android.net.Uri, java.lang.String, java.lang.String[])
*/
@Override
public int delete( Uri uri, String selection, String[] selectionArgs )
{
int match = GPStrackingProvider.sURIMatcher.match( uri );
int affected = 0;
switch( match )
{
case GPStrackingProvider.TRACK_ID:
affected = this.mDbHelper.deleteTrack( new Long( uri.getLastPathSegment() ).longValue() );
break;
case GPStrackingProvider.MEDIA_ID:
affected = this.mDbHelper.deleteMedia( new Long( uri.getLastPathSegment() ).longValue() );
break;
case GPStrackingProvider.METADATA_ID:
affected = this.mDbHelper.deleteMetaData( new Long( uri.getLastPathSegment() ).longValue() );
break;
default:
affected = 0;
break;
}
return affected;
}
@Override
public int bulkInsert( Uri uri, ContentValues[] valuesArray )
{
int inserted = 0;
int match = GPStrackingProvider.sURIMatcher.match( uri );
switch (match)
{
case WAYPOINTS:
List<String> pathSegments = uri.getPathSegments();
int trackId = Integer.parseInt( pathSegments.get( 1 ) );
int segmentId = Integer.parseInt( pathSegments.get( 3 ) );
inserted = this.mDbHelper.bulkInsertWaypoint( trackId, segmentId, valuesArray );
break;
default:
inserted = super.bulkInsert( uri, valuesArray );
break;
}
return inserted;
}
}
| 11chauhanpeeyush11-peeyush | OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/db/GPStrackingProvider.java | Java | gpl3 | 28,917 |
/*------------------------------------------------------------------------------
** Ident: Sogeti Smart Mobile Solutions
** Author: rene
** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.actions;
import nl.sogeti.android.gpstracker.R;
import nl.sogeti.android.gpstracker.db.GPStracking.Tracks;
import nl.sogeti.android.gpstracker.logger.GPSLoggerServiceManager;
import nl.sogeti.android.gpstracker.util.Constants;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
/**
* Empty Activity that pops up the dialog to name the track
*
* @version $Id$
* @author rene (c) Jul 27, 2010, Sogeti B.V.
*/
public class ControlTracking extends Activity
{
private static final int DIALOG_LOGCONTROL = 26;
private static final String TAG = "OGT.ControlTracking";
private GPSLoggerServiceManager mLoggerServiceManager;
private Button start;
private Button pause;
private Button resume;
private Button stop;
private boolean paused;
private final View.OnClickListener mLoggingControlListener = new View.OnClickListener()
{
@Override
public void onClick( View v )
{
int id = v.getId();
Intent intent = new Intent();
switch( id )
{
case R.id.logcontrol_start:
long loggerTrackId = mLoggerServiceManager.startGPSLogging( null );
// Start a naming of the track
Intent namingIntent = new Intent( ControlTracking.this, NameTrack.class );
namingIntent.setData( ContentUris.withAppendedId( Tracks.CONTENT_URI, loggerTrackId ) );
startActivity( namingIntent );
// Create data for the caller that a new track has been started
ComponentName caller = ControlTracking.this.getCallingActivity();
if( caller != null )
{
intent.setData( ContentUris.withAppendedId( Tracks.CONTENT_URI, loggerTrackId ) );
setResult( RESULT_OK, intent );
}
break;
case R.id.logcontrol_pause:
mLoggerServiceManager.pauseGPSLogging();
setResult( RESULT_OK, intent );
break;
case R.id.logcontrol_resume:
mLoggerServiceManager.resumeGPSLogging();
setResult( RESULT_OK, intent );
break;
case R.id.logcontrol_stop:
mLoggerServiceManager.stopGPSLogging();
setResult( RESULT_OK, intent );
break;
default:
setResult( RESULT_CANCELED, intent );
break;
}
finish();
}
};
private OnClickListener mDialogClickListener = new OnClickListener()
{
@Override
public void onClick( DialogInterface dialog, int which )
{
setResult( RESULT_CANCELED, new Intent() );
finish();
}
};
@Override
protected void onCreate( Bundle savedInstanceState )
{
super.onCreate( savedInstanceState );
this.setVisible( false );
paused = false;
mLoggerServiceManager = new GPSLoggerServiceManager( this );
}
@Override
protected void onResume()
{
super.onResume();
mLoggerServiceManager.startup( this, new Runnable()
{
@Override
public void run()
{
showDialog( DIALOG_LOGCONTROL );
}
} );
}
@Override
protected void onPause()
{
super.onPause();
mLoggerServiceManager.shutdown( this );
paused = true;
}
@Override
protected Dialog onCreateDialog( int id )
{
Dialog dialog = null;
LayoutInflater factory = null;
View view = null;
Builder builder = null;
switch( id )
{
case DIALOG_LOGCONTROL:
builder = new AlertDialog.Builder( this );
factory = LayoutInflater.from( this );
view = factory.inflate( R.layout.logcontrol, null );
builder.setTitle( R.string.dialog_tracking_title ).
setIcon( android.R.drawable.ic_dialog_alert ).
setNegativeButton( R.string.btn_cancel, mDialogClickListener ).
setView( view );
dialog = builder.create();
start = (Button) view.findViewById( R.id.logcontrol_start );
pause = (Button) view.findViewById( R.id.logcontrol_pause );
resume = (Button) view.findViewById( R.id.logcontrol_resume );
stop = (Button) view.findViewById( R.id.logcontrol_stop );
start.setOnClickListener( mLoggingControlListener );
pause.setOnClickListener( mLoggingControlListener );
resume.setOnClickListener( mLoggingControlListener );
stop.setOnClickListener( mLoggingControlListener );
dialog.setOnDismissListener( new OnDismissListener()
{
@Override
public void onDismiss( DialogInterface dialog )
{
if( !paused )
{
finish();
}
}
});
return dialog;
default:
return super.onCreateDialog( id );
}
}
/*
* (non-Javadoc)
* @see android.app.Activity#onPrepareDialog(int, android.app.Dialog)
*/
@Override
protected void onPrepareDialog( int id, Dialog dialog )
{
switch( id )
{
case DIALOG_LOGCONTROL:
updateDialogState( mLoggerServiceManager.getLoggingState() );
break;
default:
break;
}
super.onPrepareDialog( id, dialog );
}
private void updateDialogState( int state )
{
switch( state )
{
case Constants.STOPPED:
start.setEnabled( true );
pause.setEnabled( false );
resume.setEnabled( false );
stop.setEnabled( false );
break;
case Constants.LOGGING:
start.setEnabled( false );
pause.setEnabled( true );
resume.setEnabled( false );
stop.setEnabled( true );
break;
case Constants.PAUSED:
start.setEnabled( false );
pause.setEnabled( false );
resume.setEnabled( true );
stop.setEnabled( true );
break;
default:
Log.w( TAG, String.format( "State %d of logging, enabling and hope for the best....", state ) );
start.setEnabled( false );
pause.setEnabled( false );
resume.setEnabled( false );
stop.setEnabled( false );
break;
}
}
}
| 11chauhanpeeyush11-peeyush | OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/ControlTracking.java | Java | gpl3 | 8,784 |
/*------------------------------------------------------------------------------
** Ident: Sogeti Smart Mobile Solutions
** Author: rene
** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.actions;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;
import nl.sogeti.android.gpstracker.R;
import nl.sogeti.android.gpstracker.logger.GPSLoggerServiceManager;
import nl.sogeti.android.gpstracker.util.Constants;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/**
* Empty Activity that pops up the dialog to add a note to the most current
* point in the logger service
*
* @version $Id$
* @author rene (c) Jul 27, 2010, Sogeti B.V.
*/
public class InsertNote extends Activity
{
private static final int DIALOG_INSERTNOTE = 27;
private static final String TAG = "OGT.InsertNote";
private static final int MENU_PICTURE = 9;
private static final int MENU_VOICE = 11;
private static final int MENU_VIDEO = 12;
private static final int DIALOG_TEXT = 32;
private static final int DIALOG_NAME = 33;
private GPSLoggerServiceManager mLoggerServiceManager;
/**
* Action to take when the LoggerService is bound
*/
private Runnable mServiceBindAction;
private boolean paused;
private Button name;
private Button text;
private Button voice;
private Button picture;
private Button video;
private EditText mNoteNameView;
private EditText mNoteTextView;
private final OnClickListener mNoteTextDialogListener = new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
String noteText = mNoteTextView.getText().toString();
Calendar c = Calendar.getInstance();
String newName = String.format("Textnote_%tY-%tm-%td_%tH%tM%tS.txt", c, c, c, c, c, c);
File file = new File(Constants.getSdCardDirectory(InsertNote.this) + newName);
FileWriter filewriter = null;
try
{
file.getParentFile().mkdirs();
file.createNewFile();
filewriter = new FileWriter(file);
filewriter.append(noteText);
filewriter.flush();
}
catch (IOException e)
{
Log.e(TAG, "Note storing failed", e);
CharSequence text = e.getLocalizedMessage();
Toast toast = Toast.makeText(InsertNote.this, text, Toast.LENGTH_LONG);
toast.show();
}
finally
{
if (filewriter != null)
{
try
{
filewriter.close();
}
catch (IOException e)
{ /* */
}
}
}
InsertNote.this.mLoggerServiceManager.storeMediaUri(Uri.fromFile(file));
setResult(RESULT_CANCELED, new Intent());
finish();
}
};
private final OnClickListener mNoteNameDialogListener = new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
String name = mNoteNameView.getText().toString();
Uri media = Uri.withAppendedPath(Constants.NAME_URI, Uri.encode(name));
InsertNote.this.mLoggerServiceManager.storeMediaUri(media);
setResult(RESULT_CANCELED, new Intent());
finish();
}
};
private final View.OnClickListener mNoteInsertListener = new View.OnClickListener()
{
@Override
public void onClick(View v)
{
int id = v.getId();
switch (id)
{
case R.id.noteinsert_picture:
addPicture();
break;
case R.id.noteinsert_video:
addVideo();
break;
case R.id.noteinsert_voice:
addVoice();
break;
case R.id.noteinsert_text:
showDialog(DIALOG_TEXT);
break;
case R.id.noteinsert_name:
showDialog(DIALOG_NAME);
break;
default:
setResult(RESULT_CANCELED, new Intent());
finish();
break;
}
}
};
private OnClickListener mDialogClickListener = new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
setResult(RESULT_CANCELED, new Intent());
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setVisible(false);
paused = false;
mLoggerServiceManager = new GPSLoggerServiceManager(this);
}
@Override
protected void onResume()
{
super.onResume();
if (mServiceBindAction == null)
{
mServiceBindAction = new Runnable()
{
@Override
public void run()
{
showDialog(DIALOG_INSERTNOTE);
}
};
}
;
mLoggerServiceManager.startup(this, mServiceBindAction);
}
@Override
protected void onPause()
{
super.onPause();
mLoggerServiceManager.shutdown(this);
paused = true;
}
/*
* (non-Javadoc)
* @see android.app.Activity#onActivityResult(int, int,
* android.content.Intent)
*/
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
mServiceBindAction = new Runnable()
{
@Override
public void run()
{
if (resultCode != RESULT_CANCELED)
{
File file;
Uri uri;
File newFile;
String newName;
Uri fileUri;
android.net.Uri.Builder builder;
boolean isLocal = false;
switch (requestCode)
{
case MENU_PICTURE:
file = new File(Constants.getSdCardTmpFile(InsertNote.this));
Calendar c = Calendar.getInstance();
newName = String.format("Picture_%tY-%tm-%td_%tH%tM%tS.jpg", c, c, c, c, c, c);
newFile = new File(Constants.getSdCardDirectory(InsertNote.this) + newName);
file.getParentFile().mkdirs();
isLocal = file.renameTo(newFile); //
if (!isLocal)
{
Log.w(TAG, "Failed rename will try copy image: " + file.getAbsolutePath());
isLocal = copyFile(file, newFile);
}
if (isLocal)
{
System.gc();
Options opts = new Options();
opts.inJustDecodeBounds = true;
Bitmap bm = BitmapFactory.decodeFile(newFile.getAbsolutePath(), opts);
String height, width;
if (bm != null)
{
height = Integer.toString(bm.getHeight());
width = Integer.toString(bm.getWidth());
}
else
{
height = Integer.toString(opts.outHeight);
width = Integer.toString(opts.outWidth);
}
bm = null;
builder = new Uri.Builder();
fileUri = builder.scheme("file").appendEncodedPath("/").appendEncodedPath(newFile.getAbsolutePath())
.appendQueryParameter("width", width).appendQueryParameter("height", height).build();
InsertNote.this.mLoggerServiceManager.storeMediaUri(fileUri);
}
else
{
Log.e(TAG, "Failed either rename or copy image: " + file.getAbsolutePath());
}
break;
case MENU_VIDEO:
file = new File(Constants.getSdCardTmpFile(InsertNote.this));
c = Calendar.getInstance();
newName = String.format("Video_%tY%tm%td_%tH%tM%tS.3gp", c, c, c, c, c, c);
newFile = new File(Constants.getSdCardDirectory(InsertNote.this) + newName);
file.getParentFile().mkdirs();
isLocal = file.renameTo(newFile);
if (!isLocal)
{
Log.w(TAG, "Failed rename will try copy video: " + file.getAbsolutePath());
isLocal = copyFile(file, newFile);
}
if (isLocal)
{
builder = new Uri.Builder();
fileUri = builder.scheme("file").appendPath(newFile.getAbsolutePath()).build();
InsertNote.this.mLoggerServiceManager.storeMediaUri(fileUri);
}
else
{
Log.e(TAG, "Failed either rename or copy video: " + file.getAbsolutePath());
}
break;
case MENU_VOICE:
uri = Uri.parse(intent.getDataString());
InsertNote.this.mLoggerServiceManager.storeMediaUri(uri);
break;
default:
Log.e(TAG, "Returned form unknow activity: " + requestCode);
break;
}
}
else
{
Log.w(TAG, "Received unexpected resultcode " + resultCode);
}
setResult(resultCode, new Intent());
finish();
}
};
}
@Override
protected Dialog onCreateDialog(int id)
{
Dialog dialog = null;
LayoutInflater factory = null;
View view = null;
Builder builder = null;
switch (id)
{
case DIALOG_INSERTNOTE:
builder = new AlertDialog.Builder(this);
factory = LayoutInflater.from(this);
view = factory.inflate(R.layout.insertnote, null);
builder.setTitle(R.string.menu_insertnote).setIcon(android.R.drawable.ic_dialog_alert).setNegativeButton(R.string.btn_cancel, mDialogClickListener)
.setView(view);
dialog = builder.create();
name = (Button) view.findViewById(R.id.noteinsert_name);
text = (Button) view.findViewById(R.id.noteinsert_text);
voice = (Button) view.findViewById(R.id.noteinsert_voice);
picture = (Button) view.findViewById(R.id.noteinsert_picture);
video = (Button) view.findViewById(R.id.noteinsert_video);
name.setOnClickListener(mNoteInsertListener);
text.setOnClickListener(mNoteInsertListener);
voice.setOnClickListener(mNoteInsertListener);
picture.setOnClickListener(mNoteInsertListener);
video.setOnClickListener(mNoteInsertListener);
dialog.setOnDismissListener(new OnDismissListener()
{
@Override
public void onDismiss(DialogInterface dialog)
{
if (!paused)
{
finish();
}
}
});
return dialog;
case DIALOG_TEXT:
builder = new AlertDialog.Builder(this);
factory = LayoutInflater.from(this);
view = factory.inflate(R.layout.notetextdialog, null);
mNoteTextView = (EditText) view.findViewById(R.id.notetext);
builder.setTitle(R.string.dialog_notetext_title).setMessage(R.string.dialog_notetext_message).setIcon(android.R.drawable.ic_dialog_map)
.setPositiveButton(R.string.btn_okay, mNoteTextDialogListener).setNegativeButton(R.string.btn_cancel, null).setView(view);
dialog = builder.create();
return dialog;
case DIALOG_NAME:
builder = new AlertDialog.Builder(this);
factory = LayoutInflater.from(this);
view = factory.inflate(R.layout.notenamedialog, null);
mNoteNameView = (EditText) view.findViewById(R.id.notename);
builder.setTitle(R.string.dialog_notename_title).setMessage(R.string.dialog_notename_message).setIcon(android.R.drawable.ic_dialog_map)
.setPositiveButton(R.string.btn_okay, mNoteNameDialogListener).setNegativeButton(R.string.btn_cancel, null).setView(view);
dialog = builder.create();
return dialog;
default:
return super.onCreateDialog(id);
}
}
/*
* (non-Javadoc)
* @see android.app.Activity#onPrepareDialog(int, android.app.Dialog)
*/
@Override
protected void onPrepareDialog(int id, Dialog dialog)
{
switch (id)
{
case DIALOG_INSERTNOTE:
boolean prepared = mLoggerServiceManager.isMediaPrepared() && mLoggerServiceManager.getLoggingState() == Constants.LOGGING;
name = (Button) dialog.findViewById(R.id.noteinsert_name);
text = (Button) dialog.findViewById(R.id.noteinsert_text);
voice = (Button) dialog.findViewById(R.id.noteinsert_voice);
picture = (Button) dialog.findViewById(R.id.noteinsert_picture);
video = (Button) dialog.findViewById(R.id.noteinsert_video);
name.setEnabled(prepared);
text.setEnabled(prepared);
voice.setEnabled(prepared);
picture.setEnabled(prepared);
video.setEnabled(prepared);
break;
default:
break;
}
super.onPrepareDialog(id, dialog);
}
/***
* Collecting additional data
*/
private void addPicture()
{
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Constants.getSdCardTmpFile(this));
// Log.d( TAG, "Picture requested at: " + file );
i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
i.putExtra(android.provider.MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(i, MENU_PICTURE);
}
/***
* Collecting additional data
*/
private void addVideo()
{
Intent i = new Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
File file = new File(Constants.getSdCardTmpFile(this));
i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
i.putExtra(android.provider.MediaStore.EXTRA_VIDEO_QUALITY, 1);
try
{
startActivityForResult(i, MENU_VIDEO);
}
catch (ActivityNotFoundException e)
{
Log.e(TAG, "Unable to start Activity to record video", e);
}
}
private void addVoice()
{
Intent intent = new Intent(android.provider.MediaStore.Audio.Media.RECORD_SOUND_ACTION);
try
{
startActivityForResult(intent, MENU_VOICE);
}
catch (ActivityNotFoundException e)
{
Log.e(TAG, "Unable to start Activity to record audio", e);
}
}
private static boolean copyFile(File fileIn, File fileOut)
{
boolean succes = false;
FileInputStream in = null;
FileOutputStream out = null;
try
{
in = new FileInputStream(fileIn);
out = new FileOutputStream(fileOut);
byte[] buf = new byte[8192];
int i = 0;
while ((i = in.read(buf)) != -1)
{
out.write(buf, 0, i);
}
succes = true;
}
catch (IOException e)
{
Log.e(TAG, "File copy failed", e);
}
finally
{
if (in != null)
{
try
{
in.close();
}
catch (IOException e)
{
Log.w(TAG, "File close after copy failed", e);
}
}
if (in != null)
{
try
{
out.close();
}
catch (IOException e)
{
Log.w(TAG, "File close after copy failed", e);
}
}
}
return succes;
}
}
| 11chauhanpeeyush11-peeyush | OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/InsertNote.java | Java | gpl3 | 18,617 |
/*------------------------------------------------------------------------------
** Ident: Sogeti Smart Mobile Solutions
** Author: rene
** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.actions;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import nl.sogeti.android.gpstracker.R;
import nl.sogeti.android.gpstracker.actions.tasks.GpxCreator;
import nl.sogeti.android.gpstracker.actions.tasks.GpxSharing;
import nl.sogeti.android.gpstracker.actions.tasks.JogmapSharing;
import nl.sogeti.android.gpstracker.actions.tasks.KmzCreator;
import nl.sogeti.android.gpstracker.actions.tasks.KmzSharing;
import nl.sogeti.android.gpstracker.actions.tasks.OsmSharing;
import nl.sogeti.android.gpstracker.actions.utils.ProgressListener;
import nl.sogeti.android.gpstracker.actions.utils.StatisticsCalulator;
import nl.sogeti.android.gpstracker.actions.utils.StatisticsDelegate;
import nl.sogeti.android.gpstracker.breadcrumbs.BreadcrumbsService;
import nl.sogeti.android.gpstracker.breadcrumbs.BreadcrumbsService.LocalBinder;
import nl.sogeti.android.gpstracker.db.GPStracking.Tracks;
import nl.sogeti.android.gpstracker.util.Constants;
import nl.sogeti.android.gpstracker.util.UnitsI18n;
import nl.sogeti.android.gpstracker.viewer.map.LoggerMap;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.Spinner;
import android.widget.Toast;
public class ShareTrack extends Activity implements StatisticsDelegate
{
private static final String TAG = "OGT.ShareTrack";
private static final int EXPORT_TYPE_KMZ = 0;
private static final int EXPORT_TYPE_GPX = 1;
private static final int EXPORT_TYPE_TEXTLINE = 2;
private static final int EXPORT_TARGET_SAVE = 0;
private static final int EXPORT_TARGET_SEND = 1;
private static final int EXPORT_TARGET_JOGRUN = 2;
private static final int EXPORT_TARGET_OSM = 3;
private static final int EXPORT_TARGET_BREADCRUMBS = 4;
private static final int EXPORT_TARGET_TWITTER = 0;
private static final int EXPORT_TARGET_SMS = 1;
private static final int EXPORT_TARGET_TEXT = 2;
private static final int PROGRESS_STEPS = 10;
private static final int DIALOG_ERROR = Menu.FIRST + 28;
private static final int DIALOG_CONNECTBREADCRUMBS = Menu.FIRST + 29;
private static final int DESCRIBE = 312;
private static File sTempBitmap;
private RemoteViews mContentView;
private int barProgress = 0;
private Notification mNotification;
private NotificationManager mNotificationManager;
private EditText mFileNameView;
private EditText mTweetView;
private Spinner mShareTypeSpinner;
private Spinner mShareTargetSpinner;
private Uri mTrackUri;
private BreadcrumbsService mService;
boolean mBound = false;
private String mErrorDialogMessage;
private Throwable mErrorDialogException;
private ImageView mImageView;
private ImageButton mCloseImageView;
private Uri mImageUri;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.sharedialog);
Intent service = new Intent(this, BreadcrumbsService.class);
startService(service);
mTrackUri = getIntent().getData();
mFileNameView = (EditText) findViewById(R.id.fileNameField);
mTweetView = (EditText) findViewById(R.id.tweetField);
mImageView = (ImageView) findViewById(R.id.imageView);
mCloseImageView = (ImageButton) findViewById(R.id.closeImageView);
mShareTypeSpinner = (Spinner) findViewById(R.id.shareTypeSpinner);
ArrayAdapter<CharSequence> shareTypeAdapter = ArrayAdapter.createFromResource(this, R.array.sharetype_choices, android.R.layout.simple_spinner_item);
shareTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mShareTypeSpinner.setAdapter(shareTypeAdapter);
mShareTargetSpinner = (Spinner) findViewById(R.id.shareTargetSpinner);
mShareTargetSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView< ? > arg0, View arg1, int position, long arg3)
{
if (mShareTypeSpinner.getSelectedItemPosition() == EXPORT_TYPE_GPX && position == EXPORT_TARGET_BREADCRUMBS)
{
boolean authorized = mService.isAuthorized();
if (!authorized)
{
showDialog(DIALOG_CONNECTBREADCRUMBS);
}
}
else if (mShareTypeSpinner.getSelectedItemPosition() == EXPORT_TYPE_TEXTLINE && position != EXPORT_TARGET_SMS)
{
readScreenBitmap();
}
else
{
removeScreenBitmap();
}
}
@Override
public void onNothingSelected(AdapterView< ? > arg0)
{ /* NOOP */
}
});
mShareTypeSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView< ? > arg0, View arg1, int position, long arg3)
{
adjustTargetToType(position);
}
@Override
public void onNothingSelected(AdapterView< ? > arg0)
{ /* NOOP */
}
});
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int lastType = prefs.getInt(Constants.EXPORT_TYPE, EXPORT_TYPE_KMZ);
mShareTypeSpinner.setSelection(lastType);
adjustTargetToType(lastType);
mFileNameView.setText(queryForTrackName(getContentResolver(), mTrackUri));
Button okay = (Button) findViewById(R.id.okayshare_button);
okay.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
v.setEnabled(false);
share();
}
});
Button cancel = (Button) findViewById(R.id.cancelshare_button);
cancel.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
v.setEnabled(false);
ShareTrack.this.finish();
}
});
}
@Override
protected void onStart()
{
super.onStart();
Intent intent = new Intent(this, BreadcrumbsService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onResume()
{
super.onResume();
// Upgrade from stored OSM username/password to OAuth authorization
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (prefs.contains(Constants.OSM_USERNAME) || prefs.contains(Constants.OSM_PASSWORD))
{
Editor editor = prefs.edit();
editor.remove(Constants.OSM_USERNAME);
editor.remove(Constants.OSM_PASSWORD);
editor.commit();
}
findViewById(R.id.okayshare_button).setEnabled(true);
findViewById(R.id.cancelshare_button).setEnabled(true);
}
@Override
protected void onStop()
{
if (mBound)
{
unbindService(mConnection);
mBound = false;
mService = null;
}
super.onStop();
}
@Override
protected void onDestroy()
{
if (isFinishing())
{
Intent service = new Intent(this, BreadcrumbsService.class);
stopService(service);
}
super.onDestroy();
}
/**
* @see android.app.Activity#onCreateDialog(int)
*/
@Override
protected Dialog onCreateDialog(int id)
{
Dialog dialog = null;
Builder builder = null;
switch (id)
{
case DIALOG_ERROR:
builder = new AlertDialog.Builder(this);
String exceptionMessage = mErrorDialogException == null ? "" : " (" + mErrorDialogException.getMessage() + ") ";
builder.setIcon(android.R.drawable.ic_dialog_alert).setTitle(android.R.string.dialog_alert_title).setMessage(mErrorDialogMessage + exceptionMessage)
.setNeutralButton(android.R.string.cancel, null);
dialog = builder.create();
return dialog;
case DIALOG_CONNECTBREADCRUMBS:
builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.dialog_breadcrumbsconnect).setMessage(R.string.dialog_breadcrumbsconnect_message).setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.btn_okay, mBreadcrumbsDialogListener).setNegativeButton(R.string.btn_cancel, null);
dialog = builder.create();
return dialog;
default:
return super.onCreateDialog(id);
}
}
/**
* @see android.app.Activity#onPrepareDialog(int, android.app.Dialog)
*/
@Override
protected void onPrepareDialog(int id, Dialog dialog)
{
super.onPrepareDialog(id, dialog);
AlertDialog alert;
switch (id)
{
case DIALOG_ERROR:
alert = (AlertDialog) dialog;
String exceptionMessage = mErrorDialogException == null ? "" : " (" + mErrorDialogException.getMessage() + ") ";
alert.setMessage(mErrorDialogMessage + exceptionMessage);
break;
}
}
private void setGpxExportTargets()
{
ArrayAdapter<CharSequence> shareTargetAdapter = ArrayAdapter.createFromResource(this, R.array.sharegpxtarget_choices, android.R.layout.simple_spinner_item);
shareTargetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mShareTargetSpinner.setAdapter(shareTargetAdapter);
int lastTarget = PreferenceManager.getDefaultSharedPreferences(this).getInt(Constants.EXPORT_GPXTARGET, EXPORT_TARGET_SEND);
mShareTargetSpinner.setSelection(lastTarget);
removeScreenBitmap();
}
private void setKmzExportTargets()
{
ArrayAdapter<CharSequence> shareTargetAdapter = ArrayAdapter.createFromResource(this, R.array.sharekmztarget_choices, android.R.layout.simple_spinner_item);
shareTargetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mShareTargetSpinner.setAdapter(shareTargetAdapter);
int lastTarget = PreferenceManager.getDefaultSharedPreferences(this).getInt(Constants.EXPORT_KMZTARGET, EXPORT_TARGET_SEND);
mShareTargetSpinner.setSelection(lastTarget);
removeScreenBitmap();
}
private void setTextLineExportTargets()
{
ArrayAdapter<CharSequence> shareTargetAdapter = ArrayAdapter.createFromResource(this, R.array.sharetexttarget_choices, android.R.layout.simple_spinner_item);
shareTargetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mShareTargetSpinner.setAdapter(shareTargetAdapter);
int lastTarget = PreferenceManager.getDefaultSharedPreferences(this).getInt(Constants.EXPORT_TXTTARGET, EXPORT_TARGET_TWITTER);
mShareTargetSpinner.setSelection(lastTarget);
}
private void share()
{
String chosenFileName = mFileNameView.getText().toString();
String textLine = mTweetView.getText().toString();
int type = (int) mShareTypeSpinner.getSelectedItemId();
int target = (int) mShareTargetSpinner.getSelectedItemId();
Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putInt(Constants.EXPORT_TYPE, type);
switch (type)
{
case EXPORT_TYPE_KMZ:
editor.putInt(Constants.EXPORT_KMZTARGET, target);
editor.commit();
exportKmz(chosenFileName, target);
break;
case EXPORT_TYPE_GPX:
editor.putInt(Constants.EXPORT_GPXTARGET, target);
editor.commit();
exportGpx(chosenFileName, target);
break;
case EXPORT_TYPE_TEXTLINE:
editor.putInt(Constants.EXPORT_TXTTARGET, target);
editor.commit();
exportTextLine(textLine, target);
break;
default:
Log.e(TAG, "Failed to determine sharing type" + type);
break;
}
}
protected void exportKmz(String chosenFileName, int target)
{
switch (target)
{
case EXPORT_TARGET_SEND:
new KmzSharing(this, mTrackUri, chosenFileName, new ShareProgressListener(chosenFileName)).execute();
break;
case EXPORT_TARGET_SAVE:
new KmzCreator(this, mTrackUri, chosenFileName, new ShareProgressListener(chosenFileName)).execute();
break;
default:
Log.e(TAG, "Unable to determine target for sharing KMZ " + target);
break;
}
ShareTrack.this.finish();
}
protected void exportGpx(String chosenFileName, int target)
{
switch (target)
{
case EXPORT_TARGET_SAVE:
new GpxCreator(this, mTrackUri, chosenFileName, true, new ShareProgressListener(chosenFileName)).execute();
ShareTrack.this.finish();
break;
case EXPORT_TARGET_SEND:
new GpxSharing(this, mTrackUri, chosenFileName, true, new ShareProgressListener(chosenFileName)).execute();
ShareTrack.this.finish();
break;
case EXPORT_TARGET_JOGRUN:
new JogmapSharing(this, mTrackUri, chosenFileName, false, new ShareProgressListener(chosenFileName)).execute();
ShareTrack.this.finish();
break;
case EXPORT_TARGET_OSM:
new OsmSharing(this, mTrackUri, false, new ShareProgressListener(OsmSharing.OSM_FILENAME)).execute();
ShareTrack.this.finish();
break;
case EXPORT_TARGET_BREADCRUMBS:
sendToBreadcrumbs(mTrackUri, chosenFileName);
break;
default:
Log.e(TAG, "Unable to determine target for sharing GPX " + target);
break;
}
}
protected void exportTextLine(String message, int target)
{
String subject = "Open GPS Tracker";
switch (target)
{
case EXPORT_TARGET_TWITTER:
sendTweet(message);
break;
case EXPORT_TARGET_SMS:
sendSMS(message);
ShareTrack.this.finish();
break;
case EXPORT_TARGET_TEXT:
sentGenericText(subject, message);
ShareTrack.this.finish();
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode != RESULT_CANCELED)
{
String name;
switch (requestCode)
{
case DESCRIBE:
Uri trackUri = data.getData();
if (data.getExtras() != null && data.getExtras().containsKey(Constants.NAME))
{
name = data.getExtras().getString(Constants.NAME);
}
else
{
name = "shareToGobreadcrumbs";
}
mService.startUploadTask(this, new ShareProgressListener(name), trackUri, name);
finish();
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
}
private void sendTweet(String tweet)
{
final Intent intent = findTwitterClient();
intent.putExtra(Intent.EXTRA_TEXT, tweet);
if (mImageUri != null)
{
intent.putExtra(Intent.EXTRA_STREAM, mImageUri);
}
startActivity(intent);
ShareTrack.this.finish();
}
private void sendSMS(String msg)
{
final Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("vnd.android-dir/mms-sms");
intent.putExtra("sms_body", msg);
startActivity(intent);
}
private void sentGenericText(String subject, String msg)
{
final Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, msg);
if (mImageUri != null)
{
intent.putExtra(Intent.EXTRA_STREAM, mImageUri);
}
startActivity(intent);
}
private void sendToBreadcrumbs(Uri mTrackUri, String chosenFileName)
{
// Start a description of the track
Intent namingIntent = new Intent(this, DescribeTrack.class);
namingIntent.setData(mTrackUri);
namingIntent.putExtra(Constants.NAME, chosenFileName);
startActivityForResult(namingIntent, DESCRIBE);
}
private Intent findTwitterClient()
{
final String[] twitterApps = {
// package // name
"com.twitter.android", // official
"com.twidroid", // twidroyd
"com.handmark.tweetcaster", // Tweecaster
"com.thedeck.android" // TweetDeck
};
Intent tweetIntent = new Intent(Intent.ACTION_SEND);
tweetIntent.setType("text/plain");
final PackageManager packageManager = getPackageManager();
List<ResolveInfo> list = packageManager.queryIntentActivities(tweetIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (int i = 0; i < twitterApps.length; i++)
{
for (ResolveInfo resolveInfo : list)
{
String p = resolveInfo.activityInfo.packageName;
if (p != null && p.startsWith(twitterApps[i]))
{
tweetIntent.setPackage(p);
}
}
}
return tweetIntent;
}
private void createTweetText()
{
StatisticsCalulator calculator = new StatisticsCalulator(this, new UnitsI18n(this), this);
findViewById(R.id.tweet_progress).setVisibility(View.VISIBLE);
calculator.execute(mTrackUri);
}
@Override
public void finishedCalculations(StatisticsCalulator calculated)
{
String name = queryForTrackName(getContentResolver(), mTrackUri);
String distString = calculated.getDistanceText();
String avgSpeed = calculated.getAvgSpeedText();
String duration = calculated.getDurationText();
String tweetText = String.format(getString(R.string.tweettext, name, distString, avgSpeed, duration));
if (mTweetView.getText().toString().equals(""))
{
mTweetView.setText(tweetText);
}
findViewById(R.id.tweet_progress).setVisibility(View.GONE);
}
private void adjustTargetToType(int position)
{
switch (position)
{
case EXPORT_TYPE_KMZ:
setKmzExportTargets();
mFileNameView.setVisibility(View.VISIBLE);
mTweetView.setVisibility(View.GONE);
break;
case EXPORT_TYPE_GPX:
setGpxExportTargets();
mFileNameView.setVisibility(View.VISIBLE);
mTweetView.setVisibility(View.GONE);
break;
case EXPORT_TYPE_TEXTLINE:
setTextLineExportTargets();
mFileNameView.setVisibility(View.GONE);
mTweetView.setVisibility(View.VISIBLE);
createTweetText();
break;
default:
break;
}
}
public static void sendFile(Context context, Uri fileUri, String fileContentType, String body)
{
Intent sendActionIntent = new Intent(Intent.ACTION_SEND);
sendActionIntent.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.email_subject));
sendActionIntent.putExtra(Intent.EXTRA_TEXT, body);
sendActionIntent.putExtra(Intent.EXTRA_STREAM, fileUri);
sendActionIntent.setType(fileContentType);
context.startActivity(Intent.createChooser(sendActionIntent, context.getString(R.string.sender_chooser)));
}
public static String queryForTrackName(ContentResolver resolver, Uri trackUri)
{
Cursor trackCursor = null;
String name = null;
try
{
trackCursor = resolver.query(trackUri, new String[] { Tracks.NAME }, null, null, null);
if (trackCursor.moveToFirst())
{
name = trackCursor.getString(0);
}
}
finally
{
if (trackCursor != null)
{
trackCursor.close();
}
}
return name;
}
public static Uri storeScreenBitmap(Bitmap bm)
{
Uri fileUri = null;
FileOutputStream stream = null;
try
{
clearScreenBitmap();
sTempBitmap = File.createTempFile("shareimage", ".png");
fileUri = Uri.fromFile(sTempBitmap);
stream = new FileOutputStream(sTempBitmap);
bm.compress(CompressFormat.PNG, 100, stream);
}
catch (IOException e)
{
Log.e(TAG, "Bitmap extra storing failed", e);
}
finally
{
try
{
if (stream != null)
{
stream.close();
}
}
catch (IOException e)
{
Log.e(TAG, "Bitmap extra close failed", e);
}
}
return fileUri;
}
public static void clearScreenBitmap()
{
if (sTempBitmap != null && sTempBitmap.exists())
{
sTempBitmap.delete();
sTempBitmap = null;
}
}
private void readScreenBitmap()
{
mImageView.setVisibility(View.GONE);
mCloseImageView.setVisibility(View.GONE);
if (getIntent().getExtras() != null && getIntent().hasExtra(Intent.EXTRA_STREAM))
{
mImageUri = getIntent().getExtras().getParcelable(Intent.EXTRA_STREAM);
if (mImageUri != null)
{
InputStream is = null;
try
{
is = getContentResolver().openInputStream(mImageUri);
mImageView.setImageBitmap(BitmapFactory.decodeStream(is));
mImageView.setVisibility(View.VISIBLE);
mCloseImageView.setVisibility(View.VISIBLE);
mCloseImageView.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
removeScreenBitmap();
}
});
}
catch (FileNotFoundException e)
{
Log.e(TAG, "Failed reading image from file", e);
}
finally
{
if (is != null)
{
try
{
is.close();
}
catch (IOException e)
{
Log.e(TAG, "Failed close image from file", e);
}
}
}
}
}
}
private void removeScreenBitmap()
{
mImageView.setVisibility(View.GONE);
mCloseImageView.setVisibility(View.GONE);
mImageUri = null;
}
private ServiceConnection mConnection = new ServiceConnection()
{
@Override
public void onServiceConnected(ComponentName className, IBinder service)
{
// We've bound to LocalService, cast the IBinder and get LocalService instance
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0)
{
mBound = false;
mService = null;
}
};
private OnClickListener mBreadcrumbsDialogListener = new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
mService.collectBreadcrumbsOauthToken();
}
};
public class ShareProgressListener implements ProgressListener
{
private String mFileName;
private int mProgress;
public ShareProgressListener(String sharename)
{
mFileName = sharename;
}
public void startNotification()
{
String ns = Context.NOTIFICATION_SERVICE;
mNotificationManager = (NotificationManager) ShareTrack.this.getSystemService(ns);
int icon = android.R.drawable.ic_menu_save;
CharSequence tickerText = getString(R.string.ticker_saving) + "\"" + mFileName + "\"";
mNotification = new Notification();
PendingIntent contentIntent = PendingIntent.getActivity(ShareTrack.this, 0, new Intent(ShareTrack.this, LoggerMap.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
PendingIntent.FLAG_UPDATE_CURRENT);
mNotification.contentIntent = contentIntent;
mNotification.tickerText = tickerText;
mNotification.icon = icon;
mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
mContentView = new RemoteViews(getPackageName(), R.layout.savenotificationprogress);
mContentView.setImageViewResource(R.id.icon, icon);
mContentView.setTextViewText(R.id.progresstext, tickerText);
mNotification.contentView = mContentView;
}
private void updateNotification()
{
// Log.d( "TAG", "Progress " + progress + " of " + goal );
if (mProgress > 0 && mProgress < Window.PROGRESS_END)
{
if ((mProgress * PROGRESS_STEPS) / Window.PROGRESS_END != barProgress)
{
barProgress = (mProgress * PROGRESS_STEPS) / Window.PROGRESS_END;
mContentView.setProgressBar(R.id.progress, Window.PROGRESS_END, mProgress, false);
mNotificationManager.notify(R.layout.savenotificationprogress, mNotification);
}
}
else if (mProgress == 0)
{
mContentView.setProgressBar(R.id.progress, Window.PROGRESS_END, mProgress, true);
mNotificationManager.notify(R.layout.savenotificationprogress, mNotification);
}
else if (mProgress >= Window.PROGRESS_END)
{
mContentView.setProgressBar(R.id.progress, Window.PROGRESS_END, mProgress, false);
mNotificationManager.notify(R.layout.savenotificationprogress, mNotification);
}
}
public void endNotification(Uri file)
{
mNotificationManager.cancel(R.layout.savenotificationprogress);
}
@Override
public void setIndeterminate(boolean indeterminate)
{
Log.w(TAG, "Unsupported indeterminate progress display");
}
@Override
public void started()
{
startNotification();
}
@Override
public void setProgress(int value)
{
mProgress = value;
updateNotification();
}
@Override
public void finished(Uri result)
{
endNotification(result);
}
@Override
public void showError(String task, String errorDialogMessage, Exception errorDialogException)
{
endNotification(null);
mErrorDialogMessage = errorDialogMessage;
mErrorDialogException = errorDialogException;
if (!isFinishing())
{
showDialog(DIALOG_ERROR);
}
else
{
Toast toast = Toast.makeText(ShareTrack.this, errorDialogMessage, Toast.LENGTH_LONG);
toast.show();
}
}
}
}
| 11chauhanpeeyush11-peeyush | OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/ShareTrack.java | Java | gpl3 | 30,165 |
/*------------------------------------------------------------------------------
** Ident: Sogeti Smart Mobile Solutions
** Author: rene
** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.actions;
import java.util.List;
import nl.sogeti.android.gpstracker.R;
import nl.sogeti.android.gpstracker.breadcrumbs.BreadcrumbsService;
import nl.sogeti.android.gpstracker.breadcrumbs.BreadcrumbsService.LocalBinder;
import nl.sogeti.android.gpstracker.breadcrumbs.BreadcrumbsTracks;
import nl.sogeti.android.gpstracker.db.GPStracking.MetaData;
import nl.sogeti.android.gpstracker.util.Constants;
import nl.sogeti.android.gpstracker.util.Pair;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
/**
* Empty Activity that pops up the dialog to describe the track
*
* @version $Id: NameTrack.java 888 2011-03-14 19:44:44Z rcgroot@gmail.com $
* @author rene (c) Jul 27, 2010, Sogeti B.V.
*/
public class DescribeTrack extends Activity
{
private static final int DIALOG_TRACKDESCRIPTION = 42;
protected static final String TAG = "OGT.DescribeTrack";
private static final String ACTIVITY_ID = "ACTIVITY_ID";
private static final String BUNDLE_ID = "BUNDLE_ID";
private Spinner mActivitySpinner;
private Spinner mBundleSpinner;
private EditText mDescriptionText;
private CheckBox mPublicCheck;
private Button mOkayButton;
private boolean paused;
private Uri mTrackUri;
private ProgressBar mProgressSpinner;
private AlertDialog mDialog;
private BreadcrumbsService mService;
boolean mBound = false;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setVisible(false);
paused = false;
mTrackUri = this.getIntent().getData();
Intent service = new Intent(this, BreadcrumbsService.class);
startService(service);
}
@Override
protected void onStart()
{
super.onStart();
Intent intent = new Intent(this, BreadcrumbsService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
/*
* (non-Javadoc)
* @see com.google.android.maps.MapActivity#onPause()
*/
@Override
protected void onResume()
{
super.onResume();
if (mTrackUri != null)
{
showDialog(DIALOG_TRACKDESCRIPTION);
}
else
{
Log.e(TAG, "Describing track without a track URI supplied.");
finish();
}
}
@Override
protected void onPause()
{
super.onPause();
paused = true;
}
@Override
protected void onStop()
{
if (mBound)
{
unbindService(mConnection);
mBound = false;
mService = null;
}
super.onStop();
}
@Override
protected void onDestroy()
{
if (isFinishing())
{
Intent service = new Intent(this, BreadcrumbsService.class);
stopService(service);
}
super.onDestroy();
}
@Override
protected Dialog onCreateDialog(int id)
{
LayoutInflater factory = null;
View view = null;
Builder builder = null;
switch (id)
{
case DIALOG_TRACKDESCRIPTION:
builder = new AlertDialog.Builder(this);
factory = LayoutInflater.from(this);
view = factory.inflate(R.layout.describedialog, null);
mActivitySpinner = (Spinner) view.findViewById(R.id.activity);
mBundleSpinner = (Spinner) view.findViewById(R.id.bundle);
mDescriptionText = (EditText) view.findViewById(R.id.description);
mPublicCheck = (CheckBox) view.findViewById(R.id.public_checkbox);
mProgressSpinner = (ProgressBar) view.findViewById(R.id.progressSpinner);
builder.setTitle(R.string.dialog_description_title).setMessage(R.string.dialog_description_message).setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.btn_okay, mTrackDescriptionDialogListener).setNegativeButton(R.string.btn_cancel, mTrackDescriptionDialogListener).setView(view);
mDialog = builder.create();
setUiEnabled();
mDialog.setOnDismissListener(new OnDismissListener()
{
@Override
public void onDismiss(DialogInterface dialog)
{
if (!paused)
{
finish();
}
}
});
return mDialog;
default:
return super.onCreateDialog(id);
}
}
@Override
protected void onPrepareDialog(int id, Dialog dialog)
{
switch (id)
{
case DIALOG_TRACKDESCRIPTION:
setUiEnabled();
connectBreadcrumbs();
break;
default:
super.onPrepareDialog(id, dialog);
break;
}
}
private void connectBreadcrumbs()
{
if (mService != null && !mService.isAuthorized())
{
mService.collectBreadcrumbsOauthToken();
}
}
private void saveBreadcrumbsPreference(int activityPosition, int bundlePosition)
{
Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putInt(ACTIVITY_ID, activityPosition);
editor.putInt(BUNDLE_ID, bundlePosition);
editor.commit();
}
private void loadBreadcrumbsPreference()
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int activityPos = prefs.getInt(ACTIVITY_ID, 0);
activityPos = activityPos < mActivitySpinner.getCount() ? activityPos : 0;
mActivitySpinner.setSelection(activityPos);
int bundlePos = prefs.getInt(BUNDLE_ID, 0);
bundlePos = bundlePos < mBundleSpinner.getCount() ? bundlePos : 0;
mBundleSpinner.setSelection(bundlePos);
}
private ContentValues buildContentValues(String key, String value)
{
ContentValues contentValues = new ContentValues();
contentValues.put(MetaData.KEY, key);
contentValues.put(MetaData.VALUE, value);
return contentValues;
}
private void setUiEnabled()
{
boolean enabled = mService != null && mService.isAuthorized();
if (mProgressSpinner != null)
{
if (enabled)
{
mProgressSpinner.setVisibility(View.GONE);
}
else
{
mProgressSpinner.setVisibility(View.VISIBLE);
}
}
if (mDialog != null)
{
mOkayButton = mDialog.getButton(AlertDialog.BUTTON_POSITIVE);
}
for (View view : new View[] { mActivitySpinner, mBundleSpinner, mDescriptionText, mPublicCheck, mOkayButton })
{
if (view != null)
{
view.setEnabled(enabled);
}
}
if (enabled)
{
mActivitySpinner.setAdapter(getActivityAdapter());
mBundleSpinner.setAdapter(getBundleAdapter());
loadBreadcrumbsPreference();
}
}
public SpinnerAdapter getActivityAdapter()
{
List<Pair<Integer, Integer>> activities = mService.getActivityList();
ArrayAdapter<Pair<Integer, Integer>> adapter = new ArrayAdapter<Pair<Integer, Integer>>(this, android.R.layout.simple_spinner_item, activities);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
return adapter;
}
public SpinnerAdapter getBundleAdapter()
{
List<Pair<Integer, Integer>> bundles = mService.getBundleList();
ArrayAdapter<Pair<Integer, Integer>> adapter = new ArrayAdapter<Pair<Integer, Integer>>(this, android.R.layout.simple_spinner_item, bundles);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
return adapter;
}
private ServiceConnection mConnection = new ServiceConnection()
{
@Override
public void onServiceConnected(ComponentName className, IBinder service)
{
// We've bound to LocalService, cast the IBinder and get LocalService instance
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
setUiEnabled();
}
@Override
public void onServiceDisconnected(ComponentName arg0)
{
mService = null;
mBound = false;
}
};
private final DialogInterface.OnClickListener mTrackDescriptionDialogListener = new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
switch (which)
{
case DialogInterface.BUTTON_POSITIVE:
Uri metadataUri = Uri.withAppendedPath(mTrackUri, "metadata");
Integer activityId = ((Pair<Integer, Integer>)mActivitySpinner.getSelectedItem()).second;
Integer bundleId = ((Pair<Integer, Integer>)mBundleSpinner.getSelectedItem()).second;
saveBreadcrumbsPreference(mActivitySpinner.getSelectedItemPosition(), mBundleSpinner.getSelectedItemPosition());
String description = mDescriptionText.getText().toString();
String isPublic = Boolean.toString(mPublicCheck.isChecked());
ContentValues[] metaValues = { buildContentValues(BreadcrumbsTracks.ACTIVITY_ID, activityId.toString()), buildContentValues(BreadcrumbsTracks.BUNDLE_ID, bundleId.toString()),
buildContentValues(BreadcrumbsTracks.DESCRIPTION, description), buildContentValues(BreadcrumbsTracks.ISPUBLIC, isPublic), };
getContentResolver().bulkInsert(metadataUri, metaValues);
Intent data = new Intent();
data.setData(mTrackUri);
if (getIntent().getExtras() != null && getIntent().getExtras().containsKey(Constants.NAME))
{
data.putExtra(Constants.NAME, getIntent().getExtras().getString(Constants.NAME));
}
setResult(RESULT_OK, data);
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
default:
Log.e(TAG, "Unknown option ending dialog:" + which);
break;
}
finish();
}
};
}
| 11chauhanpeeyush11-peeyush | OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/DescribeTrack.java | Java | gpl3 | 12,639 |
/*------------------------------------------------------------------------------
** Ident: Sogeti Smart Mobile Solutions
** Author: rene
** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.actions;
import nl.sogeti.android.gpstracker.R;
import nl.sogeti.android.gpstracker.actions.utils.GraphCanvas;
import nl.sogeti.android.gpstracker.actions.utils.StatisticsCalulator;
import nl.sogeti.android.gpstracker.actions.utils.StatisticsDelegate;
import nl.sogeti.android.gpstracker.db.GPStracking.Tracks;
import nl.sogeti.android.gpstracker.util.UnitsI18n;
import nl.sogeti.android.gpstracker.viewer.TrackList;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.ContentObserver;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.ContextMenu;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ViewFlipper;
/**
* Display some calulations based on a track
*
* @version $Id$
* @author rene (c) Oct 19, 2009, Sogeti B.V.
*/
public class Statistics extends Activity implements StatisticsDelegate
{
private static final int DIALOG_GRAPHTYPE = 3;
private static final int MENU_GRAPHTYPE = 11;
private static final int MENU_TRACKLIST = 12;
private static final int MENU_SHARE = 41;
private static final String TRACKURI = "TRACKURI";
private static final String TAG = "OGT.Statistics";
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
private Uri mTrackUri = null;
private boolean calculating;
private TextView overallavgSpeedView;
private TextView avgSpeedView;
private TextView distanceView;
private TextView endtimeView;
private TextView starttimeView;
private TextView maxSpeedView;
private TextView waypointsView;
private TextView mAscensionView;
private TextView mElapsedTimeView;
private UnitsI18n mUnits;
private GraphCanvas mGraphTimeSpeed;
private ViewFlipper mViewFlipper;
private Animation mSlideLeftIn;
private Animation mSlideLeftOut;
private Animation mSlideRightIn;
private Animation mSlideRightOut;
private GestureDetector mGestureDetector;
private GraphCanvas mGraphDistanceSpeed;
private GraphCanvas mGraphTimeAltitude;
private GraphCanvas mGraphDistanceAltitude;
private final ContentObserver mTrackObserver = new ContentObserver( new Handler() )
{
@Override
public void onChange( boolean selfUpdate )
{
if( !calculating )
{
Statistics.this.drawTrackingStatistics();
}
}
};
private OnClickListener mGraphControlListener = new View.OnClickListener()
{
@Override
public void onClick( View v )
{
int id = v.getId();
switch( id )
{
case R.id.graphtype_timespeed:
mViewFlipper.setDisplayedChild( 0 );
break;
case R.id.graphtype_distancespeed:
mViewFlipper.setDisplayedChild( 1 );
break;
case R.id.graphtype_timealtitude:
mViewFlipper.setDisplayedChild( 2 );
break;
case R.id.graphtype_distancealtitude:
mViewFlipper.setDisplayedChild( 3 );
break;
default:
break;
}
dismissDialog( DIALOG_GRAPHTYPE );
}
};
class MyGestureDetector extends SimpleOnGestureListener
{
@Override
public boolean onFling( MotionEvent e1, MotionEvent e2, float velocityX, float velocityY )
{
if( Math.abs( e1.getY() - e2.getY() ) > SWIPE_MAX_OFF_PATH )
return false;
// right to left swipe
if( e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs( velocityX ) > SWIPE_THRESHOLD_VELOCITY )
{
mViewFlipper.setInAnimation( mSlideLeftIn );
mViewFlipper.setOutAnimation( mSlideLeftOut );
mViewFlipper.showNext();
}
else if( e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs( velocityX ) > SWIPE_THRESHOLD_VELOCITY )
{
mViewFlipper.setInAnimation( mSlideRightIn );
mViewFlipper.setOutAnimation( mSlideRightOut );
mViewFlipper.showPrevious();
}
return false;
}
}
/**
* Called when the activity is first created.
*/
@Override
protected void onCreate( Bundle load )
{
super.onCreate( load );
mUnits = new UnitsI18n( this, new UnitsI18n.UnitsChangeListener()
{
@Override
public void onUnitsChange()
{
drawTrackingStatistics();
}
} );
setContentView( R.layout.statistics );
mViewFlipper = (ViewFlipper) findViewById( R.id.flipper );
mViewFlipper.setDrawingCacheEnabled(true);
mSlideLeftIn = AnimationUtils.loadAnimation( this, R.anim.slide_left_in );
mSlideLeftOut = AnimationUtils.loadAnimation( this, R.anim.slide_left_out );
mSlideRightIn = AnimationUtils.loadAnimation( this, R.anim.slide_right_in );
mSlideRightOut = AnimationUtils.loadAnimation( this, R.anim.slide_right_out );
mGraphTimeSpeed = (GraphCanvas) mViewFlipper.getChildAt( 0 );
mGraphDistanceSpeed = (GraphCanvas) mViewFlipper.getChildAt( 1 );
mGraphTimeAltitude = (GraphCanvas) mViewFlipper.getChildAt( 2 );
mGraphDistanceAltitude = (GraphCanvas) mViewFlipper.getChildAt( 3 );
mGraphTimeSpeed.setType( GraphCanvas.TIMESPEEDGRAPH );
mGraphDistanceSpeed.setType( GraphCanvas.DISTANCESPEEDGRAPH );
mGraphTimeAltitude.setType( GraphCanvas.TIMEALTITUDEGRAPH );
mGraphDistanceAltitude.setType( GraphCanvas.DISTANCEALTITUDEGRAPH );
mGestureDetector = new GestureDetector( new MyGestureDetector() );
maxSpeedView = (TextView) findViewById( R.id.stat_maximumspeed );
mAscensionView = (TextView) findViewById( R.id.stat_ascension );
mElapsedTimeView = (TextView) findViewById( R.id.stat_elapsedtime );
overallavgSpeedView = (TextView) findViewById( R.id.stat_overallaveragespeed );
avgSpeedView = (TextView) findViewById( R.id.stat_averagespeed );
distanceView = (TextView) findViewById( R.id.stat_distance );
starttimeView = (TextView) findViewById( R.id.stat_starttime );
endtimeView = (TextView) findViewById( R.id.stat_endtime );
waypointsView = (TextView) findViewById( R.id.stat_waypoints );
if( load != null && load.containsKey( TRACKURI ) )
{
mTrackUri = Uri.withAppendedPath( Tracks.CONTENT_URI, load.getString( TRACKURI ) );
}
else
{
mTrackUri = this.getIntent().getData();
}
}
@Override
protected void onRestoreInstanceState( Bundle load )
{
if( load != null )
{
super.onRestoreInstanceState( load );
}
if( load != null && load.containsKey( TRACKURI ) )
{
mTrackUri = Uri.withAppendedPath( Tracks.CONTENT_URI, load.getString( TRACKURI ) );
}
if( load != null && load.containsKey( "FLIP" ) )
{
mViewFlipper.setDisplayedChild( load.getInt( "FLIP" ) );
}
}
@Override
protected void onSaveInstanceState( Bundle save )
{
super.onSaveInstanceState( save );
save.putString( TRACKURI, mTrackUri.getLastPathSegment() );
save.putInt( "FLIP" , mViewFlipper.getDisplayedChild() );
}
/*
* (non-Javadoc)
* @see android.app.Activity#onPause()
*/
@Override
protected void onPause()
{
super.onPause();
mViewFlipper.stopFlipping();
mGraphTimeSpeed.clearData();
mGraphDistanceSpeed.clearData();
mGraphTimeAltitude.clearData();
mGraphDistanceAltitude.clearData();
ContentResolver resolver = this.getContentResolver();
resolver.unregisterContentObserver( this.mTrackObserver );
}
/*
* (non-Javadoc)
* @see android.app.Activity#onResume()
*/
@Override
protected void onResume()
{
super.onResume();
drawTrackingStatistics();
ContentResolver resolver = this.getContentResolver();
resolver.registerContentObserver( mTrackUri, true, this.mTrackObserver );
}
@Override
public boolean onCreateOptionsMenu( Menu menu )
{
boolean result = super.onCreateOptionsMenu( menu );
menu.add( ContextMenu.NONE, MENU_GRAPHTYPE, ContextMenu.NONE, R.string.menu_graphtype ).setIcon( R.drawable.ic_menu_picture ).setAlphabeticShortcut( 't' );
menu.add( ContextMenu.NONE, MENU_TRACKLIST, ContextMenu.NONE, R.string.menu_tracklist ).setIcon( R.drawable.ic_menu_show_list ).setAlphabeticShortcut( 'l' );
menu.add( ContextMenu.NONE, MENU_SHARE, ContextMenu.NONE, R.string.menu_shareTrack ).setIcon( R.drawable.ic_menu_share ).setAlphabeticShortcut( 's' );
return result;
}
@Override
public boolean onOptionsItemSelected( MenuItem item )
{
boolean handled = false;
Intent intent;
switch( item.getItemId() )
{
case MENU_GRAPHTYPE:
showDialog( DIALOG_GRAPHTYPE );
handled = true;
break;
case MENU_TRACKLIST:
intent = new Intent( this, TrackList.class );
intent.putExtra( Tracks._ID, mTrackUri.getLastPathSegment() );
startActivityForResult( intent, MENU_TRACKLIST );
break;
case MENU_SHARE:
intent = new Intent( Intent.ACTION_RUN );
intent.setDataAndType( mTrackUri, Tracks.CONTENT_ITEM_TYPE );
intent.addFlags( Intent.FLAG_GRANT_READ_URI_PERMISSION );
Bitmap bm = mViewFlipper.getDrawingCache();
Uri screenStreamUri = ShareTrack.storeScreenBitmap(bm);
intent.putExtra(Intent.EXTRA_STREAM, screenStreamUri);
startActivityForResult(Intent.createChooser( intent, getString( R.string.share_track ) ), MENU_SHARE);
handled = true;
break;
default:
handled = super.onOptionsItemSelected( item );
}
return handled;
}
@Override
public boolean onTouchEvent( MotionEvent event )
{
if( mGestureDetector.onTouchEvent( event ) )
return true;
else
return false;
}
/*
* (non-Javadoc)
* @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
*/
@Override
protected void onActivityResult( int requestCode, int resultCode, Intent intent )
{
super.onActivityResult( requestCode, resultCode, intent );
switch( requestCode )
{
case MENU_TRACKLIST:
if( resultCode == RESULT_OK )
{
mTrackUri = intent.getData();
drawTrackingStatistics();
}
break;
case MENU_SHARE:
ShareTrack.clearScreenBitmap();
break;
default:
Log.w( TAG, "Unknown activity result request code" );
}
}
/*
* (non-Javadoc)
* @see android.app.Activity#onCreateDialog(int)
*/
@Override
protected Dialog onCreateDialog( int id )
{
Dialog dialog = null;
LayoutInflater factory = null;
View view = null;
Builder builder = null;
switch( id )
{
case DIALOG_GRAPHTYPE:
builder = new AlertDialog.Builder( this );
factory = LayoutInflater.from( this );
view = factory.inflate( R.layout.graphtype, null );
builder.setTitle( R.string.dialog_graphtype_title ).setIcon( android.R.drawable.ic_dialog_alert ).setNegativeButton( R.string.btn_cancel, null ).setView( view );
dialog = builder.create();
return dialog;
default:
return super.onCreateDialog( id );
}
}
/*
* (non-Javadoc)
* @see android.app.Activity#onPrepareDialog(int, android.app.Dialog)
*/
@Override
protected void onPrepareDialog( int id, Dialog dialog )
{
switch( id )
{
case DIALOG_GRAPHTYPE:
Button speedtime = (Button) dialog.findViewById( R.id.graphtype_timespeed );
Button speeddistance = (Button) dialog.findViewById( R.id.graphtype_distancespeed );
Button altitudetime = (Button) dialog.findViewById( R.id.graphtype_timealtitude );
Button altitudedistance = (Button) dialog.findViewById( R.id.graphtype_distancealtitude );
speedtime.setOnClickListener( mGraphControlListener );
speeddistance.setOnClickListener( mGraphControlListener );
altitudetime.setOnClickListener( mGraphControlListener );
altitudedistance.setOnClickListener( mGraphControlListener );
default:
break;
}
super.onPrepareDialog( id, dialog );
}
private void drawTrackingStatistics()
{
calculating = true;
StatisticsCalulator calculator = new StatisticsCalulator( this, mUnits, this );
calculator.execute(mTrackUri);
}
@Override
public void finishedCalculations(StatisticsCalulator calculated)
{
mGraphTimeSpeed.setData ( mTrackUri, calculated );
mGraphDistanceSpeed.setData ( mTrackUri, calculated );
mGraphTimeAltitude.setData ( mTrackUri, calculated );
mGraphDistanceAltitude.setData( mTrackUri, calculated );
mViewFlipper.postInvalidate();
maxSpeedView.setText( calculated.getMaxSpeedText() );
mElapsedTimeView.setText( calculated.getDurationText() );
mAscensionView.setText( calculated.getAscensionText() );
overallavgSpeedView.setText( calculated.getOverallavgSpeedText() );
avgSpeedView.setText( calculated.getAvgSpeedText() );
distanceView.setText( calculated.getDistanceText() );
starttimeView.setText( Long.toString( calculated.getStarttime() ) );
endtimeView.setText( Long.toString( calculated.getEndtime() ) );
String titleFormat = getString( R.string.stat_title );
setTitle( String.format( titleFormat, calculated.getTracknameText() ) );
waypointsView.setText( calculated.getWaypointsText() );
calculating = false;
}
}
| 11chauhanpeeyush11-peeyush | OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/Statistics.java | Java | gpl3 | 16,232 |
/*------------------------------------------------------------------------------
** Ident: Sogeti Smart Mobile Solutions
** Author: rene
** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.actions;
import java.util.Calendar;
import nl.sogeti.android.gpstracker.R;
import nl.sogeti.android.gpstracker.db.GPStracking.Tracks;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
/**
* Empty Activity that pops up the dialog to name the track
*
* @version $Id$
* @author rene (c) Jul 27, 2010, Sogeti B.V.
*/
public class NameTrack extends Activity
{
private static final int DIALOG_TRACKNAME = 23;
protected static final String TAG = "OGT.NameTrack";
private EditText mTrackNameView;
private boolean paused;
Uri mTrackUri;
private final DialogInterface.OnClickListener mTrackNameDialogListener = new DialogInterface.OnClickListener()
{
@Override
public void onClick( DialogInterface dialog, int which )
{
String trackName = null;
switch( which )
{
case DialogInterface.BUTTON_POSITIVE:
trackName = mTrackNameView.getText().toString();
ContentValues values = new ContentValues();
values.put( Tracks.NAME, trackName );
getContentResolver().update( mTrackUri, values, null, null );
clearNotification();
break;
case DialogInterface.BUTTON_NEUTRAL:
startDelayNotification();
break;
case DialogInterface.BUTTON_NEGATIVE:
clearNotification();
break;
default:
Log.e( TAG, "Unknown option ending dialog:"+which );
break;
}
finish();
}
};
private void clearNotification()
{
NotificationManager noticationManager = (NotificationManager) this.getSystemService( Context.NOTIFICATION_SERVICE );;
noticationManager.cancel( R.layout.namedialog );
}
private void startDelayNotification()
{
int resId = R.string.dialog_routename_title;
int icon = R.drawable.ic_maps_indicator_current_position;
CharSequence tickerText = getResources().getString( resId );
long when = System.currentTimeMillis();
Notification nameNotification = new Notification( icon, tickerText, when );
nameNotification.flags |= Notification.FLAG_AUTO_CANCEL;
CharSequence contentTitle = getResources().getString( R.string.app_name );
CharSequence contentText = getResources().getString( resId );
Intent notificationIntent = new Intent( this, NameTrack.class );
notificationIntent.setData( mTrackUri );
PendingIntent contentIntent = PendingIntent.getActivity( this, 0, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK );
nameNotification.setLatestEventInfo( this, contentTitle, contentText, contentIntent );
NotificationManager noticationManager = (NotificationManager) this.getSystemService( Context.NOTIFICATION_SERVICE );
noticationManager.notify( R.layout.namedialog, nameNotification );
}
@Override
protected void onCreate( Bundle savedInstanceState )
{
super.onCreate( savedInstanceState );
this.setVisible( false );
paused = false;
mTrackUri = this.getIntent().getData();
}
@Override
protected void onPause()
{
super.onPause();
paused = true;
}
/*
* (non-Javadoc)
* @see com.google.android.maps.MapActivity#onPause()
*/
@Override
protected void onResume()
{
super.onResume();
if( mTrackUri != null )
{
showDialog( DIALOG_TRACKNAME );
}
else
{
Log.e(TAG, "Naming track without a track URI supplied." );
finish();
}
}
@Override
protected Dialog onCreateDialog( int id )
{
Dialog dialog = null;
LayoutInflater factory = null;
View view = null;
Builder builder = null;
switch (id)
{
case DIALOG_TRACKNAME:
builder = new AlertDialog.Builder( this );
factory = LayoutInflater.from( this );
view = factory.inflate( R.layout.namedialog, null );
mTrackNameView = (EditText) view.findViewById( R.id.nameField );
builder
.setTitle( R.string.dialog_routename_title )
.setMessage( R.string.dialog_routename_message )
.setIcon( android.R.drawable.ic_dialog_alert )
.setPositiveButton( R.string.btn_okay, mTrackNameDialogListener )
.setNeutralButton( R.string.btn_skip, mTrackNameDialogListener )
.setNegativeButton( R.string.btn_cancel, mTrackNameDialogListener )
.setView( view );
dialog = builder.create();
dialog.setOnDismissListener( new OnDismissListener()
{
@Override
public void onDismiss( DialogInterface dialog )
{
if( !paused )
{
finish();
}
}
});
return dialog;
default:
return super.onCreateDialog( id );
}
}
@Override
protected void onPrepareDialog( int id, Dialog dialog )
{
switch (id)
{
case DIALOG_TRACKNAME:
String trackName;
Calendar c = Calendar.getInstance();
trackName = String.format( getString( R.string.dialog_routename_default ), c, c, c, c, c );
mTrackNameView.setText( trackName );
mTrackNameView.setSelection( 0, trackName.length() );
break;
default:
super.onPrepareDialog( id, dialog );
break;
}
}
}
| 11chauhanpeeyush11-peeyush | OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/NameTrack.java | Java | gpl3 | 7,765 |
/*------------------------------------------------------------------------------
** Ident: Sogeti Smart Mobile Solutions
** Author: rene
** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.actions.tasks;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.channels.FileChannel;
import java.util.Date;
import java.util.concurrent.CancellationException;
import java.util.concurrent.Executor;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import nl.sogeti.android.gpstracker.actions.utils.ProgressListener;
import nl.sogeti.android.gpstracker.db.GPStracking.Media;
import nl.sogeti.android.gpstracker.db.GPStracking.Tracks;
import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints;
import nl.sogeti.android.gpstracker.util.Constants;
import org.xmlpull.v1.XmlSerializer;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import android.view.Window;
/**
* Async XML creation task Execute without parameters (Void) Update posted with
* single Integer And result is a filename in a String
*
* @version $Id$
* @author rene (c) May 29, 2011, Sogeti B.V.
*/
public abstract class XmlCreator extends AsyncTask<Void, Integer, Uri>
{
private String TAG = "OGT.XmlCreator";
private String mExportDirectoryPath;
private boolean mNeedsBundling;
String mChosenName;
private ProgressListener mProgressListener;
protected Context mContext;
protected Uri mTrackUri;
String mFileName;
private String mErrorText;
private Exception mException;
private String mTask;
public ProgressAdmin mProgressAdmin;
XmlCreator(Context context, Uri trackUri, String chosenFileName, ProgressListener listener)
{
mChosenName = chosenFileName;
mContext = context;
mTrackUri = trackUri;
mProgressListener = listener;
mProgressAdmin = new ProgressAdmin();
String trackName = extractCleanTrackName();
mFileName = cleanFilename(mChosenName, trackName);
}
public void executeOn(Executor executor)
{
if (Build.VERSION.SDK_INT >= 11)
{
executeOnExecutor(executor);
}
else
{
execute();
}
}
private String extractCleanTrackName()
{
Cursor trackCursor = null;
ContentResolver resolver = mContext.getContentResolver();
String trackName = "Untitled";
try
{
trackCursor = resolver.query(mTrackUri, new String[] { Tracks.NAME }, null, null, null);
if (trackCursor.moveToLast())
{
trackName = cleanFilename(trackCursor.getString(0), trackName);
}
}
finally
{
if (trackCursor != null)
{
trackCursor.close();
}
}
return trackName;
}
/**
* Calculated the total progress sum expected from a export to file This is
* the sum of the number of waypoints and media entries times 100. The whole
* number is doubled when compression is needed.
*/
public void determineProgressGoal()
{
if (mProgressListener != null)
{
Uri allWaypointsUri = Uri.withAppendedPath(mTrackUri, "waypoints");
Uri allMediaUri = Uri.withAppendedPath(mTrackUri, "media");
Cursor cursor = null;
ContentResolver resolver = mContext.getContentResolver();
try
{
cursor = resolver.query(allWaypointsUri, new String[] { "count(" + Waypoints.TABLE + "." + Waypoints._ID + ")" }, null, null, null);
if (cursor.moveToLast())
{
mProgressAdmin.setWaypointCount(cursor.getInt(0));
}
cursor.close();
cursor = resolver.query(allMediaUri, new String[] { "count(" + Media.TABLE + "." + Media._ID + ")" }, null, null, null);
if (cursor.moveToLast())
{
mProgressAdmin.setMediaCount(cursor.getInt(0));
}
cursor.close();
cursor = resolver.query(allMediaUri, new String[] { "count(" + Tracks._ID + ")" }, Media.URI + " LIKE ? and " + Media.URI + " NOT LIKE ?",
new String[] { "file://%", "%txt" }, null);
if (cursor.moveToLast())
{
mProgressAdmin.setCompress( cursor.getInt(0) > 0 );
}
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
}
else
{
Log.w(TAG, "Exporting " + mTrackUri + " without progress!");
}
}
/**
* Removes all non-word chars (\W) from the text
*
* @param fileName
* @param defaultName
* @return a string larger then 0 with either word chars remaining from the
* input or the default provided
*/
public static String cleanFilename(String fileName, String defaultName)
{
if (fileName == null || "".equals(fileName))
{
fileName = defaultName;
}
else
{
fileName = fileName.replaceAll("\\W", "");
fileName = (fileName.length() > 0) ? fileName : defaultName;
}
return fileName;
}
/**
* Includes media into the export directory and returns the relative path of
* the media
*
* @param inputFilePath
* @return file path relative to the export dir
* @throws IOException
*/
protected String includeMediaFile(String inputFilePath) throws IOException
{
mNeedsBundling = true;
File source = new File(inputFilePath);
File target = new File(mExportDirectoryPath + "/" + source.getName());
// Log.d( TAG, String.format( "Copy %s to %s", source, target ) );
if (source.exists())
{
FileInputStream fileInputStream = new FileInputStream(source);
FileChannel inChannel = fileInputStream.getChannel();
FileOutputStream fileOutputStream = new FileOutputStream(target);
FileChannel outChannel = fileOutputStream.getChannel();
try
{
inChannel.transferTo(0, inChannel.size(), outChannel);
}
finally
{
if (inChannel != null) inChannel.close();
if (outChannel != null) outChannel.close();
if (fileInputStream != null) fileInputStream.close();
if (fileOutputStream != null) fileOutputStream.close();
}
}
else
{
Log.w( TAG, "Failed to add file to new XML export. Missing: "+inputFilePath );
}
mProgressAdmin.addMediaProgress();
return target.getName();
}
/**
* Just to start failing early
*
* @throws IOException
*/
protected void verifySdCardAvailibility() throws IOException
{
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state))
{
throw new IOException("The ExternalStorage is not mounted, unable to export files for sharing.");
}
}
/**
* Create a zip of the export directory based on the given filename
*
* @param fileName The directory to be replaced by a zipped file of the same
* name
* @param extension
* @return full path of the build zip file
* @throws IOException
*/
protected String bundlingMediaAndXml(String fileName, String extension) throws IOException
{
String zipFilePath;
if (fileName.endsWith(".zip") || fileName.endsWith(extension))
{
zipFilePath = Constants.getSdCardDirectory(mContext) + fileName;
}
else
{
zipFilePath = Constants.getSdCardDirectory(mContext) + fileName + extension;
}
String[] filenames = new File(mExportDirectoryPath).list();
byte[] buf = new byte[1024];
ZipOutputStream zos = null;
try
{
zos = new ZipOutputStream(new FileOutputStream(zipFilePath));
for (int i = 0; i < filenames.length; i++)
{
String entryFilePath = mExportDirectoryPath + "/" + filenames[i];
FileInputStream in = new FileInputStream(entryFilePath);
zos.putNextEntry(new ZipEntry(filenames[i]));
int len;
while ((len = in.read(buf)) >= 0)
{
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
mProgressAdmin.addCompressProgress();
}
}
finally
{
if (zos != null)
{
zos.close();
}
}
deleteRecursive(new File(mExportDirectoryPath));
return zipFilePath;
}
public static boolean deleteRecursive(File file)
{
if (file.isDirectory())
{
String[] children = file.list();
for (int i = 0; i < children.length; i++)
{
boolean success = deleteRecursive(new File(file, children[i]));
if (!success)
{
return false;
}
}
}
return file.delete();
}
public void setExportDirectoryPath(String exportDirectoryPath)
{
this.mExportDirectoryPath = exportDirectoryPath;
}
public String getExportDirectoryPath()
{
return mExportDirectoryPath;
}
public void quickTag(XmlSerializer serializer, String ns, String tag, String content) throws IllegalArgumentException, IllegalStateException, IOException
{
if( tag == null)
{
tag = "";
}
if( content == null)
{
content = "";
}
serializer.text("\n");
serializer.startTag(ns, tag);
serializer.text(content);
serializer.endTag(ns, tag);
}
public boolean needsBundling()
{
return mNeedsBundling;
}
public static String convertStreamToString(InputStream is) throws IOException
{
String result = "";
/*
* To convert the InputStream to String we use the Reader.read(char[]
* buffer) method. We iterate until the Reader return -1 which means
* there's no more data to read. We use the StringWriter class to produce
* the string.
*/
if (is != null)
{
Writer writer = new StringWriter();
char[] buffer = new char[8192];
try
{
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1)
{
writer.write(buffer, 0, n);
}
}
finally
{
is.close();
}
result = writer.toString();
}
return result;
}
public static InputStream convertStreamToLoggedStream(String tag, InputStream is) throws IOException
{
String result = "";
/*
* To convert the InputStream to String we use the Reader.read(char[]
* buffer) method. We iterate until the Reader return -1 which means
* there's no more data to read. We use the StringWriter class to produce
* the string.
*/
if (is != null)
{
Writer writer = new StringWriter();
char[] buffer = new char[8192];
try
{
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1)
{
writer.write(buffer, 0, n);
}
}
finally
{
is.close();
}
result = writer.toString();
}
InputStream in = new ByteArrayInputStream(result.getBytes("UTF-8"));
return in;
}
protected abstract String getContentType();
protected void handleError(String task, Exception e, String text)
{
Log.e(TAG, "Unable to save ", e);
mTask = task;
mException = e;
mErrorText = text;
cancel(false);
throw new CancellationException(text);
}
@Override
protected void onPreExecute()
{
if(mProgressListener!= null)
{
mProgressListener.started();
}
}
@Override
protected void onProgressUpdate(Integer... progress)
{
if(mProgressListener!= null)
{
mProgressListener.setProgress(mProgressAdmin.getProgress());
}
}
@Override
protected void onPostExecute(Uri resultFilename)
{
if(mProgressListener!= null)
{
mProgressListener.finished(resultFilename);
}
}
@Override
protected void onCancelled()
{
if(mProgressListener!= null)
{
mProgressListener.finished(null);
mProgressListener.showError(mTask, mErrorText, mException);
}
}
public class ProgressAdmin
{
long lastUpdate;
private boolean compressCount;
private boolean compressProgress;
private boolean uploadCount;
private boolean uploadProgress;
private int mediaCount;
private int mediaProgress;
private int waypointCount;
private int waypointProgress;
private long photoUploadCount ;
private long photoUploadProgress ;
public void addMediaProgress()
{
mediaProgress ++;
}
public void addCompressProgress()
{
compressProgress = true;
}
public void addUploadProgress()
{
uploadProgress = true;
}
public void addPhotoUploadProgress(long length)
{
photoUploadProgress += length;
}
/**
* Get the progress on scale 0 ... Window.PROGRESS_END
*
* @return Returns the progress as a int.
*/
public int getProgress()
{
int blocks = 0;
if( waypointCount > 0 ){ blocks++; }
if( mediaCount > 0 ){ blocks++; }
if( compressCount ){ blocks++; }
if( uploadCount ){ blocks++; }
if( photoUploadCount > 0 ){ blocks++; }
int progress;
if( blocks > 0 )
{
int blockSize = Window.PROGRESS_END / blocks;
progress = waypointCount > 0 ? blockSize * waypointProgress / waypointCount : 0;
progress += mediaCount > 0 ? blockSize * mediaProgress / mediaCount : 0;
progress += compressProgress ? blockSize : 0;
progress += uploadProgress ? blockSize : 0;
progress += photoUploadCount > 0 ? blockSize * photoUploadProgress / photoUploadCount : 0;
}
else
{
progress = 0;
}
//Log.d( TAG, "Progress updated to "+progress);
return progress;
}
public void setWaypointCount(int waypoint)
{
waypointCount = waypoint;
considerPublishProgress();
}
public void setMediaCount(int media)
{
mediaCount = media;
considerPublishProgress();
}
public void setCompress( boolean compress)
{
compressCount = compress;
considerPublishProgress();
}
public void setUpload( boolean upload)
{
uploadCount = upload;
considerPublishProgress();
}
public void setPhotoUpload(long length)
{
photoUploadCount += length;
considerPublishProgress();
}
public void addWaypointProgress(int i)
{
waypointProgress += i;
considerPublishProgress();
}
public void considerPublishProgress()
{
long now = new Date().getTime();
if( now - lastUpdate > 1000 )
{
lastUpdate = now;
publishProgress();
}
}
}
}
| 11chauhanpeeyush11-peeyush | OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/tasks/XmlCreator.java | Java | gpl3 | 17,459 |
/*------------------------------------------------------------------------------
** Ident: Delivery Center Java
** Author: rene
** Copyright: (c) Jul 9, 2011 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.actions.tasks;
import nl.sogeti.android.gpstracker.R;
import nl.sogeti.android.gpstracker.actions.ShareTrack;
import nl.sogeti.android.gpstracker.actions.utils.ProgressListener;
import android.content.Context;
import android.net.Uri;
/**
* ????
*
* @version $Id:$
* @author rene (c) Jul 9, 2011, Sogeti B.V.
*/
public class GpxSharing extends GpxCreator
{
public GpxSharing(Context context, Uri trackUri, String chosenBaseFileName, boolean attachments, ProgressListener listener)
{
super(context, trackUri, chosenBaseFileName, attachments, listener);
}
@Override
protected void onPostExecute(Uri resultFilename)
{
super.onPostExecute(resultFilename);
ShareTrack.sendFile(mContext, resultFilename, mContext.getString(R.string.email_gpxbody), getContentType());
}
}
| 11chauhanpeeyush11-peeyush | OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/tasks/GpxSharing.java | Java | gpl3 | 2,365 |
/*------------------------------------------------------------------------------
** Ident: Delivery Center Java
** Author: rene
** Copyright: (c) Jul 9, 2011 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.actions.tasks;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import nl.sogeti.android.gpstracker.R;
import nl.sogeti.android.gpstracker.actions.utils.ProgressListener;
import nl.sogeti.android.gpstracker.util.Constants;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.client.HttpClient;
import org.apache.ogt.http.client.methods.HttpPost;
import org.apache.ogt.http.entity.mime.MultipartEntity;
import org.apache.ogt.http.entity.mime.content.FileBody;
import org.apache.ogt.http.entity.mime.content.StringBody;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.util.EntityUtils;
import android.content.Context;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
/**
* ????
*
* @version $Id:$
* @author rene (c) Jul 9, 2011, Sogeti B.V.
*/
public class JogmapSharing extends GpxCreator
{
private static final String TAG = "OGT.JogmapSharing";
private String jogmapResponseText;
public JogmapSharing(Context context, Uri trackUri, String chosenBaseFileName, boolean attachments, ProgressListener listener)
{
super(context, trackUri, chosenBaseFileName, attachments, listener);
}
@Override
protected Uri doInBackground(Void... params)
{
Uri result = super.doInBackground(params);
sendToJogmap(result);
return result;
}
@Override
protected void onPostExecute(Uri resultFilename)
{
super.onPostExecute(resultFilename);
CharSequence text = mContext.getString(R.string.osm_success) + jogmapResponseText;
Toast toast = Toast.makeText(mContext, text, Toast.LENGTH_LONG);
toast.show();
}
private void sendToJogmap(Uri fileUri)
{
String authCode = PreferenceManager.getDefaultSharedPreferences(mContext).getString(Constants.JOGRUNNER_AUTH, "");
File gpxFile = new File(fileUri.getEncodedPath());
HttpClient httpclient = new DefaultHttpClient();
URI jogmap = null;
int statusCode = 0;
HttpEntity responseEntity = null;
try
{
jogmap = new URI(mContext.getString(R.string.jogmap_post_url));
HttpPost method = new HttpPost(jogmap);
MultipartEntity entity = new MultipartEntity();
entity.addPart("id", new StringBody(authCode));
entity.addPart("mFile", new FileBody(gpxFile));
method.setEntity(entity);
HttpResponse response = httpclient.execute(method);
statusCode = response.getStatusLine().getStatusCode();
responseEntity = response.getEntity();
InputStream stream = responseEntity.getContent();
jogmapResponseText = XmlCreator.convertStreamToString(stream);
}
catch (IOException e)
{
String text = mContext.getString(R.string.jogmap_failed) + e.getLocalizedMessage();
handleError(mContext.getString(R.string.jogmap_task), e, text);
}
catch (URISyntaxException e)
{
String text = mContext.getString(R.string.jogmap_failed) + e.getLocalizedMessage();
handleError(mContext.getString(R.string.jogmap_task), e, text);
}
finally
{
if (responseEntity != null)
{
try
{
EntityUtils.consume(responseEntity);
}
catch (IOException e)
{
Log.e(TAG, "Failed to close the content stream", e);
}
}
}
if (statusCode != 200)
{
Log.e(TAG, "Wrong status code " + statusCode);
jogmapResponseText = mContext.getString(R.string.jogmap_failed) + jogmapResponseText;
handleError(mContext.getString(R.string.jogmap_task), new HttpException("Unexpected status reported by Jogmap"), jogmapResponseText);
}
}
}
| 11chauhanpeeyush11-peeyush | OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/tasks/JogmapSharing.java | Java | gpl3 | 5,565 |
/*------------------------------------------------------------------------------
** Ident: Sogeti Smart Mobile Solutions
** Author: rene
** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.actions.tasks;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.Vector;
import java.util.concurrent.CancellationException;
import java.util.concurrent.Executor;
import nl.sogeti.android.gpstracker.R;
import nl.sogeti.android.gpstracker.actions.utils.ProgressListener;
import nl.sogeti.android.gpstracker.db.GPStracking.Tracks;
import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints;
import nl.sogeti.android.gpstracker.util.ProgressFilterInputStream;
import nl.sogeti.android.gpstracker.util.UnicodeReader;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;
import android.view.Window;
public class GpxParser extends AsyncTask<Uri, Void, Uri>
{
private static final String LATITUDE_ATRIBUTE = "lat";
private static final String LONGITUDE_ATTRIBUTE = "lon";
private static final String TRACK_ELEMENT = "trkpt";
private static final String SEGMENT_ELEMENT = "trkseg";
private static final String NAME_ELEMENT = "name";
private static final String TIME_ELEMENT = "time";
private static final String ELEVATION_ELEMENT = "ele";
private static final String COURSE_ELEMENT = "course";
private static final String ACCURACY_ELEMENT = "accuracy";
private static final String SPEED_ELEMENT = "speed";
public static final SimpleDateFormat ZULU_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
public static final SimpleDateFormat ZULU_DATE_FORMAT_MS = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
public static final SimpleDateFormat ZULU_DATE_FORMAT_BC = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss 'UTC'");
protected static final int DEFAULT_UNKNOWN_FILESIZE = 1024 * 1024 * 10;
private static final String TAG = "OGT.GpxParser";
static
{
TimeZone utc = TimeZone.getTimeZone("UTC");
ZULU_DATE_FORMAT.setTimeZone(utc); // ZULU_DATE_FORMAT format ends with Z for UTC so make that true
ZULU_DATE_FORMAT_MS.setTimeZone(utc);
}
private ContentResolver mContentResolver;
protected String mErrorDialogMessage;
protected Exception mErrorDialogException;
protected Context mContext;
private ProgressListener mProgressListener;
protected ProgressAdmin mProgressAdmin;
public GpxParser(Context context, ProgressListener progressListener)
{
mContext = context;
mProgressListener = progressListener;
mContentResolver = mContext.getContentResolver();
}
public void executeOn(Executor executor)
{
if (Build.VERSION.SDK_INT >= 11)
{
executeOnExecutor(executor);
}
else
{
execute();
}
}
public void determineProgressGoal(Uri importFileUri)
{
mProgressAdmin = new ProgressAdmin();
mProgressAdmin.setContentLength(DEFAULT_UNKNOWN_FILESIZE);
if (importFileUri != null && importFileUri.getScheme().equals("file"))
{
File file = new File(importFileUri.getPath());
mProgressAdmin.setContentLength(file.length());
}
}
public Uri importUri(Uri importFileUri)
{
Uri result = null;
String trackName = null;
InputStream fis = null;
if (importFileUri.getScheme().equals("file"))
{
trackName = importFileUri.getLastPathSegment();
}
try
{
fis = mContentResolver.openInputStream(importFileUri);
}
catch (IOException e)
{
handleError(e, mContext.getString(R.string.error_importgpx_io));
}
result = importTrack( fis, trackName);
return result;
}
/**
* Read a stream containing GPX XML into the OGT content provider
*
* @param fis opened stream the read from, will be closed after this call
* @param trackName
* @return
*/
public Uri importTrack( InputStream fis, String trackName )
{
Uri trackUri = null;
int eventType;
ContentValues lastPosition = null;
Vector<ContentValues> bulk = new Vector<ContentValues>();
boolean speed = false;
boolean accuracy = false;
boolean bearing = false;
boolean elevation = false;
boolean name = false;
boolean time = false;
Long importDate = Long.valueOf(new Date().getTime());
try
{
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xmlParser = factory.newPullParser();
ProgressFilterInputStream pfis = new ProgressFilterInputStream(fis, mProgressAdmin);
BufferedInputStream bis = new BufferedInputStream(pfis);
UnicodeReader ur = new UnicodeReader(bis, "UTF-8");
xmlParser.setInput(ur);
eventType = xmlParser.getEventType();
String attributeName;
Uri segmentUri = null;
while (eventType != XmlPullParser.END_DOCUMENT)
{
if (eventType == XmlPullParser.START_TAG)
{
if (xmlParser.getName().equals(NAME_ELEMENT))
{
name = true;
}
else
{
ContentValues trackContent = new ContentValues();
trackContent.put(Tracks.NAME, trackName);
if (xmlParser.getName().equals("trk") && trackUri == null)
{
trackUri = startTrack(trackContent);
}
else if (xmlParser.getName().equals(SEGMENT_ELEMENT))
{
segmentUri = startSegment(trackUri);
}
else if (xmlParser.getName().equals(TRACK_ELEMENT))
{
lastPosition = new ContentValues();
for (int i = 0; i < 2; i++)
{
attributeName = xmlParser.getAttributeName(i);
if (attributeName.equals(LATITUDE_ATRIBUTE))
{
lastPosition.put(Waypoints.LATITUDE, Double.valueOf(xmlParser.getAttributeValue(i)));
}
else if (attributeName.equals(LONGITUDE_ATTRIBUTE))
{
lastPosition.put(Waypoints.LONGITUDE, Double.valueOf(xmlParser.getAttributeValue(i)));
}
}
}
else if (xmlParser.getName().equals(SPEED_ELEMENT))
{
speed = true;
}
else if (xmlParser.getName().equals(ACCURACY_ELEMENT))
{
accuracy = true;
}
else if (xmlParser.getName().equals(COURSE_ELEMENT))
{
bearing = true;
}
else if (xmlParser.getName().equals(ELEVATION_ELEMENT))
{
elevation = true;
}
else if (xmlParser.getName().equals(TIME_ELEMENT))
{
time = true;
}
}
}
else if (eventType == XmlPullParser.END_TAG)
{
if (xmlParser.getName().equals(NAME_ELEMENT))
{
name = false;
}
else if (xmlParser.getName().equals(SPEED_ELEMENT))
{
speed = false;
}
else if (xmlParser.getName().equals(ACCURACY_ELEMENT))
{
accuracy = false;
}
else if (xmlParser.getName().equals(COURSE_ELEMENT))
{
bearing = false;
}
else if (xmlParser.getName().equals(ELEVATION_ELEMENT))
{
elevation = false;
}
else if (xmlParser.getName().equals(TIME_ELEMENT))
{
time = false;
}
else if (xmlParser.getName().equals(SEGMENT_ELEMENT))
{
if (segmentUri == null)
{
segmentUri = startSegment( trackUri );
}
mContentResolver.bulkInsert(Uri.withAppendedPath(segmentUri, "waypoints"), bulk.toArray(new ContentValues[bulk.size()]));
bulk.clear();
}
else if (xmlParser.getName().equals(TRACK_ELEMENT))
{
if (!lastPosition.containsKey(Waypoints.TIME))
{
lastPosition.put(Waypoints.TIME, importDate);
}
if (!lastPosition.containsKey(Waypoints.SPEED))
{
lastPosition.put(Waypoints.SPEED, 0);
}
bulk.add(lastPosition);
lastPosition = null;
}
}
else if (eventType == XmlPullParser.TEXT)
{
String text = xmlParser.getText();
if (name)
{
ContentValues nameValues = new ContentValues();
nameValues.put(Tracks.NAME, text);
if (trackUri == null)
{
trackUri = startTrack(new ContentValues());
}
mContentResolver.update(trackUri, nameValues, null, null);
}
else if (lastPosition != null && speed)
{
lastPosition.put(Waypoints.SPEED, Double.parseDouble(text));
}
else if (lastPosition != null && accuracy)
{
lastPosition.put(Waypoints.ACCURACY, Double.parseDouble(text));
}
else if (lastPosition != null && bearing)
{
lastPosition.put(Waypoints.BEARING, Double.parseDouble(text));
}
else if (lastPosition != null && elevation)
{
lastPosition.put(Waypoints.ALTITUDE, Double.parseDouble(text));
}
else if (lastPosition != null && time)
{
lastPosition.put(Waypoints.TIME, parseXmlDateTime(text));
}
}
eventType = xmlParser.next();
}
}
catch (XmlPullParserException e)
{
handleError(e, mContext.getString(R.string.error_importgpx_xml));
}
catch (IOException e)
{
handleError(e, mContext.getString(R.string.error_importgpx_io));
}
finally
{
try
{
fis.close();
}
catch (IOException e)
{
Log.w( TAG, "Failed closing inputstream");
}
}
return trackUri;
}
private Uri startSegment(Uri trackUri)
{
if (trackUri == null)
{
trackUri = startTrack(new ContentValues());
}
return mContentResolver.insert(Uri.withAppendedPath(trackUri, "segments"), new ContentValues());
}
private Uri startTrack(ContentValues trackContent)
{
return mContentResolver.insert(Tracks.CONTENT_URI, trackContent);
}
public static Long parseXmlDateTime(String text)
{
Long dateTime = 0L;
try
{
if(text==null)
{
throw new ParseException("Unable to parse dateTime "+text+" of length ", 0);
}
int length = text.length();
switch (length)
{
case 20:
synchronized (ZULU_DATE_FORMAT)
{
dateTime = Long.valueOf(ZULU_DATE_FORMAT.parse(text).getTime());
}
break;
case 23:
synchronized (ZULU_DATE_FORMAT_BC)
{
dateTime = Long.valueOf(ZULU_DATE_FORMAT_BC.parse(text).getTime());
}
break;
case 24:
synchronized (ZULU_DATE_FORMAT_MS)
{
dateTime = Long.valueOf(ZULU_DATE_FORMAT_MS.parse(text).getTime());
}
break;
default:
throw new ParseException("Unable to parse dateTime "+text+" of length "+length, 0);
}
}
catch (ParseException e) {
Log.w(TAG, "Failed to parse a time-date", e);
}
return dateTime;
}
/**
*
* @param e
* @param text
*/
protected void handleError(Exception dialogException, String dialogErrorMessage)
{
Log.e(TAG, "Unable to save ", dialogException);
mErrorDialogException = dialogException;
mErrorDialogMessage = dialogErrorMessage;
cancel(false);
throw new CancellationException(dialogErrorMessage);
}
@Override
protected void onPreExecute()
{
mProgressListener.started();
}
@Override
protected Uri doInBackground(Uri... params)
{
Uri importUri = params[0];
determineProgressGoal( importUri);
Uri result = importUri( importUri );
return result;
}
@Override
protected void onProgressUpdate(Void... values)
{
mProgressListener.setProgress(mProgressAdmin.getProgress());
}
@Override
protected void onPostExecute(Uri result)
{
mProgressListener.finished(result);
}
@Override
protected void onCancelled()
{
mProgressListener.showError(mContext.getString(R.string.taskerror_gpx_import), mErrorDialogMessage, mErrorDialogException);
}
public class ProgressAdmin
{
private long progressedBytes;
private long contentLength;
private int progress;
private long lastUpdate;
/**
* Get the progress.
*
* @return Returns the progress as a int.
*/
public int getProgress()
{
return progress;
}
public void addBytesProgress(int addedBytes)
{
progressedBytes += addedBytes;
progress = (int) (Window.PROGRESS_END * progressedBytes / contentLength);
considerPublishProgress();
}
public void setContentLength(long contentLength)
{
this.contentLength = contentLength;
}
public void considerPublishProgress()
{
long now = new Date().getTime();
if( now - lastUpdate > 1000 )
{
lastUpdate = now;
publishProgress();
}
}
}
}; | 11chauhanpeeyush11-peeyush | OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/tasks/GpxParser.java | Java | gpl3 | 16,565 |
/*------------------------------------------------------------------------------
** Ident: Delivery Center Java
** Author: rene
** Copyright: (c) Jul 9, 2011 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.actions.tasks;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import nl.sogeti.android.gpstracker.R;
import nl.sogeti.android.gpstracker.actions.ShareTrack;
import nl.sogeti.android.gpstracker.actions.utils.ProgressListener;
import nl.sogeti.android.gpstracker.db.GPStracking;
import nl.sogeti.android.gpstracker.db.GPStracking.Media;
import nl.sogeti.android.gpstracker.db.GPStracking.MetaData;
import nl.sogeti.android.gpstracker.oauth.PrepareRequestTokenActivity;
import nl.sogeti.android.gpstracker.util.Constants;
import nl.sogeti.android.gpstracker.viewer.map.LoggerMapHelper;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.client.methods.HttpPost;
import org.apache.ogt.http.entity.mime.HttpMultipartMode;
import org.apache.ogt.http.entity.mime.MultipartEntity;
import org.apache.ogt.http.entity.mime.content.FileBody;
import org.apache.ogt.http.entity.mime.content.StringBody;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.util.EntityUtils;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
/**
* ????
*
* @version $Id:$
* @author rene (c) Jul 9, 2011, Sogeti B.V.
*/
public class OsmSharing extends GpxCreator
{
public static final String OAUTH_TOKEN = "openstreetmap_oauth_token";
public static final String OAUTH_TOKEN_SECRET = "openstreetmap_oauth_secret";
private static final String TAG = "OGT.OsmSharing";
public static final String OSM_FILENAME = "OSM_Trace";
private String responseText;
private Uri mFileUri;
public OsmSharing(Activity context, Uri trackUri, boolean attachments, ProgressListener listener)
{
super(context, trackUri, OSM_FILENAME, attachments, listener);
}
public void resumeOsmSharing(Uri fileUri, Uri trackUri)
{
mFileUri = fileUri;
mTrackUri = trackUri;
execute();
}
@Override
protected Uri doInBackground(Void... params)
{
if( mFileUri == null )
{
mFileUri = super.doInBackground(params);
}
sendToOsm(mFileUri, mTrackUri);
return mFileUri;
}
@Override
protected void onPostExecute(Uri resultFilename)
{
super.onPostExecute(resultFilename);
CharSequence text = mContext.getString(R.string.osm_success) + responseText;
Toast toast = Toast.makeText(mContext, text, Toast.LENGTH_LONG);
toast.show();
}
/**
* POST a (GPX) file to the 0.6 API of the OpenStreetMap.org website
* publishing this track to the public.
*
* @param fileUri
* @param contentType
*/
private void sendToOsm(final Uri fileUri, final Uri trackUri)
{
CommonsHttpOAuthConsumer consumer = osmConnectionSetup();
if( consumer == null )
{
requestOpenstreetmapOauthToken();
handleError(mContext.getString(R.string.osm_task), null, mContext.getString(R.string.osmauth_message));
}
String visibility = PreferenceManager.getDefaultSharedPreferences(mContext).getString(Constants.OSM_VISIBILITY, "trackable");
File gpxFile = new File(fileUri.getEncodedPath());
String url = mContext.getString(R.string.osm_post_url);
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpResponse response = null;
int statusCode = 0;
Cursor metaData = null;
String sources = null;
HttpEntity responseEntity = null;
try
{
metaData = mContext.getContentResolver().query(Uri.withAppendedPath(trackUri, "metadata"), new String[] { MetaData.VALUE }, MetaData.KEY + " = ? ",
new String[] { Constants.DATASOURCES_KEY }, null);
if (metaData.moveToFirst())
{
sources = metaData.getString(0);
}
if (sources != null && sources.contains(LoggerMapHelper.GOOGLE_PROVIDER))
{
throw new IOException("Unable to upload track with materials derived from Google Maps.");
}
// The POST to the create node
HttpPost method = new HttpPost(url);
String tags = mContext.getString(R.string.osm_tag) + " " +queryForNotes();
// Build the multipart body with the upload data
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("file", new FileBody(gpxFile));
entity.addPart("description", new StringBody( ShareTrack.queryForTrackName(mContext.getContentResolver(), mTrackUri)));
entity.addPart("tags", new StringBody(tags));
entity.addPart("visibility", new StringBody(visibility));
method.setEntity(entity);
// Execute the POST to OpenStreetMap
consumer.sign(method);
response = httpclient.execute(method);
// Read the response
statusCode = response.getStatusLine().getStatusCode();
responseEntity = response.getEntity();
InputStream stream = responseEntity.getContent();
responseText = XmlCreator.convertStreamToString(stream);
}
catch (OAuthMessageSignerException e)
{
Editor editor = PreferenceManager.getDefaultSharedPreferences(mContext).edit();
editor.remove(OAUTH_TOKEN);
editor.remove(OAUTH_TOKEN_SECRET);
editor.commit();
responseText = mContext.getString(R.string.osm_failed) + e.getLocalizedMessage();
handleError(mContext.getString(R.string.osm_task), e, responseText);
}
catch (OAuthExpectationFailedException e)
{
Editor editor = PreferenceManager.getDefaultSharedPreferences(mContext).edit();
editor.remove(OAUTH_TOKEN);
editor.remove(OAUTH_TOKEN_SECRET);
editor.commit();
responseText = mContext.getString(R.string.osm_failed) + e.getLocalizedMessage();
handleError(mContext.getString(R.string.osm_task), e, responseText);
}
catch (OAuthCommunicationException e)
{
Editor editor = PreferenceManager.getDefaultSharedPreferences(mContext).edit();
editor.remove(OAUTH_TOKEN);
editor.remove(OAUTH_TOKEN_SECRET);
editor.commit();
responseText = mContext.getString(R.string.osm_failed) + e.getLocalizedMessage();
handleError(mContext.getString(R.string.osm_task), e, responseText);
}
catch (IOException e)
{
responseText = mContext.getString(R.string.osm_failed) + e.getLocalizedMessage();
handleError(mContext.getString(R.string.osm_task), e, responseText);
}
finally
{
if (responseEntity != null)
{
try
{
EntityUtils.consume(responseEntity);
}
catch (IOException e)
{
Log.e(TAG, "Failed to close the content stream", e);
}
}
if (metaData != null)
{
metaData.close();
}
}
if (statusCode != 200)
{
Log.e(TAG, "Failed to upload to error code " + statusCode + " " + responseText);
String text = mContext.getString(R.string.osm_failed) + responseText;
if( statusCode == 401 )
{
Editor editor = PreferenceManager.getDefaultSharedPreferences(mContext).edit();
editor.remove(OAUTH_TOKEN);
editor.remove(OAUTH_TOKEN_SECRET);
editor.commit();
}
handleError(mContext.getString(R.string.osm_task), new HttpException("Unexpected status reported by OSM"), text);
}
}
private CommonsHttpOAuthConsumer osmConnectionSetup()
{
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
String token = prefs.getString(OAUTH_TOKEN, "");
String secret = prefs.getString(OAUTH_TOKEN_SECRET, "");
boolean mAuthorized = !"".equals(token) && !"".equals(secret);
CommonsHttpOAuthConsumer consumer = null;
if (mAuthorized)
{
consumer = new CommonsHttpOAuthConsumer(mContext.getString(R.string.OSM_CONSUMER_KEY), mContext.getString(R.string.OSM_CONSUMER_SECRET));
consumer.setTokenWithSecret(token, secret);
}
return consumer;
}
private String queryForNotes()
{
StringBuilder tags = new StringBuilder();
ContentResolver resolver = mContext.getContentResolver();
Cursor mediaCursor = null;
Uri mediaUri = Uri.withAppendedPath(mTrackUri, "media");
try
{
mediaCursor = resolver.query(mediaUri, new String[] { Media.URI }, null, null, null);
if (mediaCursor.moveToFirst())
{
do
{
Uri noteUri = Uri.parse(mediaCursor.getString(0));
if (noteUri.getScheme().equals("content") && noteUri.getAuthority().equals(GPStracking.AUTHORITY + ".string"))
{
String tag = noteUri.getLastPathSegment().trim();
if (!tag.contains(" "))
{
if (tags.length() > 0)
{
tags.append(" ");
}
tags.append(tag);
}
}
}
while (mediaCursor.moveToNext());
}
}
finally
{
if (mediaCursor != null)
{
mediaCursor.close();
}
}
return tags.toString();
}
public void requestOpenstreetmapOauthToken()
{
Intent intent = new Intent(mContext.getApplicationContext(), PrepareRequestTokenActivity.class);
intent.putExtra(PrepareRequestTokenActivity.OAUTH_TOKEN_PREF, OAUTH_TOKEN);
intent.putExtra(PrepareRequestTokenActivity.OAUTH_TOKEN_SECRET_PREF, OAUTH_TOKEN_SECRET);
intent.putExtra(PrepareRequestTokenActivity.CONSUMER_KEY, mContext.getString(R.string.OSM_CONSUMER_KEY));
intent.putExtra(PrepareRequestTokenActivity.CONSUMER_SECRET, mContext.getString(R.string.OSM_CONSUMER_SECRET));
intent.putExtra(PrepareRequestTokenActivity.REQUEST_URL, Constants.OSM_REQUEST_URL);
intent.putExtra(PrepareRequestTokenActivity.ACCESS_URL, Constants.OSM_ACCESS_URL);
intent.putExtra(PrepareRequestTokenActivity.AUTHORIZE_URL, Constants.OSM_AUTHORIZE_URL);
mContext.startActivity(intent);
}
}
| 11chauhanpeeyush11-peeyush | OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/tasks/OsmSharing.java | Java | gpl3 | 12,525 |
/*------------------------------------------------------------------------------
** Ident: Sogeti Smart Mobile Solutions
** Author: rene
** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.actions.tasks;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import nl.sogeti.android.gpstracker.R;
import nl.sogeti.android.gpstracker.actions.utils.ProgressListener;
import nl.sogeti.android.gpstracker.db.GPStracking;
import nl.sogeti.android.gpstracker.db.GPStracking.Media;
import nl.sogeti.android.gpstracker.db.GPStracking.Segments;
import nl.sogeti.android.gpstracker.db.GPStracking.Tracks;
import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints;
import nl.sogeti.android.gpstracker.util.Constants;
import org.xmlpull.v1.XmlSerializer;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore.MediaColumns;
import android.util.Log;
import android.util.Xml;
/**
* Create a GPX version of a stored track
*
* @version $Id$
* @author rene (c) Mar 22, 2009, Sogeti B.V.
*/
public class GpxCreator extends XmlCreator
{
public static final String NS_SCHEMA = "http://www.w3.org/2001/XMLSchema-instance";
public static final String NS_GPX_11 = "http://www.topografix.com/GPX/1/1";
public static final String NS_GPX_10 = "http://www.topografix.com/GPX/1/0";
public static final String NS_OGT_10 = "http://gpstracker.android.sogeti.nl/GPX/1/0";
public static final SimpleDateFormat ZULU_DATE_FORMATER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
static
{
TimeZone utc = TimeZone.getTimeZone("UTC");
ZULU_DATE_FORMATER.setTimeZone(utc); // ZULU_DATE_FORMAT format ends with Z for UTC so make that true
}
private String TAG = "OGT.GpxCreator";
private boolean includeAttachments;
protected String mName;
public GpxCreator(Context context, Uri trackUri, String chosenBaseFileName, boolean attachments, ProgressListener listener)
{
super(context, trackUri, chosenBaseFileName, listener);
includeAttachments = attachments;
}
@Override
protected Uri doInBackground(Void... params)
{
determineProgressGoal();
Uri resultFilename = exportGpx();
return resultFilename;
}
protected Uri exportGpx()
{
String xmlFilePath;
if (mFileName.endsWith(".gpx") || mFileName.endsWith(".xml"))
{
setExportDirectoryPath(Constants.getSdCardDirectory(mContext) + mFileName.substring(0, mFileName.length() - 4));
xmlFilePath = getExportDirectoryPath() + "/" + mFileName;
}
else
{
setExportDirectoryPath(Constants.getSdCardDirectory(mContext) + mFileName);
xmlFilePath = getExportDirectoryPath() + "/" + mFileName + ".gpx";
}
new File(getExportDirectoryPath()).mkdirs();
String resultFilename = null;
FileOutputStream fos = null;
BufferedOutputStream buf = null;
try
{
verifySdCardAvailibility();
XmlSerializer serializer = Xml.newSerializer();
File xmlFile = new File(xmlFilePath);
fos = new FileOutputStream(xmlFile);
buf = new BufferedOutputStream(fos, 8 * 8192);
serializer.setOutput(buf, "UTF-8");
serializeTrack(mTrackUri, serializer);
buf.close();
buf = null;
fos.close();
fos = null;
if (needsBundling())
{
resultFilename = bundlingMediaAndXml(xmlFile.getParentFile().getName(), ".zip");
}
else
{
File finalFile = new File(Constants.getSdCardDirectory(mContext) + xmlFile.getName());
xmlFile.renameTo(finalFile);
resultFilename = finalFile.getAbsolutePath();
XmlCreator.deleteRecursive(xmlFile.getParentFile());
}
mFileName = new File(resultFilename).getName();
}
catch (FileNotFoundException e)
{
String text = mContext.getString(R.string.ticker_failed) + " \"" + xmlFilePath + "\" " + mContext.getString(R.string.error_filenotfound);
handleError(mContext.getString(R.string.taskerror_gpx_write), e, text);
}
catch (IllegalArgumentException e)
{
String text = mContext.getString(R.string.ticker_failed) + " \"" + xmlFilePath + "\" " + mContext.getString(R.string.error_filename);
handleError(mContext.getString(R.string.taskerror_gpx_write), e, text);
}
catch (IllegalStateException e)
{
String text = mContext.getString(R.string.ticker_failed) + " \"" + xmlFilePath + "\" " + mContext.getString(R.string.error_buildxml);
handleError(mContext.getString(R.string.taskerror_gpx_write), e, text);
}
catch (IOException e)
{
String text = mContext.getString(R.string.ticker_failed) + " \"" + xmlFilePath + "\" " + mContext.getString(R.string.error_writesdcard);
handleError(mContext.getString(R.string.taskerror_gpx_write), e, text);
}
finally
{
if (buf != null)
{
try
{
buf.close();
}
catch (IOException e)
{
Log.e(TAG, "Failed to close buf after completion, ignoring.", e);
}
}
if (fos != null)
{
try
{
fos.close();
}
catch (IOException e)
{
Log.e(TAG, "Failed to close fos after completion, ignoring.", e);
}
}
}
return Uri.fromFile(new File(resultFilename));
}
private void serializeTrack(Uri trackUri, XmlSerializer serializer) throws IllegalArgumentException, IllegalStateException, IOException
{
if (isCancelled())
{
throw new IOException("Fail to execute request due to canceling");
}
serializer.startDocument("UTF-8", true);
serializer.setPrefix("xsi", NS_SCHEMA);
serializer.setPrefix("gpx10", NS_GPX_10);
serializer.setPrefix("ogt10", NS_OGT_10);
serializer.text("\n");
serializer.startTag("", "gpx");
serializer.attribute(null, "version", "1.1");
serializer.attribute(null, "creator", "nl.sogeti.android.gpstracker");
serializer.attribute(NS_SCHEMA, "schemaLocation", NS_GPX_11 + " http://www.topografix.com/gpx/1/1/gpx.xsd");
serializer.attribute(null, "xmlns", NS_GPX_11);
// <metadata/> Big header of the track
serializeTrackHeader(mContext, serializer, trackUri);
// <wpt/> [0...] Waypoints
if (includeAttachments)
{
serializeWaypoints(mContext, serializer, Uri.withAppendedPath(trackUri, "/media"));
}
// <trk/> [0...] Track
serializer.text("\n");
serializer.startTag("", "trk");
serializer.text("\n");
serializer.startTag("", "name");
serializer.text(mName);
serializer.endTag("", "name");
// The list of segments in the track
serializeSegments(serializer, Uri.withAppendedPath(trackUri, "segments"));
serializer.text("\n");
serializer.endTag("", "trk");
serializer.text("\n");
serializer.endTag("", "gpx");
serializer.endDocument();
}
private void serializeTrackHeader(Context context, XmlSerializer serializer, Uri trackUri) throws IOException
{
if (isCancelled())
{
throw new IOException("Fail to execute request due to canceling");
}
ContentResolver resolver = context.getContentResolver();
Cursor trackCursor = null;
String databaseName = null;
try
{
trackCursor = resolver.query(trackUri, new String[] { Tracks._ID, Tracks.NAME, Tracks.CREATION_TIME }, null, null, null);
if (trackCursor.moveToFirst())
{
databaseName = trackCursor.getString(1);
serializer.text("\n");
serializer.startTag("", "metadata");
serializer.text("\n");
serializer.startTag("", "time");
Date time = new Date(trackCursor.getLong(2));
synchronized (ZULU_DATE_FORMATER)
{
serializer.text(ZULU_DATE_FORMATER.format(time));
}
serializer.endTag("", "time");
serializer.text("\n");
serializer.endTag("", "metadata");
}
}
finally
{
if (trackCursor != null)
{
trackCursor.close();
}
}
if (mName == null)
{
mName = "Untitled";
}
if (databaseName != null && !databaseName.equals(""))
{
mName = databaseName;
}
if (mChosenName != null && !mChosenName.equals(""))
{
mName = mChosenName;
}
}
private void serializeSegments(XmlSerializer serializer, Uri segments) throws IOException
{
if (isCancelled())
{
throw new IOException("Fail to execute request due to canceling");
}
Cursor segmentCursor = null;
ContentResolver resolver = mContext.getContentResolver();
try
{
segmentCursor = resolver.query(segments, new String[] { Segments._ID }, null, null, null);
if (segmentCursor.moveToFirst())
{
do
{
Uri waypoints = Uri.withAppendedPath(segments, segmentCursor.getLong(0) + "/waypoints");
serializer.text("\n");
serializer.startTag("", "trkseg");
serializeTrackPoints(serializer, waypoints);
serializer.text("\n");
serializer.endTag("", "trkseg");
}
while (segmentCursor.moveToNext());
}
}
finally
{
if (segmentCursor != null)
{
segmentCursor.close();
}
}
}
private void serializeTrackPoints(XmlSerializer serializer, Uri waypoints) throws IOException
{
if (isCancelled())
{
throw new IOException("Fail to execute request due to canceling");
}
Cursor waypointsCursor = null;
ContentResolver resolver = mContext.getContentResolver();
try
{
waypointsCursor = resolver.query(waypoints, new String[] { Waypoints.LONGITUDE, Waypoints.LATITUDE, Waypoints.TIME, Waypoints.ALTITUDE, Waypoints._ID, Waypoints.SPEED, Waypoints.ACCURACY,
Waypoints.BEARING }, null, null, null);
if (waypointsCursor.moveToFirst())
{
do
{
mProgressAdmin.addWaypointProgress(1);
serializer.text("\n");
serializer.startTag("", "trkpt");
serializer.attribute(null, "lat", Double.toString(waypointsCursor.getDouble(1)));
serializer.attribute(null, "lon", Double.toString(waypointsCursor.getDouble(0)));
serializer.text("\n");
serializer.startTag("", "ele");
serializer.text(Double.toString(waypointsCursor.getDouble(3)));
serializer.endTag("", "ele");
serializer.text("\n");
serializer.startTag("", "time");
Date time = new Date(waypointsCursor.getLong(2));
synchronized (ZULU_DATE_FORMATER)
{
serializer.text(ZULU_DATE_FORMATER.format(time));
}
serializer.endTag("", "time");
serializer.text("\n");
serializer.startTag("", "extensions");
double speed = waypointsCursor.getDouble(5);
double accuracy = waypointsCursor.getDouble(6);
double bearing = waypointsCursor.getDouble(7);
if (speed > 0.0)
{
quickTag(serializer, NS_GPX_10, "speed", Double.toString(speed));
}
if (accuracy > 0.0)
{
quickTag(serializer, NS_OGT_10, "accuracy", Double.toString(accuracy));
}
if (bearing != 0.0)
{
quickTag(serializer, NS_GPX_10, "course", Double.toString(bearing));
}
serializer.endTag("", "extensions");
serializer.text("\n");
serializer.endTag("", "trkpt");
}
while (waypointsCursor.moveToNext());
}
}
finally
{
if (waypointsCursor != null)
{
waypointsCursor.close();
}
}
}
private void serializeWaypoints(Context context, XmlSerializer serializer, Uri media) throws IOException
{
if (isCancelled())
{
throw new IOException("Fail to execute request due to canceling");
}
Cursor mediaCursor = null;
Cursor waypointCursor = null;
BufferedReader buf = null;
ContentResolver resolver = context.getContentResolver();
try
{
mediaCursor = resolver.query(media, new String[] { Media.URI, Media.TRACK, Media.SEGMENT, Media.WAYPOINT }, null, null, null);
if (mediaCursor.moveToFirst())
{
do
{
Uri waypointUri = Waypoints.buildUri(mediaCursor.getLong(1), mediaCursor.getLong(2), mediaCursor.getLong(3));
waypointCursor = resolver.query(waypointUri, new String[] { Waypoints.LATITUDE, Waypoints.LONGITUDE, Waypoints.ALTITUDE, Waypoints.TIME }, null, null, null);
serializer.text("\n");
serializer.startTag("", "wpt");
if (waypointCursor != null && waypointCursor.moveToFirst())
{
serializer.attribute(null, "lat", Double.toString(waypointCursor.getDouble(0)));
serializer.attribute(null, "lon", Double.toString(waypointCursor.getDouble(1)));
serializer.text("\n");
serializer.startTag("", "ele");
serializer.text(Double.toString(waypointCursor.getDouble(2)));
serializer.endTag("", "ele");
serializer.text("\n");
serializer.startTag("", "time");
Date time = new Date(waypointCursor.getLong(3));
synchronized (ZULU_DATE_FORMATER)
{
serializer.text(ZULU_DATE_FORMATER.format(time));
}
serializer.endTag("", "time");
}
if (waypointCursor != null)
{
waypointCursor.close();
waypointCursor = null;
}
Uri mediaUri = Uri.parse(mediaCursor.getString(0));
if (mediaUri.getScheme().equals("file"))
{
if (mediaUri.getLastPathSegment().endsWith("3gp"))
{
String fileName = includeMediaFile(mediaUri.getLastPathSegment());
quickTag(serializer, "", "name", fileName);
serializer.startTag("", "link");
serializer.attribute(null, "href", fileName);
quickTag(serializer, "", "text", fileName);
serializer.endTag("", "link");
}
else if (mediaUri.getLastPathSegment().endsWith("jpg"))
{
String mediaPathPrefix = Constants.getSdCardDirectory(mContext);
String fileName = includeMediaFile(mediaPathPrefix + mediaUri.getLastPathSegment());
quickTag(serializer, "", "name", fileName);
serializer.startTag("", "link");
serializer.attribute(null, "href", fileName);
quickTag(serializer, "", "text", fileName);
serializer.endTag("", "link");
}
else if (mediaUri.getLastPathSegment().endsWith("txt"))
{
quickTag(serializer, "", "name", mediaUri.getLastPathSegment());
serializer.startTag("", "desc");
if (buf != null)
{
buf.close();
}
buf = new BufferedReader(new FileReader(mediaUri.getEncodedPath()));
String line;
while ((line = buf.readLine()) != null)
{
serializer.text(line);
serializer.text("\n");
}
serializer.endTag("", "desc");
}
}
else if (mediaUri.getScheme().equals("content"))
{
if ((GPStracking.AUTHORITY + ".string").equals(mediaUri.getAuthority()))
{
quickTag(serializer, "", "name", mediaUri.getLastPathSegment());
}
else if (mediaUri.getAuthority().equals("media"))
{
Cursor mediaItemCursor = null;
try
{
mediaItemCursor = resolver.query(mediaUri, new String[] { MediaColumns.DATA, MediaColumns.DISPLAY_NAME }, null, null, null);
if (mediaItemCursor.moveToFirst())
{
String fileName = includeMediaFile(mediaItemCursor.getString(0));
quickTag(serializer, "", "name", fileName);
serializer.startTag("", "link");
serializer.attribute(null, "href", fileName);
quickTag(serializer, "", "text", mediaItemCursor.getString(1));
serializer.endTag("", "link");
}
}
finally
{
if (mediaItemCursor != null)
{
mediaItemCursor.close();
}
}
}
}
serializer.text("\n");
serializer.endTag("", "wpt");
}
while (mediaCursor.moveToNext());
}
}
finally
{
if (mediaCursor != null)
{
mediaCursor.close();
}
if (waypointCursor != null)
{
waypointCursor.close();
}
if (buf != null)
buf.close();
}
}
@Override
protected String getContentType()
{
return needsBundling() ? "application/zip" : "text/xml";
}
} | 11chauhanpeeyush11-peeyush | OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/tasks/GpxCreator.java | Java | gpl3 | 20,276 |