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
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Xml.Linq; using DOAN.DO; using DOAN.BL; namespace DOAN.Admin { public partial class Xemdanhsachdethi : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (Session["quyen"] == null) Response.Redirect("LoginAdmin.aspx"); lblLoi.Text = ""; loadMon(); loadDT(); } } public void loadMon() { DataTable dt = new DataTable(); if (Session["quyen"].ToString() == "GV") dt = new CT_MonhocBL().GetByUser(Session["Tendangnhap"].ToString()); else if (Session["quyen"].ToString() == "AD") dt = new MonhocBL().SelectAll(); if (dt.Rows.Count > 0) { drpMon.DataSource = dt; drpMon.DataTextField = "Tenmon"; drpMon.DataValueField = "Mamonhoc"; drpMon.DataBind(); } else { drpMon.Text = "Khong co mon"; } } public void loadDT() { DataTable dt = new DataTable(); if (Session["quyen"].ToString() == "AD") dt = new DethiBL().GetByMon(drpMon.SelectedValue); if (Session["quyen"].ToString() == "GV") dt = new DethiBL().GetByMon(drpMon.SelectedValue); griXemDethi.DataSource = dt; griXemDethi.DataBind(); } protected void griXemDethi_RowCommand(object sender, GridViewCommandEventArgs e) { int ma = int.Parse(e.CommandArgument.ToString()); if (e.CommandName == "xem") { Response.Redirect("ChitietDethi.aspx?IDDT=" + ma); } if (e.CommandName == "xoa") { int re = new DethiBL().Delete(new DethiDO { Madethi = ma }); if (re == 0) { lblLoi.Text = "Xóa thành công!"; loadDT(); } else { lblLoi.Text = "Lỗi!!"; } } } protected void gridXemDethi_PageIndexChanging(object sender, GridViewPageEventArgs e) { //string monhoc = drMonhoc1.SelectedValue; griXemDethi.PageIndex = e.NewPageIndex; this.loadDT(); } protected void drpMon_SelectedIndexChanged(object sender, EventArgs e) { loadDT(); } } }
08b2-doan
trunk/Source/DoAn/DOAN/Admin/Xemdanhsachdethi.aspx.cs
C#
gpl3
3,021
using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; namespace DOAN.Admin { public class ExportToExcel { public void Export(DataTable dt, string sheetName, string title) { //Tạo các đối tượng Excel Microsoft.Office.Interop.Excel.Application oExcel = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbooks oBooks; Microsoft.Office.Interop.Excel.Sheets oSheets; Microsoft.Office.Interop.Excel.Workbook oBook; Microsoft.Office.Interop.Excel.Worksheet oSheet; //Tạo mới một Excel WorkBook oExcel.Visible = true; oExcel.DisplayAlerts = false; oExcel.Application.SheetsInNewWorkbook = 1; oBooks = oExcel.Workbooks; oBook = (Microsoft.Office.Interop.Excel.Workbook)(oExcel.Workbooks.Add(Type.Missing)); oSheets = oBook.Worksheets; oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oSheets.get_Item(1); oSheet.Name = sheetName; // Tạo phần đầu nếu muốn Microsoft.Office.Interop.Excel.Range head = oSheet.get_Range("A1", "E1"); head.MergeCells = true; head.Value2 = title; head.Font.Bold = true; head.Font.Name = "Times New Roman"; head.Font.Size = "18"; head.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; // Tạo tiêu đề cột Microsoft.Office.Interop.Excel.Range cl1 = oSheet.get_Range("A3", "A3"); cl1.Font.Name = "Times New Roman"; cl1.Value2 = "Mã đề thi"; cl1.ColumnWidth = 13.5; Microsoft.Office.Interop.Excel.Range cl2 = oSheet.get_Range("B3", "B3"); cl2.Font.Name = "Times New Roman"; cl2.Value2 = "Họ và tên"; cl2.ColumnWidth = 30.0; Microsoft.Office.Interop.Excel.Range cl3 = oSheet.get_Range("C3", "C3"); cl3.Font.Name = "Times New Roman"; cl3.Value2 = "Lớp"; cl3.ColumnWidth = 15.0; Microsoft.Office.Interop.Excel.Range cl4 = oSheet.get_Range("D3", "D3"); cl4.Font.Name = "Times New Roman"; cl4.Value2 = "Ngày thi"; cl4.ColumnWidth = 15.0; Microsoft.Office.Interop.Excel.Range cl5 = oSheet.get_Range("E3", "E3"); cl5.Font.Name = "Times New Roman"; cl5.Value2 = "Tổng điểm"; cl5.ColumnWidth = 15.0; Microsoft.Office.Interop.Excel.Range rowHead = oSheet.get_Range("A3", "E3"); rowHead.Font.Bold = true; // Kẻ viền rowHead.Borders.LineStyle = Microsoft.Office.Interop.Excel.Constants.xlSolid; // Thiết lập màu nền rowHead.Interior.ColorIndex = 15; rowHead.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; // Tạo mẳng đối tượng để lưu dữ toàn bồ dữ liệu trong DataTable, // vì dữ liệu được được gán vào các Cell trong Excel phải thông qua object thuần. object[,] arr = new object[dt.Rows.Count, dt.Columns.Count]; //Chuyển dữ liệu từ DataTable vào mảng đối tượng for (int r = 0; r < dt.Rows.Count; r++) { DataRow dr = dt.Rows[r]; for (int c = 0; c < dt.Columns.Count; c++) { arr[r, c] = dr[c]; } } //Thiết lập vùng điền dữ liệu int rowStart = 4; int columnStart = 1; int rowEnd = rowStart + dt.Rows.Count - 1; int columnEnd = dt.Columns.Count; // Ô bắt đầu điền dữ liệu Microsoft.Office.Interop.Excel.Range c1 = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[rowStart, columnStart]; // Ô kết thúc điền dữ liệu Microsoft.Office.Interop.Excel.Range c2 = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[rowEnd, columnEnd]; // Lấy về vùng điền dữ liệu Microsoft.Office.Interop.Excel.Range range = oSheet.get_Range(c1, c2); //Điền dữ liệu vào vùng đã thiết lập range.Value2 = arr; // Kẻ viền range.Borders.LineStyle = Microsoft.Office.Interop.Excel.Constants.xlSolid; // Căn giữa cột STT Microsoft.Office.Interop.Excel.Range c3 = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[rowEnd, columnStart]; Microsoft.Office.Interop.Excel.Range c4 = oSheet.get_Range(c1, c3); oSheet.get_Range(c3, c4).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; } } }
08b2-doan
trunk/Source/DoAn/DOAN/Admin/ExportToExcel.cs
C#
gpl3
5,287
<%@ Page Language="C#" MasterPageFile="~/Admin/Admin.Master" AutoEventWireup="true" CodeBehind="ChitietDethi.aspx.cs" Inherits="DOAN.Admin.ChitietDethi" Title="Untitled Page" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server"> <asp:Label ID="lbID" runat="server"></asp:Label> <br /> <asp:Repeater ID="rpt" runat="server" onitemdatabound="rpt_ItemDataBound"> <ItemTemplate> <asp:Label ID="lblCH" Text='<%#Eval("Macauhoi")%>' runat="server"></asp:Label><br /> <%--<asp:RadioButton ID="rdA" runat="server" Checked='<%#ktraA(Eval("Phuongandung"))%>' GroupName="ck" />--%> <asp:Label ID="A" Text='<%#Eval("DananA")%>' runat="server"></asp:Label><br /> <%--<asp:RadioButton ID="rdB" runat="server" Checked='<%#ktraB(Eval("Phuongandung"))%>' GroupName="ck" />--%> <asp:Label ID="B" Text='<%#Eval("DananB")%>' runat="server"></asp:Label><br /> <%--<asp:RadioButton ID="rdC" runat="server" Checked='<%#ktraC(Eval("Phuongandung"))%>' GroupName="ck" />--%> <asp:Label ID="C" Text='<%#Eval("DananC")%>' runat="server"></asp:Label><br /> <%--<asp:RadioButton ID="rdD" runat="server" Checked='<%#ktraD(Eval("Phuongandung"))%>' GroupName="ck" />--%> <asp:Label ID="D" Text='<%#Eval("DananD")%>' runat="server"></asp:Label> </ItemTemplate> </asp:Repeater> </asp:Content>
08b2-doan
trunk/Source/DoAn/DOAN/Admin/ChitietDethi.aspx
ASP.NET
gpl3
1,547
<%@ Page Language="C#" MasterPageFile="~/Admin/Admin.Master" AutoEventWireup="true" CodeBehind="QL_Cauhoi.aspx.cs" Inherits="DOAN.Admin.QL_Cauhoi" Title="Untitled Page" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server"> <div class="content-right"> <div class="title_right"> <p class="fs24 cl2 fi font_time"> <img src="../Imagine/icon_right_title.png" alt=""/>Quản lý câu hỏi - đáp án</p> </div> <div class="register"> <div class="register mart22"> <span class="cl4"> <asp:Label ID="lblLoi" runat="server" Text=""></asp:Label></span> </div> <div class="register mart22"> <div class="label"> <asp:Label ID="lblMonhoc" runat="server" Text="Chọn môn học"></asp:Label></div> <div class="text_box2"> <asp:DropDownList ID="drMonhoc1" runat="server" Width="180px" onselectedindexchanged="drMonhoc1_SelectedIndexChanged" AutoPostBack="true" Height="16px"> </asp:DropDownList> </div> <div class="text_box2"> <asp:Button ID="btChon" runat="server" Text="Chọn" OnClick="btChon_Click" /> </div> </div> <div class="register mart22" > <asp:ImageButton ID="img_refesh" runat="server" ImageUrl="~/Imagine/icon_refresh.png" OnClick="imgRe_Click" /> Refresh <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/Imagine/true.PNG" OnClick="imgDanhsach_cauhoi_Click" Style=" margin-left: 10px" /> DS câu hỏi <asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/Imagine/true.PNG" OnClick="imgDanhsach_cauhoi_dapan_Click" Style=" margin-left: 10px" /> DS câu hỏi - đáp án <asp:ImageButton ID="Themmon" runat="server" ImageUrl="~/Imagine/icon_add.png" OnClick="imgThem_Click" Style="margin-left: 10px" /> Thêm câu hỏi <asp:ImageButton ID="ImageButton4" runat="server" ImageUrl="~/Imagine/icon_add.png" OnClick="imgImport_Click" Style=" margin-left: 10px" /> Import file excel <asp:ImageButton ID="ImageButton3" runat="server" ImageUrl="~/Imagine/icon_search.png" OnClick="imgTimkiem_Click" Style=" margin-left: 10px" /> Tìm kiếm </div> <div class="register"> <asp:Panel ID="pnTimkiem" runat="server" Visible="true"> <div class="register mart22"> <div class="label"> <asp:Label ID="lbl" runat="server" Text="Tìm kiếm"></asp:Label> </div> <div class="text_box"> <asp:TextBox ID="txtTimkiem" runat="server" Width="182px"></asp:TextBox> </div> <div class="label"> <asp:ImageButton ID="imgtk" runat="server" ImageUrl="~/Imagine/input_search.png" OnClick="imgtk_Click" Style="height: 22px" /> </div> </div> </asp:Panel> <div class="register mart22"> <asp:Panel ID="pnImport" runat="server" Visible="false" Height="150px"> <asp:Label ID="Label2" runat="server" Text="Chú ý: File import phải là file excel(.xls). Dữ liệu load từ dòng 2, dòng 1 được coi là tiêu đề( không import ). Chú ý các trường phải đúng thứ tự!" ForeColor="Red" Width="679px" style="position: static"></asp:Label> <table style="position: relative; left: 20px; top: 20px;"> <tr> <td colspan="2"> <asp:Label ID="lblError" runat="server" Visible="False" ForeColor="Red" Width="231px" style="position: static"></asp:Label></td> </tr> <tr> <td> Chọn file </td> <td style="width: 100px"> <asp:FileUpload ID="FileUpload1" runat="server" /></td> </tr> <tr align="center"> <td colspan="2"> <asp:Button ID="btnImport" runat="server" Text="Import" OnClick="btnImport_Click" /> <asp:Button ID="btnCancel" runat="server" Text="Cancel" /></td> </tr> </table> </asp:Panel> <asp:GridView runat="server" ID="gridCauhoi" AutoGenerateColumns="False" CellPadding="4" Width="679px" AllowPaging="True" OnPageIndexChanging="gridCauhoi_PageIndexChanging" OnRowCommand="gridCauhoi_RowCommand" EmptyDataText="Không có dữ liệu!" BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" > <RowStyle BackColor="White" ForeColor="#330099" /> <Columns> <asp:TemplateField HeaderText="Mã câu hỏi " HeaderStyle-HorizontalAlign="Left"> <ItemTemplate> <asp:Label runat="server" ID="lblmacauhoi" Text='<%#DataBinder.Eval(Container.DataItem,"Macauhoi") %>'> </asp:Label> </ItemTemplate> <HeaderStyle HorizontalAlign="Left"></HeaderStyle> </asp:TemplateField> <asp:TemplateField HeaderText="Mã môn học " HeaderStyle-HorizontalAlign="Left"> <ItemTemplate> <asp:Label runat="server" ID="lblmamon" Text='<%#DataBinder.Eval(Container.DataItem,"Mamonhoc") %>'> </asp:Label> </ItemTemplate> <HeaderStyle HorizontalAlign="Left"></HeaderStyle> </asp:TemplateField> <asp:TemplateField HeaderText="Nội dung" HeaderStyle-HorizontalAlign="Left"> <ItemTemplate> <asp:Label runat="server" ID="lblnd" Text='<%#DataBinder.Eval(Container.DataItem,"Noidung") %>'> </asp:Label> </ItemTemplate> <HeaderStyle HorizontalAlign="Left"></HeaderStyle> </asp:TemplateField> <asp:TemplateField HeaderText="Độ khó " HeaderStyle-HorizontalAlign="Left"> <ItemTemplate> <asp:Label runat="server" ID="lblDokhoC" Text='<%#DataBinder.Eval(Container.DataItem,"Dokho") %>'> </asp:Label> </ItemTemplate> <HeaderStyle HorizontalAlign="Left"></HeaderStyle> </asp:TemplateField> <asp:TemplateField HeaderText="Chương" HeaderStyle-HorizontalAlign="Left"> <ItemTemplate> <asp:Label runat="server" ID="lblsl" Text='<%#DataBinder.Eval(Container.DataItem,"Chuong") %>'> </asp:Label> </ItemTemplate> <HeaderStyle HorizontalAlign="Left"></HeaderStyle> </asp:TemplateField> <asp:TemplateField HeaderText="Image" HeaderStyle-HorizontalAlign="Left"> <ItemTemplate> <%--<asp:Label runat="server" ID="lbls" Text='<%#DataBinder.Eval(Container.DataItem,"Image") %>'> </asp:Label>--%> <asp:Image ImageUrl='<%#DataBinder.Eval(Container.DataItem,"Image") %>' Width="42px" Height="42px" runat="server" /> </ItemTemplate> <HeaderStyle HorizontalAlign="Left"></HeaderStyle> </asp:TemplateField> <asp:TemplateField HeaderText="Sửa" HeaderStyle-HorizontalAlign="Left"> <ItemTemplate> <asp:ImageButton runat="server" ID="img_suach" CommandName="sua" Visible="true" CommandArgument='<%#DataBinder.Eval(Container.DataItem,"Macauhoi") %>' ImageUrl="~/icon/edit_profile.png" /> </ItemTemplate> <HeaderStyle HorizontalAlign="Left"></HeaderStyle> </asp:TemplateField> <asp:TemplateField HeaderText="Xóa" HeaderStyle-HorizontalAlign="Left"> <ItemTemplate> <asp:ImageButton runat="server" ID="img_xoach" CommandName="xoa" Visible="true" CommandArgument='<%#DataBinder.Eval(Container.DataItem,"Macauhoi") %>' ImageUrl="~/icon/delete_user.png" /> </ItemTemplate> <HeaderStyle HorizontalAlign="Left"></HeaderStyle> </asp:TemplateField> </Columns> <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" /> <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" /> <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" /> <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" /> </asp:GridView> </div> <div class="register mart22"> <%--<asp:Label ID="lblError" runat="server" Text=" ForeColor="green"></asp:Label>--%> <asp:Label ID="lblMessage" runat="server" Text="" ForeColor="green"></asp:Label> <br /> <asp:GridView runat="server" ID="gridCauhoi2" AutoGenerateColumns="False" CellPadding="4" Width="679px" AllowPaging="True" OnPageIndexChanging="gridCauhoi2_PageIndexChanging" OnRowCommand="gridCauhoi2_RowCommand" EmptyDataText="Không có dữ liệu!" Visible="False" BackColor="White" PageSize="10" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px"> <RowStyle BackColor="White" ForeColor="#330099" /> <Columns> <asp:TemplateField HeaderText="Mã câu hỏi " HeaderStyle-HorizontalAlign="Left"> <ItemTemplate> <asp:Label runat="server" ID="lblmacauhoi2" Text='<%#DataBinder.Eval(Container.DataItem,"Macauhoi") %>'> </asp:Label> </ItemTemplate> <HeaderStyle HorizontalAlign="Left"></HeaderStyle> </asp:TemplateField> <asp:TemplateField HeaderText="Mã môn học " HeaderStyle-HorizontalAlign="Left"> <ItemTemplate> <asp:Label runat="server" ID="lblmamon2" Text='<%#DataBinder.Eval(Container.DataItem,"Mamonhoc") %>'> </asp:Label> </ItemTemplate> <HeaderStyle HorizontalAlign="Left"></HeaderStyle> </asp:TemplateField> <asp:TemplateField HeaderText="Nội dung" HeaderStyle-HorizontalAlign="Left"> <ItemTemplate> <asp:Label runat="server" ID="lblnd2" Text='<%#DataBinder.Eval(Container.DataItem,"Noidung") %>'> </asp:Label> </ItemTemplate> <HeaderStyle HorizontalAlign="Left"></HeaderStyle> </asp:TemplateField> <asp:TemplateField HeaderText="Đáp án A " HeaderStyle-HorizontalAlign="Left"> <ItemTemplate> <asp:Label runat="server" ID="lblDokhoC2" Text='<%#DataBinder.Eval(Container.DataItem,"DapanA") %>'> </asp:Label> </ItemTemplate> <HeaderStyle HorizontalAlign="Left"></HeaderStyle> </asp:TemplateField> <asp:TemplateField HeaderText="Đáp án B" HeaderStyle-HorizontalAlign="Left"> <ItemTemplate> <asp:Label runat="server" ID="lblsl2" Text='<%#DataBinder.Eval(Container.DataItem,"DapanB") %>'> </asp:Label> </ItemTemplate> <HeaderStyle HorizontalAlign="Left"></HeaderStyle> </asp:TemplateField> <asp:TemplateField HeaderText="Đáp án C" HeaderStyle-HorizontalAlign="Left"> <ItemTemplate> <asp:Label runat="server" ID="lbls2" Text='<%#DataBinder.Eval(Container.DataItem,"DapanC") %>'> </asp:Label> </ItemTemplate> <HeaderStyle HorizontalAlign="Left"></HeaderStyle> </asp:TemplateField> <asp:TemplateField HeaderText="Đáp án D" HeaderStyle-HorizontalAlign="Left"> <ItemTemplate> <asp:Label runat="server" ID="lbls3" Text='<%#DataBinder.Eval(Container.DataItem,"DapanD") %>'> </asp:Label> </ItemTemplate> <HeaderStyle HorizontalAlign="Left"></HeaderStyle> </asp:TemplateField> <asp:TemplateField HeaderText="Đáp án đúng" HeaderStyle-HorizontalAlign="Left"> <ItemTemplate> <asp:Label runat="server" ID="lbls4" Text='<%#DataBinder.Eval(Container.DataItem,"Phuongandung") %>'> </asp:Label> </ItemTemplate> <HeaderStyle HorizontalAlign="Left"></HeaderStyle> </asp:TemplateField> <asp:TemplateField HeaderText="Sửa" HeaderStyle-HorizontalAlign="Left"> <ItemTemplate> <asp:ImageButton runat="server" ID="img_suach2" CommandName="sua2" Visible="true" CommandArgument='<%#DataBinder.Eval(Container.DataItem,"Macauhoi") %>' ImageUrl="~/icon/edit_profile.png" /> </ItemTemplate> <HeaderStyle HorizontalAlign="Left"></HeaderStyle> </asp:TemplateField> <asp:TemplateField HeaderText="Xóa" HeaderStyle-HorizontalAlign="Left"> <ItemTemplate> <asp:ImageButton runat="server" ID="img_xoach2" CommandName="xoa2" Visible="true" CommandArgument='<%#DataBinder.Eval(Container.DataItem,"Macauhoi") %>' ImageUrl="~/icon/delete_user.png" /> </ItemTemplate> <HeaderStyle HorizontalAlign="Left"></HeaderStyle> </asp:TemplateField> </Columns> <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" /> <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" /> <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" /> <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" /> </asp:GridView> </div> <asp:Panel ID="pnSua" runat="server" Visible="false"> <div class="register mart22"> <div class="label"> <asp:Label ID="Label1" runat="server" Text="Mã câu hỏi "></asp:Label></div> <div class="text_box"> <asp:TextBox ID="txtMacauhoi" runat="server" Enabled="False" ></asp:TextBox> </div> </div> <div class="register mart22"> <div class="label"> <asp:Label ID="lblMach" runat="server" Text="Mã môn học"></asp:Label> </div> <div class="text_box"> <asp:DropDownList ID="drMonhoc2" runat="server" Width="180px"> </asp:DropDownList><br /> </div> </div> <div class="register mart22"> <div class="label"> <asp:Label ID="lblDokho" runat="server" Text="Độ khó"></asp:Label></div> <div class="text_box"> <asp:DropDownList ID="drDokho" Width="128px" runat="server"> <asp:ListItem Selected="True">1</asp:ListItem> <asp:ListItem>2</asp:ListItem> <asp:ListItem>3</asp:ListItem> </asp:DropDownList> </div> </div> <div class="register mart22"> <div class="label"> <asp:Label ID="Label21" runat="server" Text="Chương"></asp:Label></div> <div class="text_box"> <asp:DropDownList ID="drChuong" Width="128px" runat="server"> <asp:ListItem Selected="True">1</asp:ListItem> <asp:ListItem>2</asp:ListItem> <asp:ListItem>3</asp:ListItem> <asp:ListItem>4</asp:ListItem> <asp:ListItem>5</asp:ListItem> <asp:ListItem>6</asp:ListItem> <asp:ListItem>7</asp:ListItem> <asp:ListItem>8</asp:ListItem> <asp:ListItem>9</asp:ListItem> <asp:ListItem>10</asp:ListItem> </asp:DropDownList> </div> </div> <div class="register mart22"> <div class="label"> <asp:Label ID="Label25" runat="server" Text="Hình ảnh"></asp:Label></div> <div class="text_box"> <asp:FileUpload ID="upHinhAnh" runat="server"></asp:FileUpload> <div class="label"> <asp:Label ID="lblUpanh" runat="server"></asp:Label></div> </div> </div> <div class="register mart22"> <div class="label"> <asp:Label ID="lblCauhoi" runat="server" Text="Nội dung"></asp:Label></div> <div class="text_box2"> <asp:TextBox ID="txtNoidung" runat="server" TextMode="MultiLine" Width="355px"></asp:TextBox> </div> </div> <div class="register mart22"> <div class="label"> <asp:Label ID="lblDapanA" runat="server" Text="Đáp án A" ></asp:Label> </div> <div class="text_box"> <asp:TextBox ID="txtDapanA" runat="server" TextMode="MultiLine" Width="355px"></asp:TextBox><br /> </div> </div> <div class="register mart22"> <div class="label"> <asp:Label ID="lblDapanB" runat="server" Text="Đáp án B"></asp:Label> </div> <div class="text_box"> <asp:TextBox ID="txtDapanB" runat="server" TextMode="MultiLine" Width="355px"></asp:TextBox><br /> </div> </div> <div class="register mart22"> <div class="label"> <asp:Label ID="lblDapanC" runat="server" Text="Đáp án C"></asp:Label> </div> <div class="text_box"> <asp:TextBox ID="txtDapanC" runat="server" TextMode="MultiLine" Width="355px"></asp:TextBox><br /> </div> </div> <div class="register mart22"> <div class="label"> <asp:Label ID="lblDapanD" runat="server" Text="Đáp án D" Width="355px"></asp:Label> </div> <div class="text_box"> <asp:TextBox ID="txtDapanD" runat="server" TextMode="MultiLine" Width="355px"></asp:TextBox><br /> </div> </div> <div class="register mart22"> <div class="label"> <asp:Label ID="lblDapandung" runat="server" Text="Đáp án đúng" ></asp:Label> </div> <div class="text_box"> <asp:TextBox ID="txtDapandung" runat="server" TextMode="MultiLine" Width="355px"></asp:TextBox><br /> </div> </div> <div class="register mart22"> <asp:Button ID="btLuu" runat="server" Text="Sửa" OnClick="btSua_Click" ValidationGroup="test" /> <asp:Button ID="btHuy" runat="server" Text="Hủy" OnClick="btHuy_Click" /> </div> </asp:Panel> <asp:Panel ID="pnThem" runat="server" Visible="false"> <div class="register mart22"> <div class="label"> <asp:Label ID="Label3" runat="server" Text="Mã môn học"></asp:Label> </div> <div class="text_box"> <asp:DropDownList ID="drMonhoc3" runat="server" Width="180px"> </asp:DropDownList><br /> </div> </div> <div class="register mart22"> <div class="label"> <asp:Label ID="Label4" runat="server" Text="Độ khó"></asp:Label></div> <div class="text_box"> <asp:DropDownList ID="drDokho2" Width="128px" runat="server"> <asp:ListItem Selected="True">1</asp:ListItem> <asp:ListItem>2</asp:ListItem> <asp:ListItem>3</asp:ListItem> </asp:DropDownList> </div> </div> <div class="register mart22"> <div class="label"> <asp:Label ID="Label5" runat="server" Text="Chương"></asp:Label></div> <div class="text_box"> <asp:DropDownList ID="drChuong2" Width="128px" runat="server"> <asp:ListItem Selected="True">1</asp:ListItem> <asp:ListItem>2</asp:ListItem> <asp:ListItem>3</asp:ListItem> <asp:ListItem>4</asp:ListItem> <asp:ListItem>5</asp:ListItem> <asp:ListItem>6</asp:ListItem> <asp:ListItem>7</asp:ListItem> <asp:ListItem>8</asp:ListItem> <asp:ListItem>9</asp:ListItem> <asp:ListItem>10</asp:ListItem> </asp:DropDownList> </div> </div> <div class="register mart22"> <div class="label"> <asp:Label ID="Label6" runat="server" Text="Hình ảnh"></asp:Label></div> <div class="text_box"> <asp:FileUpload ID="upHinhanh2" runat="server"></asp:FileUpload> </div> </div> <div class="register mart22"> <div class="label"> <asp:Label ID="Label7" runat="server" Text="Nội dung"></asp:Label></div> <div class="text_box2"> <asp:TextBox ID="txtNoidung2" runat="server" TextMode="MultiLine" Width="355px"></asp:TextBox> </div> </div> <div class="register mart22"> <div class="label"> <asp:Label ID="lblDapanA2" runat="server" Text="Đáp án A" ></asp:Label> </div> <div class="text_box"> <asp:TextBox ID="txtDapanA2" runat="server" TextMode="MultiLine" Width="355px"></asp:TextBox><br /> </div> </div> <div class="register mart22"> <div class="label"> <asp:Label ID="Label9" runat="server" Text="Đáp án B"></asp:Label> </div> <div class="text_box"> <asp:TextBox ID="txtDapanB2" runat="server" TextMode="MultiLine" Width="355px"></asp:TextBox><br /> </div> </div> <div class="register mart22"> <div class="label"> <asp:Label ID="Label10" runat="server" Text="Đáp án C"></asp:Label> </div> <div class="text_box"> <asp:TextBox ID="txtDapanC2" runat="server" TextMode="MultiLine" Width="355px"></asp:TextBox><br /> </div> </div> <div class="register mart22"> <div class="label"> <asp:Label ID="Label11" runat="server" Text="Đáp án D" Width="355px"></asp:Label> </div> <div class="text_box"> <asp:TextBox ID="txtDapanD2" runat="server" TextMode="MultiLine" Width="355px"></asp:TextBox><br /> </div> </div> <div class="register mart22"> <div class="label"> <asp:Label ID="Label12" runat="server" Text="Đáp án đúng" ></asp:Label> </div> <div class="text_box"> <asp:TextBox ID="txtDapandung2" runat="server" TextMode="MultiLine" Width="355px"></asp:TextBox><br /> </div> </div> <div class="register mart22"> <asp:Button ID="Button1" runat="server" Text="Thêm" OnClick="btThem_Click" ValidationGroup="test" /> <asp:Button ID="Button2" runat="server" Text="Hủy" OnClick="btHuy_Click2" /> </div> </asp:Panel> </div> </div> </div> </asp:Content>
08b2-doan
trunk/Source/DoAn/DOAN/Admin/QL_Cauhoi.aspx
ASP.NET
gpl3
32,468
<%@ Application Language="C#" %> <%@ Import Namespace="System.IO" %> <script runat="server"> void Application_Start(object sender, EventArgs e) { // Code that runs on application startup Application["OnlineUsers"] = 0; } void Application_End(object sender, EventArgs e) { // Code that runs on application shutdown Application.Lock(); Application["OnlineUsers"] = (int)Application["OnlineUsers"] - 1; Application.UnLock(); } void Application_Error(object sender, EventArgs e) { // Code that runs when an unhandled error occurs } void Session_Start(object sender, EventArgs e) { // Code that runs when a new session is started Session["MaTK"] = null; Application.Lock(); Application["OnlineUsers"] = (int)Application["OnlineUsers"] + 1; Application.UnLock(); int count_visit = 0; //Kiểm tra file count_visit.txt nếu không tồn tại thì if (System.IO.File.Exists(Server.MapPath("count_visit.txt")) == false) { count_visit = 1; } // Ngược lại thì else { // Đọc dử liều từ file count_visit.txt System.IO.StreamReader read = new System.IO.StreamReader(Server.MapPath("count_visit.txt")); count_visit = int.Parse(read.ReadLine()); read.Close(); // Tăng biến count_visit thêm 1 count_visit++; } // khóa website Application.Lock(); // gán biến Application count_visit Application["count_visit"] = count_visit; // Mở khóa website Application.UnLock(); // Lưu dử liệu vào file count_visit.txt System.IO.StreamWriter writer = new System.IO.StreamWriter(Server.MapPath("count_visit.txt")); writer.WriteLine(count_visit); writer.Close(); } void Session_End(object sender, EventArgs e) { // Code that runs when a session ends. // Note: The Session_End event is raised only when the sessionstate mode // is set to InProc in the Web.config file. If session mode is set to StateServer // or SQLServer, the event is not raised. Application.Lock(); Application["OnlineUsers"] = (int)Application["OnlineUsers"] - 1; Application.UnLock(); } </script>
08b2-doan
trunk/Source/DoAn/DOAN/Global.asax
ASP.NET
gpl3
2,628
using System.Reflection; using System.Runtime.CompilerServices; using 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. [assembly: AssemblyTitle("DOAN")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DOAN")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3d5900ae-111a-45be-96b3-d9e4606ca793")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
08b2-doan
trunk/Source/DoAn/DOAN/Properties/AssemblyInfo.cs
C#
gpl3
1,379
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Xml.Linq; using DOAN.DO; using DOAN.BL; namespace DOAN { public partial class DoiMK : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (Session["Tendangnhap"] == null) Response.Redirect("Dangnhap.aspx"); } } protected void btn_Click(object sender, EventArgs e) { if (txtmk2.Text == txtmk3.Text) { string s = Session["Tendangnhap"].ToString(); ThanhvienDO obj = new ThanhvienBL().Select(new ThanhvienDO { Tentaikhoan = s }); if (obj.Matkhau == txtmk.Text) { obj.Matkhau = txtmk2.Text; int kq = new ThanhvienBL().Update(obj); if (kq != 0) { ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Có lỗi xảy ra, vui lòng thử lại!');", true); } else { Response.Write("<script>alert('Đổi thanh cong')</script>"); //Response.Redirect("Default.aspx"); } } else ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Mật khẩu cũ không đúng!');", true); } else { Label4.Text = "Hai Mật khẩu ko khớp"; } } } }
08b2-doan
trunk/Source/DoAn/DOAN/DoiMK.aspx.cs
C#
gpl3
1,947
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; namespace DOAN { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } } }
08b2-doan
trunk/Source/DoAn/DOAN/Default.aspx.cs
C#
gpl3
499
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Thi.aspx.cs" Inherits="DOAN.Thi" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <br /> <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br /> <br /> <asp:Label ID="Label2" runat="server" Text="0" Visible="false"></asp:Label> <br /> <asp:Panel ID="Panel1" runat="server"> <b>Đáp án</b><br /> <table style="width: 100%;"> <tr> <td> <asp:RadioButton ID="RadioButton1" GroupName="grda" runat="server" /> </td> <td> <asp:RadioButton ID="RadioButton2" GroupName="grda" runat="server" /> </td> </tr> <tr> <td> <asp:RadioButton ID="RadioButton3" GroupName="grda" runat="server" /> </td> <td> <asp:RadioButton ID="RadioButton4" GroupName="grda" runat="server" /> </td> </tr> </table> <br /> <center><asp:Button ID="Button1" runat="server" Text="Trả lời" onclick="Button1_Click" /></center> </asp:Panel> <br /> </div> <asp:Label ID="Label3" runat="server" Text="Label" Visible="false"></asp:Label> </form> </body> </html>
08b2-doan
trunk/Source/DoAn/DOAN/Thi.aspx
ASP.NET
gpl3
1,660
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Xml.Linq; using DOAN.DO; using DOAN.BL; namespace DOAN { public partial class Lambai : System.Web.UI.Page { public double seconds; protected void Page_Load(object sender, EventArgs e) { seconds = 1 * 60; loadMon(); } public void loadMon() { MonhocDO obj = new MonhocDO(); DataTable dt = new MonhocBL().SelectAll(); if (dt.Rows.Count > 0) { drpMon.DataSource = dt; drpMon.DataTextField = "Tenmon"; drpMon.DataValueField = "Mamonhoc"; drpMon.DataBind(); } } public string getid() { return txtmade.Text; } public string getmon() { return drpMon.Text; } public int getthoigian() { DethiDO obj = new DethiBL().Select(new DethiDO { Madethi = int.Parse(txtmade.Text) }); return obj.Thoigian; } protected void btn_Click(object sender, EventArgs e) { Literal1.Text = "<iframe src='Thi.aspx?MaDT=<%=getid()%>&Cau=1' id='thi' width='600' height='400'></iframe>"; } } }
08b2-doan
trunk/Source/DoAn/DOAN/Lambai.aspx.cs
C#
gpl3
1,594
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Xml.Linq; using DOAN.DO; using DOAN.BL; namespace DOAN { public partial class ThiTracNghiem : System.Web.UI.Page { public double seconds; protected void Page_Load(object sender, EventArgs e) { seconds = 1 * 60; loadMon(); } public void loadMon() { MonhocDO obj = new MonhocDO(); DataTable dt = new MonhocBL().SelectAll(); if (dt.Rows.Count > 0) { drpMon.DataSource = dt; drpMon.DataTextField = "Tenmon"; drpMon.DataValueField = "Mamonhoc"; drpMon.DataBind(); } } public string getid() { return txtmade.Text; } public string getmon() { return drpMon.Text; } public int getthoigian() { DethiDO obj = new DethiBL().Select(new DethiDO { Madethi = int.Parse(txtmade.Text) }); return obj.Thoigian; } protected void btn_Click(object sender, EventArgs e) { Response.Redirect("Lambai.aspx?MaDT=2&Cau=2"); } } }
08b2-doan
trunk/Source/DoAn/DOAN/ThiTracNghiem.aspx.cs
C#
gpl3
1,537
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="home2.aspx.cs" Inherits="DOAN.home2" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> </div> </form> </body> </html>
08b2-doan
trunk/Source/DoAn/DOAN/home2.aspx
ASP.NET
gpl3
447
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DOAN._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> </div> </form> </body> </html>
08b2-doan
trunk/Source/DoAn/DOAN/Default.aspx
ASP.NET
gpl3
452
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Xml.Linq; using System.Timers; using DOAN.DO; using DOAN.BL; namespace DOAN { public partial class Baithi : System.Web.UI.Page { string dad = ""; string datl = ""; public double seconds; protected void Page_Load(object sender, EventArgs e) { seconds = 1 * 60; if (!IsPostBack) { lblLoi.Text = ""; loadMon(); } } public void loadMon() { drpMon.DataSource = new MonhocBL().SelectAll(); drpMon.DataTextField = "Tenmon"; drpMon.DataValueField = "Mamonhoc"; drpMon.DataBind(); } private string getcauhoi(int id) { return new DethiBL().SelectDeThi(new DethiDO { Madethi = id }, Session["Tendangnhap"].ToString()).Macauhoi; } public BailamDO init() { BailamDO obj = new BailamDO(); obj.Madethi = int.Parse(txtma.Text); obj.Ngaythi = DateTime.Now.ToShortDateString(); obj.Tentaikhoan = Session["Tendangnhap"].ToString(); return obj; } protected void btoke_Click(object sender, EventArgs e) { BailamDO objBailam = init(); btXemdapan.Visible = true; for (int i = 0; i < dtCauhoi.Items.Count; i++) { string tem = ""; RadioButton rdA = (RadioButton)dtCauhoi.Items[i].FindControl("Rd1"); RadioButton rdB = (RadioButton)dtCauhoi.Items[i].FindControl("Rd2"); RadioButton rdC = (RadioButton)dtCauhoi.Items[i].FindControl("Rd3"); RadioButton rdD = (RadioButton)dtCauhoi.Items[i].FindControl("Rd4"); if (rdA.Checked == true) tem = "A-"; else if (rdB.Checked == true) tem = "B-"; else if (rdC.Checked == true) tem = "C-"; else tem = "D-"; datl += tem; } objBailam.Traloi = datl; string[] separator = new string[] { "-" }; string[] tl = datl.Split(separator, StringSplitOptions.RemoveEmptyEntries); string[] da = Session["DAD"].ToString().Split(separator, StringSplitOptions.RemoveEmptyEntries); int socaudung = 0; for (int j = 0; j < da.Length; j++) { if (tl[j] == da[j]) { socaudung++; } } lbda.Text = "Dap an dung:" + Session["DAD"].ToString() + "&&& Dap an tra loi: " + datl; lblTT_Socaudung.Text = "<span style='color:Red;' ><b><i>" + socaudung.ToString() + "</i></b></span>"; lblTT_Sodiem.Text = "<span style='color:Red;' ><b><i>" + (float)(socaudung* (100) / da.Length) + "</i></b></span>"; objBailam.Tongdiem = (double)(socaudung * (100) / da.Length); new BailamBL().Insert(objBailam); btNopbai.Visible = false; Timer1.Enabled = false; btbegin.Visible = true; } protected void btbegin_Click(object sender, EventArgs e) { pnTT.Visible = true; pnthi.Visible = true; if (Session["Tendangnhap"] != null) { ThanhvienDO obj = new ThanhvienBL().Select(new ThanhvienDO { Tentaikhoan = Session["Tendangnhap"].ToString() }); lblTT_hoten.Text = "<span style='color:Red;' ><b><i>" + obj.Hovaten+"</i></b></span>"; } else { Response.Redirect("Dangnhap.aspx"); //lblTT_hoten.Text = "<span style='color:Red;' >Khach</span>"; } lblTT_monthi.Text = drpMon.SelectedItem.Text; try { string macauhoi = getcauhoi(int.Parse(txtma.Text)); DethiDO objDeThi = new DethiBL().SelectDeThi(new DethiDO { Madethi = int.Parse(txtma.Text) }, Session["Tendangnhap"].ToString()); lbTG.Text = "<b>Tuhoi gian: </b>" + objDeThi.Thoigian.ToString(); seconds = Convert.ToDouble(int.Parse(objDeThi.Thoigian.ToString())*60); Timer1.Enabled = true; Timer1.Interval = Convert.ToInt32(int.Parse(objDeThi.Thoigian.ToString()) * 60)*1000; //Timer1.s DataTable dt = new CauhoiBL().GetCH(macauhoi); for (int i = 0; i < dt.Rows.Count; i++) { dad += dt.Rows[i].ItemArray[11].ToString() + "-"; } if (dt.Rows.Count > 0) { dtCauhoi.DataSource = dt; dtCauhoi.DataBind(); } Session["DAD"] = dad; btNopbai.Visible = true; btbegin.Visible = false; } catch (Exception eee) { lblLoi.Text = "Ma de thi ko chinh xac hoặc bạn đã làm đề thi này!"; } } protected void Timer1_Tick(object sender, EventArgs e) { btoke_Click(sender, e); } //void timer1_elapse(whatever obj, whatever args) //{ // response.write("It has been 10 seconds, firing now"); // Timer1.stop(); // will stop the timer, so it will not execute every 10 seconds. //} } }
08b2-doan
trunk/Source/DoAn/DOAN/Baithi.aspx.cs
C#
gpl3
6,013
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; namespace DOAN { public partial class TrangChu : System.Web.UI.MasterPage { protected void Page_Load(object sender, EventArgs e) { } protected void LinkButton1_Click(object sender, EventArgs e) { Response.Redirect("Dangnhap.aspx"); } // protected void LinkButton2_Click(object sender, EventArgs e) //{ // Response.Redirect("Dangky.aspx"); //} protected void lbThoat_Click(object sender, EventArgs e) { Session["Tendangnhap"] = ""; LinkButton1.Visible = true; //lbDangky.Visible = true; lblDnthanhcong.Visible = false; lbThoat.Visible = false; lbtendn.Visible = false; } } }
08b2-doan
trunk/Source/DoAn/DOAN/TrangChu.Master.cs
C#
gpl3
1,127
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using DOAN.DO; using DOAN.BL; namespace DOAN { public partial class Thi : System.Web.UI.Page { int socau; int maDT; string[] traloi = new string[200]; string dad = ""; protected void Page_Load(object sender, EventArgs e) { if (Session["TraLoiDung"] == null) { Session["TraLoiDung"] = 0; } if (Request.QueryString["MaDT"].ToString() != null) { string s = Request.QueryString["MaDT"].ToString(); maDT = int.Parse(s); Session["MaDT"] = maDT; int a = getsocauhoi(maDT); Label2.Text = a.ToString(); socau = int.Parse(Request.QueryString["Cau"]); string macauhoi = getcauhoi(maDT); string[] separator = new string[] { "-" }; string[] maCH = macauhoi.Split(separator, StringSplitOptions.RemoveEmptyEntries); foreach (string ma in maCH) { DataTable dt = new CauhoiBL().Select2(new CauhoiDO { Macauhoi = int.Parse(ma) }); if (dt.Rows.Count != 0) { Panel1.Visible = true; Label1.Text = "<b>Câu hỏi " + socau + ": </b>" + dt.Rows[0].ItemArray[2].ToString(); RadioButton1.Text = dt.Rows[0].ItemArray[7].ToString(); RadioButton2.Text = dt.Rows[0].ItemArray[8].ToString(); RadioButton3.Text = dt.Rows[0].ItemArray[9].ToString(); RadioButton4.Text = dt.Rows[0].ItemArray[10].ToString(); dad = dt.Rows[0].ItemArray[11].ToString() + "-"; } else { Panel1.Visible = false; Label1.Text = "De thi hien tai chua co cau hoi"; } } } } private int getsocauhoi(int id) { return new DethiBL().Select(new DethiDO { Madethi = id }).Socau; } private string getcauhoi(int id) { return new DethiBL().Select(new DethiDO { Madethi = id }).Macauhoi; } private void nextch() { socau = socau + 1; string url = string.Format("Thi.aspx?MaDT={0}&Cau={1}", maDT, socau.ToString()); if (socau == int.Parse(Label2.Text) + 1) { Response.Redirect("thongbao1.aspx"); } else { Response.Redirect(url); } } protected void Button1_Click(object sender, EventArgs e) { if (RadioButton1.Checked) { if (RadioButton1.Text == Label3.Text) { Session["TraLoiDung"] = Convert.ToInt32(Session["TraLoiDung"]) + 1; Response.Write(Session["TraLoiDung"].ToString()); } } if (RadioButton2.Checked) { if (RadioButton2.Text == Label3.Text) { Session["TraLoiDung"] = Convert.ToInt32(Session["TraLoiDung"]) + 1; Response.Write(Session["TraLoiDung"].ToString()); } } if (RadioButton3.Checked) { if (RadioButton3.Text == Label3.Text) { Session["TraLoiDung"] = Convert.ToInt32(Session["TraLoiDung"]) + 1; Response.Write(Session["TraLoiDung"].ToString()); } } if (RadioButton4.Checked) { if (RadioButton4.Text == Label3.Text) { Session["TraLoiDung"] = Convert.ToInt32(Session["TraLoiDung"]) + 1; Response.Write(Session["TraLoiDung"].ToString()); } } nextch(); } } }
08b2-doan
trunk/Source/DoAn/DOAN/Thi.aspx.cs
C#
gpl3
4,516
<%@ Page Language="C#" MasterPageFile="~/TrangChu.Master" AutoEventWireup="true" CodeBehind="Lambai.aspx.cs" Inherits="DOAN.Lambai" Title="Untitled Page" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server"> <meta http-equiv="refresh" content="<%=seconds%>;url=thongbao.aspx"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server"> <asp:DropDownList ID="drpMon" runat="server"></asp:DropDownList><br /> <asp:TextBox ID="txtmade" runat="server"></asp:TextBox> <asp:Button ID="btn" runat="server" Text="Bat Dau" onclick="btn_Click" /> <table style="width: 100%;"> <tr> <td> Bài thi môn : <b><%=getmon() %></b> </td> <td> Mã đề thi : <b><%=getid() %></b> </td> <td> <div id="timelabel"> </div> </td> </tr> </table> <script type="text/javascript"> var leave =<%=seconds %>; CounterTimer(); var interv=setInterval(CounterTimer,1000); function CounterTimer() { if(leave==0) { alert("thoi gian da het"); } else{ var day = Math.floor(leave / ( 60 * 60 * 24)) var hour = Math.floor(leave / 3600)-(day * 24) var minute = Math.floor(leave / 60)- (day * 24 *60)-(hour * 60) var second = Math.floor(leave)-(day * 24 *60*60)- (hour * 60 * 60)-(minute*60) hour=hour<10 ? "0" + hour : hour; minute=minute<10 ? "0"+ minute : minute; second=second<10 ? "0" + second : second; var remain=hour + ":"+minute+":"+second; leave=leave-1; document.getElementById("timelabel").innerHTML="<b>Thời gian:</b>" +remain; } } //Test </script> <center> <asp:Literal id="Literal1" runat="server"></asp:Literal> <br /> <iframe src="Thi.aspx?MaDT=<%=getid() %>&Cau=1" id="thi" width="600" height="400"></iframe> </center> </asp:Content>
08b2-doan
trunk/Source/DoAn/DOAN/Lambai.aspx
ASP.NET
gpl3
2,206
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Xml.Linq; using DOAN.DO; using DOAN.BL; namespace DOAN { public partial class home : System.Web.UI.Page { public void Page_Load(object sender, EventArgs e) { if (Session["Tendangnhap"] != null) { MasterPage mt = this.Master as MasterPage; LinkButton lb = mt.FindControl("LinkButton1") as LinkButton; lb.Visible = false; Label bl = mt.FindControl("lblDnthanhcong") as Label; bl.Visible = true; Label blten = mt.FindControl("lbtendn") as Label; blten.Visible = true; blten.Text = Session["Tendangnhap"].ToString(); LinkButton lbDangky = mt.FindControl("lbDangky") as LinkButton; //lbDangky.Visible = false; LinkButton lbthoat = mt.FindControl("lbThoat") as LinkButton; lbthoat.Visible = true; LoadData(); } //string sql = "Select *,Left(Tieude,50) as 'TomTat' from Thongbao"; //rptNoidungkhac.DataSource = Database.GetData(sql); //rptNoidungkhac.DataBind(); } public void LoadData() { DataTable dt = new ThongbaoBL().SelectAll(); if (dt.Rows.Count > 0) { //rpt.DataSource = dt; //rpt.DataBind(); rptNoidungkhac.DataSource = dt; rptNoidungkhac.DataBind(); } } } }
08b2-doan
trunk/Source/DoAn/DOAN/home.aspx.cs
C#
gpl3
1,867
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Data; using System.Configuration; using System.Collections; using DOAN.DAL; using DOAN.DO; /// <summary> /// Summary description for ThongbaoBL /// </summary> namespace DOAN.BL { public class ThongbaoBL { #region Private Variables ThongbaoDAL objThongbaoDAL; #endregion #region Public Constructors public ThongbaoBL() { // // TODO: Add constructor logic here // objThongbaoDAL=new ThongbaoDAL(); } #endregion #region Public Methods public int Insert(ThongbaoDO objThongbaoDO) { return objThongbaoDAL.Insert(objThongbaoDO); } public int Update(ThongbaoDO objThongbaoDO) { return objThongbaoDAL.Update(objThongbaoDO); } public int Delete(ThongbaoDO objThongbaoDO) { return objThongbaoDAL.Delete(objThongbaoDO); } public int DeleteAll() { return objThongbaoDAL.DeleteAll(); } public ThongbaoDO Select(ThongbaoDO objThongbaoDO) { return objThongbaoDAL.Select(objThongbaoDO); } public ArrayList SelectAll1( ) { return objThongbaoDAL.SelectAll1(); } public DataTable SelectAll( ) { return objThongbaoDAL.SelectAll(); } public DataTable SelectAll2() { return objThongbaoDAL.SelectAll2(); } public DataTable TimKiem(int tt, string nd) { return objThongbaoDAL.TimKiem(tt,nd); } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.BL/ThongbaoBL.cs
C#
gpl3
1,917
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Data; using System.Configuration; using System.Collections; using DOAN.DAL; using DOAN.DO; /// <summary> /// Summary description for ThanhvienBL /// </summary> namespace DOAN.BL { public class ThanhvienBL { #region Private Variables ThanhvienDAL objThanhvienDAL; #endregion #region Public Constructors public ThanhvienBL() { // // TODO: Add constructor logic here // objThanhvienDAL=new ThanhvienDAL(); } #endregion #region Public Methods public int Insert(ThanhvienDO objThanhvienDO) { return objThanhvienDAL.Insert(objThanhvienDO); } public int Update(ThanhvienDO objThanhvienDO) { return objThanhvienDAL.Update(objThanhvienDO); } public DataTable GetGV() { return objThanhvienDAL.GetGV(); } public DataTable GetTV() { return objThanhvienDAL.GetTV(); } public int Delete(ThanhvienDO objThanhvienDO) { return objThanhvienDAL.Delete(objThanhvienDO); } public int DeleteAll() { return objThanhvienDAL.DeleteAll(); } public ThanhvienDO Login(string tk,string mk) { return objThanhvienDAL.login(tk,mk); } public DataTable Select2(ThanhvienDO objThanhvienDO) { return objThanhvienDAL.Select2(objThanhvienDO); } public ThanhvienDO Select(ThanhvienDO objThanhvienDO) { return objThanhvienDAL.Select(objThanhvienDO); } public DataTable SelectByEmail(string email) { return objThanhvienDAL.SelectByEmail(email); } public ArrayList SelectAll1( ) { return objThanhvienDAL.SelectAll1(); } public DataTable SelectAll( ) { return objThanhvienDAL.SelectAll(); } #endregion public DataTable TimKiem(int tt, string tk) { return objThanhvienDAL.TimKiem(tt, tk); } public DataTable GetAllLop() { return objThanhvienDAL.GetAllLop(); } public ThanhvienDO SelectobjByEmail(string email) { return objThanhvienDAL.SelectobjByEmail(email); } public DataTable SelectByLop(string lop) { return objThanhvienDAL.SelectByLop(lop); } } }
08b2-doan
trunk/Source/DoAn/DOAN.BL/ThanhvienBL.cs
C#
gpl3
2,835
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Data; using System.Configuration; using System.Collections; using DOAN.DAL; using DOAN.DO; /// <summary> /// Summary description for CT_DethiBL /// </summary> namespace DOAN.BL { public class CT_DethiBL { #region Private Variables CT_DethiDAL objCT_DethiDAL; #endregion #region Public Constructors public CT_DethiBL() { // // TODO: Add constructor logic here // objCT_DethiDAL=new CT_DethiDAL(); } #endregion #region Public Methods public int Insert(CT_DethiDO objCT_DethiDO) { return objCT_DethiDAL.Insert(objCT_DethiDO); } public int Update(CT_DethiDO objCT_DethiDO) { return objCT_DethiDAL.Update(objCT_DethiDO); } public int Delete(CT_DethiDO objCT_DethiDO) { return objCT_DethiDAL.Delete(objCT_DethiDO); } public int DeleteAll() { return objCT_DethiDAL.DeleteAll(); } public CT_DethiDO Select(CT_DethiDO objCT_DethiDO) { return objCT_DethiDAL.Select(objCT_DethiDO); } public ArrayList SelectAll1( ) { return objCT_DethiDAL.SelectAll1(); } public DataTable SelectAll( ) { return objCT_DethiDAL.SelectAll(); } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.BL/CT_DethiBL.cs
C#
gpl3
1,679
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Data; using System.Configuration; using System.Collections; using DOAN.DAL; using DOAN.DO; /// <summary> /// Summary description for PhanquyenBL /// </summary> namespace DOAN.BL { public class PhanquyenBL { #region Private Variables PhanquyenDAL objPhanquyenDAL; #endregion #region Public Constructors public PhanquyenBL() { // // TODO: Add constructor logic here // objPhanquyenDAL=new PhanquyenDAL(); } #endregion #region Public Methods public int Insert(PhanquyenDO objPhanquyenDO) { return objPhanquyenDAL.Insert(objPhanquyenDO); } public int Update(PhanquyenDO objPhanquyenDO) { return objPhanquyenDAL.Update(objPhanquyenDO); } public int Delete(PhanquyenDO objPhanquyenDO) { return objPhanquyenDAL.Delete(objPhanquyenDO); } public int DeleteAll() { return objPhanquyenDAL.DeleteAll(); } public PhanquyenDO Select(PhanquyenDO objPhanquyenDO) { return objPhanquyenDAL.Select(objPhanquyenDO); } public ArrayList SelectAll1( ) { return objPhanquyenDAL.SelectAll1(); } public DataTable SelectAll( ) { return objPhanquyenDAL.SelectAll(); } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.BL/PhanquyenBL.cs
C#
gpl3
1,706
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Data; using System.Configuration; using System.Collections; using DOAN.DAL; using DOAN.DO; /// <summary> /// Summary description for MonhocBL /// </summary> namespace DOAN.BL { public class MonhocBL { #region Private Variables MonhocDAL objMonhocDAL; #endregion #region Public Constructors public MonhocBL() { // // TODO: Add constructor logic here // objMonhocDAL=new MonhocDAL(); } #endregion #region Public Methods public int Insert(MonhocDO objMonhocDO) { return objMonhocDAL.Insert(objMonhocDO); } public object GetSoChuong(string mon) { return objMonhocDAL.GetSoChuong(mon); } public int Update(MonhocDO objMonhocDO) { return objMonhocDAL.Update(objMonhocDO); } public int Delete(MonhocDO objMonhocDO) { return objMonhocDAL.Delete(objMonhocDO); } public int DeleteAll() { return objMonhocDAL.DeleteAll(); } public MonhocDO Select(MonhocDO objMonhocDO) { return objMonhocDAL.Select(objMonhocDO); } public ArrayList SelectAll1( ) { return objMonhocDAL.SelectAll1(); } public DataTable TimKiem(int tt,string tk) { return objMonhocDAL.TimKiem(tt,tk); } public DataTable SelectAllDistiny() { return objMonhocDAL.SelectAllDistiny(); } public DataTable SelectAll( ) { return objMonhocDAL.SelectAll(); } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.BL/MonhocBL.cs
C#
gpl3
1,986
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Data; using System.Configuration; using System.Collections; using DOAN.DAL; using DOAN.DO; /// <summary> /// Summary description for CT_BailamBL /// </summary> namespace DOAN.BL { public class CT_BailamBL { #region Private Variables CT_BailamDAL objCT_BailamDAL; #endregion #region Public Constructors public CT_BailamBL() { // // TODO: Add constructor logic here // objCT_BailamDAL=new CT_BailamDAL(); } #endregion #region Public Methods public int Insert(CT_BailamDO objCT_BailamDO) { return objCT_BailamDAL.Insert(objCT_BailamDO); } public int Update(CT_BailamDO objCT_BailamDO) { return objCT_BailamDAL.Update(objCT_BailamDO); } public int Delete(CT_BailamDO objCT_BailamDO) { return objCT_BailamDAL.Delete(objCT_BailamDO); } public int DeleteAll() { return objCT_BailamDAL.DeleteAll(); } public CT_BailamDO Select(CT_BailamDO objCT_BailamDO) { return objCT_BailamDAL.Select(objCT_BailamDO); } public ArrayList SelectAll1( ) { return objCT_BailamDAL.SelectAll1(); } public DataTable SelectAll( ) { return objCT_BailamDAL.SelectAll(); } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.BL/CT_BailamBL.cs
C#
gpl3
1,706
using System.Reflection; using System.Runtime.CompilerServices; using 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. [assembly: AssemblyTitle("DOAN.BL")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DOAN.BL")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("62b1944d-9b2e-4068-8ccb-aa2848aea006")] // 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")]
08b2-doan
trunk/Source/DoAn/DOAN.BL/Properties/AssemblyInfo.cs
C#
gpl3
1,426
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Data; using System.Configuration; using System.Collections; using DOAN.DAL; using DOAN.DO; /// <summary> /// Summary description for BailamBL /// </summary> namespace DOAN.BL { public class BailamBL { #region Private Variables BailamDAL objBailamDAL; #endregion #region Public Constructors public BailamBL() { // // TODO: Add constructor logic here // objBailamDAL=new BailamDAL(); } #endregion #region Public Methods public int Insert(BailamDO objBailamDO) { return objBailamDAL.Insert(objBailamDO); } public int Update(BailamDO objBailamDO) { return objBailamDAL.Update(objBailamDO); } public int Delete(BailamDO objBailamDO) { return objBailamDAL.Delete(objBailamDO); } public int DeleteAll() { return objBailamDAL.DeleteAll(); } public BailamDO Select(BailamDO objBailamDO) { return objBailamDAL.Select(objBailamDO); } public ArrayList SelectAll1( ) { return objBailamDAL.SelectAll1(); } public DataTable SelectAll( ) { return objBailamDAL.SelectAll(); } #endregion public DataTable GetByMonAndNgay(string mamon,string lop, string dat) { return objBailamDAL.GetByMonAndNgay(mamon,lop, dat); } } }
08b2-doan
trunk/Source/DoAn/DOAN.BL/BailamBL.cs
C#
gpl3
1,794
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Data; using System.Configuration; using System.Collections; using DOAN.DAL; using DOAN.DO; /// <summary> /// Summary description for YkienBL /// </summary> namespace DOAN.BL { public class YkienBL { #region Private Variables YkienDAL objYkienDAL; #endregion #region Public Constructors public YkienBL() { // // TODO: Add constructor logic here // objYkienDAL=new YkienDAL(); } #endregion #region Public Methods public int Insert(YkienDO objYkienDO) { return objYkienDAL.Insert(objYkienDO); } public int Update(YkienDO objYkienDO) { return objYkienDAL.Update(objYkienDO); } public int Delete(YkienDO objYkienDO) { return objYkienDAL.Delete(objYkienDO); } public int DeleteAll() { return objYkienDAL.DeleteAll(); } public YkienDO Select(YkienDO objYkienDO) { return objYkienDAL.Select(objYkienDO); } public ArrayList SelectAll1( ) { return objYkienDAL.SelectAll1(); } public DataTable SelectAll( ) { return objYkienDAL.SelectAll(); } #endregion public DataTable TimKiem(int tt, string tk) { return objYkienDAL.TimKiem(tt, tk); } } }
08b2-doan
trunk/Source/DoAn/DOAN.BL/YkienBL.cs
C#
gpl3
1,724
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Data; using System.Configuration; using System.Collections; using DOAN.DAL; using DOAN.DO; /// <summary> /// Summary description for CT_MonhocBL /// </summary> namespace DOAN.BL { public class CT_MonhocBL { #region Private Variables CT_MonhocDAL objCT_MonhocDAL; #endregion #region Public Constructors public CT_MonhocBL() { // // TODO: Add constructor logic here // objCT_MonhocDAL=new CT_MonhocDAL(); } #endregion #region Public Methods public int Insert(CT_MonhocDO objCT_MonhocDO) { return objCT_MonhocDAL.Insert(objCT_MonhocDO); } public DataTable GetAllByUser(string tk) { return objCT_MonhocDAL.GetAllByUser(tk); } public DataTable GetByUser(string tk) { return objCT_MonhocDAL.GetByUser(tk); } public DataTable GetByMon(string tk) { return objCT_MonhocDAL.GetByMon(tk); } public int Update(CT_MonhocDO objCT_MonhocDO) { return objCT_MonhocDAL.Update(objCT_MonhocDO); } public int Delete(CT_MonhocDO objCT_MonhocDO) { return objCT_MonhocDAL.Delete(objCT_MonhocDO); } public DataTable Timkiem(string tk) { return objCT_MonhocDAL.Timkiem(tk); } public int DeleteAll() { return objCT_MonhocDAL.DeleteAll(); } public CT_MonhocDO Select(CT_MonhocDO objCT_MonhocDO) { return objCT_MonhocDAL.Select(objCT_MonhocDO); } public ArrayList SelectAll1( ) { return objCT_MonhocDAL.SelectAll1(); } public DataTable SelectAll( ) { return objCT_MonhocDAL.SelectAll(); } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.BL/CT_MonhocBL.cs
C#
gpl3
2,184
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DOAN.BL { public class Class1 { } }
08b2-doan
trunk/Source/DoAn/DOAN.BL/Class1.cs
C#
gpl3
159
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Data; using System.Configuration; using System.Collections; using DOAN.DAL; using DOAN.DO; /// <summary> /// Summary description for DethiBL /// </summary> namespace DOAN.BL { public class DethiBL { #region Private Variables DethiDAL objDethiDAL; #endregion #region Public Constructors public DethiBL() { // // TODO: Add constructor logic here // objDethiDAL=new DethiDAL(); } #endregion #region Public Methods public int Insert(DethiDO objDethiDO) { return objDethiDAL.Insert(objDethiDO); } public int Update(DethiDO objDethiDO) { return objDethiDAL.Update(objDethiDO); } public DataTable GetByMonAndUser(string suser, string mamon) { return objDethiDAL.GetByMonAndUser(suser, mamon); } public DataTable GetByMon(string mamon) { return objDethiDAL.GetByMon(mamon); } public int Delete(DethiDO objDethiDO) { return objDethiDAL.Delete(objDethiDO); } public int DeleteAll() { return objDethiDAL.DeleteAll(); } public DethiDO Select(DethiDO objDethiDO) { return objDethiDAL.Select(objDethiDO); } public DethiDO SelectDeThi(DethiDO objDethiDO, string Tentaikhoan) { return objDethiDAL.SelectDeThi(objDethiDO, Tentaikhoan); } public ArrayList SelectAll1( ) { return objDethiDAL.SelectAll1(); } public DataTable SelectAll( ) { return objDethiDAL.SelectAll(); } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.BL/DethiBL.cs
C#
gpl3
2,049
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Data; using System.Configuration; using System.Collections; using System.Data.SqlClient; using DOAN.DO; /// <summary> /// Summary description for CT_BailamDAL /// </summary> namespace DOAN.DAL { public class CT_BailamDAL : BaseDAL { #region Private Variables #endregion #region Public Constructors public CT_BailamDAL() { // // TODO: Add constructor logic here // } #endregion #region Public Methods public int Insert(CT_BailamDO objCT_BailamDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCT_Bailam_Insert"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Mabailam", SqlDbType.VarChar); Sqlparam.Value = objCT_BailamDO.Mabailam; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Macauhoi", SqlDbType.VarChar); Sqlparam.Value = objCT_BailamDO.Macauhoi; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@PAChon", SqlDbType.NVarChar); Sqlparam.Value = objCT_BailamDO.PAChon; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@ID", SqlDbType.Int); Sqlparam.Direction = ParameterDirection.ReturnValue; Sqlcomm.Parameters.Add(Sqlparam); int result =base.ExecuteNoneQuery(Sqlcomm); if(!Convert.IsDBNull(Sqlcomm.Parameters["@ID"])) result = Convert.ToInt32(Sqlcomm.Parameters["@ID"].Value); return result; } public int Update(CT_BailamDO objCT_BailamDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCT_Bailam_UpdateByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Mabailam", SqlDbType.VarChar); Sqlparam.Value = objCT_BailamDO.Mabailam; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Macauhoi", SqlDbType.VarChar); Sqlparam.Value = objCT_BailamDO.Macauhoi; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@PAChon", SqlDbType.NVarChar); Sqlparam.Value = objCT_BailamDO.PAChon; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@ErrorCode", SqlDbType.Int); Sqlparam.Direction = ParameterDirection.ReturnValue; Sqlcomm.Parameters.Add(Sqlparam); int result=base.ExecuteNoneQuery(Sqlcomm); if (!Convert.IsDBNull(Sqlcomm.Parameters["@ErrorCode"])) result = Convert.ToInt32(Sqlcomm.Parameters["@ErrorCode"].Value); return result; } public int Delete(CT_BailamDO objCT_BailamDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCT_Bailam_DeleteByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Mabailam", SqlDbType.VarChar); Sqlparam.Value = objCT_BailamDO.Mabailam; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Macauhoi", SqlDbType.VarChar); Sqlparam.Value = objCT_BailamDO.Macauhoi; Sqlcomm.Parameters.Add(Sqlparam); int result=base.ExecuteNoneQuery(Sqlcomm); return result; } public int DeleteAll() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCT_Bailam_DeleteAll"; int result=base.ExecuteNoneQuery(Sqlcomm); return result; } public CT_BailamDO Select(CT_BailamDO objCT_BailamDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCT_Bailam_GetByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Mabailam", SqlDbType.VarChar); Sqlparam.Value = objCT_BailamDO.Mabailam; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Macauhoi", SqlDbType.VarChar); Sqlparam.Value = objCT_BailamDO.Macauhoi; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataRow dr = null; if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { dr = ds.Tables[0].Rows[0]; if(!Convert.IsDBNull(dr["Mabailam"])) objCT_BailamDO.Mabailam=Convert.ToString(dr["Mabailam"]); if(!Convert.IsDBNull(dr["Macauhoi"])) objCT_BailamDO.Macauhoi=Convert.ToString(dr["Macauhoi"]); if(!Convert.IsDBNull(dr["PAChon"])) objCT_BailamDO.PAChon=Convert.ToString(dr["PAChon"]); } return objCT_BailamDO; } public ArrayList SelectAll1( ) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCT_Bailam_GetAll"; DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; ArrayList arrCT_BailamDO = new ArrayList(); if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; foreach(DataRow dr in dt.Rows) { CT_BailamDO objCT_BailamDO= new CT_BailamDO(); if(!Convert.IsDBNull(dr["Mabailam"])) objCT_BailamDO.Mabailam=Convert.ToString(dr["Mabailam"]); if(!Convert.IsDBNull(dr["Macauhoi"])) objCT_BailamDO.Macauhoi=Convert.ToString(dr["Macauhoi"]); if(!Convert.IsDBNull(dr["PAChon"])) objCT_BailamDO.PAChon=Convert.ToString(dr["PAChon"]); arrCT_BailamDO.Add(objCT_BailamDO); } } return arrCT_BailamDO; } public DataTable SelectAll( ) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCT_Bailam_GetAll"; DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; } return dt; } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.BL/CT_BailamDAL.cs
C#
gpl3
6,795
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Data; using System.Configuration; using System.Collections; using DOAN.DAL; using DOAN.DO; /// <summary> /// Summary description for CauhoiBL /// </summary> namespace DOAN.BL { public class CauhoiBL { #region Private Variables CauhoiDAL objCauhoiDAL; #endregion #region Public Constructors public CauhoiBL() { // // TODO: Add constructor logic here // objCauhoiDAL=new CauhoiDAL(); } #endregion #region Public Methods public int Insert(CauhoiDO objCauhoiDO) { return objCauhoiDAL.Insert(objCauhoiDO); } public DataTable TaoDe(string mon, int kho, int tb, int de) { return objCauhoiDAL.TaoDe(mon, kho, tb, de); } public DataTable TaoDe2(string mon, int c1, int c2, int c3, int c4, int c5, int c6, int c7, int c8, int c9, int c10) { return objCauhoiDAL.TaoDe2(mon, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10); } public DataTable GetByMon(string s) { return objCauhoiDAL.GetByMon(s); } public int Update(CauhoiDO objCauhoiDO) { return objCauhoiDAL.Update(objCauhoiDO); } public DataTable GetCH(string s) { return objCauhoiDAL.GetCH(s); } public int Delete(CauhoiDO objCauhoiDO) { return objCauhoiDAL.Delete(objCauhoiDO); } public DataTable timkiem(string tk) { return objCauhoiDAL.Timkiem(tk); } public int DeleteAll() { return objCauhoiDAL.DeleteAll(); } public CauhoiDO Select(CauhoiDO objCauhoiDO) { return objCauhoiDAL.Select(objCauhoiDO); } public DataTable Select2(CauhoiDO objCauhoiDO) { return objCauhoiDAL.Select2(objCauhoiDO); } public ArrayList SelectAll1( ) { return objCauhoiDAL.SelectAll1(); } public DataTable SelectAll( ) { return objCauhoiDAL.SelectAll(); } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.BL/CauhoiBL.cs
C#
gpl3
2,485
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Collections; namespace DOAN.DO { [Serializable ] public class MonhocDO { /// <summary> /// Summary description for MonhocDO /// </summary> #region Public Constants (Fields name) public const string MAMONHOC_FIELD ="Mamonhoc"; public const string TENMON_FIELD ="Tenmon"; public const string SOCHUONG_FIELD ="Sochuong"; #endregion #region Private Variables private String _Mamonhoc; private String _Tenmon; private String _Sochuong; #endregion #region Public Properties public String Mamonhoc { get { return _Mamonhoc; } set { _Mamonhoc = value; } } public String Tenmon { get { return _Tenmon; } set { _Tenmon = value; } } public String Sochuong { get { return _Sochuong; } set { _Sochuong = value; } } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.DO/MonhocDO.cs
C#
gpl3
1,090
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Collections; namespace DOAN.DO { [Serializable ] public class DethiDO { /// <summary> /// Summary description for DethiDO /// </summary> #region Public Constants (Fields name) public const string MADETHI_FIELD ="Madethi"; public const string MAMONHOC_FIELD ="Mamonhoc"; public const string MACAUHOI_FIELD ="Macauhoi"; public const string TIEUDE_FIELD ="Tieude"; public const string SOCAU_FIELD ="Socau"; public const string SODIEM_FIELD ="Sodiem"; public const string THOIGIAN_FIELD ="Thoigian"; public const string NGAYTAO_FIELD ="Ngaytao"; public const string TENTAIKHOAN_FIELD ="Tentaikhoan"; public const string TRANGTHAI_FIELD ="Trangthai"; #endregion #region Private Variables private Int32 _Madethi; private String _Mamonhoc; private String _Macauhoi; private String _Tieude; private Int32 _Socau; private Double _Sodiem; private Int32 _Thoigian; private String _Ngaytao; private String _Tentaikhoan; private Boolean _Trangthai; #endregion #region Public Properties public Int32 Madethi { get { return _Madethi; } set { _Madethi = value; } } public String Mamonhoc { get { return _Mamonhoc; } set { _Mamonhoc = value; } } public String Macauhoi { get { return _Macauhoi; } set { _Macauhoi = value; } } public String Tieude { get { return _Tieude; } set { _Tieude = value; } } public Int32 Socau { get { return _Socau; } set { _Socau = value; } } public Double Sodiem { get { return _Sodiem; } set { _Sodiem = value; } } public Int32 Thoigian { get { return _Thoigian; } set { _Thoigian = value; } } public String Ngaytao { get { return _Ngaytao; } set { _Ngaytao = value; } } public String Tentaikhoan { get { return _Tentaikhoan; } set { _Tentaikhoan = value; } } public Boolean Trangthai { get { return _Trangthai; } set { _Trangthai = value; } } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.DO/DethiDO.cs
C#
gpl3
2,532
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Collections; namespace DOAN.DO { [Serializable ] public class CT_BailamDO { /// <summary> /// Summary description for CT_BailamDO /// </summary> #region Public Constants (Fields name) public const string MABAILAM_FIELD ="Mabailam"; public const string MACAUHOI_FIELD ="Macauhoi"; public const string PACHON_FIELD ="PAChon"; #endregion #region Private Variables private String _Mabailam; private String _Macauhoi; private String _PAChon; #endregion #region Public Properties public String Mabailam { get { return _Mabailam; } set { _Mabailam = value; } } public String Macauhoi { get { return _Macauhoi; } set { _Macauhoi = value; } } public String PAChon { get { return _PAChon; } set { _PAChon = value; } } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.DO/CT_BailamDO.cs
C#
gpl3
1,096
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Collections; namespace DOAN.DO { [Serializable ] public class CauhoiDO { /// <summary> /// Summary description for CauhoiDO /// </summary> #region Public Constants (Fields name) public const string MACAUHOI_FIELD ="Macauhoi"; public const string MAMONHOC_FIELD ="Mamonhoc"; public const string NOIDUNG_FIELD ="Noidung"; public const string DOKHO_FIELD ="Dokho"; public const string CHUONG_FIELD ="Chuong"; public const string IMAGE_FIELD ="Image"; public const string VIDEO_FIELD ="Video"; public const string DAPANA_FIELD ="DapanA"; public const string DAPANB_FIELD ="DapanB"; public const string DAPANC_FIELD ="DapanC"; public const string DAPAND_FIELD ="DapanD"; public const string PHUONGANDUNG_FIELD ="Phuongandung"; #endregion #region Private Variables private Int32 _Macauhoi; private String _Mamonhoc; private String _Noidung; private Int32 _Dokho; private Int32 _Chuong; private String _Image; private String _Video; private String _DapanA; private String _DapanB; private String _DapanC; private String _DapanD; private String _Phuongandung; #endregion #region Public Properties public Int32 Macauhoi { get { return _Macauhoi; } set { _Macauhoi = value; } } public String Mamonhoc { get { return _Mamonhoc; } set { _Mamonhoc = value; } } public String Noidung { get { return _Noidung; } set { _Noidung = value; } } public Int32 Dokho { get { return _Dokho; } set { _Dokho = value; } } public Int32 Chuong { get { return _Chuong; } set { _Chuong = value; } } public String Image { get { return _Image; } set { _Image = value; } } public String Video { get { return _Video; } set { _Video = value; } } public String DapanA { get { return _DapanA; } set { _DapanA = value; } } public String DapanB { get { return _DapanB; } set { _DapanB = value; } } public String DapanC { get { return _DapanC; } set { _DapanC = value; } } public String DapanD { get { return _DapanD; } set { _DapanD = value; } } public String Phuongandung { get { return _Phuongandung; } set { _Phuongandung = value; } } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.DO/CauhoiDO.cs
C#
gpl3
2,710
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Collections; namespace DOAN.DO { [Serializable ] public class CT_DethiDO { /// <summary> /// Summary description for CT_DethiDO /// </summary> #region Public Constants (Fields name) public const string ID_FIELD ="ID"; public const string MADETHI_FIELD ="Madethi"; public const string MACAUHOI_FIELD ="Macauhoi"; #endregion #region Private Variables private Int32 _ID; private Int32 _Madethi; private Int32 _Macauhoi; #endregion #region Public Properties public Int32 ID { get { return _ID; } set { _ID = value; } } public Int32 Madethi { get { return _Madethi; } set { _Madethi = value; } } public Int32 Macauhoi { get { return _Macauhoi; } set { _Macauhoi = value; } } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.DO/CT_DethiDO.cs
C#
gpl3
1,058
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Collections; namespace DOAN.DO { [Serializable ] public class PhanquyenDO { /// <summary> /// Summary description for PhanquyenDO /// </summary> #region Public Constants (Fields name) public const string MAQUYEN_FIELD ="Maquyen"; public const string MOTA_FIELD ="Mota"; #endregion #region Private Variables private String _Maquyen; private String _Mota; #endregion #region Public Properties public String Maquyen { get { return _Maquyen; } set { _Maquyen = value; } } public String Mota { get { return _Mota; } set { _Mota = value; } } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.DO/PhanquyenDO.cs
C#
gpl3
888
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Collections; namespace DOAN.DO { [Serializable ] public class ThongbaoDO { /// <summary> /// Summary description for ThongbaoDO /// </summary> #region Public Constants (Fields name) public const string ID_FIELD ="ID"; public const string TENTB_FIELD ="TenTB"; public const string ND_FIELD ="ND"; #endregion #region Private Variables private Int32 _ID; private String _TenTB; private String _ND; #endregion #region Public Properties public Int32 ID { get { return _ID; } set { _ID = value; } } public String TenTB { get { return _TenTB; } set { _TenTB = value; } } public String ND { get { return _ND; } set { _ND = value; } } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.DO/ThongbaoDO.cs
C#
gpl3
1,014
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Collections; namespace DOAN.DO { [Serializable ] public class ThanhvienDO { /// <summary> /// Summary description for ThanhvienDO /// </summary> #region Public Constants (Fields name) public const string TENTAIKHOAN_FIELD ="Tentaikhoan"; public const string MAQUYEN_FIELD ="Maquyen"; public const string MATKHAU_FIELD ="Matkhau"; public const string EMAIL_FIELD ="Email"; public const string SODIENTHOAI_FIELD ="Sodienthoai"; public const string HOVATEN_FIELD ="Hovaten"; public const string NGAYSINH_FIELD ="Ngaysinh"; public const string GIOITINH_FIELD ="Gioitinh"; public const string LOP_FIELD ="Lop"; #endregion #region Private Variables private String _Tentaikhoan; private String _Maquyen; private String _Matkhau; private String _Email; private String _Sodienthoai; private String _Hovaten; private String _Ngaysinh; private Int32 _Gioitinh; private String _Lop; #endregion #region Public Properties public String Tentaikhoan { get { return _Tentaikhoan; } set { _Tentaikhoan = value; } } public String Maquyen { get { return _Maquyen; } set { _Maquyen = value; } } public String Matkhau { get { return _Matkhau; } set { _Matkhau = value; } } public String Email { get { return _Email; } set { _Email = value; } } public String Sodienthoai { get { return _Sodienthoai; } set { _Sodienthoai = value; } } public String Hovaten { get { return _Hovaten; } set { _Hovaten = value; } } public String Ngaysinh { get { return _Ngaysinh; } set { _Ngaysinh = value; } } public Int32 Gioitinh { get { return _Gioitinh; } set { _Gioitinh = value; } } public String Lop { get { return _Lop; } set { _Lop = value; } } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.DO/ThanhvienDO.cs
C#
gpl3
2,216
using System.Reflection; using System.Runtime.CompilerServices; using 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. [assembly: AssemblyTitle("DOAN.DO")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DOAN.DO")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ead1381e-dbff-4534-aa50-785d5606b8e0")] // 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")]
08b2-doan
trunk/Source/DoAn/DOAN.DO/Properties/AssemblyInfo.cs
C#
gpl3
1,426
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DOAN.DO { public class Class1 { } }
08b2-doan
trunk/Source/DoAn/DOAN.DO/Class1.cs
C#
gpl3
159
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Collections; namespace DOAN.DO { [Serializable ] public class CT_MonhocDO { /// <summary> /// Summary description for CT_MonhocDO /// </summary> #region Public Constants (Fields name) public const string ID_FIELD ="ID"; public const string MAMONHOC_FIELD ="Mamonhoc"; public const string TENTAIKHOAN_FIELD ="Tentaikhoan"; #endregion #region Private Variables private Int32 _ID; private String _Mamonhoc; private String _Tentaikhoan; #endregion #region Public Properties public Int32 ID { get { return _ID; } set { _ID = value; } } public String Mamonhoc { get { return _Mamonhoc; } set { _Mamonhoc = value; } } public String Tentaikhoan { get { return _Tentaikhoan; } set { _Tentaikhoan = value; } } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.DO/CT_MonhocDO.cs
C#
gpl3
1,088
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Collections; namespace DOAN.DO { [Serializable ] public class BailamDO { /// <summary> /// Summary description for BailamDO /// </summary> #region Public Constants (Fields name) public const string MABAILAM_FIELD ="Mabailam"; public const string MADETHI_FIELD ="Madethi"; public const string TRALOI_FIELD ="Traloi"; public const string TONGDIEM_FIELD ="Tongdiem"; public const string NGAYTHI_FIELD ="Ngaythi"; public const string TENTAIKHOAN_FIELD ="Tentaikhoan"; #endregion #region Private Variables private Int32 _Mabailam; private Int32 _Madethi; private String _Traloi; private Double _Tongdiem; private String _Ngaythi; private String _Tentaikhoan; #endregion #region Public Properties public Int32 Mabailam { get { return _Mabailam; } set { _Mabailam = value; } } public Int32 Madethi { get { return _Madethi; } set { _Madethi = value; } } public String Traloi { get { return _Traloi; } set { _Traloi = value; } } public Double Tongdiem { get { return _Tongdiem; } set { _Tongdiem = value; } } public String Ngaythi { get { return _Ngaythi; } set { _Ngaythi = value; } } public String Tentaikhoan { get { return _Tentaikhoan; } set { _Tentaikhoan = value; } } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.DO/BailamDO.cs
C#
gpl3
1,662
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Collections; namespace DOAN.DO { [Serializable ] public class YkienDO { /// <summary> /// Summary description for YkienDO /// </summary> #region Public Constants (Fields name) public const string MAYKIEN_FIELD ="Maykien"; public const string TENTAIKHOAN_FIELD ="Tentaikhoan"; public const string NOIDUNG_FIELD ="Noidung"; public const string EMAIL_FIELD ="Email"; #endregion #region Private Variables private Int32 _Maykien; private String _Tentaikhoan; private String _Noidung; private String _Email; #endregion #region Public Properties public Int32 Maykien { get { return _Maykien; } set { _Maykien = value; } } public String Tentaikhoan { get { return _Tentaikhoan; } set { _Tentaikhoan = value; } } public String Noidung { get { return _Noidung; } set { _Noidung = value; } } public String Email { get { return _Email; } set { _Email = value; } } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.DO/YkienDO.cs
C#
gpl3
1,276
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Data; using System.Configuration; using System.Collections; using System.Data.SqlClient; using DOAN.DO; /// <summary> /// Summary description for CT_MonhocDAL /// </summary> namespace DOAN.DAL { public class CT_MonhocDAL : BaseDAL { #region Private Variables #endregion #region Public Constructors public CT_MonhocDAL() { // // TODO: Add constructor logic here // } #endregion #region Public Methods public int Insert(CT_MonhocDO objCT_MonhocDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCT_Monhoc_Insert"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Mamonhoc", SqlDbType.VarChar); Sqlparam.Value = objCT_MonhocDO.Mamonhoc; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Tentaikhoan", SqlDbType.VarChar); Sqlparam.Value = objCT_MonhocDO.Tentaikhoan; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@ID", SqlDbType.Int); Sqlparam.Direction = ParameterDirection.ReturnValue; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); if (!Convert.IsDBNull(Sqlcomm.Parameters["@ID"])) result = Convert.ToInt32(Sqlcomm.Parameters["@ID"].Value); return result; } public int Update(CT_MonhocDO objCT_MonhocDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCT_Monhoc_UpdateByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@ID", SqlDbType.Int); Sqlparam.Value = objCT_MonhocDO.ID; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Mamonhoc", SqlDbType.VarChar); Sqlparam.Value = objCT_MonhocDO.Mamonhoc; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Tentaikhoan", SqlDbType.VarChar); Sqlparam.Value = objCT_MonhocDO.Tentaikhoan; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@ErrorCode", SqlDbType.Int); Sqlparam.Direction = ParameterDirection.ReturnValue; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); if (!Convert.IsDBNull(Sqlcomm.Parameters["@ErrorCode"])) result = Convert.ToInt32(Sqlcomm.Parameters["@ErrorCode"].Value); return result; } public DataTable GetByMon(string tk) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCauHoi_GetByMon"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Mamon", SqlDbType.NChar); Sqlparam.Value = tk; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; } return dt; } public DataTable Timkiem(string tk) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCT_Monhoc_Tim"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Mamon", SqlDbType.NChar); Sqlparam.Value = tk; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; } return dt; } public DataTable GetAllByUser(string tk) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "sp_CT_Monhoc_GetAll"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@user", SqlDbType.NChar); Sqlparam.Value = tk; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; } return dt; } public DataTable GetByUser(string tk) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "sp_CT_Monhoc_GetByUser"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@user", SqlDbType.NChar); Sqlparam.Value = tk; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; } return dt; } public int Delete(CT_MonhocDO objCT_MonhocDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCT_Monhoc_DeleteByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@ID", SqlDbType.Int); Sqlparam.Value = objCT_MonhocDO.ID; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); return result; } public int DeleteAll() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCT_Monhoc_DeleteAll"; int result = base.ExecuteNoneQuery(Sqlcomm); return result; } public CT_MonhocDO Select(CT_MonhocDO objCT_MonhocDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCT_Monhoc_GetByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@ID", SqlDbType.Int); Sqlparam.Value = objCT_MonhocDO.ID; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataRow dr = null; if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { dr = ds.Tables[0].Rows[0]; if (!Convert.IsDBNull(dr["ID"])) objCT_MonhocDO.ID = Convert.ToInt32(dr["ID"]); if (!Convert.IsDBNull(dr["Mamonhoc"])) objCT_MonhocDO.Mamonhoc = Convert.ToString(dr["Mamonhoc"]); if (!Convert.IsDBNull(dr["Tentaikhoan"])) objCT_MonhocDO.Tentaikhoan = Convert.ToString(dr["Tentaikhoan"]); } return objCT_MonhocDO; } public ArrayList SelectAll1() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCT_Monhoc_GetAll"; DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; ArrayList arrCT_MonhocDO = new ArrayList(); if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; foreach (DataRow dr in dt.Rows) { CT_MonhocDO objCT_MonhocDO = new CT_MonhocDO(); if (!Convert.IsDBNull(dr["ID"])) objCT_MonhocDO.ID = Convert.ToInt32(dr["ID"]); if (!Convert.IsDBNull(dr["Mamonhoc"])) objCT_MonhocDO.Mamonhoc = Convert.ToString(dr["Mamonhoc"]); if (!Convert.IsDBNull(dr["Tentaikhoan"])) objCT_MonhocDO.Tentaikhoan = Convert.ToString(dr["Tentaikhoan"]); arrCT_MonhocDO.Add(objCT_MonhocDO); } } return arrCT_MonhocDO; } public DataTable SelectAll() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCT_Monhoc_GetAll"; DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; } return dt; } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.DAL/CT_MonhocDAL.cs
C#
gpl3
9,400
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Data; using System.Configuration; using System.Collections; using System.Data.SqlClient; using DOAN.DO; /// <summary> /// Summary description for YkienDAL /// </summary> namespace DOAN.DAL { public class YkienDAL : BaseDAL { #region Private Variables #endregion #region Public Constructors public YkienDAL() { // // TODO: Add constructor logic here // } #endregion #region Public Methods public int Insert(YkienDO objYkienDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spYkien_Insert"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Tentaikhoan", SqlDbType.VarChar); Sqlparam.Value = objYkienDO.Tentaikhoan; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Noidung", SqlDbType.NVarChar); Sqlparam.Value = objYkienDO.Noidung; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Email", SqlDbType.VarChar); Sqlparam.Value = objYkienDO.Email; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@ID", SqlDbType.Int); Sqlparam.Direction = ParameterDirection.ReturnValue; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); if (!Convert.IsDBNull(Sqlcomm.Parameters["@ID"])) result = Convert.ToInt32(Sqlcomm.Parameters["@ID"].Value); return result; } public int Update(YkienDO objYkienDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spYkien_UpdateByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Maykien", SqlDbType.Int); Sqlparam.Value = objYkienDO.Maykien; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Tentaikhoan", SqlDbType.VarChar); Sqlparam.Value = objYkienDO.Tentaikhoan; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Noidung", SqlDbType.NVarChar); Sqlparam.Value = objYkienDO.Noidung; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Email", SqlDbType.VarChar); Sqlparam.Value = objYkienDO.Email; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@ErrorCode", SqlDbType.Int); Sqlparam.Direction = ParameterDirection.ReturnValue; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); if (!Convert.IsDBNull(Sqlcomm.Parameters["@ErrorCode"])) result = Convert.ToInt32(Sqlcomm.Parameters["@ErrorCode"].Value); return result; } public int Delete(YkienDO objYkienDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spYkien_DeleteByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Maykien", SqlDbType.Int); Sqlparam.Value = objYkienDO.Maykien; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); return result; } public int DeleteAll() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spYkien_DeleteAll"; int result = base.ExecuteNoneQuery(Sqlcomm); return result; } public YkienDO Select(YkienDO objYkienDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spYkien_GetByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Maykien", SqlDbType.Int); Sqlparam.Value = objYkienDO.Maykien; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataRow dr = null; if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { dr = ds.Tables[0].Rows[0]; if (!Convert.IsDBNull(dr["Maykien"])) objYkienDO.Maykien = Convert.ToInt32(dr["Maykien"]); if (!Convert.IsDBNull(dr["Tentaikhoan"])) objYkienDO.Tentaikhoan = Convert.ToString(dr["Tentaikhoan"]); if (!Convert.IsDBNull(dr["Noidung"])) objYkienDO.Noidung = Convert.ToString(dr["Noidung"]); if (!Convert.IsDBNull(dr["Email"])) objYkienDO.Email = Convert.ToString(dr["Email"]); } return objYkienDO; } public ArrayList SelectAll1() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spYkien_GetAll"; DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; ArrayList arrYkienDO = new ArrayList(); if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; foreach (DataRow dr in dt.Rows) { YkienDO objYkienDO = new YkienDO(); if (!Convert.IsDBNull(dr["Maykien"])) objYkienDO.Maykien = Convert.ToInt32(dr["Maykien"]); if (!Convert.IsDBNull(dr["Tentaikhoan"])) objYkienDO.Tentaikhoan = Convert.ToString(dr["Tentaikhoan"]); if (!Convert.IsDBNull(dr["Noidung"])) objYkienDO.Noidung = Convert.ToString(dr["Noidung"]); if (!Convert.IsDBNull(dr["Email"])) objYkienDO.Email = Convert.ToString(dr["Email"]); arrYkienDO.Add(objYkienDO); } } return arrYkienDO; } public DataTable SelectAll() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spYkien_GetAll"; DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; } return dt; } public DataTable TimKiem(int tt, string tk) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spYkien_Timkiem"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@tt", SqlDbType.Int); Sqlparam.Value = tt; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Tenmon", SqlDbType.NVarChar); Sqlparam.Value = tk; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; } return dt; } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.DAL/YkienDAL.cs
C#
gpl3
8,029
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Data; using System.Configuration; using System.Collections; using System.Data.SqlClient; using DOAN.DO; /// <summary> /// Summary description for CT_DethiDAL /// </summary> namespace DOAN.DAL { public class CT_DethiDAL : BaseDAL { #region Private Variables #endregion #region Public Constructors public CT_DethiDAL() { // // TODO: Add constructor logic here // } #endregion #region Public Methods public int Insert(CT_DethiDO objCT_DethiDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCT_Dethi_Insert"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Madethi", SqlDbType.Int); Sqlparam.Value = objCT_DethiDO.Madethi; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Macauhoi", SqlDbType.VarChar); Sqlparam.Value = objCT_DethiDO.Macauhoi; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@ID", SqlDbType.Int); Sqlparam.Direction = ParameterDirection.ReturnValue; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); if (!Convert.IsDBNull(Sqlcomm.Parameters["@ID"])) result = Convert.ToInt32(Sqlcomm.Parameters["@ID"].Value); return result; } public int Update(CT_DethiDO objCT_DethiDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCT_Dethi_UpdateByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@ID", SqlDbType.Int); Sqlparam.Value = objCT_DethiDO.ID; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Madethi", SqlDbType.VarChar); Sqlparam.Value = objCT_DethiDO.Madethi; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Macauhoi", SqlDbType.VarChar); Sqlparam.Value = objCT_DethiDO.Macauhoi; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@ErrorCode", SqlDbType.Int); Sqlparam.Direction = ParameterDirection.ReturnValue; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); if (!Convert.IsDBNull(Sqlcomm.Parameters["@ErrorCode"])) result = Convert.ToInt32(Sqlcomm.Parameters["@ErrorCode"].Value); return result; } public int Delete(CT_DethiDO objCT_DethiDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCT_Dethi_DeleteByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@ID", SqlDbType.Int); Sqlparam.Value = objCT_DethiDO.ID; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); return result; } public int DeleteAll() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCT_Dethi_DeleteAll"; int result = base.ExecuteNoneQuery(Sqlcomm); return result; } public CT_DethiDO Select(CT_DethiDO objCT_DethiDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCT_Dethi_GetByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@ID", SqlDbType.Int); Sqlparam.Value = objCT_DethiDO.ID; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataRow dr = null; if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { dr = ds.Tables[0].Rows[0]; if (!Convert.IsDBNull(dr["ID"])) objCT_DethiDO.ID = Convert.ToInt32(dr["ID"]); if (!Convert.IsDBNull(dr["Madethi"])) objCT_DethiDO.Madethi = Convert.ToInt32(dr["Madethi"]); if (!Convert.IsDBNull(dr["Macauhoi"])) objCT_DethiDO.Macauhoi = Convert.ToInt32(dr["Macauhoi"]); } return objCT_DethiDO; } public ArrayList SelectAll1() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCT_Dethi_GetAll"; DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; ArrayList arrCT_DethiDO = new ArrayList(); if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; foreach (DataRow dr in dt.Rows) { CT_DethiDO objCT_DethiDO = new CT_DethiDO(); if (!Convert.IsDBNull(dr["ID"])) objCT_DethiDO.ID = Convert.ToInt32(dr["ID"]); if (!Convert.IsDBNull(dr["Madethi"])) objCT_DethiDO.Madethi = Convert.ToInt32(dr["Madethi"]); if (!Convert.IsDBNull(dr["Macauhoi"])) objCT_DethiDO.Macauhoi = Convert.ToInt32(dr["Macauhoi"]); arrCT_DethiDO.Add(objCT_DethiDO); } } return arrCT_DethiDO; } public DataTable SelectAll() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCT_Dethi_GetAll"; DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; } return dt; } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.DAL/CT_DethiDAL.cs
C#
gpl3
6,641
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Data; using System.Configuration; using System.Collections; using System.Data.SqlClient; using DOAN.DO; /// <summary> /// Summary description for ThongbaoDAL /// </summary> namespace DOAN.DAL { public class ThongbaoDAL : BaseDAL { #region Private Variables #endregion #region Public Constructors public ThongbaoDAL() { // // TODO: Add constructor logic here // } #endregion #region Public Methods public int Insert(ThongbaoDO objThongbaoDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spThongbao_Insert"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@TenTB", SqlDbType.NVarChar); Sqlparam.Value = objThongbaoDO.TenTB; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@ND", SqlDbType.NText); Sqlparam.Value = objThongbaoDO.ND; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@ID", SqlDbType.Int); Sqlparam.Direction = ParameterDirection.ReturnValue; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); if (!Convert.IsDBNull(Sqlcomm.Parameters["@ID"])) result = Convert.ToInt32(Sqlcomm.Parameters["@ID"].Value); return result; } public int Update(ThongbaoDO objThongbaoDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spThongbao_UpdateByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@ID", SqlDbType.Int); Sqlparam.Value = objThongbaoDO.ID; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@TenTB", SqlDbType.NVarChar); Sqlparam.Value = objThongbaoDO.TenTB; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@ND", SqlDbType.NText); Sqlparam.Value = objThongbaoDO.ND; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@ErrorCode", SqlDbType.Int); Sqlparam.Direction = ParameterDirection.ReturnValue; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); if (!Convert.IsDBNull(Sqlcomm.Parameters["@ErrorCode"])) result = Convert.ToInt32(Sqlcomm.Parameters["@ErrorCode"].Value); return result; } public int Delete(ThongbaoDO objThongbaoDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spThongbao_DeleteByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@ID", SqlDbType.Int); Sqlparam.Value = objThongbaoDO.ID; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); return result; } public int DeleteAll() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spThongbao_DeleteAll"; int result = base.ExecuteNoneQuery(Sqlcomm); return result; } public ThongbaoDO Select(ThongbaoDO objThongbaoDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spThongbao_GetByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@ID", SqlDbType.Int); Sqlparam.Value = objThongbaoDO.ID; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataRow dr = null; if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { dr = ds.Tables[0].Rows[0]; if (!Convert.IsDBNull(dr["ID"])) objThongbaoDO.ID = Convert.ToInt32(dr["ID"]); if (!Convert.IsDBNull(dr["TenTB"])) objThongbaoDO.TenTB = Convert.ToString(dr["TenTB"]); if (!Convert.IsDBNull(dr["ND"])) objThongbaoDO.ND = Convert.ToString(dr["ND"]); } return objThongbaoDO; } public ArrayList SelectAll1() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spThongbao_GetAll"; DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; ArrayList arrThongbaoDO = new ArrayList(); if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; foreach (DataRow dr in dt.Rows) { ThongbaoDO objThongbaoDO = new ThongbaoDO(); if (!Convert.IsDBNull(dr["ID"])) objThongbaoDO.ID = Convert.ToInt32(dr["ID"]); if (!Convert.IsDBNull(dr["TenTB"])) objThongbaoDO.TenTB = Convert.ToString(dr["TenTB"]); if (!Convert.IsDBNull(dr["ND"])) objThongbaoDO.ND = Convert.ToString(dr["ND"]); arrThongbaoDO.Add(objThongbaoDO); } } return arrThongbaoDO; } public DataTable SelectAll() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spThongbao_GetAll"; DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; } return dt; } public DataTable SelectAll2() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spThongbao_GetAll2"; DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; } return dt; } public DataTable TimKiem(int tt,string nd) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spThongbao_Timkiem"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@tt", SqlDbType.Int); Sqlparam.Value = tt; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@nd", SqlDbType.NVarChar); Sqlparam.Value = nd; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; } return dt; } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.DAL/ThongbaoDAL.cs
C#
gpl3
7,857
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Data; using System.Configuration; using System.Collections; using System.Data.SqlClient; using DOAN.DO; /// <summary> /// Summary description for CauhoiDAL /// </summary> namespace DOAN.DAL { public class CauhoiDAL : BaseDAL { #region Private Variables #endregion #region Public Constructors public CauhoiDAL() { // // TODO: Add constructor logic here // } #endregion #region Public Methods public int Insert(CauhoiDO objCauhoiDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCauhoi_Insert"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Mamonhoc", SqlDbType.VarChar); Sqlparam.Value = objCauhoiDO.Mamonhoc; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Noidung", SqlDbType.NVarChar); Sqlparam.Value = objCauhoiDO.Noidung; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Dokho", SqlDbType.Int); Sqlparam.Value = objCauhoiDO.Dokho; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Chuong", SqlDbType.Int); Sqlparam.Value = objCauhoiDO.Chuong; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Image", SqlDbType.NVarChar); Sqlparam.Value = objCauhoiDO.Image; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Video", SqlDbType.NVarChar); Sqlparam.Value = objCauhoiDO.Video; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@DapanA", SqlDbType.NVarChar); Sqlparam.Value = objCauhoiDO.DapanA; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@DapanB", SqlDbType.NVarChar); Sqlparam.Value = objCauhoiDO.DapanB; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@DapanC", SqlDbType.NVarChar); Sqlparam.Value = objCauhoiDO.DapanC; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@DapanD", SqlDbType.NVarChar); Sqlparam.Value = objCauhoiDO.DapanD; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Phuongandung", SqlDbType.NVarChar); Sqlparam.Value = objCauhoiDO.Phuongandung; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@ID", SqlDbType.Int); Sqlparam.Direction = ParameterDirection.ReturnValue; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); if (!Convert.IsDBNull(Sqlcomm.Parameters["@ID"])) result = Convert.ToInt32(Sqlcomm.Parameters["@ID"].Value); return result; } public DataTable TaoDe(string mon, int kho, int tb, int de) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCauhoi_Taode"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@mon", SqlDbType.VarChar); Sqlparam.Value = mon; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@kho", SqlDbType.Int); Sqlparam.Value = kho; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@tb", SqlDbType.Int); Sqlparam.Value = tb; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@de", SqlDbType.Int); Sqlparam.Value = de; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = new DataTable(); if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { dt = ds.Tables[0]; } return dt; } public DataTable TaoDe2(string mon, int c1, int c2, int c3, int c4, int c5, int c6, int c7, int c8, int c9, int c10) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCauhoi_Taode2"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@mon", SqlDbType.VarChar); Sqlparam.Value = mon; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@c1", SqlDbType.Int); Sqlparam.Value = c1; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@c2", SqlDbType.Int); Sqlparam.Value = c2; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@c3", SqlDbType.Int); Sqlparam.Value = c3; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@c4", SqlDbType.Int); Sqlparam.Value = c4; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@c5", SqlDbType.Int); Sqlparam.Value = c5; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@c6", SqlDbType.Int); Sqlparam.Value = c6; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@c7", SqlDbType.Int); Sqlparam.Value = c7; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@c8", SqlDbType.Int); Sqlparam.Value = c8; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@c9", SqlDbType.Int); Sqlparam.Value = c9; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@c10", SqlDbType.Int); Sqlparam.Value = c10; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = new DataTable(); if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { dt = ds.Tables[0]; } return dt; } public int Update(CauhoiDO objCauhoiDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCauhoi_UpdateByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Macauhoi", SqlDbType.Int); Sqlparam.Value = objCauhoiDO.Macauhoi; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Mamonhoc", SqlDbType.VarChar); Sqlparam.Value = objCauhoiDO.Mamonhoc; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Noidung", SqlDbType.NVarChar); Sqlparam.Value = objCauhoiDO.Noidung; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Dokho", SqlDbType.Int); Sqlparam.Value = objCauhoiDO.Dokho; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Chuong", SqlDbType.Int); Sqlparam.Value = objCauhoiDO.Chuong; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Image", SqlDbType.NVarChar); Sqlparam.Value = objCauhoiDO.Image; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Video", SqlDbType.NVarChar); Sqlparam.Value = objCauhoiDO.Video; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@DapanA", SqlDbType.NVarChar); Sqlparam.Value = objCauhoiDO.DapanA; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@DapanB", SqlDbType.NVarChar); Sqlparam.Value = objCauhoiDO.DapanB; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@DapanC", SqlDbType.NVarChar); Sqlparam.Value = objCauhoiDO.DapanC; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@DapanD", SqlDbType.NVarChar); Sqlparam.Value = objCauhoiDO.DapanD; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Phuongandung", SqlDbType.NVarChar); Sqlparam.Value = objCauhoiDO.Phuongandung; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@ErrorCode", SqlDbType.Int); Sqlparam.Direction = ParameterDirection.ReturnValue; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); if (!Convert.IsDBNull(Sqlcomm.Parameters["@ErrorCode"])) result = Convert.ToInt32(Sqlcomm.Parameters["@ErrorCode"].Value); return result; } public int Delete(CauhoiDO objCauhoiDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCauhoi_DeleteByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Macauhoi", SqlDbType.Int); Sqlparam.Value = objCauhoiDO.Macauhoi; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); return result; } public int DeleteAll() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCauhoi_DeleteAll"; int result = base.ExecuteNoneQuery(Sqlcomm); return result; } public DataTable Timkiem(string tk) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCauhoi_Timkiem"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@tk", SqlDbType.NVarChar); Sqlparam.Value = tk; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = new DataTable(); if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { dt = ds.Tables[0]; } return dt; } public DataTable GetByMon(string s) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCauHoi_GetByMon"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Mamon", SqlDbType.VarChar); Sqlparam.Value = s; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = new DataTable(); if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { dt = ds.Tables[0]; } return dt; } public DataTable GetCH(string s) { string[] separator = new string[] { "-" }; string[] kq = s.Split(separator, StringSplitOptions.RemoveEmptyEntries); DataTable data = new DataTable(); int i = 1; foreach (string ma in kq) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCauhoi_GetByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Macauhoi", SqlDbType.Int); Sqlparam.Value = int.Parse(ma); Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = new DataTable(); if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { dt = ds.Tables[0]; dt.Columns.Add("STT"); dt.Rows[0].ItemArray[11] = i; i++; } data.Merge(dt); //DataRow dr = null; //if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) //{ // dr = ds.Tables[0].Rows[0]; //} //data.ImportRow(dr); } return data; } public DataTable Select2(CauhoiDO objCauhoiDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCauhoi_GetByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Macauhoi", SqlDbType.Int); Sqlparam.Value = objCauhoiDO.Macauhoi; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = new DataTable(); if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { dt = ds.Tables[0]; } return dt; } public CauhoiDO Select(CauhoiDO objCauhoiDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCauhoi_GetByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Macauhoi", SqlDbType.Int); Sqlparam.Value = objCauhoiDO.Macauhoi; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataRow dr = null; if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { dr = ds.Tables[0].Rows[0]; if (!Convert.IsDBNull(dr["Macauhoi"])) objCauhoiDO.Macauhoi = Convert.ToInt32(dr["Macauhoi"]); if (!Convert.IsDBNull(dr["Mamonhoc"])) objCauhoiDO.Mamonhoc = Convert.ToString(dr["Mamonhoc"]); if (!Convert.IsDBNull(dr["Noidung"])) objCauhoiDO.Noidung = Convert.ToString(dr["Noidung"]); if (!Convert.IsDBNull(dr["Dokho"])) objCauhoiDO.Dokho = Convert.ToInt32(dr["Dokho"]); if (!Convert.IsDBNull(dr["Chuong"])) objCauhoiDO.Chuong = Convert.ToInt32(dr["Chuong"]); if (!Convert.IsDBNull(dr["Image"])) objCauhoiDO.Image = Convert.ToString(dr["Image"]); if (!Convert.IsDBNull(dr["Video"])) objCauhoiDO.Video = Convert.ToString(dr["Video"]); if (!Convert.IsDBNull(dr["DapanA"])) objCauhoiDO.DapanA = Convert.ToString(dr["DapanA"]); if (!Convert.IsDBNull(dr["DapanB"])) objCauhoiDO.DapanB = Convert.ToString(dr["DapanB"]); if (!Convert.IsDBNull(dr["DapanC"])) objCauhoiDO.DapanC = Convert.ToString(dr["DapanC"]); if (!Convert.IsDBNull(dr["DapanD"])) objCauhoiDO.DapanD = Convert.ToString(dr["DapanD"]); if (!Convert.IsDBNull(dr["Phuongandung"])) objCauhoiDO.Phuongandung = Convert.ToString(dr["Phuongandung"]); } return objCauhoiDO; } public ArrayList SelectAll1() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCauhoi_GetAll"; DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; ArrayList arrCauhoiDO = new ArrayList(); if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; foreach (DataRow dr in dt.Rows) { CauhoiDO objCauhoiDO = new CauhoiDO(); if (!Convert.IsDBNull(dr["Macauhoi"])) objCauhoiDO.Macauhoi = Convert.ToInt32(dr["Macauhoi"]); if (!Convert.IsDBNull(dr["Mamonhoc"])) objCauhoiDO.Mamonhoc = Convert.ToString(dr["Mamonhoc"]); if (!Convert.IsDBNull(dr["Noidung"])) objCauhoiDO.Noidung = Convert.ToString(dr["Noidung"]); if (!Convert.IsDBNull(dr["Dokho"])) objCauhoiDO.Dokho = Convert.ToInt32(dr["Dokho"]); if (!Convert.IsDBNull(dr["Chuong"])) objCauhoiDO.Chuong = Convert.ToInt32(dr["Chuong"]); if (!Convert.IsDBNull(dr["Image"])) objCauhoiDO.Image = Convert.ToString(dr["Image"]); if (!Convert.IsDBNull(dr["Video"])) objCauhoiDO.Video = Convert.ToString(dr["Video"]); if (!Convert.IsDBNull(dr["DapanA"])) objCauhoiDO.DapanA = Convert.ToString(dr["DapanA"]); if (!Convert.IsDBNull(dr["DapanB"])) objCauhoiDO.DapanB = Convert.ToString(dr["DapanB"]); if (!Convert.IsDBNull(dr["DapanC"])) objCauhoiDO.DapanC = Convert.ToString(dr["DapanC"]); if (!Convert.IsDBNull(dr["DapanD"])) objCauhoiDO.DapanD = Convert.ToString(dr["DapanD"]); if (!Convert.IsDBNull(dr["Phuongandung"])) objCauhoiDO.Phuongandung = Convert.ToString(dr["Phuongandung"]); arrCauhoiDO.Add(objCauhoiDO); } } return arrCauhoiDO; } public DataTable SelectAll() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCauhoi_GetAll"; DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; } return dt; } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.DAL/CauhoiDAL.cs
C#
gpl3
19,213
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Data; using System.Configuration; using System.Data.SqlClient; /// <summary> /// Summary description for BaseDAL /// </summary> namespace DOAN.DAL { public class BaseDAL { #region PrivateVariables private SqlConnection SqlConn; #endregion #region Constructor public BaseDAL() { // // TODO: Add constructor logic here // if (SqlConn == null) { SqlConn = new SqlConnection(); SqlConn.ConnectionString = ConfigurationManager.ConnectionStrings["SqlProvider"].ConnectionString; } } #endregion #region PrivateMethods private void OpenSqlConnection() { if (SqlConn.State != ConnectionState.Open) { SqlConn.Open(); } } private void CloseSqlConnection() { if (SqlConn.State == ConnectionState.Open) { SqlConn.Close(); } } #endregion #region PublicMethods public DataSet GetDataSet(SqlCommand SqlComm) { SqlDataAdapter SqlDataAdp; DataSet dsData; try { SqlComm.Connection = SqlConn; SqlDataAdp = new SqlDataAdapter(SqlComm); dsData = new DataSet(); SqlDataAdp.Fill(dsData); return dsData; } catch (Exception ex) { throw ex; } finally { SqlDataAdp = null; dsData = null; } } public int ExecuteNoneQuery(SqlCommand SqlComm) { try { OpenSqlConnection(); SqlComm.Connection = SqlConn; int i = SqlComm.ExecuteNonQuery(); return i; } catch (Exception ex) { throw ex; } finally { CloseSqlConnection(); } } public Object ExecuteScalar(SqlCommand SqlComm) { try { OpenSqlConnection(); SqlComm.Connection = SqlConn; return SqlComm.ExecuteScalar(); } catch (Exception ex) { throw ex; } finally { CloseSqlConnection(); } } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.DAL/BaseDAL.cs
C#
gpl3
2,905
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Data; using System.Configuration; using System.Collections; using System.Data.SqlClient; using DOAN.DO; /// <summary> /// Summary description for DethiDAL /// </summary> namespace DOAN.DAL { public class DethiDAL : BaseDAL { #region Private Variables #endregion #region Public Constructors public DethiDAL() { // // TODO: Add constructor logic here // } #endregion #region Public Methods public int Insert(DethiDO objDethiDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spDethi_Insert"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Mamonhoc", SqlDbType.VarChar); Sqlparam.Value = objDethiDO.Mamonhoc; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Tieude", SqlDbType.NVarChar); Sqlparam.Value = objDethiDO.Tieude; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Macauhoi", SqlDbType.NVarChar); Sqlparam.Value = objDethiDO.Macauhoi; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Socau", SqlDbType.Int); Sqlparam.Value = objDethiDO.Socau; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Sodiem", SqlDbType.Float); Sqlparam.Value = objDethiDO.Sodiem; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Thoigian", SqlDbType.Int); Sqlparam.Value = objDethiDO.Thoigian; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Ngaytao", SqlDbType.VarChar); Sqlparam.Value = objDethiDO.Ngaytao; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Tentaikhoan", SqlDbType.VarChar); Sqlparam.Value = objDethiDO.Tentaikhoan; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@ID", SqlDbType.Int); Sqlparam.Direction = ParameterDirection.ReturnValue; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); if (!Convert.IsDBNull(Sqlcomm.Parameters["@ID"])) result = Convert.ToInt32(Sqlcomm.Parameters["@ID"].Value); return result; } public int Update(DethiDO objDethiDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spDethi_UpdateByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Madethi", SqlDbType.VarChar); Sqlparam.Value = objDethiDO.Madethi; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Mamonhoc", SqlDbType.VarChar); Sqlparam.Value = objDethiDO.Mamonhoc; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Tieude", SqlDbType.NVarChar); Sqlparam.Value = objDethiDO.Tieude; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Socau", SqlDbType.Int); Sqlparam.Value = objDethiDO.Socau; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Sodiem", SqlDbType.Float); Sqlparam.Value = objDethiDO.Sodiem; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Thoigian", SqlDbType.Int); Sqlparam.Value = objDethiDO.Thoigian; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Ngaytao", SqlDbType.VarChar); Sqlparam.Value = objDethiDO.Ngaytao; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Tentaikhoan", SqlDbType.VarChar); Sqlparam.Value = objDethiDO.Tentaikhoan; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@ErrorCode", SqlDbType.Int); Sqlparam.Direction = ParameterDirection.ReturnValue; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); if (!Convert.IsDBNull(Sqlcomm.Parameters["@ErrorCode"])) result = Convert.ToInt32(Sqlcomm.Parameters["@ErrorCode"].Value); return result; } public int Delete(DethiDO objDethiDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spDethi_DeleteByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Madethi", SqlDbType.VarChar); Sqlparam.Value = objDethiDO.Madethi; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); return result; } public int DeleteAll() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spDethi_DeleteAll"; int result = base.ExecuteNoneQuery(Sqlcomm); return result; } public DataTable GetByMonAndUser(string suser, string mamon) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spDethi_GetByUserMon"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@mon", SqlDbType.VarChar); Sqlparam.Value = mamon; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@user", SqlDbType.VarChar); Sqlparam.Value = suser; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; } return dt; } public DataTable GetByMon(string mamon) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spDethi_GetByMon"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@mon", SqlDbType.VarChar); Sqlparam.Value = mamon; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; } return dt; } public DethiDO Select(DethiDO objDethiDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spDethi_GetByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Madethi", SqlDbType.VarChar); Sqlparam.Value = objDethiDO.Madethi; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataRow dr = null; if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { dr = ds.Tables[0].Rows[0]; if (!Convert.IsDBNull(dr["Madethi"])) objDethiDO.Madethi = Convert.ToInt32(dr["Madethi"]); if (!Convert.IsDBNull(dr["Mamonhoc"])) objDethiDO.Mamonhoc = Convert.ToString(dr["Mamonhoc"]); if (!Convert.IsDBNull(dr["Macauhoi"])) objDethiDO.Macauhoi = Convert.ToString(dr["Macauhoi"]); if (!Convert.IsDBNull(dr["Tieude"])) objDethiDO.Tieude = Convert.ToString(dr["Tieude"]); if (!Convert.IsDBNull(dr["Socau"])) objDethiDO.Socau = Convert.ToInt32(dr["Socau"]); if (!Convert.IsDBNull(dr["Sodiem"])) objDethiDO.Sodiem = Convert.ToDouble(dr["Sodiem"]); if (!Convert.IsDBNull(dr["Thoigian"])) objDethiDO.Thoigian = Convert.ToInt32(dr["Thoigian"]); if (!Convert.IsDBNull(dr["Ngaytao"])) objDethiDO.Ngaytao = Convert.ToString(dr["Ngaytao"]); if (!Convert.IsDBNull(dr["Tentaikhoan"])) objDethiDO.Tentaikhoan = Convert.ToString(dr["Tentaikhoan"]); } return objDethiDO; } public DethiDO SelectDeThi(DethiDO objDethiDO, string Tentaikhoan) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spDethi_ThiGetByPK2"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Madethi", SqlDbType.VarChar); Sqlparam.Value = objDethiDO.Madethi; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Tentaikhoan", SqlDbType.VarChar); Sqlparam.Value = Tentaikhoan; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataRow dr = null; if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { dr = ds.Tables[0].Rows[0]; if (!Convert.IsDBNull(dr["Madethi"])) objDethiDO.Madethi = Convert.ToInt32(dr["Madethi"]); if (!Convert.IsDBNull(dr["Mamonhoc"])) objDethiDO.Mamonhoc = Convert.ToString(dr["Mamonhoc"]); if (!Convert.IsDBNull(dr["Macauhoi"])) objDethiDO.Macauhoi = Convert.ToString(dr["Macauhoi"]); if (!Convert.IsDBNull(dr["Tieude"])) objDethiDO.Tieude = Convert.ToString(dr["Tieude"]); if (!Convert.IsDBNull(dr["Socau"])) objDethiDO.Socau = Convert.ToInt32(dr["Socau"]); if (!Convert.IsDBNull(dr["Sodiem"])) objDethiDO.Sodiem = Convert.ToDouble(dr["Sodiem"]); if (!Convert.IsDBNull(dr["Thoigian"])) objDethiDO.Thoigian = Convert.ToInt32(dr["Thoigian"]); if (!Convert.IsDBNull(dr["Ngaytao"])) objDethiDO.Ngaytao = Convert.ToString(dr["Ngaytao"]); if (!Convert.IsDBNull(dr["Tentaikhoan"])) objDethiDO.Tentaikhoan = Convert.ToString(dr["Tentaikhoan"]); } return objDethiDO; } public ArrayList SelectAll1() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spDethi_GetAll"; DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; ArrayList arrDethiDO = new ArrayList(); if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; foreach (DataRow dr in dt.Rows) { DethiDO objDethiDO = new DethiDO(); if (!Convert.IsDBNull(dr["Madethi"])) objDethiDO.Madethi = Convert.ToInt32(dr["Madethi"]); if (!Convert.IsDBNull(dr["Mamonhoc"])) objDethiDO.Mamonhoc = Convert.ToString(dr["Mamonhoc"]); if (!Convert.IsDBNull(dr["Tieude"])) objDethiDO.Tieude = Convert.ToString(dr["Tieude"]); if (!Convert.IsDBNull(dr["Socau"])) objDethiDO.Socau = Convert.ToInt32(dr["Socau"]); if (!Convert.IsDBNull(dr["Sodiem"])) objDethiDO.Sodiem = Convert.ToDouble(dr["Sodiem"]); if (!Convert.IsDBNull(dr["Thoigian"])) objDethiDO.Thoigian = Convert.ToInt32(dr["Thoigian"]); if (!Convert.IsDBNull(dr["Ngaytao"])) objDethiDO.Ngaytao = Convert.ToString(dr["Ngaytao"]); if (!Convert.IsDBNull(dr["Tentaikhoan"])) objDethiDO.Tentaikhoan = Convert.ToString(dr["Tentaikhoan"]); arrDethiDO.Add(objDethiDO); } } return arrDethiDO; } public DataTable SelectAll() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spDethi_GetAll"; DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; } return dt; } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.DAL/DethiDAL.cs
C#
gpl3
13,598
using System.Reflection; using System.Runtime.CompilerServices; using 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. [assembly: AssemblyTitle("DOAN.DAL")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DOAN.DAL")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("34fd7ffe-f394-4f0c-9ece-f711111999c7")] // 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")]
08b2-doan
trunk/Source/DoAn/DOAN.DAL/Properties/AssemblyInfo.cs
C#
gpl3
1,428
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Data; using System.Configuration; using System.Collections; using System.Data.SqlClient; using DOAN.DO; /// <summary> /// Summary description for PhanquyenDAL /// </summary> namespace DOAN.DAL { public class PhanquyenDAL : BaseDAL { #region Private Variables #endregion #region Public Constructors public PhanquyenDAL() { // // TODO: Add constructor logic here // } #endregion #region Public Methods public int Insert(PhanquyenDO objPhanquyenDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spPhanquyen_Insert"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Maquyen", SqlDbType.VarChar); Sqlparam.Value = objPhanquyenDO.Maquyen; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Mota", SqlDbType.NVarChar); Sqlparam.Value = objPhanquyenDO.Mota; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@ID", SqlDbType.Int); Sqlparam.Direction = ParameterDirection.ReturnValue; Sqlcomm.Parameters.Add(Sqlparam); int result =base.ExecuteNoneQuery(Sqlcomm); if(!Convert.IsDBNull(Sqlcomm.Parameters["@ID"])) result = Convert.ToInt32(Sqlcomm.Parameters["@ID"].Value); return result; } public int Update(PhanquyenDO objPhanquyenDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spPhanquyen_UpdateByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Maquyen", SqlDbType.VarChar); Sqlparam.Value = objPhanquyenDO.Maquyen; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Mota", SqlDbType.NVarChar); Sqlparam.Value = objPhanquyenDO.Mota; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@ErrorCode", SqlDbType.Int); Sqlparam.Direction = ParameterDirection.ReturnValue; Sqlcomm.Parameters.Add(Sqlparam); int result=base.ExecuteNoneQuery(Sqlcomm); if (!Convert.IsDBNull(Sqlcomm.Parameters["@ErrorCode"])) result = Convert.ToInt32(Sqlcomm.Parameters["@ErrorCode"].Value); return result; } public int Delete(PhanquyenDO objPhanquyenDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spPhanquyen_DeleteByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Maquyen", SqlDbType.VarChar); Sqlparam.Value = objPhanquyenDO.Maquyen; Sqlcomm.Parameters.Add(Sqlparam); int result=base.ExecuteNoneQuery(Sqlcomm); return result; } public int DeleteAll() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spPhanquyen_DeleteAll"; int result=base.ExecuteNoneQuery(Sqlcomm); return result; } public PhanquyenDO Select(PhanquyenDO objPhanquyenDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spPhanquyen_GetByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Maquyen", SqlDbType.VarChar); Sqlparam.Value = objPhanquyenDO.Maquyen; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataRow dr = null; if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { dr = ds.Tables[0].Rows[0]; if(!Convert.IsDBNull(dr["Maquyen"])) objPhanquyenDO.Maquyen=Convert.ToString(dr["Maquyen"]); if(!Convert.IsDBNull(dr["Mota"])) objPhanquyenDO.Mota=Convert.ToString(dr["Mota"]); } return objPhanquyenDO; } public ArrayList SelectAll1( ) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spPhanquyen_GetAll"; DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; ArrayList arrPhanquyenDO = new ArrayList(); if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; foreach(DataRow dr in dt.Rows) { PhanquyenDO objPhanquyenDO= new PhanquyenDO(); if(!Convert.IsDBNull(dr["Maquyen"])) objPhanquyenDO.Maquyen=Convert.ToString(dr["Maquyen"]); if(!Convert.IsDBNull(dr["Mota"])) objPhanquyenDO.Mota=Convert.ToString(dr["Mota"]); arrPhanquyenDO.Add(objPhanquyenDO); } } return arrPhanquyenDO; } public DataTable SelectAll( ) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spPhanquyen_GetAll"; DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; } return dt; } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.DAL/PhanquyenDAL.cs
C#
gpl3
6,017
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Data; using System.Configuration; using System.Collections; using System.Data.SqlClient; using DOAN.DO; /// <summary> /// Summary description for MonhocDAL /// </summary> namespace DOAN.DAL { public class MonhocDAL : BaseDAL { #region Private Variables #endregion #region Public Constructors public MonhocDAL() { // // TODO: Add constructor logic here // } #endregion #region Public Methods public int Insert(MonhocDO objMonhocDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spMonhoc_Insert"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Mamonhoc", SqlDbType.VarChar); Sqlparam.Value = objMonhocDO.Mamonhoc; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Tenmon", SqlDbType.NVarChar); Sqlparam.Value = objMonhocDO.Tenmon; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Sochuong", SqlDbType.VarChar); Sqlparam.Value = objMonhocDO.Sochuong; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@ID", SqlDbType.Int); Sqlparam.Direction = ParameterDirection.ReturnValue; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); if (!Convert.IsDBNull(Sqlcomm.Parameters["@ID"])) result = Convert.ToInt32(Sqlcomm.Parameters["@ID"].Value); return result; } public int Update(MonhocDO objMonhocDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spMonhoc_UpdateByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Mamonhoc", SqlDbType.VarChar); Sqlparam.Value = objMonhocDO.Mamonhoc; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Tenmon", SqlDbType.NVarChar); Sqlparam.Value = objMonhocDO.Tenmon; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Sochuong", SqlDbType.VarChar); Sqlparam.Value = objMonhocDO.Sochuong; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@ErrorCode", SqlDbType.Int); Sqlparam.Direction = ParameterDirection.ReturnValue; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); if (!Convert.IsDBNull(Sqlcomm.Parameters["@ErrorCode"])) result = Convert.ToInt32(Sqlcomm.Parameters["@ErrorCode"].Value); return result; } public int Delete(MonhocDO objMonhocDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spMonhoc_DeleteByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Mamonhoc", SqlDbType.VarChar); Sqlparam.Value = objMonhocDO.Mamonhoc; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); return result; } public int DeleteAll() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spMonhoc_DeleteAll"; int result = base.ExecuteNoneQuery(Sqlcomm); return result; } public MonhocDO Select(MonhocDO objMonhocDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spMonhoc_GetByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Mamonhoc", SqlDbType.VarChar); Sqlparam.Value = objMonhocDO.Mamonhoc; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataRow dr = null; if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { dr = ds.Tables[0].Rows[0]; if (!Convert.IsDBNull(dr["Mamonhoc"])) objMonhocDO.Mamonhoc = Convert.ToString(dr["Mamonhoc"]); if (!Convert.IsDBNull(dr["Tenmon"])) objMonhocDO.Tenmon = Convert.ToString(dr["Tenmon"]); if (!Convert.IsDBNull(dr["Sochuong"])) objMonhocDO.Sochuong = Convert.ToString(dr["Sochuong"]); } return objMonhocDO; } public DataTable TimKiem(int tt,string tk) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "[spMonhoc_Timkiem]"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@tt", SqlDbType.VarChar); Sqlparam.Value = tt; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Tenmon", SqlDbType.VarChar); Sqlparam.Value = tk; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = new DataTable(); if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { dt = ds.Tables[0]; } return dt; } public ArrayList SelectAll1() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spMonhoc_GetAll"; DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; ArrayList arrMonhocDO = new ArrayList(); if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; foreach (DataRow dr in dt.Rows) { MonhocDO objMonhocDO = new MonhocDO(); if (!Convert.IsDBNull(dr["Mamonhoc"])) objMonhocDO.Mamonhoc = Convert.ToString(dr["Mamonhoc"]); if (!Convert.IsDBNull(dr["Tenmon"])) objMonhocDO.Tenmon = Convert.ToString(dr["Tenmon"]); if (!Convert.IsDBNull(dr["Sochuong"])) objMonhocDO.Sochuong = Convert.ToString(dr["Sochuong"]); arrMonhocDO.Add(objMonhocDO); } } return arrMonhocDO; } public DataTable SelectAllDistiny() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spMonHoc_SelectAllDistiny"; DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; } return dt; } public DataTable SelectAll() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spMonhoc_GetAll"; DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; } return dt; } public object GetSoChuong(string mon) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spMonhoc_GetChuong"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Mamonhoc", SqlDbType.VarChar); Sqlparam.Value = mon; Sqlcomm.Parameters.Add(Sqlparam); object obj = base.ExecuteScalar(Sqlcomm); return obj; } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.DAL/MonhocDAL.cs
C#
gpl3
8,696
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Data; using System.Configuration; using System.Collections; using System.Data.SqlClient; using DOAN.DO; /// <summary> /// Summary description for ThanhvienDAL /// </summary> namespace DOAN.DAL { public class ThanhvienDAL : BaseDAL { #region Private Variables #endregion #region Public Constructors public ThanhvienDAL() { // // TODO: Add constructor logic here // } #endregion #region Public Methods public int Insert(ThanhvienDO objThanhvienDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spThanhvien_Insert"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Tentaikhoan", SqlDbType.VarChar); Sqlparam.Value = objThanhvienDO.Tentaikhoan; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Maquyen", SqlDbType.VarChar); Sqlparam.Value = objThanhvienDO.Maquyen; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Matkhau", SqlDbType.VarChar); Sqlparam.Value = objThanhvienDO.Matkhau; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Email", SqlDbType.VarChar); Sqlparam.Value = objThanhvienDO.Email; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Sodienthoai", SqlDbType.VarChar); Sqlparam.Value = objThanhvienDO.Sodienthoai; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Hovaten", SqlDbType.NVarChar); Sqlparam.Value = objThanhvienDO.Hovaten; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Ngaysinh", SqlDbType.VarChar); Sqlparam.Value = objThanhvienDO.Ngaysinh; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Gioitinh", SqlDbType.Int); Sqlparam.Value = objThanhvienDO.Gioitinh; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Lop", SqlDbType.VarChar); Sqlparam.Value = objThanhvienDO.Lop; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@ID", SqlDbType.Int); Sqlparam.Direction = ParameterDirection.ReturnValue; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); if (!Convert.IsDBNull(Sqlcomm.Parameters["@ID"])) result = Convert.ToInt32(Sqlcomm.Parameters["@ID"].Value); return result; } public int Update(ThanhvienDO objThanhvienDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spThanhvien_UpdateByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Tentaikhoan", SqlDbType.VarChar); Sqlparam.Value = objThanhvienDO.Tentaikhoan; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Maquyen", SqlDbType.VarChar); Sqlparam.Value = objThanhvienDO.Maquyen; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Matkhau", SqlDbType.VarChar); Sqlparam.Value = objThanhvienDO.Matkhau; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Email", SqlDbType.VarChar); Sqlparam.Value = objThanhvienDO.Email; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Sodienthoai", SqlDbType.VarChar); Sqlparam.Value = objThanhvienDO.Sodienthoai; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Hovaten", SqlDbType.NVarChar); Sqlparam.Value = objThanhvienDO.Hovaten; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Ngaysinh", SqlDbType.VarChar); Sqlparam.Value = objThanhvienDO.Ngaysinh; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Gioitinh", SqlDbType.Int); Sqlparam.Value = objThanhvienDO.Gioitinh; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Lop", SqlDbType.VarChar); Sqlparam.Value = objThanhvienDO.Lop; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@ErrorCode", SqlDbType.Int); Sqlparam.Direction = ParameterDirection.ReturnValue; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); if (!Convert.IsDBNull(Sqlcomm.Parameters["@ErrorCode"])) result = Convert.ToInt32(Sqlcomm.Parameters["@ErrorCode"].Value); return result; } public int Delete(ThanhvienDO objThanhvienDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spThanhvien_DeleteByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Tentaikhoan", SqlDbType.VarChar); Sqlparam.Value = objThanhvienDO.Tentaikhoan; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); return result; } public int DeleteAll() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spThanhvien_DeleteAll"; int result = base.ExecuteNoneQuery(Sqlcomm); return result; } public ThanhvienDO login(string tk, string mk) { ThanhvienDO objThanhvienDO = new ThanhvienDO(); SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "Dangnhaptv"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Tendangnhap", SqlDbType.VarChar); Sqlparam.Value = tk; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Matkhau2", SqlDbType.VarChar); Sqlparam.Value = mk; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataRow dr = null; if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { dr = ds.Tables[0].Rows[0]; if (!Convert.IsDBNull(dr["Tentaikhoan"])) objThanhvienDO.Tentaikhoan = Convert.ToString(dr["Tentaikhoan"]); if (!Convert.IsDBNull(dr["Maquyen"])) objThanhvienDO.Maquyen = Convert.ToString(dr["Maquyen"]); if (!Convert.IsDBNull(dr["Matkhau"])) objThanhvienDO.Matkhau = Convert.ToString(dr["Matkhau"]); if (!Convert.IsDBNull(dr["Email"])) objThanhvienDO.Email = Convert.ToString(dr["Email"]); if (!Convert.IsDBNull(dr["Sodienthoai"])) objThanhvienDO.Sodienthoai = Convert.ToString(dr["Sodienthoai"]); if (!Convert.IsDBNull(dr["Hovaten"])) objThanhvienDO.Hovaten = Convert.ToString(dr["Hovaten"]); if (!Convert.IsDBNull(dr["Ngaysinh"])) objThanhvienDO.Ngaysinh = Convert.ToString(dr["Ngaysinh"]); if (!Convert.IsDBNull(dr["Gioitinh"])) objThanhvienDO.Gioitinh = Convert.ToInt32(dr["Gioitinh"]); if (!Convert.IsDBNull(dr["Lop"])) objThanhvienDO.Lop = Convert.ToString(dr["Lop"]); } return objThanhvienDO; } public DataTable Select2(ThanhvienDO objThanhvienDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spThanhvien_GetByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Tentaikhoan", SqlDbType.VarChar); Sqlparam.Value = objThanhvienDO.Tentaikhoan; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = new DataTable(); if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { dt = ds.Tables[0]; } return dt; } public ThanhvienDO Select(ThanhvienDO objThanhvienDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spThanhvien_GetByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Tentaikhoan", SqlDbType.VarChar); Sqlparam.Value = objThanhvienDO.Tentaikhoan; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataRow dr = null; if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { dr = ds.Tables[0].Rows[0]; if (!Convert.IsDBNull(dr["Tentaikhoan"])) objThanhvienDO.Tentaikhoan = Convert.ToString(dr["Tentaikhoan"]); if (!Convert.IsDBNull(dr["Maquyen"])) objThanhvienDO.Maquyen = Convert.ToString(dr["Maquyen"]); if (!Convert.IsDBNull(dr["Matkhau"])) objThanhvienDO.Matkhau = Convert.ToString(dr["Matkhau"]); if (!Convert.IsDBNull(dr["Email"])) objThanhvienDO.Email = Convert.ToString(dr["Email"]); if (!Convert.IsDBNull(dr["Sodienthoai"])) objThanhvienDO.Sodienthoai = Convert.ToString(dr["Sodienthoai"]); if (!Convert.IsDBNull(dr["Hovaten"])) objThanhvienDO.Hovaten = Convert.ToString(dr["Hovaten"]); if (!Convert.IsDBNull(dr["Ngaysinh"])) objThanhvienDO.Ngaysinh = Convert.ToString(dr["Ngaysinh"]); if (!Convert.IsDBNull(dr["Gioitinh"])) objThanhvienDO.Gioitinh = Convert.ToInt32(dr["Gioitinh"]); if (!Convert.IsDBNull(dr["Lop"])) objThanhvienDO.Lop = Convert.ToString(dr["Lop"]); } return objThanhvienDO; } public ThanhvienDO SelectobjByEmail(string email) { ThanhvienDO objThanhvienDO = new ThanhvienDO(); SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spThanhvien_GetByEmail"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@email ", SqlDbType.VarChar); Sqlparam.Value = email; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataRow dr = null; if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { dr = ds.Tables[0].Rows[0]; if (!Convert.IsDBNull(dr["Tentaikhoan"])) objThanhvienDO.Tentaikhoan = Convert.ToString(dr["Tentaikhoan"]); if (!Convert.IsDBNull(dr["Maquyen"])) objThanhvienDO.Maquyen = Convert.ToString(dr["Maquyen"]); if (!Convert.IsDBNull(dr["Matkhau"])) objThanhvienDO.Matkhau = Convert.ToString(dr["Matkhau"]); if (!Convert.IsDBNull(dr["Email"])) objThanhvienDO.Email = Convert.ToString(dr["Email"]); if (!Convert.IsDBNull(dr["Sodienthoai"])) objThanhvienDO.Sodienthoai = Convert.ToString(dr["Sodienthoai"]); if (!Convert.IsDBNull(dr["Hovaten"])) objThanhvienDO.Hovaten = Convert.ToString(dr["Hovaten"]); if (!Convert.IsDBNull(dr["Ngaysinh"])) objThanhvienDO.Ngaysinh = Convert.ToString(dr["Ngaysinh"]); if (!Convert.IsDBNull(dr["Gioitinh"])) objThanhvienDO.Gioitinh = Convert.ToInt32(dr["Gioitinh"]); if (!Convert.IsDBNull(dr["Lop"])) objThanhvienDO.Lop = Convert.ToString(dr["Lop"]); } return objThanhvienDO; } public DataTable SelectByEmail(string email) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spThanhvien_GetByEmail"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@email ", SqlDbType.VarChar); Sqlparam.Value = email; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = new DataTable(); if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { dt = ds.Tables[0]; } return dt; } public ArrayList SelectAll1() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spThanhvien_GetAll"; DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; ArrayList arrThanhvienDO = new ArrayList(); if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; foreach (DataRow dr in dt.Rows) { ThanhvienDO objThanhvienDO = new ThanhvienDO(); if (!Convert.IsDBNull(dr["Tentaikhoan"])) objThanhvienDO.Tentaikhoan = Convert.ToString(dr["Tentaikhoan"]); if (!Convert.IsDBNull(dr["Maquyen"])) objThanhvienDO.Maquyen = Convert.ToString(dr["Maquyen"]); if (!Convert.IsDBNull(dr["Matkhau"])) objThanhvienDO.Matkhau = Convert.ToString(dr["Matkhau"]); if (!Convert.IsDBNull(dr["Email"])) objThanhvienDO.Email = Convert.ToString(dr["Email"]); if (!Convert.IsDBNull(dr["Sodienthoai"])) objThanhvienDO.Sodienthoai = Convert.ToString(dr["Sodienthoai"]); if (!Convert.IsDBNull(dr["Hovaten"])) objThanhvienDO.Hovaten = Convert.ToString(dr["Hovaten"]); if (!Convert.IsDBNull(dr["Ngaysinh"])) objThanhvienDO.Ngaysinh = Convert.ToString(dr["Ngaysinh"]); if (!Convert.IsDBNull(dr["Gioitinh"])) objThanhvienDO.Gioitinh = Convert.ToInt32(dr["Gioitinh"]); if (!Convert.IsDBNull(dr["Lop"])) objThanhvienDO.Lop = Convert.ToString(dr["Lop"]); arrThanhvienDO.Add(objThanhvienDO); } } return arrThanhvienDO; } public DataTable SelectAll() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spThanhvien_GetAll"; DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; } return dt; } public DataTable GetGV() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spThanhvien_GetGV"; DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; } return dt; } public DataTable GetTV() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spThanhvien_GetAllTV"; DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; } return dt; } public DataTable SelectByLop(string lop) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spThanhvien_GetLop"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@lop", SqlDbType.VarChar); Sqlparam.Value = lop; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; } return dt; } public DataTable GetAllLop() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spThanhvien_getAllLop"; DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; } return dt; } public DataTable TimKiem(int tt,string tk) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spThanhvien_TimKiem"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@tt", SqlDbType.VarChar); Sqlparam.Value = tt; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Tenmon", SqlDbType.VarChar); Sqlparam.Value = tk; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; } return dt; } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.DAL/ThanhvienDAL.cs
C#
gpl3
19,299
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DOAN.DAL { public class Class1 { } }
08b2-doan
trunk/Source/DoAn/DOAN.DAL/Class1.cs
C#
gpl3
160
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Data; using System.Configuration; using System.Collections; using System.Data.SqlClient; using DOAN.DO; /// <summary> /// Summary description for CT_BailamDAL /// </summary> namespace DOAN.DAL { public class CT_BailamDAL : BaseDAL { #region Private Variables #endregion #region Public Constructors public CT_BailamDAL() { // // TODO: Add constructor logic here // } #endregion #region Public Methods public int Insert(CT_BailamDO objCT_BailamDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCT_Bailam_Insert"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Mabailam", SqlDbType.VarChar); Sqlparam.Value = objCT_BailamDO.Mabailam; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Macauhoi", SqlDbType.VarChar); Sqlparam.Value = objCT_BailamDO.Macauhoi; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@PAChon", SqlDbType.NVarChar); Sqlparam.Value = objCT_BailamDO.PAChon; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@ID", SqlDbType.Int); Sqlparam.Direction = ParameterDirection.ReturnValue; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); if (!Convert.IsDBNull(Sqlcomm.Parameters["@ID"])) result = Convert.ToInt32(Sqlcomm.Parameters["@ID"].Value); return result; } public int Update(CT_BailamDO objCT_BailamDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCT_Bailam_UpdateByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Mabailam", SqlDbType.VarChar); Sqlparam.Value = objCT_BailamDO.Mabailam; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Macauhoi", SqlDbType.VarChar); Sqlparam.Value = objCT_BailamDO.Macauhoi; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@PAChon", SqlDbType.NVarChar); Sqlparam.Value = objCT_BailamDO.PAChon; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@ErrorCode", SqlDbType.Int); Sqlparam.Direction = ParameterDirection.ReturnValue; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); if (!Convert.IsDBNull(Sqlcomm.Parameters["@ErrorCode"])) result = Convert.ToInt32(Sqlcomm.Parameters["@ErrorCode"].Value); return result; } public int Delete(CT_BailamDO objCT_BailamDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCT_Bailam_DeleteByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Mabailam", SqlDbType.VarChar); Sqlparam.Value = objCT_BailamDO.Mabailam; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Macauhoi", SqlDbType.VarChar); Sqlparam.Value = objCT_BailamDO.Macauhoi; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); return result; } public int DeleteAll() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCT_Bailam_DeleteAll"; int result = base.ExecuteNoneQuery(Sqlcomm); return result; } public CT_BailamDO Select(CT_BailamDO objCT_BailamDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCT_Bailam_GetByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Mabailam", SqlDbType.VarChar); Sqlparam.Value = objCT_BailamDO.Mabailam; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Macauhoi", SqlDbType.VarChar); Sqlparam.Value = objCT_BailamDO.Macauhoi; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataRow dr = null; if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { dr = ds.Tables[0].Rows[0]; if (!Convert.IsDBNull(dr["Mabailam"])) objCT_BailamDO.Mabailam = Convert.ToString(dr["Mabailam"]); if (!Convert.IsDBNull(dr["Macauhoi"])) objCT_BailamDO.Macauhoi = Convert.ToString(dr["Macauhoi"]); if (!Convert.IsDBNull(dr["PAChon"])) objCT_BailamDO.PAChon = Convert.ToString(dr["PAChon"]); } return objCT_BailamDO; } public ArrayList SelectAll1() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCT_Bailam_GetAll"; DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; ArrayList arrCT_BailamDO = new ArrayList(); if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; foreach (DataRow dr in dt.Rows) { CT_BailamDO objCT_BailamDO = new CT_BailamDO(); if (!Convert.IsDBNull(dr["Mabailam"])) objCT_BailamDO.Mabailam = Convert.ToString(dr["Mabailam"]); if (!Convert.IsDBNull(dr["Macauhoi"])) objCT_BailamDO.Macauhoi = Convert.ToString(dr["Macauhoi"]); if (!Convert.IsDBNull(dr["PAChon"])) objCT_BailamDO.PAChon = Convert.ToString(dr["PAChon"]); arrCT_BailamDO.Add(objCT_BailamDO); } } return arrCT_BailamDO; } public DataTable SelectAll() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spCT_Bailam_GetAll"; DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; } return dt; } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.DAL/CT_BailamDAL.cs
C#
gpl3
7,301
/* Copyright 2009 Smart Enterprise Solution Corp. Email: contact@ses.vn - Website: http://www.ses.vn KimNgan Project. */ using System; using System.Data; using System.Configuration; using System.Collections; using System.Data.SqlClient; using DOAN.DO; /// <summary> /// Summary description for BailamDAL /// </summary> namespace DOAN.DAL { public class BailamDAL : BaseDAL { #region Private Variables #endregion #region Public Constructors public BailamDAL() { // // TODO: Add constructor logic here // } #endregion #region Public Methods public int Insert(BailamDO objBailamDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spBailam_Insert"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Madethi", SqlDbType.Int); Sqlparam.Value = objBailamDO.Madethi; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Tongdiem", SqlDbType.Int); Sqlparam.Value = objBailamDO.Tongdiem; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Ngaythi", SqlDbType.VarChar); Sqlparam.Value = objBailamDO.Ngaythi; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Tentaikhoan", SqlDbType.VarChar); Sqlparam.Value = objBailamDO.Tentaikhoan; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Traloi", SqlDbType.VarChar); Sqlparam.Value = objBailamDO.Traloi; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@ID", SqlDbType.Int); Sqlparam.Direction = ParameterDirection.ReturnValue; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); if (!Convert.IsDBNull(Sqlcomm.Parameters["@ID"])) result = Convert.ToInt32(Sqlcomm.Parameters["@ID"].Value); return result; } public int Update(BailamDO objBailamDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spBailam_UpdateByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Mabailam", SqlDbType.Int); Sqlparam.Value = objBailamDO.Mabailam; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Madethi", SqlDbType.Int); Sqlparam.Value = objBailamDO.Madethi; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Tongdiem", SqlDbType.Int); Sqlparam.Value = objBailamDO.Tongdiem; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Ngaythi", SqlDbType.VarChar); Sqlparam.Value = objBailamDO.Ngaythi; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@Tentaikhoan", SqlDbType.VarChar); Sqlparam.Value = objBailamDO.Tentaikhoan; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@ErrorCode", SqlDbType.Int); Sqlparam.Direction = ParameterDirection.ReturnValue; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); if (!Convert.IsDBNull(Sqlcomm.Parameters["@ErrorCode"])) result = Convert.ToInt32(Sqlcomm.Parameters["@ErrorCode"].Value); return result; } public int Delete(BailamDO objBailamDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spBailam_DeleteByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Mabailam", SqlDbType.Int); Sqlparam.Value = objBailamDO.Mabailam; Sqlcomm.Parameters.Add(Sqlparam); int result = base.ExecuteNoneQuery(Sqlcomm); return result; } public int DeleteAll() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spBailam_DeleteAll"; int result = base.ExecuteNoneQuery(Sqlcomm); return result; } public DataTable GetByMonAndNgay(string mamon, string lop, string dat) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spBailam_GetByMonAndNgay2"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@mamon", SqlDbType.VarChar); Sqlparam.Value = mamon; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@lop", SqlDbType.VarChar); Sqlparam.Value = lop; Sqlcomm.Parameters.Add(Sqlparam); Sqlparam = new SqlParameter("@date", SqlDbType.VarChar); Sqlparam.Value = dat; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = new DataTable(); if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { dt = ds.Tables[0]; } return dt; } public BailamDO Select(BailamDO objBailamDO) { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spBailam_GetByPK"; SqlParameter Sqlparam; Sqlparam = new SqlParameter("@Mabailam", SqlDbType.Int); Sqlparam.Value = objBailamDO.Mabailam; Sqlcomm.Parameters.Add(Sqlparam); DataSet ds = base.GetDataSet(Sqlcomm); DataRow dr = null; if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { dr = ds.Tables[0].Rows[0]; if (!Convert.IsDBNull(dr["Mabailam"])) objBailamDO.Mabailam = Convert.ToInt32(dr["Mabailam"]); if (!Convert.IsDBNull(dr["Madethi"])) objBailamDO.Madethi = Convert.ToInt32(dr["Madethi"]); if (!Convert.IsDBNull(dr["Tongdiem"])) objBailamDO.Tongdiem = Convert.ToInt32(dr["Tongdiem"]); if (!Convert.IsDBNull(dr["Ngaythi"])) objBailamDO.Ngaythi = Convert.ToString(dr["Ngaythi"]); if (!Convert.IsDBNull(dr["Tentaikhoan"])) objBailamDO.Tentaikhoan = Convert.ToString(dr["Tentaikhoan"]); } return objBailamDO; } public ArrayList SelectAll1() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spBailam_GetAll"; DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; ArrayList arrBailamDO = new ArrayList(); if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; foreach (DataRow dr in dt.Rows) { BailamDO objBailamDO = new BailamDO(); if (!Convert.IsDBNull(dr["Mabailam"])) objBailamDO.Mabailam = Convert.ToInt32(dr["Mabailam"]); if (!Convert.IsDBNull(dr["Madethi"])) objBailamDO.Madethi = Convert.ToInt32(dr["Madethi"]); if (!Convert.IsDBNull(dr["Tongdiem"])) objBailamDO.Tongdiem = Convert.ToInt32(dr["Tongdiem"]); if (!Convert.IsDBNull(dr["Ngaythi"])) objBailamDO.Ngaythi = Convert.ToString(dr["Ngaythi"]); if (!Convert.IsDBNull(dr["Tentaikhoan"])) objBailamDO.Tentaikhoan = Convert.ToString(dr["Tentaikhoan"]); arrBailamDO.Add(objBailamDO); } } return arrBailamDO; } public DataTable SelectAll() { SqlCommand Sqlcomm = new SqlCommand(); Sqlcomm.CommandType = CommandType.StoredProcedure; Sqlcomm.CommandText = "spBailam_GetAll"; DataSet ds = base.GetDataSet(Sqlcomm); DataTable dt = null; if (ds != null && ds.Tables.Count > 0) { dt = ds.Tables[0]; } return dt; } #endregion } }
08b2-doan
trunk/Source/DoAn/DOAN.DAL/BailamDAL.cs
C#
gpl3
9,126
package integrity; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.Signature; import java.security.spec.X509EncodedKeySpec; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; public class VerifyKey { /** * @param args * @throws Exception * @throws Exception */ public static boolean VerifyFile() throws Exception { //Generating the assymetric secret key KeyGenerator kg = KeyGenerator.getInstance("AES"); kg.init(128); SecretKey k = kg.generateKey(); //System.out.println("Checking Encrypted folder for publicKey.."); //Loading the Public key from the Encrypted folder FileInputStream publicKeyLoad = new FileInputStream("PublicKey.publickey"); byte[] encKey = new byte[publicKeyLoad.available()]; publicKeyLoad.read(encKey); X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encKey); //Using the RSA keyfactory KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey pubKey = keyFactory.generatePublic(pubKeySpec); //System.out.println("Getting the signedFile..."); FileInputStream signedFileInput = new FileInputStream("credentials_signed.txt"); byte[] signatureToVerify = new byte[signedFileInput.available()]; signedFileInput.read(signatureToVerify); signedFileInput.close(); //System.out.println("Verifying the signedFile with the publicKey"); //Verifying the signed file Signature sig = Signature.getInstance("SHA1withRSA"); sig.initVerify(pubKey); FileInputStream enctryptedFileLoad = new FileInputStream("credentials.txt"); BufferedInputStream bufin = new BufferedInputStream(enctryptedFileLoad); byte[] buffer = new byte[1024]; int len; while (bufin.available() != 0) { len = bufin.read(buffer); sig.update(buffer, 0, len); }; bufin.close(); boolean verfication = sig.verify(signatureToVerify); return verfication; } }
02239-cryptography-01
Java Authentication Lab/src/integrity/VerifyKey.java
Java
epl
2,085
package integrity; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.Signature; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; public class SignKey { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub //Generating the assymetric secret key KeyGenerator kg = KeyGenerator.getInstance("AES"); kg.init(128); SecretKey k = kg.generateKey(); //Generate Public and Private key System.out.println("Generating your public and private key"); KeyPairGenerator keyParGen = KeyPairGenerator.getInstance("RSA"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN"); keyParGen.initialize(1024, random); KeyPair pair = keyParGen.generateKeyPair(); PrivateKey privateKey = pair.getPrivate(); PublicKey publicKey = pair.getPublic(); //Generating the signature and signing it with the privateKey Signature signedSignature = Signature.getInstance("SHA1withRSA"); signedSignature.initSign(privateKey); FileInputStream loadedEnctryptedFile = new FileInputStream("credentials.txt"); BufferedInputStream bufin = new BufferedInputStream(loadedEnctryptedFile); byte[] buffer = new byte[1024]; int len; while ((len = bufin.read(buffer)) >= 0) { signedSignature.update(buffer, 0, len); }; bufin.close(); byte[] realSignature = signedSignature.sign(); //Saving the signed file FileOutputStream signedFileOut = new FileOutputStream("credentials_signed.txt"); signedFileOut.write(realSignature); System.out.println("Signed file saved..."); signedFileOut.close(); //Saving the public key file byte[] publicKeyEncode = publicKey.getEncoded(); FileOutputStream publicKeyOut = new FileOutputStream("PublicKey." +"publicKey"); publicKeyOut.write(publicKeyEncode); System.out.println("Public key saved..."); } }
02239-cryptography-01
Java Authentication Lab/src/integrity/SignKey.java
Java
epl
2,338
/* * @(#)SamplePrincipal.java 1.4 00/01/11 * * Copyright (c) 2000, 2002, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * -Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * -Redistribution in binary form must reproduct the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Oracle or the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY * DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT OF OR * RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR * ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE * FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, * SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF * THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN * ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that Software is not designed, licensed or * intended for use in the design, construction, operation or * maintenance of any nuclear facility. */ package sample.principal; import java.security.Principal; /** * <p> This class implements the <code>Principal</code> interface * and represents a Sample user. * * <p> Principals such as this <code>SamplePrincipal</code> * may be associated with a particular <code>Subject</code> * to augment that <code>Subject</code> with an additional * identity. Refer to the <code>Subject</code> class for more information * on how to achieve this. Authorization decisions can then be based upon * the Principals associated with a <code>Subject</code>. * * @version 1.4, 01/11/00 * @see java.security.Principal * @see javax.security.auth.Subject */ public class SamplePrincipal implements Principal, java.io.Serializable { /** * @serial */ private String name; /** * Create a SamplePrincipal with a Sample username. * * <p> * * @param name the Sample username for this user. * * @exception NullPointerException if the <code>name</code> * is <code>null</code>. */ public SamplePrincipal(String name) { if (name == null) throw new NullPointerException("illegal null input"); this.name = name; } /** * Return the Sample username for this <code>SamplePrincipal</code>. * * <p> * * @return the Sample username for this <code>SamplePrincipal</code> */ public String getName() { return name; } /** * Return a string representation of this <code>SamplePrincipal</code>. * * <p> * * @return a string representation of this <code>SamplePrincipal</code>. */ public String toString() { return("SamplePrincipal: " + name); } /** * Compares the specified Object with this <code>SamplePrincipal</code> * for equality. Returns true if the given object is also a * <code>SamplePrincipal</code> and the two SamplePrincipals * have the same username. * * <p> * * @param o Object to be compared for equality with this * <code>SamplePrincipal</code>. * * @return true if the specified Object is equal equal to this * <code>SamplePrincipal</code>. */ public boolean equals(Object o) { if (o == null) return false; if (this == o) return true; if (!(o instanceof SamplePrincipal)) return false; SamplePrincipal that = (SamplePrincipal)o; if (this.getName().equals(that.getName())) return true; return false; } /** * Return a hash code for this <code>SamplePrincipal</code>. * * <p> * * @return a hash code for this <code>SamplePrincipal</code>. */ public int hashCode() { return name.hashCode(); } }
02239-cryptography-01
Java Authentication Lab/src/sample/principal/SamplePrincipal.java
Java
epl
4,612
/* * @(#)SampleAcn.java * * Copyright (c) 2001, 2002, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * -Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * -Redistribution in binary form must reproduct the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Oracle or the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY * DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT OF OR * RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR * ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE * FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, * SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF * THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN * ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that Software is not designed, licensed or * intended for use in the design, construction, operation or * maintenance of any nuclear facility. */ package sample; import java.io.*; import java.util.*; import javax.security.auth.login.*; import javax.security.auth.*; import javax.security.auth.callback.*; /** * <p> This Sample application attempts to authenticate a user * and reports whether or not the authentication was successful. */ public class SampleAcn { /** * Attempt to authenticate the user. * * <p> * * @param args input arguments for this application. These are ignored. */ public static void main(String[] args) { // Obtain a LoginContext, needed for authentication. Tell it // to use the LoginModule implementation specified by the // entry named "Sample" in the JAAS login configuration // file and to also use the specified CallbackHandler. LoginContext lc = null; try { lc = new LoginContext("Sample", new MyCallbackHandler()); } catch (LoginException le) { System.err.println("Cannot create LoginContext. " + le.getMessage()); System.exit(-1); } catch (SecurityException se) { System.err.println("Cannot create LoginContext. " + se.getMessage()); System.exit(-1); } // the user has 3 attempts to authenticate successfully int i; for (i = 0; i < 3; i++) { try { // attempt authentication lc.login(); // if we return with no exception, authentication succeeded break; } catch (LoginException le) { System.err.println("Authentication failed:"); System.err.println(" " + le.getMessage()); try { Thread.currentThread().sleep(3000); } catch (Exception e) { // ignore } } } // did they fail three times? if (i == 3) { System.out.println("Sorry"); System.exit(-1); } System.out.println("Authentication succeeded!"); } } /** * The application implements the CallbackHandler. * * <p> This application is text-based. Therefore it displays information * to the user using the OutputStreams System.out and System.err, * and gathers input from the user using the InputStream System.in. */ class MyCallbackHandler implements CallbackHandler { /** * Invoke an array of Callbacks. * * <p> * * @param callbacks an array of <code>Callback</code> objects which contain * the information requested by an underlying security * service to be retrieved or displayed. * * @exception java.io.IOException if an input or output error occurs. <p> * * @exception UnsupportedCallbackException if the implementation of this * method does not support one or more of the Callbacks * specified in the <code>callbacks</code> parameter. */ public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (int i = 0; i < callbacks.length; i++) { if (callbacks[i] instanceof TextOutputCallback) { // display the message according to the specified type TextOutputCallback toc = (TextOutputCallback)callbacks[i]; switch (toc.getMessageType()) { case TextOutputCallback.INFORMATION: System.out.println(toc.getMessage()); break; case TextOutputCallback.ERROR: System.out.println("ERROR: " + toc.getMessage()); break; case TextOutputCallback.WARNING: System.out.println("WARNING: " + toc.getMessage()); break; default: throw new IOException("Unsupported message type: " + toc.getMessageType()); } } else if (callbacks[i] instanceof NameCallback) { // prompt the user for a username NameCallback nc = (NameCallback)callbacks[i]; System.err.print(nc.getPrompt()); System.err.flush(); nc.setName((new BufferedReader (new InputStreamReader(System.in))).readLine()); } else if (callbacks[i] instanceof PasswordCallback) { // prompt the user for sensitive information PasswordCallback pc = (PasswordCallback)callbacks[i]; System.err.print(pc.getPrompt()); System.err.flush(); pc.setPassword(readPassword(System.in)); } else { throw new UnsupportedCallbackException (callbacks[i], "Unrecognized Callback"); } } } // Reads user password from given input stream. private char[] readPassword(InputStream in) throws IOException { char[] lineBuffer; char[] buf; int i; buf = lineBuffer = new char[128]; int room = buf.length; int offset = 0; int c; loop: while (true) { switch (c = in.read()) { case -1: case '\n': break loop; case '\r': int c2 = in.read(); if ((c2 != '\n') && (c2 != -1)) { if (!(in instanceof PushbackInputStream)) { in = new PushbackInputStream(in); } ((PushbackInputStream)in).unread(c2); } else break loop; default: if (--room < 0) { buf = new char[offset + 128]; room = buf.length - offset - 1; System.arraycopy(lineBuffer, 0, buf, 0, offset); Arrays.fill(lineBuffer, ' '); lineBuffer = buf; } buf[offset++] = (char) c; break; } } if (offset == 0) { return null; } char[] ret = new char[offset]; System.arraycopy(buf, 0, ret, 0, offset); Arrays.fill(buf, ' '); return ret; } }
02239-cryptography-01
Java Authentication Lab/src/sample/SampleAcn.java
Java
epl
7,044
package sample.module; public class Credentials { String username; String password; String salt; public Credentials() { } public Credentials(String username, String password, String salt) { super(); this.username = username; this.password = password; this.salt = salt; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } }
02239-cryptography-01
Java Authentication Lab/src/sample/module/Credentials.java
Java
epl
681
/* * @(#)SampleLoginModule.java 1.18 00/01/11 * * Copyright (c) 2000, 2002, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * -Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * -Redistribution in binary form must reproduct the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Oracle or the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY * DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT OF OR * RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR * ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE * FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, * SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF * THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN * ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that Software is not designed, licensed or * intended for use in the design, construction, operation or * maintenance of any nuclear facility. */ package sample.module; import java.util.*; import java.io.IOException; import javax.security.auth.*; import javax.security.auth.callback.*; import javax.security.auth.login.*; import javax.security.auth.spi.*; import sample.principal.SamplePrincipal; /** * <p> This sample LoginModule authenticates users with a password. * * <p> This LoginModule only recognizes one user: testUser * <p> testUser's password is: testPassword * * <p> If testUser successfully authenticates itself, * a <code>SamplePrincipal</code> with the testUser's user name * is added to the Subject. * * <p> This LoginModule recognizes the debug option. * If set to true in the login Configuration, * debug messages will be output to the output stream, System.out. * * @version 1.18, 01/11/00 */ public class SampleLoginModule implements LoginModule { // initial state private Subject subject; private CallbackHandler callbackHandler; private Map sharedState; private Map options; // configurable option private boolean debug = false; // the authentication status private boolean succeeded = false; private boolean commitSucceeded = false; // username and password private String username; private char[] password; // testUser's SamplePrincipal private SamplePrincipal userPrincipal; /** * Initialize this <code>LoginModule</code>. * * <p> * * @param subject the <code>Subject</code> to be authenticated. <p> * * @param callbackHandler a <code>CallbackHandler</code> for communicating * with the end user (prompting for user names and * passwords, for example). <p> * * @param sharedState shared <code>LoginModule</code> state. <p> * * @param options options specified in the login * <code>Configuration</code> for this particular * <code>LoginModule</code>. */ public void initialize(Subject subject, CallbackHandler callbackHandler, Map<java.lang.String, ?> sharedState, Map<java.lang.String, ?> options) { this.subject = subject; this.callbackHandler = callbackHandler; this.sharedState = sharedState; this.options = options; // initialize any configured options debug = "true".equalsIgnoreCase((String)options.get("debug")); } /** * Authenticate the user by prompting for a user name and password. * * <p> * * @return true in all cases since this <code>LoginModule</code> * should not be ignored. * * @exception FailedLoginException if the authentication fails. <p> * * @exception LoginException if this <code>LoginModule</code> * is unable to perform the authentication. */ public boolean login() throws LoginException { // prompt for a user name and password if (callbackHandler == null) throw new LoginException("Error: no CallbackHandler available " + "to garner authentication information from the user"); Callback[] callbacks = new Callback[2]; callbacks[0] = new NameCallback("user name: "); callbacks[1] = new PasswordCallback("password: ", false); try { callbackHandler.handle(callbacks); username = ((NameCallback)callbacks[0]).getName(); char[] tmpPassword = ((PasswordCallback)callbacks[1]).getPassword(); if (tmpPassword == null) { // treat a NULL password as an empty password tmpPassword = new char[0]; } password = new char[tmpPassword.length]; System.arraycopy(tmpPassword, 0, password, 0, tmpPassword.length); ((PasswordCallback)callbacks[1]).clearPassword(); } catch (java.io.IOException ioe) { throw new LoginException(ioe.toString()); } catch (UnsupportedCallbackException uce) { throw new LoginException("Error: " + uce.getCallback().toString() + " not available to garner authentication information " + "from the user"); } // print debugging information if (debug) { System.out.println("\t\t[SampleLoginModule] " + "user entered user name: " + username); System.out.print("\t\t[SampleLoginModule] " + "user entered password: "); for (int i = 0; i < password.length; i++) System.out.print(password[i]); System.out.println(); } // verify the username/password boolean usernameCorrect = false; boolean passwordCorrect = false; if (username.equals("testUser")) usernameCorrect = true; if (usernameCorrect && password.length == 12 && password[0] == 't' && password[1] == 'e' && password[2] == 's' && password[3] == 't' && password[4] == 'P' && password[5] == 'a' && password[6] == 's' && password[7] == 's' && password[8] == 'w' && password[9] == 'o' && password[10] == 'r' && password[11] == 'd') { // authentication succeeded!!! passwordCorrect = true; if (debug) System.out.println("\t\t[SampleLoginModule] " + "authentication succeeded"); succeeded = true; return true; } else { // authentication failed -- clean out state if (debug) System.out.println("\t\t[SampleLoginModule] " + "authentication failed"); succeeded = false; username = null; for (int i = 0; i < password.length; i++) password[i] = ' '; password = null; if (!usernameCorrect) { throw new FailedLoginException("User Name Incorrect"); } else { throw new FailedLoginException("Password Incorrect"); } } } /** * <p> This method is called if the LoginContext's * overall authentication succeeded * (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules * succeeded). * * <p> If this LoginModule's own authentication attempt * succeeded (checked by retrieving the private state saved by the * <code>login</code> method), then this method associates a * <code>SamplePrincipal</code> * with the <code>Subject</code> located in the * <code>LoginModule</code>. If this LoginModule's own * authentication attempted failed, then this method removes * any state that was originally saved. * * <p> * * @exception LoginException if the commit fails. * * @return true if this LoginModule's own login and commit * attempts succeeded, or false otherwise. */ public boolean commit() throws LoginException { if (succeeded == false) { return false; } else { // add a Principal (authenticated identity) // to the Subject // assume the user we authenticated is the SamplePrincipal userPrincipal = new SamplePrincipal(username); if (!subject.getPrincipals().contains(userPrincipal)) subject.getPrincipals().add(userPrincipal); if (debug) { System.out.println("\t\t[SampleLoginModule] " + "added SamplePrincipal to Subject"); } // in any case, clean out state username = null; for (int i = 0; i < password.length; i++) password[i] = ' '; password = null; commitSucceeded = true; return true; } } /** * <p> This method is called if the LoginContext's * overall authentication failed. * (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules * did not succeed). * * <p> If this LoginModule's own authentication attempt * succeeded (checked by retrieving the private state saved by the * <code>login</code> and <code>commit</code> methods), * then this method cleans up any state that was originally saved. * * <p> * * @exception LoginException if the abort fails. * * @return false if this LoginModule's own login and/or commit attempts * failed, and true otherwise. */ public boolean abort() throws LoginException { if (succeeded == false) { return false; } else if (succeeded == true && commitSucceeded == false) { // login succeeded but overall authentication failed succeeded = false; username = null; if (password != null) { for (int i = 0; i < password.length; i++) password[i] = ' '; password = null; } userPrincipal = null; } else { // overall authentication succeeded and commit succeeded, // but someone else's commit failed logout(); } return true; } /** * Logout the user. * * <p> This method removes the <code>SamplePrincipal</code> * that was added by the <code>commit</code> method. * * <p> * * @exception LoginException if the logout fails. * * @return true in all cases since this <code>LoginModule</code> * should not be ignored. */ public boolean logout() throws LoginException { subject.getPrincipals().remove(userPrincipal); succeeded = false; succeeded = commitSucceeded; username = null; if (password != null) { for (int i = 0; i < password.length; i++) password[i] = ' '; password = null; } userPrincipal = null; return true; } }
02239-cryptography-01
Java Authentication Lab/src/sample/module/SampleLoginModule.java
Java
epl
10,844
/* * @(#)SampleLoginModule.java 1.18 00/01/11 * * Copyright (c) 2000, 2002, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * -Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * -Redistribution in binary form must reproduct the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Oracle or the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY * DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT OF OR * RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR * ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE * FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, * SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF * THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN * ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that Software is not designed, licensed or * intended for use in the design, construction, operation or * maintenance of any nuclear facility. */ package sample.module; import integrity.VerifyKey; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.math.BigInteger; import javax.security.auth.*; import javax.security.auth.callback.*; import javax.security.auth.login.*; import javax.security.auth.spi.*; import sample.principal.SamplePrincipal; /** * <p> This sample LoginModule authenticates users with a password. * * <p> This LoginModule only recognizes one user: testUser * <p> testUser's password is: testPassword * * <p> If testUser successfully authenticates itself, * a <code>SamplePrincipal</code> with the testUser's user name * is added to the Subject. * * <p> This LoginModule recognizes the debug option. * If set to true in the login Configuration, * debug messages will be output to the output stream, System.out. * * @version 1.18, 01/11/00 */ public class SampleLoginModuleFileInput implements LoginModule { // initial state private Subject subject; private CallbackHandler callbackHandler; private Map sharedState; private Map options; // configurable option private boolean debug = false; // the authentication status private boolean succeeded = false; private boolean commitSucceeded = false; // username and password private String username; private char[] password; // testUser's SamplePrincipal private SamplePrincipal userPrincipal; /** * Initialize this <code>LoginModule</code>. * * <p> * * @param subject the <code>Subject</code> to be authenticated. <p> * * @param callbackHandler a <code>CallbackHandler</code> for communicating * with the end user (prompting for user names and * passwords, for example). <p> * * @param sharedState shared <code>LoginModule</code> state. <p> * * @param options options specified in the login * <code>Configuration</code> for this particular * <code>LoginModule</code>. */ public void initialize(Subject subject, CallbackHandler callbackHandler, Map<java.lang.String, ?> sharedState, Map<java.lang.String, ?> options) { this.subject = subject; this.callbackHandler = callbackHandler; this.sharedState = sharedState; this.options = options; // initialize any configured options debug = "true".equalsIgnoreCase((String)options.get("debug")); } /** * Authenticate the user by prompting for a user name and password. * * <p> * * @return true in all cases since this <code>LoginModule</code> * should not be ignored. * * @exception FailedLoginException if the authentication fails. <p> * * @exception LoginException if this <code>LoginModule</code> * is unable to perform the authentication. */ public boolean login() throws LoginException { // prompt for a user name and password if (callbackHandler == null) throw new LoginException("Error: no CallbackHandler available " + "to garner authentication information from the user"); System.out.println("Trying to verify the db..."); Callback[] callbacks = new Callback[2]; try { if (VerifyKey.VerifyFile() == true) { System.out.println("The signed files is OK! Please login..."); callbacks[0] = new NameCallback("user name: "); callbacks[1] = new PasswordCallback("password: ", false); } else { System.out.println("The signed files has been tampered with..."); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } try { callbackHandler.handle(callbacks); username = ((NameCallback)callbacks[0]).getName(); char[] tmpPassword = ((PasswordCallback)callbacks[1]).getPassword(); if (tmpPassword == null) { // treat a NULL password as an empty password tmpPassword = new char[0]; } password = new char[tmpPassword.length]; System.arraycopy(tmpPassword, 0, password, 0, tmpPassword.length); ((PasswordCallback)callbacks[1]).clearPassword(); } catch (java.io.IOException ioe) { throw new LoginException(ioe.toString()); } catch (UnsupportedCallbackException uce) { throw new LoginException("Error: " + uce.getCallback().toString() + " not available to garner authentication information " + "from the user"); } // print debugging information if (debug) { System.out.println("\t\t[SampleLoginModule] " + "user entered user name: " + username); System.out.print("\t\t[SampleLoginModule] " + "user entered password: "); for (int i = 0; i < password.length; i++) System.out.print(password[i]); System.out.println(); } // verify the username/password boolean usernameCorrect = false; boolean passwordCorrect = false; HashMap<String, Credentials> userlist = readFile(); if (userlist.containsKey(username)) usernameCorrect = true; if (usernameCorrect && userlist.get(username).password.equals(hashPassword(new String(password), userlist.get(username).getSalt()))) { // authentication succeeded!!! passwordCorrect = true; if (debug) System.out.println("\t\t[SampleLoginModule] " + "authentication succeeded"); succeeded = true; return true; } else { // authentication failed -- clean out state if (debug) System.out.println("\t\t[SampleLoginModule] " + "authentication failed"); succeeded = false; username = null; for (int i = 0; i < password.length; i++) password[i] = ' '; password = null; if (!usernameCorrect) { throw new FailedLoginException("User Name Incorrect"); } else { throw new FailedLoginException("Password Incorrect"); } } } /** * <p> This method is called if the LoginContext's * overall authentication succeeded * (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules * succeeded). * * <p> If this LoginModule's own authentication attempt * succeeded (checked by retrieving the private state saved by the * <code>login</code> method), then this method associates a * <code>SamplePrincipal</code> * with the <code>Subject</code> located in the * <code>LoginModule</code>. If this LoginModule's own * authentication attempted failed, then this method removes * any state that was originally saved. * * <p> * * @exception LoginException if the commit fails. * * @return true if this LoginModule's own login and commit * attempts succeeded, or false otherwise. */ public boolean commit() throws LoginException { if (succeeded == false) { return false; } else { // add a Principal (authenticated identity) // to the Subject // assume the user we authenticated is the SamplePrincipal userPrincipal = new SamplePrincipal(username); if (!subject.getPrincipals().contains(userPrincipal)) subject.getPrincipals().add(userPrincipal); if (debug) { System.out.println("\t\t[SampleLoginModule] " + "added SamplePrincipal to Subject"); } // in any case, clean out state username = null; for (int i = 0; i < password.length; i++) password[i] = ' '; password = null; commitSucceeded = true; return true; } } /** * <p> This method is called if the LoginContext's * overall authentication failed. * (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules * did not succeed). * * <p> If this LoginModule's own authentication attempt * succeeded (checked by retrieving the private state saved by the * <code>login</code> and <code>commit</code> methods), * then this method cleans up any state that was originally saved. * * <p> * * @exception LoginException if the abort fails. * * @return false if this LoginModule's own login and/or commit attempts * failed, and true otherwise. */ public boolean abort() throws LoginException { if (succeeded == false) { return false; } else if (succeeded == true && commitSucceeded == false) { // login succeeded but overall authentication failed succeeded = false; username = null; if (password != null) { for (int i = 0; i < password.length; i++) password[i] = ' '; password = null; } userPrincipal = null; } else { // overall authentication succeeded and commit succeeded, // but someone else's commit failed logout(); } return true; } /** * Logout the user. * * <p> This method removes the <code>SamplePrincipal</code> * that was added by the <code>commit</code> method. * * <p> * * @exception LoginException if the logout fails. * * @return true in all cases since this <code>LoginModule</code> * should not be ignored. */ public boolean logout() throws LoginException { subject.getPrincipals().remove(userPrincipal); succeeded = false; succeeded = commitSucceeded; username = null; if (password != null) { for (int i = 0; i < password.length; i++) password[i] = ' '; password = null; } userPrincipal = null; return true; } public HashMap<String, Credentials> readFile() { String filename = "credentials.txt"; HashMap<String, Credentials> hashmap = new HashMap<String, Credentials>(); try { BufferedReader file = new BufferedReader(new FileReader(filename)); String readText; while ((readText = file.readLine()) != null) { String[] fileinput=readText.split(","); Credentials cre = new Credentials(); cre.setUsername(fileinput[0]); cre.setPassword(fileinput[1]); cre.setSalt(fileinput[2]); //addding the user object to the hashmap of all the users hashmap.put(cre.getUsername(), cre); } } catch (Exception e) { System.out.println("File Read Error"); } return hashmap; } public String hashPassword(String pwd, String slt) { //Using SHA-1 encryption on the password MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { System.out.println("WHOOPS. No such algorithm..."); } //Updating the digest with the password //get the password in bytes digest.update(pwd.getBytes()); //Updating the hash again with the salt //get the salt in bytes digest.update(slt.getBytes()); //converting the bytes to integers and converting it toString to get the hashValue. return new BigInteger(1, digest.digest()).toString(16); } }
02239-cryptography-01
Java Authentication Lab/src/sample/module/SampleLoginModuleFileInput.java
Java
epl
12,767
import java.awt.Color; import java.awt.GridLayout; import java.awt.event.*; //import javax.swing.*; import com.sun.java.swing.*; import java.io.*; import java.net.*; import java.rmi.*; import java.rmi.server.*; import javax.crypto.*; import javax.swing.*; import java.security.*; import java.security.interfaces.*; class RMIClient1 extends JFrame implements ActionListener{ JLabel col1, col2; JLabel totalItems, totalCost; JLabel cardNum, custID; JLabel applechk, pearchk, peachchk; JButton purchase, reset; JPanel panel; JTextField appleqnt, pearqnt, peachqnt; JTextField creditCard, customer; JTextArea items, cost; static Send send; int itotal=0; double icost=0; RMIClient1(){ //Begin Constructor //Create left and right column labels col1 = new JLabel("Select Items"); col2 = new JLabel("Specify Quantity"); //Create labels and text field components applechk = new JLabel(" Apples"); appleqnt = new JTextField(); appleqnt.addActionListener(this); pearchk = new JLabel(" Pears"); pearqnt = new JTextField(); pearqnt.addActionListener(this); peachchk = new JLabel(" Peaches"); peachqnt = new JTextField(); peachqnt.addActionListener(this); cardNum = new JLabel(" Credit Card:"); creditCard = new JTextField(); pearqnt.setNextFocusableComponent(creditCard); customer = new JTextField(); custID = new JLabel(" Customer ID:"); //Create labels and text area components totalItems = new JLabel("Total Items:"); totalCost = new JLabel("Total Cost:"); items = new JTextArea(); cost = new JTextArea(); //Create buttons and make action listeners purchase = new JButton("Purchase"); purchase.addActionListener(this); reset = new JButton("Reset"); reset.addActionListener(this); creditCard.setNextFocusableComponent(reset); //Create a panel for the components panel = new JPanel(); //Set panel layout to 2-column grid //on a white background panel.setLayout(new GridLayout(0,2)); panel.setBackground(Color.white); //Add components to panel columns //going left to right and top to bottom getContentPane().add(panel); panel.add(col1); panel.add(col2); panel.add(applechk); panel.add(appleqnt); panel.add(peachchk); panel.add(peachqnt); panel.add(pearchk); panel.add(pearqnt); panel.add(totalItems); panel.add(items); panel.add(totalCost); panel.add(cost); panel.add(cardNum); panel.add(creditCard); panel.add(custID); panel.add(customer); panel.add(reset); panel.add(purchase); } //End Constructor private void encrypt(String creditCardNumber) throws Exception { // Create cipher for symmetric key encryption (DES) Cipher myCipher = Cipher.getInstance("DES"); // Create a key generator KeyGenerator kg = KeyGenerator.getInstance("DES"); // Create a secret (session) key with key generator SecretKey sk = kg.generateKey(); // Initialize cipher for encryption with session key myCipher.init(Cipher.DECRYPT_MODE, sk); // Encrypt credit card number with cipher myCipher.doFinal(creditCardNumber.getBytes()); // Get public key from server // Create cipher for asymmetric encryption (so not use RSA) // Initialize cipher for encryption with public key // Seal session key using asymmetric cipher // Serialize sealed session key // Send encrypted credit card number and // sealed session key to server } public void actionPerformed(ActionEvent event){ Object source = event.getSource(); Integer applesNo, peachesNo, pearsNo, num; Double cost; String number, cardnum, custID, apples, peaches, pears, text, text2; //If Purchase button pressed if(source == purchase){ //Get data from text fields cardnum = creditCard.getText(); custID = customer.getText(); apples = appleqnt.getText(); peaches = peachqnt.getText(); pears = pearqnt.getText(); //Calculate total items if(apples.length() > 0){ //Catch invalid number error try{ applesNo = Integer.valueOf(apples); itotal += applesNo.intValue(); }catch(java.lang.NumberFormatException e){ appleqnt.setText("Invalid Value"); } } else { itotal += 0; } if(peaches.length() > 0){ //Catch invalid number error try{ peachesNo = Integer.valueOf(peaches); itotal += peachesNo.intValue(); }catch(java.lang.NumberFormatException e){ peachqnt.setText("Invalid Value"); } } else { itotal += 0; } if(pears.length() > 0){ //Catch invalid number error try{ pearsNo = Integer.valueOf(pears); itotal += pearsNo.intValue(); }catch(java.lang.NumberFormatException e){ pearqnt.setText("Invalid Value"); } } else { itotal += 0; } //Display running total num = new Integer(itotal); text = num.toString(); this.items.setText(text); //Calculate and display running cost icost = (itotal * 1.25); cost = new Double(icost); text2 = cost.toString(); this.cost.setText(text2); //Encrypt credit card number try { encrypt(cardnum); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //Send data over net try{ send.sendCustID(custID); send.sendAppleQnt(apples); send.sendPeachQnt(peaches); send.sendPearQnt(pears); send.sendTotalCost(icost); send.sendTotalItems(itotal); } catch (java.rmi.RemoteException e) { System.out.println("sendData exception: " + e.getMessage()); } } //If Reset button pressed //Clear all fields if(source == reset){ creditCard.setText(""); appleqnt.setText(""); peachqnt.setText(""); pearqnt.setText(""); creditCard.setText(""); customer.setText(""); icost = 0; cost = new Double(icost); text2 = cost.toString(); this.cost.setText(text2); itotal = 0; num = new Integer(itotal); text = num.toString(); this.items.setText(text); } } public static void main(String[] args){ try{ UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName()); }catch (Exception e) { System.out.println("Couldn't use the cross-platform" + "look and feel: " + e); } RMIClient1 frame = new RMIClient1(); frame.setTitle("Fruit $1.25 Each"); WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }; frame.addWindowListener(l); frame.pack(); frame.setVisible(true); if(System.getSecurityManager() == null) { System.setSecurityManager(new RMISecurityManager()); } try { String name = "//" + args[0] + "/Send"; send = ((Send) Naming.lookup(name)); } catch (Exception e) { System.out.println("RMIClient1 exception: " + e.getMessage()); e.printStackTrace(); } } }
02239-cryptography-01
02239_Lab1_Cryptography/src/RMIClient1.java
Java
epl
7,123
public interface Send { void sendCustID(String custID); void sendAppleQnt(String apples); void sendPeachQnt(String peaches); void sendPearQnt(String pears); void sendTotalCost(double icost); void sendTotalItems(int itotal); String getCustID(); String getAppleQnt(); String getPeachQnt(); String getPearQnt(); double getTotalCost(); int getTotalItems(); byte[] getKey(); byte[] getEncrypted(); }
02239-cryptography-01
02239_Lab1_Cryptography/src/Send.java
Java
epl
427
import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PublicKey; import java.security.SecureRandom; public class RemoteServer { //Generate and getPublicKey public PublicKey getPublicKey() throws NoSuchAlgorithmException, NoSuchProviderException { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC"); keyGen.initialize(512, new SecureRandom()); KeyPair keyPair = keyGen.generateKeyPair(); java.io.FileOutputStream fos = new java.io.FileOutputStream("test.txt"); fos.close(); return keyPair.getPublic(); } //A method to send the encryped credit card number //A method to get the encrypted credit card number //A method to send the encrypted symmetric key //A method to get the encrypted symmetric key }
02239-cryptography-01
02239_Lab1_Cryptography/src/RemoteServer.java
Java
epl
918
public class Kryptering01 { public static void main() { } }
02239-cryptography-01
02239_Lab1_Cryptography/src/Kryptering01.java
Java
epl
69
import java.awt.Color; import java.awt.GridLayout; import java.awt.event.*; //import javax.swing.*; import com.sun.java.swing.*; import java.io.*; import java.net.*; import java.rmi.*; import java.rmi.server.*; import java.io.FileInputStream.*; import java.io.RandomAccessFile.*; import java.io.File; import java.util.*; import javax.crypto.*; import javax.crypto.spec.*; import javax.swing.*; import java.security.*; class RMIClient2 extends JFrame implements ActionListener { JLabel creditCard, custID, apples, peaches, pears, total, cost, clicked; JButton view, reset; JPanel panel; JTextArea creditNo, customerNo, applesNo, peachesNo, pearsNo, itotal, icost; Socket socket = null; PrintWriter out = null; static Send send; String customer; RMIClient2(){ //Begin Constructor //Create labels creditCard = new JLabel("Credit Card:"); custID = new JLabel("Customer ID:"); apples = new JLabel("Apples:"); peaches = new JLabel("Peaches:"); pears = new JLabel("Pears:"); total = new JLabel("Total Items:"); cost = new JLabel("Total Cost:"); //Create text area components creditNo = new JTextArea(); customerNo = new JTextArea(); applesNo = new JTextArea(); peachesNo = new JTextArea(); pearsNo = new JTextArea(); itotal = new JTextArea(); icost = new JTextArea(); //Create buttons view = new JButton("View Order"); view.addActionListener(this); reset = new JButton("Reset"); reset.addActionListener(this); //Create panel for 2-column layout //Set white background color panel = new JPanel(); panel.setLayout(new GridLayout(0,2)); panel.setBackground(Color.white); //Add components to panel columns //going left to right and top to bottom getContentPane().add(panel); panel.add(creditCard); panel.add(creditNo); panel.add(custID); panel.add(customerNo); panel.add(apples); panel.add(applesNo); panel.add(peaches); panel.add(peachesNo); panel.add(pears); panel.add(pearsNo); panel.add(total); panel.add(itotal); panel.add(cost); panel.add(icost); panel.add(view); panel.add(reset); } //End Constructor public String decrypt(sealed key, encrypted credit card number){ // Get private key from file // Create asymmetric cipher (do not use RSA) // Initialize cipher for decryption with private key // Unseal wrapped session key using asymmetric cipher // Create symmetric cipher // Initialize cipher for decryption with session key // Decrypt credit card number with symmetric cipher } public void actionPerformed(ActionEvent event){ Object source = event.getSource(); String text=null, unit, i; byte[] wrappedKey; byte[] encrypted; double cost; Double price; int items; Integer itms; //If View button pressed //Get data from server and display it if(source == view){ try{ wrappedKey = send.getKey(); encrypted = send.getEncrypted(); //Decrypt credit card number String credit = decrypt(sealed, encrypted); creditNo.setText(new String(credit)); text = send.getCustID(); customerNo.setText(text); text = send.getAppleQnt(); applesNo.setText(text); text = send.getPeachQnt(); peachesNo.setText(text); text = send.getPearQnt(); pearsNo.setText(text); cost = send.getTotalCost(); price = new Double(cost); unit = price.toString(); icost.setText(unit); items = send.getTotalItems(); itms = new Integer(items); i = itms.toString(); itotal.setText(i); } catch (java.rmi.RemoteException e) { System.out.println("sendData exception: " + e.getMessage()); } } //If Reset button pressed //Clear all fields if(source == reset){ creditNo.setText(""); customerNo.setText(""); applesNo.setText(""); peachesNo.setText(""); pearsNo.setText(""); itotal.setText(""); icost.setText(""); } } public static void main(String[] args){ RMIClient2 frame = new RMIClient2(); frame.setTitle("Fruit Order"); WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }; frame.addWindowListener(l); frame.pack(); frame.setVisible(true); if(System.getSecurityManager() == null) { System.setSecurityManager(new RMISecurityManager()); } try { String name = "//" + args[0] + "/Send"; send = ((Send) Naming.lookup(name)); } catch (java.rmi.NotBoundException e) { System.out.println("Cannot access data in server"); } catch(java.rmi.RemoteException e){ System.out.println("Cannot access data in server"); } catch(java.net.MalformedURLException e) { System.out.println("Cannot access data in server"); } } }
02239-cryptography-01
02239_Lab1_Cryptography/src/RMIClient2.java
Java
epl
4,974
import javax.crypto.*; import javax.crypto.spec.SecretKeySpec; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.*; import java.security.interfaces.*; import java.security.spec.X509EncodedKeySpec; import java.util.Arrays; import java.util.Scanner; public class GenerateSignature { /** * @param args * @throws UnsupportedEncodingException * @throws NoSuchAlgorithmException */ public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException { Scanner scan= new Scanner(System.in); //byte[] keyBytes = ("this is my key").getBytes("UTF-8"); // keyBytes = Arrays.copyOf(keyBytes, 16); KeyGenerator keygen=KeyGenerator.getInstance("AES"); keygen.init(128); SecretKey skey=keygen.generateKey(); Boolean run=true; while(run){ System.out.println("Press 1 for signing your file and 2 for verifying your file and 3 for terminating program:"); int choice = scan.nextInt(); scan.nextLine(); switch(choice){ case 1: System.out.println("Generating private and public key.."); try{ //read in file scan.reset(); System.out.println("Write path to the data file:"); String path=scan.nextLine(); String folderPath=path.substring(0, path.lastIndexOf("client 1")); File file= new File(path); byte[] data = new byte[(int)file.length()]; FileInputStream fileInput=new FileInputStream(file); fileInput.read(data); //encrypt byte data System.out.println("input text : " + new String(data)); Cipher c = Cipher.getInstance("AES"); //SecretKeySpec k = new SecretKeySpec(keyBytes, "AES"); c.init(Cipher.ENCRYPT_MODE, skey); byte[] encryptedData = c.doFinal(data); System.out.println("encrypted data: " + new String(encryptedData)); //save encrypted data in file FileOutputStream fos = new FileOutputStream(folderPath+"client 2\\encryptedData"); fos.write(encryptedData); fos.close(); //make private and public key for signature System.out.println("Generating private and public key"); KeyPairGenerator keyGen= KeyPairGenerator.getInstance("RSA"); SecureRandom random=SecureRandom.getInstance("SHA1PRNG", "SUN"); keyGen.initialize(1024, random); KeyPair pair=keyGen.generateKeyPair(); PrivateKey privateK=pair.getPrivate(); PublicKey publicK=pair.getPublic(); System.out.println("Generating signature for file"); Signature sigDSA=Signature.getInstance("SHA1withRSA"); sigDSA.initSign(privateK); FileInputStream fis=new FileInputStream(folderPath+"\\client 2\\encryptedData"); BufferedInputStream buf= new BufferedInputStream(fis); byte[] buffer=new byte[1024]; int len; while((len=buf.read(buffer))>=0){ sigDSA.update(buffer, 0, len); } buf.close(); byte [] finalSig=sigDSA.sign(); /* save the signature in a file */ FileOutputStream sigfos = new FileOutputStream(folderPath+"\\client 2\\signedFile"); sigfos.write(finalSig); sigfos.close(); /* save the public key in a file */ byte[] publicKey = publicK.getEncoded(); FileOutputStream keyfos = new FileOutputStream(folderPath+"client 2\\publicKey"); keyfos.write(publicKey); keyfos.close(); } catch(Exception e){ System.err.println(e.getMessage()); } break; case 2: try{ System.out.println("Write path to the folder where public key, signed file and ecrypted data is located:"); String folderPathPubAndSig=scan.nextLine(); System.out.println("getting public key"); FileInputStream keyInput = new FileInputStream(folderPathPubAndSig+"\\publicKey"); byte[] encKey = new byte[keyInput.available()]; keyInput.read(encKey); keyInput.close(); X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encKey); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey pubKey = keyFactory.generatePublic(pubKeySpec); System.out.println("getting signed file"); FileInputStream sigInput = new FileInputStream(folderPathPubAndSig+"\\signedFile"); byte[] sigToVerify = new byte[sigInput.available()]; sigInput.read(sigToVerify); sigInput.close(); Signature sig = Signature.getInstance("SHA1withRSA"); sig.initVerify(pubKey); System.out.println("getting ecrypted data"); FileInputStream dataInput = new FileInputStream(folderPathPubAndSig+"\\encryptedData"); BufferedInputStream bufin = new BufferedInputStream(dataInput); byte[] buffer = new byte[1024]; int len; while (bufin.available() != 0) { len = bufin.read(buffer); sig.update(buffer, 0, len); }; bufin.close(); boolean verifies = sig.verify(sigToVerify); System.out.println("signature verifies: " + verifies); if(verifies){ System.out.println("the decrypted messeage: "); File file= new File(folderPathPubAndSig+"\\encryptedData"); byte[] encryptedData = new byte[(int)file.length()]; FileInputStream fileInput=new FileInputStream(file); fileInput.read(encryptedData); Cipher c = Cipher.getInstance("AES"); //SecretKeySpec k = new SecretKeySpec(keyBytes, "AES"); c.init(Cipher.DECRYPT_MODE, skey); byte[] decryptData = c.doFinal(encryptedData); System.out.println("Decrypted data: " + new String(decryptData)); } } catch(Exception e2) { } break; case 3: run=false; break; } } } }
02239-cryptography-01
FirstLabDataSec/src/GenerateSignature.java
Java
epl
5,808
# -*- coding: utf-8 -*- from ragendja.settings_pre import * # Increase this when you update your on the production site, so users # don't have to refresh their cache. By setting this your MEDIA_URL # automatically becomes /media/MEDIA_VERSION/ MEDIA_VERSION = 1 # By hosting media on a different domain we can get a speedup (more parallel # browser connections). #if on_production_server or not have_appserver: # MEDIA_URL = 'http://media.mydomain.com/media/%d/' # Add base media (jquery can be easily added via INSTALLED_APPS) COMBINE_MEDIA = { 'combined-%(LANGUAGE_CODE)s.js': ( # See documentation why site_data can be useful: # http://code.google.com/p/app-engine-patch/wiki/MediaGenerator '.site_data.js', ), 'combined-%(LANGUAGE_DIR)s.css': ( 'global/look.css', ), } # Change your email settings if on_production_server: DEFAULT_FROM_EMAIL = 'drkkojima@gmail.com' SERVER_EMAIL = DEFAULT_FROM_EMAIL # Make this unique, and don't share it with anybody. SECRET_KEY = '19720403' #ENABLE_PROFILER = True #ONLY_FORCED_PROFILE = True #PROFILE_PERCENTAGE = 25 #SORT_PROFILE_RESULTS_BY = 'cumulative' # default is 'time' # Profile only datastore calls #PROFILE_PATTERN = 'ext.db..+\((?:get|get_by_key_name|fetch|count|put)\)' # Enable I18N and set default language to 'en' USE_I18N = True TIME_ZONE = 'Asia/Tokyo' LANGUAGE_CODE = 'en' # Restrict supported languages (and JS media generation) LANGUAGES = ( # ('de', 'German'), ('en', 'English'), # ('ja', 'Japanese'), ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.auth', 'django.core.context_processors.media', 'django.core.context_processors.request', 'django.core.context_processors.i18n', ) MIDDLEWARE_CLASSES = ( 'ragendja.middleware.ErrorMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'httpauth.Middleware', # Django authentication 'django.contrib.auth.middleware.AuthenticationMiddleware', # Google authentication #'ragendja.auth.middleware.GoogleAuthenticationMiddleware', # Hybrid Django/Google authentication #'ragendja.auth.middleware.HybridAuthenticationMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.locale.LocaleMiddleware', 'ragendja.sites.dynamicsite.DynamicSiteIDMiddleware', 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware', 'django.contrib.redirects.middleware.RedirectFallbackMiddleware', ) # Google authentication #AUTH_USER_MODULE = 'ragendja.auth.google_models' #AUTH_ADMIN_MODULE = 'ragendja.auth.google_admin' # Hybrid Django/Google authentication #AUTH_USER_MODULE = 'ragendja.auth.hybrid_models' LOGIN_URL = '/account/login/' LOGOUT_URL = '/account/logout/' LOGIN_REDIRECT_URL = '/haco/report/' INSTALLED_APPS = ( # Add jquery support (app is in "common" folder). This automatically # adds jquery to your COMBINE_MEDIA['combined-%(LANGUAGE_CODE)s.js'] # Note: the order of your INSTALLED_APPS specifies the order in which # your app-specific media files get combined, so jquery should normally # come first. 'jquery', # Add blueprint CSS (http://blueprintcss.org/) 'blueprintcss', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.admin', 'django.contrib.webdesign', 'django.contrib.flatpages', 'django.contrib.redirects', 'django.contrib.sites', 'appenginepatcher', 'ragendja', 'myapp', 'registration', 'mediautils', 'haco', ) # List apps which should be left out from app settings and urlsauto loading IGNORE_APP_SETTINGS = IGNORE_APP_URLSAUTO = ( # Example: # 'django.contrib.admin', # 'django.contrib.auth', # 'yetanotherapp', ) # Remote access to production server (e.g., via manage.py shell --remote) DATABASE_OPTIONS = { # Override remoteapi handler's path (default: '/remote_api'). # This is a good idea, so you make it not too easy for hackers. ;) # Don't forget to also update your app.yaml! #'remote_url': '/remote-secret-url', # !!!Normally, the following settings should not be used!!! # Always use remoteapi (no need to add manage.py --remote option) #'use_remote': True, # Change appid for remote connection (by default it's the same as in # your app.yaml) #'remote_id': 'otherappid', # Change domain (default: <remoteid>.appspot.com) #'remote_host': 'bla.com', } import sys, os rootdir = os.path.dirname(__file__) sys.path.insert(0, os.path.join(rootdir, "lib")) from ragendja.settings_post import *
100uhaco
trunk/GAE/settings.py
Python
asf20
4,619
from ragendja.settings_post import settings settings.add_app_media('combined-%(LANGUAGE_CODE)s.js', 'myapp/code.js', )
100uhaco
trunk/GAE/myapp/settings.py
Python
asf20
123
# -*- coding: utf-8 -*- from django.conf.urls.defaults import * rootpatterns = patterns('', (r'^person/', include('myapp.urls')), )
100uhaco
trunk/GAE/myapp/urlsauto.py
Python
asf20
137
# -*- coding: utf-8 -*- from django.db.models import permalink, signals from google.appengine.ext import db from ragendja.dbutils import cleanup_relations class Person(db.Model): """Basic user profile with personal details.""" first_name = db.StringProperty(required=True) last_name = db.StringProperty(required=True) def __unicode__(self): return '%s %s' % (self.first_name, self.last_name) @permalink def get_absolute_url(self): return ('myapp.views.show_person', (), {'key': self.key()}) signals.pre_delete.connect(cleanup_relations, sender=Person) class File(db.Model): owner = db.ReferenceProperty(Person, required=True, collection_name='file_set') name = db.StringProperty(required=True) file = db.BlobProperty(required=True) @permalink def get_absolute_url(self): return ('myapp.views.download_file', (), {'key': self.key(), 'name': self.name}) def __unicode__(self): return u'File: %s' % self.name class Contract(db.Model): employer = db.ReferenceProperty(Person, required=True, collection_name='employee_contract_set') employee = db.ReferenceProperty(Person, required=True, collection_name='employer_contract_set') start_date = db.DateTimeProperty() end_date = db.DateTimeProperty()
100uhaco
trunk/GAE/myapp/models.py
Python
asf20
1,346
# -*- coding: utf-8 -*- from django import forms from django.contrib.auth.models import User from django.core.files.uploadedfile import UploadedFile from django.utils.translation import ugettext_lazy as _, ugettext as __ from myapp.models import Person, File, Contract from ragendja.auth.models import UserTraits from ragendja.forms import FormWithSets, FormSetField from registration.forms import RegistrationForm, RegistrationFormUniqueEmail from registration.models import RegistrationProfile class UserRegistrationForm(forms.ModelForm): username = forms.RegexField(regex=r'^\w+$', max_length=30, label=_(u'Username')) email = forms.EmailField(widget=forms.TextInput(attrs=dict(maxlength=75)), label=_(u'Email address')) city =forms.RegexField(regex=r'^\w+$', max_length=30, label=_(u'city')) password1 = forms.CharField(widget=forms.PasswordInput(render_value=False), label=_(u'Password')) password2 = forms.CharField(widget=forms.PasswordInput(render_value=False), label=_(u'Password (again)')) def clean_username(self): """ Validate that the username is alphanumeric and is not already in use. """ user = User.get_by_key_name("key_"+self.cleaned_data['username'].lower()) if user and user.is_active: raise forms.ValidationError(__(u'This username is already taken. Please choose another.')) return self.cleaned_data['username'] def clean(self): """ Verifiy that the values entered into the two password fields match. Note that an error here will end up in ``non_field_errors()`` because it doesn't apply to a single field. """ if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data: if self.cleaned_data['password1'] != self.cleaned_data['password2']: raise forms.ValidationError(__(u'You must type the same password each time')) return self.cleaned_data def save(self, domain_override=""): """ Create the new ``User`` and ``RegistrationProfile``, and returns the ``User``. This is essentially a light wrapper around ``RegistrationProfile.objects.create_inactive_user()``, feeding it the form data and a profile callback (see the documentation on ``create_inactive_user()`` for details) if supplied. """ new_user = RegistrationProfile.objects.create_inactive_user( username=self.cleaned_data['username'], password=self.cleaned_data['password1'], email=self.cleaned_data['email'], domain_override=domain_override) self.instance = new_user return super(UserRegistrationForm, self).save() def clean_email(self): """ Validate that the supplied email address is unique for the site. """ email = self.cleaned_data['email'].lower() if User.all().filter('email =', email).filter( 'is_active =', True).count(1): raise forms.ValidationError(__(u'This email address is already in use. Please supply a different email address.')) return email class Meta: model = User exclude = UserTraits.properties().keys() class FileForm(forms.ModelForm): name = forms.CharField(required=False, label='Name (set automatically)') def clean(self): file = self.cleaned_data.get('file') if not self.cleaned_data.get('name'): if isinstance(file, UploadedFile): self.cleaned_data['name'] = file.name else: del self.cleaned_data['name'] return self.cleaned_data class Meta: model = File class PersonForm(forms.ModelForm): files = FormSetField(File, form=FileForm, exclude='content_type') employers = FormSetField(Contract, fk_name='employee') employees = FormSetField(Contract, fk_name='employer') class Meta: model = Person PersonForm = FormWithSets(PersonForm)
100uhaco
trunk/GAE/myapp/forms.py
Python
asf20
4,129
# -*- coding: utf-8 -*- from django.conf.urls.defaults import * urlpatterns = patterns('myapp.views', (r'^create_admin_user$', 'create_admin_user'), (r'^$', 'list_people'), (r'^create/$', 'add_person'), (r'^show/(?P<key>.+)$', 'show_person'), (r'^edit/(?P<key>.+)$', 'edit_person'), (r'^delete/(?P<key>.+)$', 'delete_person'), (r'^download/(?P<key>.+)/(?P<name>.+)$', 'download_file'), )
100uhaco
trunk/GAE/myapp/urls.py
Python
asf20
417
(function($) { $('#clickme').live('click', function() { $(this).append(' Click!'); }); })(jQuery);
100uhaco
trunk/GAE/myapp/media/code.js
JavaScript
asf20
107
{% extends 'base.html' %} {% block title %}Admin created{% endblock %} {% block content %} <h1>Admin created</h1> <p>You've created an admin user with the username and password "admin". Let's have a look at the <a href="/admin/">admin interface</a>, now!</p> {% endblock %}
100uhaco
trunk/GAE/myapp/templates/admin_created.html
HTML
asf20
275
{% extends 'base.html' %} {% block title %}Person listing{% endblock %} {% block content %} <h1>Person listing</h1> <a href="{% url myapp.views.add_person %}">Create person</a> <ul> {% for person in object_list %} <li> <a href="{% url myapp.views.show_person key=person.key %}">{{ person.first_name }} {{ person.last_name }}</a> <a href="{% url myapp.views.edit_person key=person.key %}">Edit</a> <a href="{% url myapp.views.delete_person key=person.key %}">Delete</a> </li> {% endfor %} </ul> <div> {% if has_previous %} <a href="{% url myapp.views.list_people %}?page={{ previous }}">&lt;-previous</a> {% endif %} {% if has_next %} <a href="{% url myapp.views.list_people %}?page={{ next }}">next-&gt;</a> {% endif %} </div> {% endblock %}
100uhaco
trunk/GAE/myapp/templates/person_list.html
HTML
asf20
791
{% extends 'base.html' %} {% block title %}Create person{% endblock %} {% block content %} <h1>Create person</h1> <a href="{% url myapp.views.list_people %}">Back to listing</a> <form action="" method="post" enctype="multipart/form-data"> <table> {{ form.as_table }} <tr><td colspan="2"> <input type="submit" value="{% if object %}Apply changes{% else %}Create{% endif %}" /> </td></tr> </table> </form> {% endblock %}
100uhaco
trunk/GAE/myapp/templates/person_form.html
HTML
asf20
451
{% extends 'base.html' %} {% block title %}Person details{% endblock %} {% block content %} <h1>Person details</h1> <a href="{% url myapp.views.list_people %}">Back to listing</a> <a href="{% url myapp.views.edit_person key=object.key %}">Edit</a> <a href="{% url myapp.views.delete_person key=object.key %}">Delete</a> <ul> <li>First name: {{ object.first_name }}</li> <li>Last name: {{ object.last_name }}</li> <li>Files: {% if object.file_set %}<ul>{% for file in object.file_set %}<li><a href="{{ file.get_absolute_url }}">{{ file.name }}</a></li>{% endfor %}</ul>{% endif %}</li> <li>Employers: {% if object.employer_contract_set %}<ul>{% for contract in object.employer_contract_set %}<li>{{ contract.employer.first_name }} {{ contract.employer.last_name }}</li>{% endfor %}</ul>{% endif %}</li> <li>Employees: {% if object.employee_contract_set %}<ul>{% for contract in object.employee_contract_set %}<li>{{ contract.employee.first_name }} {{ contract.employee.last_name }}</li>{% endfor %}</ul>{% endif %}</li> </ul> {% endblock %}
100uhaco
trunk/GAE/myapp/templates/person_detail.html
HTML
asf20
1,052
{% extends 'base.html' %} {% block title %}Delete person{% endblock %} {% block content %} <h1>Delete person</h1> <a href="{% url myapp.views.list_people %}">Back to listing</a> <a href="{% url myapp.views.show_person key=object.key %}">Back to person</a> <p> Do you really want to delete {{ object.first_name }} {{ object.last_name }}? <form action="" method="post"> <input type="submit" name="delete" value="Delete" /> </form> </p> {% endblock %}
100uhaco
trunk/GAE/myapp/templates/person_confirm_delete.html
HTML
asf20
455
# -*- coding: utf-8 -*- from django.core.urlresolvers import reverse from django.contrib.auth.models import User from django.http import HttpResponse, Http404 from django.views.generic.list_detail import object_list, object_detail from django.views.generic.create_update import create_object, delete_object, \ update_object from google.appengine.ext import db from mimetypes import guess_type from myapp.forms import PersonForm from myapp.models import Contract, File, Person from ragendja.dbutils import get_object_or_404 from ragendja.template import render_to_response def list_people(request): return object_list(request, Person.all(), paginate_by=10) def show_person(request, key): return object_detail(request, Person.all(), key) def add_person(request): return create_object(request, form_class=PersonForm, post_save_redirect=reverse('myapp.views.show_person', kwargs=dict(key='%(key)s'))) def edit_person(request, key): return update_object(request, object_id=key, form_class=PersonForm) def delete_person(request, key): return delete_object(request, Person, object_id=key, post_delete_redirect=reverse('myapp.views.list_people')) def download_file(request, key, name): file = get_object_or_404(File, key) if file.name != name: raise Http404('Could not find file with this name!') return HttpResponse(file.file, content_type=guess_type(file.name)[0] or 'application/octet-stream') def create_admin_user(request): user = User.get_by_key_name('admin') if not user or user.username != 'admin' or not (user.is_active and user.is_staff and user.is_superuser and user.check_password('admin')): user = User(key_name='admin', username='admin', email='admin@localhost', first_name='Boss', last_name='Admin', is_active=True, is_staff=True, is_superuser=True) user.set_password('admin') user.put() return render_to_response(request, 'myapp/admin_created.html')
100uhaco
trunk/GAE/myapp/views.py
Python
asf20
2,052
from django.contrib import admin from myapp.models import Person, File class FileInline(admin.TabularInline): model = File class PersonAdmin(admin.ModelAdmin): inlines = (FileInline,) list_display = ('first_name', 'last_name') admin.site.register(Person, PersonAdmin)
100uhaco
trunk/GAE/myapp/admin.py
Python
asf20
283
#!/usr/bin/env python if __name__ == '__main__': from common.appenginepatch.aecmd import setup_env setup_env(manage_py_env=True) # Recompile translation files from mediautils.compilemessages import updatemessages updatemessages() # Generate compressed media files for manage.py update import sys from mediautils.generatemedia import updatemedia if len(sys.argv) >= 2 and sys.argv[1] == 'update': updatemedia(True) import settings from django.core.management import execute_manager execute_manager(settings)
100uhaco
trunk/GAE/.svn/text-base/manage.py.svn-base
Python
asf20
566
''' Django middleware for HTTP authentication. Copyright (c) 2007, Accense Technology, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Accense Technology nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ''' from django.contrib.auth.models import User, AnonymousUser from django.contrib.auth import authenticate from django.http import HttpResponse import base64 import logging # Written by sgk. # This code depends on the implementation internals of the Django builtin # 'django.contrib.auth.middleware.AuthenticationMiddleware' authentication # middleware, specifically the 'request._cached_user' member. class ByHttpServerMiddleware(object): ''' Reflect the authentication result by HTTP server which hosts Django. This middleware must be placed in the 'settings.py' MIDDLEWARE_CLASSES definition before the above Django builtin 'AuthenticationMiddleware'. You can use the ordinaly '@login_required' decorator to restrict views to authenticated users. Set the 'settings.py' LOGIN_URL definition appropriately if required. ''' def process_request(self, request): if hasattr(request, '_cached_user'): return None try: username = request.META['REMOTE_USER'] user = User.objects.get(username=username) except (KeyError, User.DoesNotExist): # Fallback to other authentication middleware. return None request._cached_user = user return None class Middleware(object): ''' Django implementation of the HTTP basic authentication. This middleware must be placed in the 'settings.py' MIDDLEWARE_CLASSES definition before the above Django builtin 'AuthenticationMiddleware'. Set the 'settings.py' LOGIN_URL definition appropriately if required. To show the browser generated login dialog to user, you have to use the following '@http_login_required(realm=realm)' decorator instead of the ordinaly '@login_required' decorator. ''' def process_request(self, request): if hasattr(request, '_cached_user'): return None try: (method, encoded) = request.META['HTTP_AUTHORIZATION'].split() if method.lower() != 'basic': return None (username, password) = base64.b64decode(encoded).split(':') user =authenticate( username=username, password=password) except (KeyError, TypeError): # Fallback to other authentication middleware. return None request._cached_user = user return None def http_login_required(realm=None): ''' Decorator factory to restrict views to authenticated user and show the browser generated login dialog if the user is not authenticated. This is the function that returns a decorator. To use the decorator, use '@http_login_required()' or '@http_login_required(realm='...')'. ''' def decorator(func): def handler(request, *args, **kw): if request.user.is_authenticated(): return func(request, *args, **kw) response = HttpResponse(status=401) response['WWW-Authenticate'] = 'Basic realm="%s"' % (realm or 'Django') return response return handler return decorator
100uhaco
trunk/GAE/httpauth.py
Python
asf20
4,442
# -*- coding: utf-8 -*- from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.http import HttpResponseRedirect from django.utils.translation import ugettext as _ from ragendja.template import render_to_response from django.template import Context, RequestContext, loader from django.views.generic.list_detail import object_list from django.views.generic.simple import direct_to_template from django.forms.formsets import formset_factory from haco.models import * from httpauth import * from haco.jsTime import * from haco.convert import * import logging import time @login_required def repo_all( request): u = User.all() u = u.filter( 'username', request.user.username) u = u.filter( 'is_superuser', True) if u.count() == 0: return HttpResponse("you don't have the right to access this page") else: logging.info("repo_all") if request.GET.has_key( 'delta'): day = someday(int(request.GET['delta'])) else: day = today() q = HacoUser.all() mes = "<html><head></head><body>" for hacoUser in q: user = hacoUser.user mes += str(hacoUser.user.username) mes +="<div>" t_list = [-1.0] * 144 l_list = [-1.0] * 144 w_list = [-1.0] * 144 q =Haco.all() q =q.order( 'pnum') q =q.filter( 'user', user) q =q.filter( 'date', day) q =q.order( 'pnum') for h in q: t_list[h.pnum] = h.temp l_list[h.pnum] = h.light w_list[h.pnum] = h.watt mes += t_chart(t_list) mes += l_chart(l_list) mes += w_chart(w_list) mes +="</div>" mes +="</body></html>" return HttpResponse( mes) def t_chart( a_list): chart = "<img src='http://chart.apis.google.com/chart?chs=750x185&cht=lc&chco=00b379&chxt=y&chxr=0,0,40&chds=0,40&chd=t:" for data in a_list: chart += str(data) +"," chart = chart[0:len(chart)-1] chart += "&chtt=temperature&chg=4.17,25,1,4&chl=0|||||1|||||2|||||3|||||4|||||5|||||6|||||7|||||8|||||9|||||10|||||11|||||12|||||13|||||14|||||15|||||16|||||17|||||18|||||19|||||20|||||21|||||22|||||23|||||'>" return chart def l_chart( a_list): chart = "<img src='http://chart.apis.google.com/chart?chs=750x185&cht=lc&chxt =y&chxr=0,0,700&chds=0,700&chd=t:" for data in a_list: chart += str(data) +"," chart = chart[0:len(chart)-1] chart += "&cht=lc&chtt=light&chg=4.17,14.3,1,2&chl=0|||||1|||||2|||||3|||||4|||||5|||||6|||||7|||||8|||||9|||||10|||||11|||||12|||||13|||||14|||||15|||||16|||||17|||||18|||||19|||||20|||||21|||||22|||||23|||||'>" return chart def w_chart( a_list): chart = "<img src='http://chart.apis.google.com/chart?chs=750x185&cht=lc&chco=009CD1&chxt=y&chxr=0,0,1000&chds=0,1000&chd=t:" for data in a_list: chart += str(data) +"," chart = chart[0:len(chart)-1] chart += "&cht=lc&chtt=watt&chg=4.17,20.00,1,2&chl=0|||||1|||||2|||||3|||||4|||||5|||||6|||||7|||||8|||||9|||||10|||||11|||||12|||||13|||||14|||||15|||||16|||||17|||||18|||||19|||||20|||||21|||||22|||||23|||||'>" return chart
100uhaco
trunk/GAE/haco/views2.py
Python
asf20
3,415
# -*- coding: utf-8 -*- from django.utils.translation import ugettext_lazy as _ from google.appengine.ext import db from django.contrib.auth.models import User #from datetime import * import datetime class HacoUser( db.Model): user =db.ReferenceProperty( User) zip =db.StringProperty() twitterID =db.StringProperty() address =db.StringProperty() geoPt =db.GeoPtProperty() class Haco( db.Model): user =db.ReferenceProperty( User) username =db.StringProperty( str(User)) pnum =db.IntegerProperty() temp =db.FloatProperty() light =db.FloatProperty() watt =db.FloatProperty() date =db.DateTimeProperty() timestamp = db.DateTimeProperty() class Mention( db.Model): postUser =db.StringProperty() postText =db.StringProperty() postDate =db.DateTimeProperty()
100uhaco
trunk/GAE/haco/models.py
Python
asf20
824
# -*- coding: utf-8 -*- from django import forms from django.contrib.auth.models import User from django.core.files.uploadedfile import UploadedFile from django.utils.translation import ugettext_lazy as _, ugettext as __ from myapp.models import Person, File, Contract from ragendja.auth.models import UserTraits from ragendja.forms import FormWithSets, FormSetField from registration.forms import RegistrationForm, RegistrationFormUniqueEmail from registration.models import RegistrationProfile from hashlib import sha1 from haco.models import HacoUser class UserRegistrationForm(forms.ModelForm): username =forms.RegexField(regex=r'^\w+$', max_length=30, label=_(u'Username')) email = forms.EmailField(widget=forms.TextInput(attrs=dict(maxlength=75)), label=_(u'Email address')) twitterID =forms.RegexField(regex=r'^\w+$', max_length=30, label=_(u'TwitterID')) zip =forms.RegexField(regex=r'^[0-9]+$', max_length=30, label=_(u'Zip')) password1 = forms.CharField(widget=forms.PasswordInput(render_value=False), label=_(u'Password')) password2 = forms.CharField(widget=forms.PasswordInput(render_value=False), label=_(u'Password (again)')) def clean_username(self): """ Validate that the username is alphanumeric and is not already in use. """ user = User.get_by_key_name("key_"+self.cleaned_data['username'].lower()) if user and user.is_active: raise forms.ValidationError(__(u'This username is already taken. Please choose another.')) return self.cleaned_data['username'] def clean(self): """ Verifiy that the values entered into the two password fields match. Note that an error here will end up in ``non_field_errors()`` because it doesn't apply to a single field. """ if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data: if self.cleaned_data['password1'] != self.cleaned_data['password2']: raise forms.ValidationError(__(u'You must type the same password each time')) return self.cleaned_data def save(self, domain_override="", user=""): """ Create the new ``User`` and ``RegistrationProfile``, and returns the ``User``. This is essentially a light wrapper around ``RegistrationProfile.objects.create_inactive_user()``, feeding it the form data and a profile callback (see the documentation on ``create_inactive_user()`` for details) if supplied. """ new_user = RegistrationProfile.objects.create_inactive_user( username=self.cleaned_data['username'], password=self.cleaned_data['password1'], email=self.cleaned_data['email'], domain_override=domain_override, send_email=False) self.instance = new_user if super(UserRegistrationForm, self).save(): haco_users =HacoUser.all().filter( 'user =', self.instance) if haco_users.count() ==0: haco_user =HacoUser() haco_user.user =new_user haco_user.zip =self.cleaned_data['twitterID'] haco_user.zip =self.cleaned_data['zip'] haco_user.put() else: for haco_user in haco_users: haco_user.zip =self.cleaned_data['twitterID'] haco_user.zip =self.cleaned_data['zip'] haco_user.put() def clean_email(self): """ Validate that the supplied email address is unique for the site. """ email = self.cleaned_data['email'].lower() if User.all().filter('email =', email).filter( 'is_active =', True).count(1): raise forms.ValidationError(__(u'This email address is already in use. Please supply a different email address.')) return email class Meta: model =User exclude = UserTraits.properties().keys() class UserConfigForm(forms.Form): twitterID =forms.RegexField(regex=r'^\w+$', max_length=30, label=_(u'TwitterID')) zip = forms.RegexField(required=True, regex=r'^[0-9]+$', max_length=7,label=_(u'Zip')) def save(self, key=""): q =HacoUser.all() q =q.filter( 'user',key) for hacoUser in q: ID = hacoUser.key().id() hacouser = HacoUser.get_by_id(ID) hacouser.user = key hacouser.zip = self.cleaned_data['zip'] hacouser.twitterID = self.cleaned_data['twitterID'] hacouser.put() class QueryForm(forms.Form): username = forms.RegexField(regex=r'^\w+$', max_length=30) delta = forms.RegexField(regex=r'^-[0-9]+$', max_length=3) pnum = forms.RegexField(regex=r'^[0-9]+$', max_length=3) ##class UserConfigurationForm(forms.Form): ## ## email = forms.EmailField(widget=forms.TextInput(attrs=dict(maxlength=75)), ## label=_(u'Email address')) ## ## first_name = forms.RegexField(regex=r'^\w+$', max_length=30, ## label=_(u'First name')) ## ## last_name = forms.RegexField(regex=r'^\w+$', max_length=30, ## label=_(u'Last name')) ## ## twitterID =forms.RegexField(regex=r'^\w+$', max_length=30, ## label=_(u'TwitterID')) ## ## zip =forms.RegexField(regex=r'^[0-9]+$', max_length=30, ## label=_(u'zip')) ## ## password1 = forms.CharField(widget=forms.PasswordInput(render_value=False), ## label=_(u'Password')) ## ## password2 = forms.CharField(widget=forms.PasswordInput(render_value=False), ## label=_(u'Password (again)')) ## ## def clean(self): ## return self.cleaned_data ## ## def save(self, key=""): ## ## auth_user = User.get( key) ## ## ## q =HacoUser.all() ## q =q.filter( 'user',key) ## for hacoUser in q: ## ID = hacoUser.key().id() ## ## user = User.get(key) ## user.email = self.cleaned_data['zip'] ## user.first_name = self.cleaned_data['first_name'] ## user.last_name = self.cleaned_data['last_name'] ## user.password = sha1(self.cleaned_data['password1']).hexdigest() ## user.put() ## ## ## ## hacouser = HacoUser.get_by_id(ID) ## hacouser.user = key ## hacouser.zip = self.cleaned_data['zip'] ## hacouser.twitterID = self.cleaned_data['twitterID'] ## hacouser.put() ## ## class FileForm(forms.ModelForm): name = forms.CharField(required=False, label='Name (set automatically)') def clean(self): file = self.cleaned_data.get('file') if not self.cleaned_data.get('name'): if isinstance(file, UploadedFile): self.cleaned_data['name'] = file.name else: del self.cleaned_data['name'] return self.cleaned_data class Meta: model = File #class PersonForm(forms.ModelForm): # files = FormSetField(File, form=FileForm, exclude='content_type') # employers = FormSetField(Contract, fk_name='employee') # employees = FormSetField(Contract, fk_name='employer') # # class Meta: # model = Person #PersonForm = FormWithSets(PersonForm)
100uhaco
trunk/GAE/haco/forms.py
Python
asf20
7,775
#!/usr/bin/python """ NOTE: Tango is being renamed to Twython; all basic strings have been changed below, but there's still work ongoing in this department. Twython is an up-to-date library for Python that wraps the Twitter API. Other Python Twitter libraries seem to have fallen a bit behind, and Twitter's API has evolved a bit. Here's hoping this helps. TODO: OAuth, Streaming API? Questions, comments? ryan@venodesigns.net """ import httplib, urllib, urllib2, mimetypes, mimetools from urllib2 import HTTPError __author__ = "Ryan McGrath <ryan@venodesigns.net>" __version__ = "0.8.0.1" """Twython - Easy Twitter utilities in Python""" try: import simplejson except ImportError: try: import json as simplejson except: raise Exception("Twython requires the simplejson library (or Python 2.6) to work. http://www.undefined.org/python/") try: import oauth except ImportError: pass class TangoError(Exception): def __init__(self, msg, error_code=None): self.msg = msg if error_code == 400: raise APILimit(msg) def __str__(self): return repr(self.msg) class APILimit(TangoError): def __init__(self, msg): self.msg = msg def __str__(self): return repr(self.msg) class setup: def __init__(self, authtype = "OAuth", username = None, password = None, oauth_keys = None, headers = None): self.authtype = authtype self.authenticated = False self.username = username self.password = password self.oauth_keys = oauth_keys if self.username is not None and self.password is not None: if self.authtype == "OAuth": self.request_token_url = 'https://twitter.com/oauth/request_token' self.access_token_url = 'https://twitter.com/oauth/access_token' self.authorization_url = 'http://twitter.com/oauth/authorize' self.signin_url = 'http://twitter.com/oauth/authenticate' # Do OAuth type stuff here - how should this be handled? Seems like a framework question... elif self.authtype == "Basic": self.auth_manager = urllib2.HTTPPasswordMgrWithDefaultRealm() self.auth_manager.add_password(None, "http://twitter.com", self.username, self.password) self.handler = urllib2.HTTPBasicAuthHandler(self.auth_manager) self.opener = urllib2.build_opener(self.handler) if headers is not None: self.opener.addheaders = [('User-agent', headers)] try: simplejson.load(self.opener.open("http://twitter.com/account/verify_credentials.json")) self.authenticated = True except HTTPError, e: raise TangoError("Authentication failed with your provided credentials. Try again? (%s failure)" % `e.code`, e.code) # OAuth functions; shortcuts for verifying the credentials. def fetch_response_oauth(self, oauth_request): pass def get_unauthorized_request_token(self): pass def get_authorization_url(self, token): pass def exchange_tokens(self, request_token): pass # URL Shortening function huzzah def shortenURL(self, url_to_shorten, shortener = "http://is.gd/api.php", query = "longurl"): try: return urllib2.urlopen(shortener + "?" + urllib.urlencode({query: url_to_shorten})).read() except HTTPError, e: raise TangoError("shortenURL() failed with a %s error code." % `e.code`) def constructApiURL(self, base_url, params): return base_url + "?" + "&".join(["%s=%s" %(key, value) for (key, value) in params.iteritems()]) def getRateLimitStatus(self, rate_for = "requestingIP"): try: if rate_for == "requestingIP": return simplejson.load(urllib2.urlopen("http://twitter.com/account/rate_limit_status.json")) else: if self.authenticated is True: return simplejson.load(self.opener.open("http://twitter.com/account/rate_limit_status.json")) else: raise TangoError("You need to be authenticated to check a rate limit status on an account.") except HTTPError, e: raise TangoError("It seems that there's something wrong. Twitter gave you a %s error code; are you doing something you shouldn't be?" % `e.code`, e.code) def getPublicTimeline(self): try: return simplejson.load(urllib2.urlopen("http://twitter.com/statuses/public_timeline.json")) except HTTPError, e: raise TangoError("getPublicTimeline() failed with a %s error code." % `e.code`) def getFriendsTimeline(self, **kwargs): if self.authenticated is True: try: friendsTimelineURL = self.constructApiURL("http://twitter.com/statuses/friends_timeline.json", kwargs) return simplejson.load(self.opener.open(friendsTimelineURL)) except HTTPError, e: raise TangoError("getFriendsTimeline() failed with a %s error code." % `e.code`) else: raise TangoError("getFriendsTimeline() requires you to be authenticated.") def getUserTimeline(self, id = None, **kwargs): if id is not None and kwargs.has_key("user_id") is False and kwargs.has_key("screen_name") is False: userTimelineURL = self.constructApiURL("http://twitter.com/statuses/user_timeline/" + id + ".json", kwargs) elif id is None and kwargs.has_key("user_id") is False and kwargs.has_key("screen_name") is False and self.authenticated is True: userTimelineURL = self.constructApiURL("http://twitter.com/statuses/user_timeline/" + self.username + ".json", kwargs) else: userTimelineURL = self.constructApiURL("http://twitter.com/statuses/user_timeline.json", kwargs) try: # We do our custom opener if we're authenticated, as it helps avoid cases where it's a protected user if self.authenticated is True: return simplejson.load(self.opener.open(userTimelineURL)) else: return simplejson.load(urllib2.urlopen(userTimelineURL)) except HTTPError, e: raise TangoError("Failed with a %s error code. Does this user hide/protect their updates? If so, you'll need to authenticate and be their friend to get their timeline." % `e.code`, e.code) def getUserMentions(self, **kwargs): if self.authenticated is True: try: mentionsFeedURL = self.constructApiURL("http://twitter.com/statuses/mentions.json", kwargs) return simplejson.load(self.opener.open(mentionsFeedURL)) except HTTPError, e: raise TangoError("getUserMentions() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("getUserMentions() requires you to be authenticated.") def showStatus(self, id): try: if self.authenticated is True: return simplejson.load(self.opener.open("http://twitter.com/statuses/show/%s.json" % id)) else: return simplejson.load(urllib2.urlopen("http://twitter.com/statuses/show/%s.json" % id)) except HTTPError, e: raise TangoError("Failed with a %s error code. Does this user hide/protect their updates? You'll need to authenticate and be friends to get their timeline." % `e.code`, e.code) def updateStatus(self, status, in_reply_to_status_id = None): if self.authenticated is True: if len(list(status)) > 140: raise TangoError("This status message is over 140 characters. Trim it down!") try: return simplejson.load(self.opener.open("http://twitter.com/statuses/update.json?", urllib.urlencode({"status": status, "in_reply_to_status_id": in_reply_to_status_id}))) except HTTPError, e: raise TangoError("updateStatus() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("updateStatus() requires you to be authenticated.") def destroyStatus(self, id): if self.authenticated is True: try: return simplejson.load(self.opener.open("http://twitter.com/status/destroy/%s.json", "POST" % id)) except HTTPError, e: raise TangoError("destroyStatus() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("destroyStatus() requires you to be authenticated.") def endSession(self): if self.authenticated is True: try: self.opener.open("http://twitter.com/account/end_session.json", "") self.authenticated = False except HTTPError, e: raise TangoError("endSession failed with a %s error code." % `e.code`, e.code) else: raise TangoError("You can't end a session when you're not authenticated to begin with.") def getDirectMessages(self, since_id = None, max_id = None, count = None, page = "1"): if self.authenticated is True: apiURL = "http://twitter.com/direct_messages.json?page=" + page if since_id is not None: apiURL += "&since_id=" + since_id if max_id is not None: apiURL += "&max_id=" + max_id if count is not None: apiURL += "&count=" + count try: return simplejson.load(self.opener.open(apiURL)) except HTTPError, e: raise TangoError("getDirectMessages() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("getDirectMessages() requires you to be authenticated.") def getSentMessages(self, since_id = None, max_id = None, count = None, page = "1"): if self.authenticated is True: apiURL = "http://twitter.com/direct_messages/sent.json?page=" + page if since_id is not None: apiURL += "&since_id=" + since_id if max_id is not None: apiURL += "&max_id=" + max_id if count is not None: apiURL += "&count=" + count try: return simplejson.load(self.opener.open(apiURL)) except HTTPError, e: raise TangoError("getSentMessages() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("getSentMessages() requires you to be authenticated.") def sendDirectMessage(self, user, text): if self.authenticated is True: if len(list(text)) < 140: try: return self.opener.open("http://twitter.com/direct_messages/new.json", urllib.urlencode({"user": user, "text": text})) except HTTPError, e: raise TangoError("sendDirectMessage() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("Your message must not be longer than 140 characters") else: raise TangoError("You must be authenticated to send a new direct message.") def destroyDirectMessage(self, id): if self.authenticated is True: try: return self.opener.open("http://twitter.com/direct_messages/destroy/%s.json" % id, "") except HTTPError, e: raise TangoError("destroyDirectMessage() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("You must be authenticated to destroy a direct message.") def createFriendship(self, id = None, user_id = None, screen_name = None, follow = "false"): if self.authenticated is True: apiURL = "" if id is not None: apiURL = "http://twitter.com/friendships/create/" + id + ".json" + "?follow=" + follow if user_id is not None: apiURL = "http://twitter.com/friendships/create.json?user_id=" + user_id + "&follow=" + follow if screen_name is not None: apiURL = "http://twitter.com/friendships/create.json?screen_name=" + screen_name + "&follow=" + follow try: return simplejson.load(self.opener.open(apiURL)) except HTTPError, e: # Rate limiting is done differently here for API reasons... if e.code == 403: raise TangoError("You've hit the update limit for this method. Try again in 24 hours.") raise TangoError("createFriendship() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("createFriendship() requires you to be authenticated.") def destroyFriendship(self, id = None, user_id = None, screen_name = None): if self.authenticated is True: apiURL = "" if id is not None: apiURL = "http://twitter.com/friendships/destroy/" + id + ".json" if user_id is not None: apiURL = "http://twitter.com/friendships/destroy.json?user_id=" + user_id if screen_name is not None: apiURL = "http://twitter.com/friendships/destroy.json?screen_name=" + screen_name try: return simplejson.load(self.opener.open(apiURL)) except HTTPError, e: raise TangoError("destroyFriendship() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("destroyFriendship() requires you to be authenticated.") def checkIfFriendshipExists(self, user_a, user_b): if self.authenticated is True: try: return simplejson.load(self.opener.open("http://twitter.com/friendships/exists.json", urllib.urlencode({"user_a": user_a, "user_b": user_b}))) except HTTPError, e: raise TangoError("checkIfFriendshipExists() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("checkIfFriendshipExists(), oddly, requires that you be authenticated.") def updateDeliveryDevice(self, device_name = "none"): if self.authenticated is True: try: return self.opener.open("http://twitter.com/account/update_delivery_device.json?", urllib.urlencode({"device": device_name})) except HTTPError, e: raise TangoError("updateDeliveryDevice() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("updateDeliveryDevice() requires you to be authenticated.") def updateProfileColors(self, **kwargs): if self.authenticated is True: try: return self.opener.open(self.constructApiURL("http://twitter.com/account/update_profile_colors.json?", kwargs)) except HTTPError, e: raise TangoError("updateProfileColors() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("updateProfileColors() requires you to be authenticated.") def updateProfile(self, name = None, email = None, url = None, location = None, description = None): if self.authenticated is True: useAmpersands = False updateProfileQueryString = "" if name is not None: if len(list(name)) < 20: updateProfileQueryString += "name=" + name useAmpersands = True else: raise TangoError("Twitter has a character limit of 20 for all usernames. Try again.") if email is not None and "@" in email: if len(list(email)) < 40: if useAmpersands is True: updateProfileQueryString += "&email=" + email else: updateProfileQueryString += "email=" + email useAmpersands = True else: raise TangoError("Twitter has a character limit of 40 for all email addresses, and the email address must be valid. Try again.") if url is not None: if len(list(url)) < 100: if useAmpersands is True: updateProfileQueryString += "&" + urllib.urlencode({"url": url}) else: updateProfileQueryString += urllib.urlencode({"url": url}) useAmpersands = True else: raise TangoError("Twitter has a character limit of 100 for all urls. Try again.") if location is not None: if len(list(location)) < 30: if useAmpersands is True: updateProfileQueryString += "&" + urllib.urlencode({"location": location}) else: updateProfileQueryString += urllib.urlencode({"location": location}) useAmpersands = True else: raise TangoError("Twitter has a character limit of 30 for all locations. Try again.") if description is not None: if len(list(description)) < 160: if useAmpersands is True: updateProfileQueryString += "&" + urllib.urlencode({"description": description}) else: updateProfileQueryString += urllib.urlencode({"description": description}) else: raise TangoError("Twitter has a character limit of 160 for all descriptions. Try again.") if updateProfileQueryString != "": try: return self.opener.open("http://twitter.com/account/update_profile.json?", updateProfileQueryString) except HTTPError, e: raise TangoError("updateProfile() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("updateProfile() requires you to be authenticated.") def getFavorites(self, page = "1"): if self.authenticated is True: try: return simplejson.load(self.opener.open("http://twitter.com/favorites.json?page=" + page)) except HTTPError, e: raise TangoError("getFavorites() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("getFavorites() requires you to be authenticated.") def createFavorite(self, id): if self.authenticated is True: try: return simplejson.load(self.opener.open("http://twitter.com/favorites/create/" + id + ".json", "")) except HTTPError, e: raise TangoError("createFavorite() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("createFavorite() requires you to be authenticated.") def destroyFavorite(self, id): if self.authenticated is True: try: return simplejson.load(self.opener.open("http://twitter.com/favorites/destroy/" + id + ".json", "")) except HTTPError, e: raise TangoError("destroyFavorite() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("destroyFavorite() requires you to be authenticated.") def notificationFollow(self, id = None, user_id = None, screen_name = None): if self.authenticated is True: apiURL = "" if id is not None: apiURL = "http://twitter.com/notifications/follow/" + id + ".json" if user_id is not None: apiURL = "http://twitter.com/notifications/follow/follow.json?user_id=" + user_id if screen_name is not None: apiURL = "http://twitter.com/notifications/follow/follow.json?screen_name=" + screen_name try: return simplejson.load(self.opener.open(apiURL, "")) except HTTPError, e: raise TangoError("notificationFollow() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("notificationFollow() requires you to be authenticated.") def notificationLeave(self, id = None, user_id = None, screen_name = None): if self.authenticated is True: apiURL = "" if id is not None: apiURL = "http://twitter.com/notifications/leave/" + id + ".json" if user_id is not None: apiURL = "http://twitter.com/notifications/leave/leave.json?user_id=" + user_id if screen_name is not None: apiURL = "http://twitter.com/notifications/leave/leave.json?screen_name=" + screen_name try: return simplejson.load(self.opener.open(apiURL, "")) except HTTPError, e: raise TangoError("notificationLeave() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("notificationLeave() requires you to be authenticated.") def getFriendsIDs(self, id = None, user_id = None, screen_name = None, page = "1"): apiURL = "" if id is not None: apiURL = "http://twitter.com/friends/ids/" + id + ".json" + "?page=" + page if user_id is not None: apiURL = "http://twitter.com/friends/ids.json?user_id=" + user_id + "&page=" + page if screen_name is not None: apiURL = "http://twitter.com/friends/ids.json?screen_name=" + screen_name + "&page=" + page try: return simplejson.load(urllib2.urlopen(apiURL)) except HTTPError, e: raise TangoError("getFriendsIDs() failed with a %s error code." % `e.code`, e.code) def getFollowersIDs(self, id = None, user_id = None, screen_name = None, page = "1"): apiURL = "" if id is not None: apiURL = "http://twitter.com/followers/ids/" + id + ".json" + "?page=" + page if user_id is not None: apiURL = "http://twitter.com/followers/ids.json?user_id=" + user_id + "&page=" + page if screen_name is not None: apiURL = "http://twitter.com/followers/ids.json?screen_name=" + screen_name + "&page=" + page try: return simplejson.load(urllib2.urlopen(apiURL)) except HTTPError, e: raise TangoError("getFollowersIDs() failed with a %s error code." % `e.code`, e.code) def createBlock(self, id): if self.authenticated is True: try: return simplejson.load(self.opener.open("http://twitter.com/blocks/create/" + id + ".json", "")) except HTTPError, e: raise TangoError("createBlock() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("createBlock() requires you to be authenticated.") def destroyBlock(self, id): if self.authenticated is True: try: return simplejson.load(self.opener.open("http://twitter.com/blocks/destroy/" + id + ".json", "")) except HTTPError, e: raise TangoError("destroyBlock() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("destroyBlock() requires you to be authenticated.") def checkIfBlockExists(self, id = None, user_id = None, screen_name = None): apiURL = "" if id is not None: apiURL = "http://twitter.com/blocks/exists/" + id + ".json" if user_id is not None: apiURL = "http://twitter.com/blocks/exists.json?user_id=" + user_id if screen_name is not None: apiURL = "http://twitter.com/blocks/exists.json?screen_name=" + screen_name try: return simplejson.load(urllib2.urlopen(apiURL)) except HTTPError, e: raise TangoError("checkIfBlockExists() failed with a %s error code." % `e.code`, e.code) def getBlocking(self, page = "1"): if self.authenticated is True: try: return simplejson.load(self.opener.open("http://twitter.com/blocks/blocking.json?page=" + page)) except HTTPError, e: raise TangoError("getBlocking() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("getBlocking() requires you to be authenticated") def getBlockedIDs(self): if self.authenticated is True: try: return simplejson.load(self.opener.open("http://twitter.com/blocks/blocking/ids.json")) except HTTPError, e: raise TangoError("getBlockedIDs() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("getBlockedIDs() requires you to be authenticated.") def searchTwitter(self, search_query, **kwargs): searchURL = self.constructApiURL("http://search.twitter.com/search.json", kwargs) + "&" + urllib.urlencode({"q": search_query}) try: return simplejson.load(urllib2.urlopen(searchURL)) except HTTPError, e: raise TangoError("getSearchTimeline() failed with a %s error code." % `e.code`, e.code) def getCurrentTrends(self, excludeHashTags = False): apiURL = "http://search.twitter.com/trends/current.json" if excludeHashTags is True: apiURL += "?exclude=hashtags" try: return simplejson.load(urllib.urlopen(apiURL)) except HTTPError, e: raise TangoError("getCurrentTrends() failed with a %s error code." % `e.code`, e.code) def getDailyTrends(self, date = None, exclude = False): apiURL = "http://search.twitter.com/trends/daily.json" questionMarkUsed = False if date is not None: apiURL += "?date=" + date questionMarkUsed = True if exclude is True: if questionMarkUsed is True: apiURL += "&exclude=hashtags" else: apiURL += "?exclude=hashtags" try: return simplejson.load(urllib.urlopen(apiURL)) except HTTPError, e: raise TangoError("getDailyTrends() failed with a %s error code." % `e.code`, e.code) def getWeeklyTrends(self, date = None, exclude = False): apiURL = "http://search.twitter.com/trends/daily.json" questionMarkUsed = False if date is not None: apiURL += "?date=" + date questionMarkUsed = True if exclude is True: if questionMarkUsed is True: apiURL += "&exclude=hashtags" else: apiURL += "?exclude=hashtags" try: return simplejson.load(urllib.urlopen(apiURL)) except HTTPError, e: raise TangoError("getWeeklyTrends() failed with a %s error code." % `e.code`, e.code) def getSavedSearches(self): if self.authenticated is True: try: return simplejson.load(self.opener.open("http://twitter.com/saved_searches.json")) except HTTPError, e: raise TangoError("getSavedSearches() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("getSavedSearches() requires you to be authenticated.") def showSavedSearch(self, id): if self.authenticated is True: try: return simplejson.load(self.opener.open("http://twitter.com/saved_searches/show/" + id + ".json")) except HTTPError, e: raise TangoError("showSavedSearch() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("showSavedSearch() requires you to be authenticated.") def createSavedSearch(self, query): if self.authenticated is True: try: return simplejson.load(self.opener.open("http://twitter.com/saved_searches/create.json?query=" + query, "")) except HTTPError, e: raise TangoError("createSavedSearch() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("createSavedSearch() requires you to be authenticated.") def destroySavedSearch(self, id): if self.authenticated is True: try: return simplejson.load(self.opener.open("http://twitter.com/saved_searches/destroy/" + id + ".json", "")) except HTTPError, e: raise TangoError("destroySavedSearch() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("destroySavedSearch() requires you to be authenticated.") # The following methods are apart from the other Account methods, because they rely on a whole multipart-data posting function set. def updateProfileBackgroundImage(self, filename, tile="true"): if self.authenticated is True: try: files = [("image", filename, open(filename).read())] fields = [] content_type, body = self.encode_multipart_formdata(fields, files) headers = {'Content-Type': content_type, 'Content-Length': str(len(body))} r = urllib2.Request("http://twitter.com/account/update_profile_background_image.json?tile=" + tile, body, headers) return self.opener.open(r).read() except HTTPError, e: raise TangoError("updateProfileBackgroundImage() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("You realize you need to be authenticated to change a background image, right?") def updateProfileImage(self, filename): if self.authenticated is True: try: files = [("image", filename, open(filename).read())] fields = [] content_type, body = self.encode_multipart_formdata(fields, files) headers = {'Content-Type': content_type, 'Content-Length': str(len(body))} r = urllib2.Request("http://twitter.com/account/update_profile_image.json", body, headers) return self.opener.open(r).read() except HTTPError, e: raise TangoError("updateProfileImage() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("You realize you need to be authenticated to change a profile image, right?") def encode_multipart_formdata(self, fields, files): BOUNDARY = mimetools.choose_boundary() CRLF = '\r\n' L = [] for (key, value) in fields: L.append('--' + BOUNDARY) L.append('Content-Disposition: form-data; name="%s"' % key) L.append('') L.append(value) for (key, filename, value) in files: L.append('--' + BOUNDARY) L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) L.append('Content-Type: %s' % self.get_content_type(filename)) L.append('') L.append(value) L.append('--' + BOUNDARY + '--') L.append('') body = CRLF.join(L) content_type = 'multipart/form-data; boundary=%s' % BOUNDARY return content_type, body def get_content_type(self, filename): return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
100uhaco
trunk/GAE/haco/.svn/text-base/twython.py.svn-base
Python
asf20
26,871
#!/usr/bin/python2.4 # # Copyright 2007 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. '''A library that provides a python interface to the Twitter API''' __author__ = 'dewitt@google.com' __version__ = '0.6-devel' import base64 import calendar import os import rfc822 import simplejson import sys import tempfile import textwrap import time import urllib import urllib2 import urlparse try: from hashlib import md5 except ImportError: from md5 import md5 CHARACTER_LIMIT = 140 class TwitterError(Exception): '''Base class for Twitter errors''' @property def message(self): '''Returns the first argument used to construct this error.''' return self.args[0] class Status(object): '''A class representing the Status structure used by the twitter API. The Status structure exposes the following properties: status.created_at status.created_at_in_seconds # read only status.favorited status.in_reply_to_screen_name status.in_reply_to_user_id status.in_reply_to_status_id status.truncated status.source status.id status.text status.relative_created_at # read only status.user ''' def __init__(self, created_at=None, favorited=None, id=None, text=None, user=None, in_reply_to_screen_name=None, in_reply_to_user_id=None, in_reply_to_status_id=None, truncated=None, source=None, now=None): '''An object to hold a Twitter status message. This class is normally instantiated by the twitter.Api class and returned in a sequence. Note: Dates are posted in the form "Sat Jan 27 04:17:38 +0000 2007" Args: created_at: The time this status message was posted favorited: Whether this is a favorite of the authenticated user id: The unique id of this status message text: The text of this status message relative_created_at: A human readable string representing the posting time user: A twitter.User instance representing the person posting the message now: The current time, if the client choses to set it. Defaults to the wall clock time. ''' self.created_at = created_at self.favorited = favorited self.id = id self.text = text self.user = user self.now = now self.in_reply_to_screen_name = in_reply_to_screen_name self.in_reply_to_user_id = in_reply_to_user_id self.in_reply_to_status_id = in_reply_to_status_id self.truncated = truncated self.source = source def GetCreatedAt(self): '''Get the time this status message was posted. Returns: The time this status message was posted ''' return self._created_at def SetCreatedAt(self, created_at): '''Set the time this status message was posted. Args: created_at: The time this status message was created ''' self._created_at = created_at created_at = property(GetCreatedAt, SetCreatedAt, doc='The time this status message was posted.') def GetCreatedAtInSeconds(self): '''Get the time this status message was posted, in seconds since the epoch. Returns: The time this status message was posted, in seconds since the epoch. ''' return calendar.timegm(rfc822.parsedate(self.created_at)) created_at_in_seconds = property(GetCreatedAtInSeconds, doc="The time this status message was " "posted, in seconds since the epoch") def GetFavorited(self): '''Get the favorited setting of this status message. Returns: True if this status message is favorited; False otherwise ''' return self._favorited def SetFavorited(self, favorited): '''Set the favorited state of this status message. Args: favorited: boolean True/False favorited state of this status message ''' self._favorited = favorited favorited = property(GetFavorited, SetFavorited, doc='The favorited state of this status message.') def GetId(self): '''Get the unique id of this status message. Returns: The unique id of this status message ''' return self._id def SetId(self, id): '''Set the unique id of this status message. Args: id: The unique id of this status message ''' self._id = id id = property(GetId, SetId, doc='The unique id of this status message.') def GetInReplyToScreenName(self): return self._in_reply_to_screen_name def SetInReplyToScreenName(self, in_reply_to_screen_name): self._in_reply_to_screen_name = in_reply_to_screen_name in_reply_to_screen_name = property(GetInReplyToScreenName, SetInReplyToScreenName, doc='') def GetInReplyToUserId(self): return self._in_reply_to_user_id def SetInReplyToUserId(self, in_reply_to_user_id): self._in_reply_to_user_id = in_reply_to_user_id in_reply_to_user_id = property(GetInReplyToUserId, SetInReplyToUserId, doc='') def GetInReplyToStatusId(self): return self._in_reply_to_status_id def SetInReplyToStatusId(self, in_reply_to_status_id): self._in_reply_to_status_id = in_reply_to_status_id in_reply_to_status_id = property(GetInReplyToStatusId, SetInReplyToStatusId, doc='') def GetTruncated(self): return self._truncated def SetTruncated(self, truncated): self._truncated = truncated truncated = property(GetTruncated, SetTruncated, doc='') def GetSource(self): return self._source def SetSource(self, source): self._source = source source = property(GetSource, SetSource, doc='') def GetText(self): '''Get the text of this status message. Returns: The text of this status message. ''' return self._text def SetText(self, text): '''Set the text of this status message. Args: text: The text of this status message ''' self._text = text text = property(GetText, SetText, doc='The text of this status message') def GetRelativeCreatedAt(self): '''Get a human redable string representing the posting time Returns: A human readable string representing the posting time ''' fudge = 1.25 delta = long(self.now) - long(self.created_at_in_seconds) if delta < (1 * fudge): return 'about a second ago' elif delta < (60 * (1/fudge)): return 'about %d seconds ago' % (delta) elif delta < (60 * fudge): return 'about a minute ago' elif delta < (60 * 60 * (1/fudge)): return 'about %d minutes ago' % (delta / 60) elif delta < (60 * 60 * fudge): return 'about an hour ago' elif delta < (60 * 60 * 24 * (1/fudge)): return 'about %d hours ago' % (delta / (60 * 60)) elif delta < (60 * 60 * 24 * fudge): return 'about a day ago' else: return 'about %d days ago' % (delta / (60 * 60 * 24)) relative_created_at = property(GetRelativeCreatedAt, doc='Get a human readable string representing' 'the posting time') def GetUser(self): '''Get a twitter.User reprenting the entity posting this status message. Returns: A twitter.User reprenting the entity posting this status message ''' return self._user def SetUser(self, user): '''Set a twitter.User reprenting the entity posting this status message. Args: user: A twitter.User reprenting the entity posting this status message ''' self._user = user user = property(GetUser, SetUser, doc='A twitter.User reprenting the entity posting this ' 'status message') def GetNow(self): '''Get the wallclock time for this status message. Used to calculate relative_created_at. Defaults to the time the object was instantiated. Returns: Whatever the status instance believes the current time to be, in seconds since the epoch. ''' if self._now is None: self._now = time.time() return self._now def SetNow(self, now): '''Set the wallclock time for this status message. Used to calculate relative_created_at. Defaults to the time the object was instantiated. Args: now: The wallclock time for this instance. ''' self._now = now now = property(GetNow, SetNow, doc='The wallclock time for this status instance.') def __ne__(self, other): return not self.__eq__(other) def __eq__(self, other): try: return other and \ self.created_at == other.created_at and \ self.id == other.id and \ self.text == other.text and \ self.user == other.user and \ self.in_reply_to_screen_name == other.in_reply_to_screen_name and \ self.in_reply_to_user_id == other.in_reply_to_user_id and \ self.in_reply_to_status_id == other.in_reply_to_status_id and \ self.truncated == other.truncated and \ self.favorited == other.favorited and \ self.source == other.source except AttributeError: return False def __str__(self): '''A string representation of this twitter.Status instance. The return value is the same as the JSON string representation. Returns: A string representation of this twitter.Status instance. ''' return self.AsJsonString() def AsJsonString(self): '''A JSON string representation of this twitter.Status instance. Returns: A JSON string representation of this twitter.Status instance ''' return simplejson.dumps(self.AsDict(), sort_keys=True) def AsDict(self): '''A dict representation of this twitter.Status instance. The return value uses the same key names as the JSON representation. Return: A dict representing this twitter.Status instance ''' data = {} if self.created_at: data['created_at'] = self.created_at if self.favorited: data['favorited'] = self.favorited if self.id: data['id'] = self.id if self.text: data['text'] = self.text if self.user: data['user'] = self.user.AsDict() if self.in_reply_to_screen_name: data['in_reply_to_screen_name'] = self.in_reply_to_screen_name if self.in_reply_to_user_id: data['in_reply_to_user_id'] = self.in_reply_to_user_id if self.in_reply_to_status_id: data['in_reply_to_status_id'] = self.in_reply_to_status_id if self.truncated is not None: data['truncated'] = self.truncated if self.favorited is not None: data['favorited'] = self.favorited if self.source: data['source'] = self.source return data @staticmethod def NewFromJsonDict(data): '''Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.Status instance ''' if 'user' in data: user = User.NewFromJsonDict(data['user']) else: user = None return Status(created_at=data.get('created_at', None), favorited=data.get('favorited', None), id=data.get('id', None), text=data.get('text', None), in_reply_to_screen_name=data.get('in_reply_to_screen_name', None), in_reply_to_user_id=data.get('in_reply_to_user_id', None), in_reply_to_status_id=data.get('in_reply_to_status_id', None), truncated=data.get('truncated', None), source=data.get('source', None), user=user) class User(object): '''A class representing the User structure used by the twitter API. The User structure exposes the following properties: user.id user.name user.screen_name user.location user.description user.profile_image_url user.profile_background_tile user.profile_background_image_url user.profile_sidebar_fill_color user.profile_background_color user.profile_link_color user.profile_text_color user.protected user.utc_offset user.time_zone user.url user.status user.statuses_count user.followers_count user.friends_count user.favourites_count ''' def __init__(self, id=None, name=None, screen_name=None, location=None, description=None, profile_image_url=None, profile_background_tile=None, profile_background_image_url=None, profile_sidebar_fill_color=None, profile_background_color=None, profile_link_color=None, profile_text_color=None, protected=None, utc_offset=None, time_zone=None, followers_count=None, friends_count=None, statuses_count=None, favourites_count=None, url=None, status=None): self.id = id self.name = name self.screen_name = screen_name self.location = location self.description = description self.profile_image_url = profile_image_url self.profile_background_tile = profile_background_tile self.profile_background_image_url = profile_background_image_url self.profile_sidebar_fill_color = profile_sidebar_fill_color self.profile_background_color = profile_background_color self.profile_link_color = profile_link_color self.profile_text_color = profile_text_color self.protected = protected self.utc_offset = utc_offset self.time_zone = time_zone self.followers_count = followers_count self.friends_count = friends_count self.statuses_count = statuses_count self.favourites_count = favourites_count self.url = url self.status = status def GetId(self): '''Get the unique id of this user. Returns: The unique id of this user ''' return self._id def SetId(self, id): '''Set the unique id of this user. Args: id: The unique id of this user. ''' self._id = id id = property(GetId, SetId, doc='The unique id of this user.') def GetName(self): '''Get the real name of this user. Returns: The real name of this user ''' return self._name def SetName(self, name): '''Set the real name of this user. Args: name: The real name of this user ''' self._name = name name = property(GetName, SetName, doc='The real name of this user.') def GetScreenName(self): '''Get the short username of this user. Returns: The short username of this user ''' return self._screen_name def SetScreenName(self, screen_name): '''Set the short username of this user. Args: screen_name: the short username of this user ''' self._screen_name = screen_name screen_name = property(GetScreenName, SetScreenName, doc='The short username of this user.') def GetLocation(self): '''Get the geographic location of this user. Returns: The geographic location of this user ''' return self._location def SetLocation(self, location): '''Set the geographic location of this user. Args: location: The geographic location of this user ''' self._location = location location = property(GetLocation, SetLocation, doc='The geographic location of this user.') def GetDescription(self): '''Get the short text description of this user. Returns: The short text description of this user ''' return self._description def SetDescription(self, description): '''Set the short text description of this user. Args: description: The short text description of this user ''' self._description = description description = property(GetDescription, SetDescription, doc='The short text description of this user.') def GetUrl(self): '''Get the homepage url of this user. Returns: The homepage url of this user ''' return self._url def SetUrl(self, url): '''Set the homepage url of this user. Args: url: The homepage url of this user ''' self._url = url url = property(GetUrl, SetUrl, doc='The homepage url of this user.') def GetProfileImageUrl(self): '''Get the url of the thumbnail of this user. Returns: The url of the thumbnail of this user ''' return self._profile_image_url def SetProfileImageUrl(self, profile_image_url): '''Set the url of the thumbnail of this user. Args: profile_image_url: The url of the thumbnail of this user ''' self._profile_image_url = profile_image_url profile_image_url= property(GetProfileImageUrl, SetProfileImageUrl, doc='The url of the thumbnail of this user.') def GetProfileBackgroundTile(self): '''Boolean for whether to tile the profile background image. Returns: True if the background is to be tiled, False if not, None if unset. ''' return self._profile_background_tile def SetProfileBackgroundTile(self, profile_background_tile): '''Set the boolean flag for whether to tile the profile background image. Args: profile_background_tile: Boolean flag for whether to tile or not. ''' self._profile_background_tile = profile_background_tile profile_background_tile = property(GetProfileBackgroundTile, SetProfileBackgroundTile, doc='Boolean for whether to tile the background image.') def GetProfileBackgroundImageUrl(self): return self._profile_background_image_url def SetProfileBackgroundImageUrl(self, profile_background_image_url): self._profile_background_image_url = profile_background_image_url profile_background_image_url = property(GetProfileBackgroundImageUrl, SetProfileBackgroundImageUrl, doc='The url of the profile background of this user.') def GetProfileSidebarFillColor(self): return self._profile_sidebar_fill_color def SetProfileSidebarFillColor(self, profile_sidebar_fill_color): self._profile_sidebar_fill_color = profile_sidebar_fill_color profile_sidebar_fill_color = property(GetProfileSidebarFillColor, SetProfileSidebarFillColor) def GetProfileBackgroundColor(self): return self._profile_background_color def SetProfileBackgroundColor(self, profile_background_color): self._profile_background_color = profile_background_color profile_background_color = property(GetProfileBackgroundColor, SetProfileBackgroundColor) def GetProfileLinkColor(self): return self._profile_link_color def SetProfileLinkColor(self, profile_link_color): self._profile_link_color = profile_link_color profile_link_color = property(GetProfileLinkColor, SetProfileLinkColor) def GetProfileTextColor(self): return self._profile_text_color def SetProfileTextColor(self, profile_text_color): self._profile_text_color = profile_text_color profile_text_color = property(GetProfileTextColor, SetProfileTextColor) def GetProtected(self): return self._protected def SetProtected(self, protected): self._protected = protected protected = property(GetProtected, SetProtected) def GetUtcOffset(self): return self._utc_offset def SetUtcOffset(self, utc_offset): self._utc_offset = utc_offset utc_offset = property(GetUtcOffset, SetUtcOffset) def GetTimeZone(self): '''Returns the current time zone string for the user. Returns: The descriptive time zone string for the user. ''' return self._time_zone def SetTimeZone(self, time_zone): '''Sets the user's time zone string. Args: time_zone: The descriptive time zone to assign for the user. ''' self._time_zone = time_zone time_zone = property(GetTimeZone, SetTimeZone) def GetStatus(self): '''Get the latest twitter.Status of this user. Returns: The latest twitter.Status of this user ''' return self._status def SetStatus(self, status): '''Set the latest twitter.Status of this user. Args: status: The latest twitter.Status of this user ''' self._status = status status = property(GetStatus, SetStatus, doc='The latest twitter.Status of this user.') def GetFriendsCount(self): '''Get the friend count for this user. Returns: The number of users this user has befriended. ''' return self._friends_count def SetFriendsCount(self, count): '''Set the friend count for this user. Args: count: The number of users this user has befriended. ''' self._friends_count = count friends_count = property(GetFriendsCount, SetFriendsCount, doc='The number of friends for this user.') def GetFollowersCount(self): '''Get the follower count for this user. Returns: The number of users following this user. ''' return self._followers_count def SetFollowersCount(self, count): '''Set the follower count for this user. Args: count: The number of users following this user. ''' self._followers_count = count followers_count = property(GetFollowersCount, SetFollowersCount, doc='The number of users following this user.') def GetStatusesCount(self): '''Get the number of status updates for this user. Returns: The number of status updates for this user. ''' return self._statuses_count def SetStatusesCount(self, count): '''Set the status update count for this user. Args: count: The number of updates for this user. ''' self._statuses_count = count statuses_count = property(GetStatusesCount, SetStatusesCount, doc='The number of updates for this user.') def GetFavouritesCount(self): '''Get the number of favourites for this user. Returns: The number of favourites for this user. ''' return self._favourites_count def SetFavouritesCount(self, count): '''Set the favourite count for this user. Args: count: The number of favourites for this user. ''' self._favourites_count = count favourites_count = property(GetFavouritesCount, SetFavouritesCount, doc='The number of favourites for this user.') def __ne__(self, other): return not self.__eq__(other) def __eq__(self, other): try: return other and \ self.id == other.id and \ self.name == other.name and \ self.screen_name == other.screen_name and \ self.location == other.location and \ self.description == other.description and \ self.profile_image_url == other.profile_image_url and \ self.profile_background_tile == other.profile_background_tile and \ self.profile_background_image_url == other.profile_background_image_url and \ self.profile_sidebar_fill_color == other.profile_sidebar_fill_color and \ self.profile_background_color == other.profile_background_color and \ self.profile_link_color == other.profile_link_color and \ self.profile_text_color == other.profile_text_color and \ self.protected == other.protected and \ self.utc_offset == other.utc_offset and \ self.time_zone == other.time_zone and \ self.url == other.url and \ self.statuses_count == other.statuses_count and \ self.followers_count == other.followers_count and \ self.favourites_count == other.favourites_count and \ self.friends_count == other.friends_count and \ self.status == other.status except AttributeError: return False def __str__(self): '''A string representation of this twitter.User instance. The return value is the same as the JSON string representation. Returns: A string representation of this twitter.User instance. ''' return self.AsJsonString() def AsJsonString(self): '''A JSON string representation of this twitter.User instance. Returns: A JSON string representation of this twitter.User instance ''' return simplejson.dumps(self.AsDict(), sort_keys=True) def AsDict(self): '''A dict representation of this twitter.User instance. The return value uses the same key names as the JSON representation. Return: A dict representing this twitter.User instance ''' data = {} if self.id: data['id'] = self.id if self.name: data['name'] = self.name if self.screen_name: data['screen_name'] = self.screen_name if self.location: data['location'] = self.location if self.description: data['description'] = self.description if self.profile_image_url: data['profile_image_url'] = self.profile_image_url if self.profile_background_tile is not None: data['profile_background_tile'] = self.profile_background_tile if self.profile_background_image_url: data['profile_sidebar_fill_color'] = self.profile_background_image_url if self.profile_background_color: data['profile_background_color'] = self.profile_background_color if self.profile_link_color: data['profile_link_color'] = self.profile_link_color if self.profile_text_color: data['profile_text_color'] = self.profile_text_color if self.protected is not None: data['protected'] = self.protected if self.utc_offset: data['utc_offset'] = self.utc_offset if self.time_zone: data['time_zone'] = self.time_zone if self.url: data['url'] = self.url if self.status: data['status'] = self.status.AsDict() if self.friends_count: data['friends_count'] = self.friends_count if self.followers_count: data['followers_count'] = self.followers_count if self.statuses_count: data['statuses_count'] = self.statuses_count if self.favourites_count: data['favourites_count'] = self.favourites_count return data @staticmethod def NewFromJsonDict(data): '''Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.User instance ''' if 'status' in data: status = Status.NewFromJsonDict(data['status']) else: status = None return User(id=data.get('id', None), name=data.get('name', None), screen_name=data.get('screen_name', None), location=data.get('location', None), description=data.get('description', None), statuses_count=data.get('statuses_count', None), followers_count=data.get('followers_count', None), favourites_count=data.get('favourites_count', None), friends_count=data.get('friends_count', None), profile_image_url=data.get('profile_image_url', None), profile_background_tile = data.get('profile_background_tile', None), profile_background_image_url = data.get('profile_background_image_url', None), profile_sidebar_fill_color = data.get('profile_sidebar_fill_color', None), profile_background_color = data.get('profile_background_color', None), profile_link_color = data.get('profile_link_color', None), profile_text_color = data.get('profile_text_color', None), protected = data.get('protected', None), utc_offset = data.get('utc_offset', None), time_zone = data.get('time_zone', None), url=data.get('url', None), status=status) class DirectMessage(object): '''A class representing the DirectMessage structure used by the twitter API. The DirectMessage structure exposes the following properties: direct_message.id direct_message.created_at direct_message.created_at_in_seconds # read only direct_message.sender_id direct_message.sender_screen_name direct_message.recipient_id direct_message.recipient_screen_name direct_message.text ''' def __init__(self, id=None, created_at=None, sender_id=None, sender_screen_name=None, recipient_id=None, recipient_screen_name=None, text=None): '''An object to hold a Twitter direct message. This class is normally instantiated by the twitter.Api class and returned in a sequence. Note: Dates are posted in the form "Sat Jan 27 04:17:38 +0000 2007" Args: id: The unique id of this direct message created_at: The time this direct message was posted sender_id: The id of the twitter user that sent this message sender_screen_name: The name of the twitter user that sent this message recipient_id: The id of the twitter that received this message recipient_screen_name: The name of the twitter that received this message text: The text of this direct message ''' self.id = id self.created_at = created_at self.sender_id = sender_id self.sender_screen_name = sender_screen_name self.recipient_id = recipient_id self.recipient_screen_name = recipient_screen_name self.text = text def GetId(self): '''Get the unique id of this direct message. Returns: The unique id of this direct message ''' return self._id def SetId(self, id): '''Set the unique id of this direct message. Args: id: The unique id of this direct message ''' self._id = id id = property(GetId, SetId, doc='The unique id of this direct message.') def GetCreatedAt(self): '''Get the time this direct message was posted. Returns: The time this direct message was posted ''' return self._created_at def SetCreatedAt(self, created_at): '''Set the time this direct message was posted. Args: created_at: The time this direct message was created ''' self._created_at = created_at created_at = property(GetCreatedAt, SetCreatedAt, doc='The time this direct message was posted.') def GetCreatedAtInSeconds(self): '''Get the time this direct message was posted, in seconds since the epoch. Returns: The time this direct message was posted, in seconds since the epoch. ''' return calendar.timegm(rfc822.parsedate(self.created_at)) created_at_in_seconds = property(GetCreatedAtInSeconds, doc="The time this direct message was " "posted, in seconds since the epoch") def GetSenderId(self): '''Get the unique sender id of this direct message. Returns: The unique sender id of this direct message ''' return self._sender_id def SetSenderId(self, sender_id): '''Set the unique sender id of this direct message. Args: sender id: The unique sender id of this direct message ''' self._sender_id = sender_id sender_id = property(GetSenderId, SetSenderId, doc='The unique sender id of this direct message.') def GetSenderScreenName(self): '''Get the unique sender screen name of this direct message. Returns: The unique sender screen name of this direct message ''' return self._sender_screen_name def SetSenderScreenName(self, sender_screen_name): '''Set the unique sender screen name of this direct message. Args: sender_screen_name: The unique sender screen name of this direct message ''' self._sender_screen_name = sender_screen_name sender_screen_name = property(GetSenderScreenName, SetSenderScreenName, doc='The unique sender screen name of this direct message.') def GetRecipientId(self): '''Get the unique recipient id of this direct message. Returns: The unique recipient id of this direct message ''' return self._recipient_id def SetRecipientId(self, recipient_id): '''Set the unique recipient id of this direct message. Args: recipient id: The unique recipient id of this direct message ''' self._recipient_id = recipient_id recipient_id = property(GetRecipientId, SetRecipientId, doc='The unique recipient id of this direct message.') def GetRecipientScreenName(self): '''Get the unique recipient screen name of this direct message. Returns: The unique recipient screen name of this direct message ''' return self._recipient_screen_name def SetRecipientScreenName(self, recipient_screen_name): '''Set the unique recipient screen name of this direct message. Args: recipient_screen_name: The unique recipient screen name of this direct message ''' self._recipient_screen_name = recipient_screen_name recipient_screen_name = property(GetRecipientScreenName, SetRecipientScreenName, doc='The unique recipient screen name of this direct message.') def GetText(self): '''Get the text of this direct message. Returns: The text of this direct message. ''' return self._text def SetText(self, text): '''Set the text of this direct message. Args: text: The text of this direct message ''' self._text = text text = property(GetText, SetText, doc='The text of this direct message') def __ne__(self, other): return not self.__eq__(other) def __eq__(self, other): try: return other and \ self.id == other.id and \ self.created_at == other.created_at and \ self.sender_id == other.sender_id and \ self.sender_screen_name == other.sender_screen_name and \ self.recipient_id == other.recipient_id and \ self.recipient_screen_name == other.recipient_screen_name and \ self.text == other.text except AttributeError: return False def __str__(self): '''A string representation of this twitter.DirectMessage instance. The return value is the same as the JSON string representation. Returns: A string representation of this twitter.DirectMessage instance. ''' return self.AsJsonString() def AsJsonString(self): '''A JSON string representation of this twitter.DirectMessage instance. Returns: A JSON string representation of this twitter.DirectMessage instance ''' return simplejson.dumps(self.AsDict(), sort_keys=True) def AsDict(self): '''A dict representation of this twitter.DirectMessage instance. The return value uses the same key names as the JSON representation. Return: A dict representing this twitter.DirectMessage instance ''' data = {} if self.id: data['id'] = self.id if self.created_at: data['created_at'] = self.created_at if self.sender_id: data['sender_id'] = self.sender_id if self.sender_screen_name: data['sender_screen_name'] = self.sender_screen_name if self.recipient_id: data['recipient_id'] = self.recipient_id if self.recipient_screen_name: data['recipient_screen_name'] = self.recipient_screen_name if self.text: data['text'] = self.text return data @staticmethod def NewFromJsonDict(data): '''Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.DirectMessage instance ''' return DirectMessage(created_at=data.get('created_at', None), recipient_id=data.get('recipient_id', None), sender_id=data.get('sender_id', None), text=data.get('text', None), sender_screen_name=data.get('sender_screen_name', None), id=data.get('id', None), recipient_screen_name=data.get('recipient_screen_name', None)) class Api(object): '''A python interface into the Twitter API By default, the Api caches results for 1 minute. Example usage: To create an instance of the twitter.Api class, with no authentication: >>> import twitter >>> api = twitter.Api() To fetch the most recently posted public twitter status messages: >>> statuses = api.GetPublicTimeline() >>> print [s.user.name for s in statuses] [u'DeWitt', u'Kesuke Miyagi', u'ev', u'Buzz Andersen', u'Biz Stone'] #... To fetch a single user's public status messages, where "user" is either a Twitter "short name" or their user id. >>> statuses = api.GetUserTimeline(user) >>> print [s.text for s in statuses] To use authentication, instantiate the twitter.Api class with a username and password: >>> api = twitter.Api(username='twitter user', password='twitter pass') To fetch your friends (after being authenticated): >>> users = api.GetFriends() >>> print [u.name for u in users] To post a twitter status message (after being authenticated): >>> status = api.PostUpdate('I love python-twitter!') >>> print status.text I love python-twitter! There are many other methods, including: >>> api.PostUpdates(status) >>> api.PostDirectMessage(user, text) >>> api.GetUser(user) >>> api.GetReplies() >>> api.GetUserTimeline(user) >>> api.GetStatus(id) >>> api.DestroyStatus(id) >>> api.GetFriendsTimeline(user) >>> api.GetFriends(user) >>> api.GetFollowers() >>> api.GetFeatured() >>> api.GetDirectMessages() >>> api.PostDirectMessage(user, text) >>> api.DestroyDirectMessage(id) >>> api.DestroyFriendship(user) >>> api.CreateFriendship(user) >>> api.GetUserByEmail(email) ''' DEFAULT_CACHE_TIMEOUT = 60 # cache for 1 minute _API_REALM = 'Twitter API' def __init__(self, username=None, password=None, input_encoding=None, request_headers=None): '''Instantiate a new twitter.Api object. Args: username: The username of the twitter account. [optional] password: The password for the twitter account. [optional] input_encoding: The encoding used to encode input strings. [optional] request_header: A dictionary of additional HTTP request headers. [optional] ''' self._cache = _FileCache() self._urllib = urllib2 self._cache_timeout = Api.DEFAULT_CACHE_TIMEOUT self._InitializeRequestHeaders(request_headers) self._InitializeUserAgent() self._InitializeDefaultParameters() self._input_encoding = input_encoding self.SetCredentials(username, password) def GetPublicTimeline(self, since_id=None): '''Fetch the sequnce of public twitter.Status message for all users. Args: since_id: Returns only public statuses with an ID greater than (that is, more recent than) the specified ID. [Optional] Returns: An sequence of twitter.Status instances, one for each message ''' parameters = {} if since_id: parameters['since_id'] = since_id url = 'http://twitter.com/statuses/public_timeline.json' json = self._FetchUrl(url, parameters=parameters) data = simplejson.loads(json) self._CheckForTwitterError(data) return [Status.NewFromJsonDict(x) for x in data] def GetFriendsTimeline(self, user=None, count=None, since=None, since_id=None): '''Fetch the sequence of twitter.Status messages for a user's friends The twitter.Api instance must be authenticated if the user is private. Args: user: Specifies the ID or screen name of the user for whom to return the friends_timeline. If unspecified, the username and password must be set in the twitter.Api instance. [Optional] count: Specifies the number of statuses to retrieve. May not be greater than 200. [Optional] since: Narrows the returned results to just those statuses created after the specified HTTP-formatted date. [Optional] since_id: Returns only public statuses with an ID greater than (that is, more recent than) the specified ID. [Optional] Returns: A sequence of twitter.Status instances, one for each message ''' if user: url = 'http://twitter.com/statuses/friends_timeline/%s.json' % user elif not user and not self._username: raise TwitterError("User must be specified if API is not authenticated.") else: url = 'http://twitter.com/statuses/friends_timeline.json' parameters = {} if count is not None: try: if int(count) > 200: raise TwitterError("'count' may not be greater than 200") except ValueError: raise TwitterError("'count' must be an integer") parameters['count'] = count if since: parameters['since'] = since if since_id: parameters['since_id'] = since_id json = self._FetchUrl(url, parameters=parameters) data = simplejson.loads(json) self._CheckForTwitterError(data) return [Status.NewFromJsonDict(x) for x in data] def GetUserTimeline(self, user=None, count=None, since=None, since_id=None): '''Fetch the sequence of public twitter.Status messages for a single user. The twitter.Api instance must be authenticated if the user is private. Args: user: either the username (short_name) or id of the user to retrieve. If not specified, then the current authenticated user is used. [optional] count: the number of status messages to retrieve [optional] since: Narrows the returned results to just those statuses created after the specified HTTP-formatted date. [optional] since_id: Returns only public statuses with an ID greater than (that is, more recent than) the specified ID. [Optional] Returns: A sequence of twitter.Status instances, one for each message up to count ''' try: if count: int(count) except: raise TwitterError("Count must be an integer") parameters = {} if count: parameters['count'] = count if since: parameters['since'] = since if since_id: parameters['since_id'] = since_id if user: url = 'http://twitter.com/statuses/user_timeline/%s.json' % user elif not user and not self._username: raise TwitterError("User must be specified if API is not authenticated.") else: url = 'http://twitter.com/statuses/user_timeline.json' json = self._FetchUrl(url, parameters=parameters) data = simplejson.loads(json) self._CheckForTwitterError(data) return [Status.NewFromJsonDict(x) for x in data] def GetStatus(self, id): '''Returns a single status message. The twitter.Api instance must be authenticated if the status message is private. Args: id: The numerical ID of the status you're trying to retrieve. Returns: A twitter.Status instance representing that status message ''' try: if id: long(id) except: raise TwitterError("id must be an long integer") url = 'http://twitter.com/statuses/show/%s.json' % id json = self._FetchUrl(url) data = simplejson.loads(json) self._CheckForTwitterError(data) return Status.NewFromJsonDict(data) def DestroyStatus(self, id): '''Destroys the status specified by the required ID parameter. The twitter.Api instance must be authenticated and thee authenticating user must be the author of the specified status. Args: id: The numerical ID of the status you're trying to destroy. Returns: A twitter.Status instance representing the destroyed status message ''' try: if id: long(id) except: raise TwitterError("id must be an integer") url = 'http://twitter.com/statuses/destroy/%s.json' % id json = self._FetchUrl(url, post_data={}) data = simplejson.loads(json) self._CheckForTwitterError(data) return Status.NewFromJsonDict(data) def PostUpdate(self, status, in_reply_to_status_id=None): '''Post a twitter status message from the authenticated user. The twitter.Api instance must be authenticated. Args: status: The message text to be posted. Must be less than or equal to 140 characters. in_reply_to_status_id: The ID of an existing status that the status to be posted is in reply to. This implicitly sets the in_reply_to_user_id attribute of the resulting status to the user ID of the message being replied to. Invalid/missing status IDs will be ignored. [Optional] Returns: A twitter.Status instance representing the message posted. ''' if not self._username: raise TwitterError("The twitter.Api instance must be authenticated.") url = 'http://twitter.com/statuses/update.json' if len(status) > CHARACTER_LIMIT: raise TwitterError("Text must be less than or equal to %d characters. " "Consider using PostUpdates." % CHARACTER_LIMIT) data = {'status': status} if in_reply_to_status_id: data['in_reply_to_status_id'] = in_reply_to_status_id json = self._FetchUrl(url, post_data=data) data = simplejson.loads(json) self._CheckForTwitterError(data) return Status.NewFromJsonDict(data) def PostUpdates(self, status, continuation=None, **kwargs): '''Post one or more twitter status messages from the authenticated user. Unlike api.PostUpdate, this method will post multiple status updates if the message is longer than 140 characters. The twitter.Api instance must be authenticated. Args: status: The message text to be posted. May be longer than 140 characters. continuation: The character string, if any, to be appended to all but the last message. Note that Twitter strips trailing '...' strings from messages. Consider using the unicode \u2026 character (horizontal ellipsis) instead. [Defaults to None] **kwargs: See api.PostUpdate for a list of accepted parameters. Returns: A of list twitter.Status instance representing the messages posted. ''' results = list() if continuation is None: continuation = '' line_length = CHARACTER_LIMIT - len(continuation) lines = textwrap.wrap(status, line_length) for line in lines[0:-1]: results.append(self.PostUpdate(line + continuation, **kwargs)) results.append(self.PostUpdate(lines[-1], **kwargs)) return results def GetReplies(self, since=None, since_id=None, page=None): '''Get a sequence of status messages representing the 20 most recent replies (status updates prefixed with @username) to the authenticating user. Args: page: since: Narrows the returned results to just those statuses created after the specified HTTP-formatted date. [optional] since_id: Returns only public statuses with an ID greater than (that is, more recent than) the specified ID. [Optional] Returns: A sequence of twitter.Status instances, one for each reply to the user. ''' url = 'http://twitter.com/statuses/replies.json' if not self._username: raise TwitterError("The twitter.Api instance must be authenticated.") parameters = {} if since: parameters['since'] = since if since_id: parameters['since_id'] = since_id if page: parameters['page'] = page json = self._FetchUrl(url, parameters=parameters) data = simplejson.loads(json) self._CheckForTwitterError(data) return [Status.NewFromJsonDict(x) for x in data] def GetFriends(self, user=None, page=None): '''Fetch the sequence of twitter.User instances, one for each friend. Args: user: the username or id of the user whose friends you are fetching. If not specified, defaults to the authenticated user. [optional] The twitter.Api instance must be authenticated. Returns: A sequence of twitter.User instances, one for each friend ''' if not self._username: raise TwitterError("twitter.Api instance must be authenticated") if user: url = 'http://twitter.com/statuses/friends/%s.json' % user else: url = 'http://twitter.com/statuses/friends.json' parameters = {} if page: parameters['page'] = page json = self._FetchUrl(url, parameters=parameters) data = simplejson.loads(json) self._CheckForTwitterError(data) return [User.NewFromJsonDict(x) for x in data] def GetFollowers(self, page=None): '''Fetch the sequence of twitter.User instances, one for each follower The twitter.Api instance must be authenticated. Returns: A sequence of twitter.User instances, one for each follower ''' if not self._username: raise TwitterError("twitter.Api instance must be authenticated") url = 'http://twitter.com/statuses/followers.json' parameters = {} if page: parameters['page'] = page json = self._FetchUrl(url, parameters=parameters) data = simplejson.loads(json) self._CheckForTwitterError(data) return [User.NewFromJsonDict(x) for x in data] def GetFeatured(self): '''Fetch the sequence of twitter.User instances featured on twitter.com The twitter.Api instance must be authenticated. Returns: A sequence of twitter.User instances ''' url = 'http://twitter.com/statuses/featured.json' json = self._FetchUrl(url) data = simplejson.loads(json) self._CheckForTwitterError(data) return [User.NewFromJsonDict(x) for x in data] def GetUser(self, user): '''Returns a single user. The twitter.Api instance must be authenticated. Args: user: The username or id of the user to retrieve. Returns: A twitter.User instance representing that user ''' url = 'http://twitter.com/users/show/%s.json' % user json = self._FetchUrl(url) data = simplejson.loads(json) self._CheckForTwitterError(data) return User.NewFromJsonDict(data) def GetDirectMessages(self, since=None, since_id=None, page=None): '''Returns a list of the direct messages sent to the authenticating user. The twitter.Api instance must be authenticated. Args: since: Narrows the returned results to just those statuses created after the specified HTTP-formatted date. [optional] since_id: Returns only public statuses with an ID greater than (that is, more recent than) the specified ID. [Optional] Returns: A sequence of twitter.DirectMessage instances ''' url = 'http://twitter.com/direct_messages.json' if not self._username: raise TwitterError("The twitter.Api instance must be authenticated.") parameters = {} if since: parameters['since'] = since if since_id: parameters['since_id'] = since_id if page: parameters['page'] = page json = self._FetchUrl(url, parameters=parameters) data = simplejson.loads(json) self._CheckForTwitterError(data) return [DirectMessage.NewFromJsonDict(x) for x in data] def PostDirectMessage(self, user, text): '''Post a twitter direct message from the authenticated user The twitter.Api instance must be authenticated. Args: user: The ID or screen name of the recipient user. text: The message text to be posted. Must be less than 140 characters. Returns: A twitter.DirectMessage instance representing the message posted ''' if not self._username: raise TwitterError("The twitter.Api instance must be authenticated.") url = 'http://twitter.com/direct_messages/new.json' data = {'text': text, 'user': user} json = self._FetchUrl(url, post_data=data) data = simplejson.loads(json) self._CheckForTwitterError(data) return DirectMessage.NewFromJsonDict(data) def DestroyDirectMessage(self, id): '''Destroys the direct message specified in the required ID parameter. The twitter.Api instance must be authenticated, and the authenticating user must be the recipient of the specified direct message. Args: id: The id of the direct message to be destroyed Returns: A twitter.DirectMessage instance representing the message destroyed ''' url = 'http://twitter.com/direct_messages/destroy/%s.json' % id json = self._FetchUrl(url, post_data={}) data = simplejson.loads(json) self._CheckForTwitterError(data) return DirectMessage.NewFromJsonDict(data) def CreateFriendship(self, user): '''Befriends the user specified in the user parameter as the authenticating user. The twitter.Api instance must be authenticated. Args: The ID or screen name of the user to befriend. Returns: A twitter.User instance representing the befriended user. ''' url = 'http://twitter.com/friendships/create/%s.json' % user json = self._FetchUrl(url, post_data={}) data = simplejson.loads(json) self._CheckForTwitterError(data) return User.NewFromJsonDict(data) def DestroyFriendship(self, user): '''Discontinues friendship with the user specified in the user parameter. The twitter.Api instance must be authenticated. Args: The ID or screen name of the user with whom to discontinue friendship. Returns: A twitter.User instance representing the discontinued friend. ''' url = 'http://twitter.com/friendships/destroy/%s.json' % user json = self._FetchUrl(url, post_data={}) data = simplejson.loads(json) self._CheckForTwitterError(data) return User.NewFromJsonDict(data) def CreateFavorite(self, status): '''Favorites the status specified in the status parameter as the authenticating user. Returns the favorite status when successful. The twitter.Api instance must be authenticated. Args: The twitter.Status instance to mark as a favorite. Returns: A twitter.Status instance representing the newly-marked favorite. ''' url = 'http://twitter.com/favorites/create/%s.json' % status.id json = self._FetchUrl(url, post_data={}) data = simplejson.loads(json) self._CheckForTwitterError(data) return Status.NewFromJsonDict(data) def DestroyFavorite(self, status): '''Un-favorites the status specified in the ID parameter as the authenticating user. Returns the un-favorited status in the requested format when successful. The twitter.Api instance must be authenticated. Args: The twitter.Status to unmark as a favorite. Returns: A twitter.Status instance representing the newly-unmarked favorite. ''' url = 'http://twitter.com/favorites/destroy/%s.json' % status.id json = self._FetchUrl(url, post_data={}) data = simplejson.loads(json) self._CheckForTwitterError(data) return Status.NewFromJsonDict(data) def GetUserByEmail(self, email): '''Returns a single user by email address. Args: email: The email of the user to retrieve. Returns: A twitter.User instance representing that user ''' url = 'http://twitter.com/users/show.json?email=%s' % email json = self._FetchUrl(url) data = simplejson.loads(json) self._CheckForTwitterError(data) return User.NewFromJsonDict(data) def SetCredentials(self, username, password): '''Set the username and password for this instance Args: username: The twitter username. password: The twitter password. ''' self._username = username self._password = password def ClearCredentials(self): '''Clear the username and password for this instance ''' self._username = None self._password = None def SetCache(self, cache): '''Override the default cache. Set to None to prevent caching. Args: cache: an instance that supports the same API as the twitter._FileCache ''' self._cache = cache def SetUrllib(self, urllib): '''Override the default urllib implementation. Args: urllib: an instance that supports the same API as the urllib2 module ''' self._urllib = urllib def SetCacheTimeout(self, cache_timeout): '''Override the default cache timeout. Args: cache_timeout: time, in seconds, that responses should be reused. ''' self._cache_timeout = cache_timeout def SetUserAgent(self, user_agent): '''Override the default user agent Args: user_agent: a string that should be send to the server as the User-agent ''' self._request_headers['User-Agent'] = user_agent def SetXTwitterHeaders(self, client, url, version): '''Set the X-Twitter HTTP headers that will be sent to the server. Args: client: The client name as a string. Will be sent to the server as the 'X-Twitter-Client' header. url: The URL of the meta.xml as a string. Will be sent to the server as the 'X-Twitter-Client-URL' header. version: The client version as a string. Will be sent to the server as the 'X-Twitter-Client-Version' header. ''' self._request_headers['X-Twitter-Client'] = client self._request_headers['X-Twitter-Client-URL'] = url self._request_headers['X-Twitter-Client-Version'] = version def SetSource(self, source): '''Suggest the "from source" value to be displayed on the Twitter web site. The value of the 'source' parameter must be first recognized by the Twitter server. New source values are authorized on a case by case basis by the Twitter development team. Args: source: The source name as a string. Will be sent to the server as the 'source' parameter. ''' self._default_params['source'] = source def _BuildUrl(self, url, path_elements=None, extra_params=None): # Break url into consituent parts (scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url) # Add any additional path elements to the path if path_elements: # Filter out the path elements that have a value of None p = [i for i in path_elements if i] if not path.endswith('/'): path += '/' path += '/'.join(p) # Add any additional query parameters to the query string if extra_params and len(extra_params) > 0: extra_query = self._EncodeParameters(extra_params) # Add it to the existing query if query: query += '&' + extra_query else: query = extra_query # Return the rebuilt URL return urlparse.urlunparse((scheme, netloc, path, params, query, fragment)) def _InitializeRequestHeaders(self, request_headers): if request_headers: self._request_headers = request_headers else: self._request_headers = {} def _InitializeUserAgent(self): user_agent = 'Python-urllib/%s (python-twitter/%s)' % \ (self._urllib.__version__, __version__) self.SetUserAgent(user_agent) def _InitializeDefaultParameters(self): self._default_params = {} def _AddAuthorizationHeader(self, username, password): if username and password: basic_auth = base64.encodestring('%s:%s' % (username, password))[:-1] self._request_headers['Authorization'] = 'Basic %s' % basic_auth def _RemoveAuthorizationHeader(self): if self._request_headers and 'Authorization' in self._request_headers: del self._request_headers['Authorization'] def _GetOpener(self, url, username=None, password=None): if username and password: self._AddAuthorizationHeader(username, password) handler = self._urllib.HTTPBasicAuthHandler() (scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url) handler.add_password(Api._API_REALM, netloc, username, password) opener = self._urllib.build_opener(handler) else: opener = self._urllib.build_opener() opener.addheaders = self._request_headers.items() return opener def _Encode(self, s): if self._input_encoding: return unicode(s, self._input_encoding).encode('utf-8') else: return unicode(s).encode('utf-8') def _EncodeParameters(self, parameters): '''Return a string in key=value&key=value form Values of None are not included in the output string. Args: parameters: A dict of (key, value) tuples, where value is encoded as specified by self._encoding Returns: A URL-encoded string in "key=value&key=value" form ''' if parameters is None: return None else: return urllib.urlencode(dict([(k, self._Encode(v)) for k, v in parameters.items() if v is not None])) def _EncodePostData(self, post_data): '''Return a string in key=value&key=value form Values are assumed to be encoded in the format specified by self._encoding, and are subsequently URL encoded. Args: post_data: A dict of (key, value) tuples, where value is encoded as specified by self._encoding Returns: A URL-encoded string in "key=value&key=value" form ''' if post_data is None: return None else: return urllib.urlencode(dict([(k, self._Encode(v)) for k, v in post_data.items()])) def _CheckForTwitterError(self, data): """Raises a TwitterError if twitter returns an error message. Args: data: A python dict created from the Twitter json response Raises: TwitterError wrapping the twitter error message if one exists. """ # Twitter errors are relatively unlikely, so it is faster # to check first, rather than try and catch the exception if 'error' in data: raise TwitterError(data['error']) def _FetchUrl(self, url, post_data=None, parameters=None, no_cache=None): '''Fetch a URL, optionally caching for a specified time. Args: url: The URL to retrieve post_data: A dict of (str, unicode) key/value pairs. If set, POST will be used. parameters: A dict whose key/value pairs should encoded and added to the query string. [OPTIONAL] no_cache: If true, overrides the cache on the current request Returns: A string containing the body of the response. ''' # Build the extra parameters dict extra_params = {} if self._default_params: extra_params.update(self._default_params) if parameters: extra_params.update(parameters) # Add key/value parameters to the query string of the url url = self._BuildUrl(url, extra_params=extra_params) # Get a url opener that can handle basic auth opener = self._GetOpener(url, username=self._username, password=self._password) encoded_post_data = self._EncodePostData(post_data) # Open and return the URL immediately if we're not going to cache if encoded_post_data or no_cache or not self._cache or not self._cache_timeout: url_data = opener.open(url, encoded_post_data).read() opener.close() else: # Unique keys are a combination of the url and the username if self._username: key = self._username + ':' + url else: key = url # See if it has been cached before last_cached = self._cache.GetCachedTime(key) # If the cached version is outdated then fetch another and store it if not last_cached or time.time() >= last_cached + self._cache_timeout: url_data = opener.open(url, encoded_post_data).read() opener.close() self._cache.Set(key, url_data) else: url_data = self._cache.Get(key) # Always return the latest version return url_data class _FileCacheError(Exception): '''Base exception class for FileCache related errors''' class _FileCache(object): DEPTH = 3 def __init__(self,root_directory=None): self._InitializeRootDirectory(root_directory) def Get(self,key): path = self._GetPath(key) if os.path.exists(path): return open(path).read() else: return None def Set(self,key,data): path = self._GetPath(key) directory = os.path.dirname(path) if not os.path.exists(directory): os.makedirs(directory) if not os.path.isdir(directory): raise _FileCacheError('%s exists but is not a directory' % directory) temp_fd, temp_path = tempfile.mkstemp() temp_fp = os.fdopen(temp_fd, 'w') temp_fp.write(data) temp_fp.close() if not path.startswith(self._root_directory): raise _FileCacheError('%s does not appear to live under %s' % (path, self._root_directory)) if os.path.exists(path): os.remove(path) os.rename(temp_path, path) def Remove(self,key): path = self._GetPath(key) if not path.startswith(self._root_directory): raise _FileCacheError('%s does not appear to live under %s' % (path, self._root_directory )) if os.path.exists(path): os.remove(path) def GetCachedTime(self,key): path = self._GetPath(key) if os.path.exists(path): return os.path.getmtime(path) else: return None def _GetUsername(self): '''Attempt to find the username in a cross-platform fashion.''' try: return os.getenv('USER') or \ os.getenv('LOGNAME') or \ os.getenv('USERNAME') or \ os.getlogin() or \ 'nobody' except (IOError, OSError), e: return 'nobody' def _GetTmpCachePath(self): username = self.name() cache_directory = 'python.cache_' + username return os.path.join(tempfile.gettempdir(), cache_directory) def _InitializeRootDirectory(self, root_directory): if not root_directory: root_directory = self._GetTmpCachePath() root_directory = os.path.abspath(root_directory) if not os.path.exists(root_directory): os.mkdir(root_directory) if not os.path.isdir(root_directory): raise _FileCacheError('%s exists but is not a directory' % root_directory) self._root_directory = root_directory def _GetPath(self,key): try: hashed_key = md5(key).hexdigest() except TypeError: hashed_key = md5.new(key).hexdigest() return os.path.join(self._root_directory, self._GetPrefix(hashed_key), hashed_key) def _GetPrefix(self,hashed_key): return os.path.sep.join(hashed_key[0:_FileCache.DEPTH])
100uhaco
trunk/GAE/haco/libs/.svn/text-base/twitter.py.svn-base
Python
asf20
67,981
# -*- coding: utf8 -*- from twitter import Api import simplejson import urllib2 import logging class Api(Api): ''' twitter.Apiクラスの拡張 self._cacheの影響でファイル入出力が発生するため、 Apiクラスのラッパーとして利用する。 ''' def __init__(self, username=None, password=None, input_encoding=None, request_headers=None): '''gaetwitter.Api オブジェクトの初期化 Args: username: The username of the twitter account. [optional] password: The password for the twitter account. [optional] input_encoding: The encoding used to encode input strings. [optional] request_header: A dictionary of additional HTTP request headers. [optional] ''' self._cache = None self._urllib = urllib2 self._cache_timeout = Api.DEFAULT_CACHE_TIMEOUT self._InitializeRequestHeaders(request_headers) self._InitializeUserAgent() self._InitializeDefaultParameters() self._input_encoding = input_encoding self.SetCredentials(username, password) def Search(self, q=None): parameters = {} if q: parameters['q'] = q url = 'http://search.twitter.com/search.json' json = self._FetchUrl(url, parameters=parameters) data = simplejson.loads(json) self._CheckForTwitterError(data) return [Search.NewFromJsonDict(x) for x in data['results']] class Search(object): def __init(self, text=None): self.text = text @staticmethod def NewFromJsonDict(data): if 'from_user' in data: return data['from_user']
100uhaco
trunk/GAE/haco/libs/gaetwitter.py
Python
asf20
1,758
#!/usr/bin/python2.4 # # Copyright 2007 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. '''A library that provides a python interface to the Twitter API''' __author__ = 'dewitt@google.com' __version__ = '0.6-devel' import base64 import calendar import os import rfc822 import simplejson import sys import tempfile import textwrap import time import urllib import urllib2 import urlparse try: from hashlib import md5 except ImportError: from md5 import md5 CHARACTER_LIMIT = 140 class TwitterError(Exception): '''Base class for Twitter errors''' @property def message(self): '''Returns the first argument used to construct this error.''' return self.args[0] class Status(object): '''A class representing the Status structure used by the twitter API. The Status structure exposes the following properties: status.created_at status.created_at_in_seconds # read only status.favorited status.in_reply_to_screen_name status.in_reply_to_user_id status.in_reply_to_status_id status.truncated status.source status.id status.text status.relative_created_at # read only status.user ''' def __init__(self, created_at=None, favorited=None, id=None, text=None, user=None, in_reply_to_screen_name=None, in_reply_to_user_id=None, in_reply_to_status_id=None, truncated=None, source=None, now=None): '''An object to hold a Twitter status message. This class is normally instantiated by the twitter.Api class and returned in a sequence. Note: Dates are posted in the form "Sat Jan 27 04:17:38 +0000 2007" Args: created_at: The time this status message was posted favorited: Whether this is a favorite of the authenticated user id: The unique id of this status message text: The text of this status message relative_created_at: A human readable string representing the posting time user: A twitter.User instance representing the person posting the message now: The current time, if the client choses to set it. Defaults to the wall clock time. ''' self.created_at = created_at self.favorited = favorited self.id = id self.text = text self.user = user self.now = now self.in_reply_to_screen_name = in_reply_to_screen_name self.in_reply_to_user_id = in_reply_to_user_id self.in_reply_to_status_id = in_reply_to_status_id self.truncated = truncated self.source = source def GetCreatedAt(self): '''Get the time this status message was posted. Returns: The time this status message was posted ''' return self._created_at def SetCreatedAt(self, created_at): '''Set the time this status message was posted. Args: created_at: The time this status message was created ''' self._created_at = created_at created_at = property(GetCreatedAt, SetCreatedAt, doc='The time this status message was posted.') def GetCreatedAtInSeconds(self): '''Get the time this status message was posted, in seconds since the epoch. Returns: The time this status message was posted, in seconds since the epoch. ''' return calendar.timegm(rfc822.parsedate(self.created_at)) created_at_in_seconds = property(GetCreatedAtInSeconds, doc="The time this status message was " "posted, in seconds since the epoch") def GetFavorited(self): '''Get the favorited setting of this status message. Returns: True if this status message is favorited; False otherwise ''' return self._favorited def SetFavorited(self, favorited): '''Set the favorited state of this status message. Args: favorited: boolean True/False favorited state of this status message ''' self._favorited = favorited favorited = property(GetFavorited, SetFavorited, doc='The favorited state of this status message.') def GetId(self): '''Get the unique id of this status message. Returns: The unique id of this status message ''' return self._id def SetId(self, id): '''Set the unique id of this status message. Args: id: The unique id of this status message ''' self._id = id id = property(GetId, SetId, doc='The unique id of this status message.') def GetInReplyToScreenName(self): return self._in_reply_to_screen_name def SetInReplyToScreenName(self, in_reply_to_screen_name): self._in_reply_to_screen_name = in_reply_to_screen_name in_reply_to_screen_name = property(GetInReplyToScreenName, SetInReplyToScreenName, doc='') def GetInReplyToUserId(self): return self._in_reply_to_user_id def SetInReplyToUserId(self, in_reply_to_user_id): self._in_reply_to_user_id = in_reply_to_user_id in_reply_to_user_id = property(GetInReplyToUserId, SetInReplyToUserId, doc='') def GetInReplyToStatusId(self): return self._in_reply_to_status_id def SetInReplyToStatusId(self, in_reply_to_status_id): self._in_reply_to_status_id = in_reply_to_status_id in_reply_to_status_id = property(GetInReplyToStatusId, SetInReplyToStatusId, doc='') def GetTruncated(self): return self._truncated def SetTruncated(self, truncated): self._truncated = truncated truncated = property(GetTruncated, SetTruncated, doc='') def GetSource(self): return self._source def SetSource(self, source): self._source = source source = property(GetSource, SetSource, doc='') def GetText(self): '''Get the text of this status message. Returns: The text of this status message. ''' return self._text def SetText(self, text): '''Set the text of this status message. Args: text: The text of this status message ''' self._text = text text = property(GetText, SetText, doc='The text of this status message') def GetRelativeCreatedAt(self): '''Get a human redable string representing the posting time Returns: A human readable string representing the posting time ''' fudge = 1.25 delta = long(self.now) - long(self.created_at_in_seconds) if delta < (1 * fudge): return 'about a second ago' elif delta < (60 * (1/fudge)): return 'about %d seconds ago' % (delta) elif delta < (60 * fudge): return 'about a minute ago' elif delta < (60 * 60 * (1/fudge)): return 'about %d minutes ago' % (delta / 60) elif delta < (60 * 60 * fudge): return 'about an hour ago' elif delta < (60 * 60 * 24 * (1/fudge)): return 'about %d hours ago' % (delta / (60 * 60)) elif delta < (60 * 60 * 24 * fudge): return 'about a day ago' else: return 'about %d days ago' % (delta / (60 * 60 * 24)) relative_created_at = property(GetRelativeCreatedAt, doc='Get a human readable string representing' 'the posting time') def GetUser(self): '''Get a twitter.User reprenting the entity posting this status message. Returns: A twitter.User reprenting the entity posting this status message ''' return self._user def SetUser(self, user): '''Set a twitter.User reprenting the entity posting this status message. Args: user: A twitter.User reprenting the entity posting this status message ''' self._user = user user = property(GetUser, SetUser, doc='A twitter.User reprenting the entity posting this ' 'status message') def GetNow(self): '''Get the wallclock time for this status message. Used to calculate relative_created_at. Defaults to the time the object was instantiated. Returns: Whatever the status instance believes the current time to be, in seconds since the epoch. ''' if self._now is None: self._now = time.time() return self._now def SetNow(self, now): '''Set the wallclock time for this status message. Used to calculate relative_created_at. Defaults to the time the object was instantiated. Args: now: The wallclock time for this instance. ''' self._now = now now = property(GetNow, SetNow, doc='The wallclock time for this status instance.') def __ne__(self, other): return not self.__eq__(other) def __eq__(self, other): try: return other and \ self.created_at == other.created_at and \ self.id == other.id and \ self.text == other.text and \ self.user == other.user and \ self.in_reply_to_screen_name == other.in_reply_to_screen_name and \ self.in_reply_to_user_id == other.in_reply_to_user_id and \ self.in_reply_to_status_id == other.in_reply_to_status_id and \ self.truncated == other.truncated and \ self.favorited == other.favorited and \ self.source == other.source except AttributeError: return False def __str__(self): '''A string representation of this twitter.Status instance. The return value is the same as the JSON string representation. Returns: A string representation of this twitter.Status instance. ''' return self.AsJsonString() def AsJsonString(self): '''A JSON string representation of this twitter.Status instance. Returns: A JSON string representation of this twitter.Status instance ''' return simplejson.dumps(self.AsDict(), sort_keys=True) def AsDict(self): '''A dict representation of this twitter.Status instance. The return value uses the same key names as the JSON representation. Return: A dict representing this twitter.Status instance ''' data = {} if self.created_at: data['created_at'] = self.created_at if self.favorited: data['favorited'] = self.favorited if self.id: data['id'] = self.id if self.text: data['text'] = self.text if self.user: data['user'] = self.user.AsDict() if self.in_reply_to_screen_name: data['in_reply_to_screen_name'] = self.in_reply_to_screen_name if self.in_reply_to_user_id: data['in_reply_to_user_id'] = self.in_reply_to_user_id if self.in_reply_to_status_id: data['in_reply_to_status_id'] = self.in_reply_to_status_id if self.truncated is not None: data['truncated'] = self.truncated if self.favorited is not None: data['favorited'] = self.favorited if self.source: data['source'] = self.source return data @staticmethod def NewFromJsonDict(data): '''Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.Status instance ''' if 'user' in data: user = User.NewFromJsonDict(data['user']) else: user = None return Status(created_at=data.get('created_at', None), favorited=data.get('favorited', None), id=data.get('id', None), text=data.get('text', None), in_reply_to_screen_name=data.get('in_reply_to_screen_name', None), in_reply_to_user_id=data.get('in_reply_to_user_id', None), in_reply_to_status_id=data.get('in_reply_to_status_id', None), truncated=data.get('truncated', None), source=data.get('source', None), user=user) class User(object): '''A class representing the User structure used by the twitter API. The User structure exposes the following properties: user.id user.name user.screen_name user.location user.description user.profile_image_url user.profile_background_tile user.profile_background_image_url user.profile_sidebar_fill_color user.profile_background_color user.profile_link_color user.profile_text_color user.protected user.utc_offset user.time_zone user.url user.status user.statuses_count user.followers_count user.friends_count user.favourites_count ''' def __init__(self, id=None, name=None, screen_name=None, location=None, description=None, profile_image_url=None, profile_background_tile=None, profile_background_image_url=None, profile_sidebar_fill_color=None, profile_background_color=None, profile_link_color=None, profile_text_color=None, protected=None, utc_offset=None, time_zone=None, followers_count=None, friends_count=None, statuses_count=None, favourites_count=None, url=None, status=None): self.id = id self.name = name self.screen_name = screen_name self.location = location self.description = description self.profile_image_url = profile_image_url self.profile_background_tile = profile_background_tile self.profile_background_image_url = profile_background_image_url self.profile_sidebar_fill_color = profile_sidebar_fill_color self.profile_background_color = profile_background_color self.profile_link_color = profile_link_color self.profile_text_color = profile_text_color self.protected = protected self.utc_offset = utc_offset self.time_zone = time_zone self.followers_count = followers_count self.friends_count = friends_count self.statuses_count = statuses_count self.favourites_count = favourites_count self.url = url self.status = status def GetId(self): '''Get the unique id of this user. Returns: The unique id of this user ''' return self._id def SetId(self, id): '''Set the unique id of this user. Args: id: The unique id of this user. ''' self._id = id id = property(GetId, SetId, doc='The unique id of this user.') def GetName(self): '''Get the real name of this user. Returns: The real name of this user ''' return self._name def SetName(self, name): '''Set the real name of this user. Args: name: The real name of this user ''' self._name = name name = property(GetName, SetName, doc='The real name of this user.') def GetScreenName(self): '''Get the short username of this user. Returns: The short username of this user ''' return self._screen_name def SetScreenName(self, screen_name): '''Set the short username of this user. Args: screen_name: the short username of this user ''' self._screen_name = screen_name screen_name = property(GetScreenName, SetScreenName, doc='The short username of this user.') def GetLocation(self): '''Get the geographic location of this user. Returns: The geographic location of this user ''' return self._location def SetLocation(self, location): '''Set the geographic location of this user. Args: location: The geographic location of this user ''' self._location = location location = property(GetLocation, SetLocation, doc='The geographic location of this user.') def GetDescription(self): '''Get the short text description of this user. Returns: The short text description of this user ''' return self._description def SetDescription(self, description): '''Set the short text description of this user. Args: description: The short text description of this user ''' self._description = description description = property(GetDescription, SetDescription, doc='The short text description of this user.') def GetUrl(self): '''Get the homepage url of this user. Returns: The homepage url of this user ''' return self._url def SetUrl(self, url): '''Set the homepage url of this user. Args: url: The homepage url of this user ''' self._url = url url = property(GetUrl, SetUrl, doc='The homepage url of this user.') def GetProfileImageUrl(self): '''Get the url of the thumbnail of this user. Returns: The url of the thumbnail of this user ''' return self._profile_image_url def SetProfileImageUrl(self, profile_image_url): '''Set the url of the thumbnail of this user. Args: profile_image_url: The url of the thumbnail of this user ''' self._profile_image_url = profile_image_url profile_image_url= property(GetProfileImageUrl, SetProfileImageUrl, doc='The url of the thumbnail of this user.') def GetProfileBackgroundTile(self): '''Boolean for whether to tile the profile background image. Returns: True if the background is to be tiled, False if not, None if unset. ''' return self._profile_background_tile def SetProfileBackgroundTile(self, profile_background_tile): '''Set the boolean flag for whether to tile the profile background image. Args: profile_background_tile: Boolean flag for whether to tile or not. ''' self._profile_background_tile = profile_background_tile profile_background_tile = property(GetProfileBackgroundTile, SetProfileBackgroundTile, doc='Boolean for whether to tile the background image.') def GetProfileBackgroundImageUrl(self): return self._profile_background_image_url def SetProfileBackgroundImageUrl(self, profile_background_image_url): self._profile_background_image_url = profile_background_image_url profile_background_image_url = property(GetProfileBackgroundImageUrl, SetProfileBackgroundImageUrl, doc='The url of the profile background of this user.') def GetProfileSidebarFillColor(self): return self._profile_sidebar_fill_color def SetProfileSidebarFillColor(self, profile_sidebar_fill_color): self._profile_sidebar_fill_color = profile_sidebar_fill_color profile_sidebar_fill_color = property(GetProfileSidebarFillColor, SetProfileSidebarFillColor) def GetProfileBackgroundColor(self): return self._profile_background_color def SetProfileBackgroundColor(self, profile_background_color): self._profile_background_color = profile_background_color profile_background_color = property(GetProfileBackgroundColor, SetProfileBackgroundColor) def GetProfileLinkColor(self): return self._profile_link_color def SetProfileLinkColor(self, profile_link_color): self._profile_link_color = profile_link_color profile_link_color = property(GetProfileLinkColor, SetProfileLinkColor) def GetProfileTextColor(self): return self._profile_text_color def SetProfileTextColor(self, profile_text_color): self._profile_text_color = profile_text_color profile_text_color = property(GetProfileTextColor, SetProfileTextColor) def GetProtected(self): return self._protected def SetProtected(self, protected): self._protected = protected protected = property(GetProtected, SetProtected) def GetUtcOffset(self): return self._utc_offset def SetUtcOffset(self, utc_offset): self._utc_offset = utc_offset utc_offset = property(GetUtcOffset, SetUtcOffset) def GetTimeZone(self): '''Returns the current time zone string for the user. Returns: The descriptive time zone string for the user. ''' return self._time_zone def SetTimeZone(self, time_zone): '''Sets the user's time zone string. Args: time_zone: The descriptive time zone to assign for the user. ''' self._time_zone = time_zone time_zone = property(GetTimeZone, SetTimeZone) def GetStatus(self): '''Get the latest twitter.Status of this user. Returns: The latest twitter.Status of this user ''' return self._status def SetStatus(self, status): '''Set the latest twitter.Status of this user. Args: status: The latest twitter.Status of this user ''' self._status = status status = property(GetStatus, SetStatus, doc='The latest twitter.Status of this user.') def GetFriendsCount(self): '''Get the friend count for this user. Returns: The number of users this user has befriended. ''' return self._friends_count def SetFriendsCount(self, count): '''Set the friend count for this user. Args: count: The number of users this user has befriended. ''' self._friends_count = count friends_count = property(GetFriendsCount, SetFriendsCount, doc='The number of friends for this user.') def GetFollowersCount(self): '''Get the follower count for this user. Returns: The number of users following this user. ''' return self._followers_count def SetFollowersCount(self, count): '''Set the follower count for this user. Args: count: The number of users following this user. ''' self._followers_count = count followers_count = property(GetFollowersCount, SetFollowersCount, doc='The number of users following this user.') def GetStatusesCount(self): '''Get the number of status updates for this user. Returns: The number of status updates for this user. ''' return self._statuses_count def SetStatusesCount(self, count): '''Set the status update count for this user. Args: count: The number of updates for this user. ''' self._statuses_count = count statuses_count = property(GetStatusesCount, SetStatusesCount, doc='The number of updates for this user.') def GetFavouritesCount(self): '''Get the number of favourites for this user. Returns: The number of favourites for this user. ''' return self._favourites_count def SetFavouritesCount(self, count): '''Set the favourite count for this user. Args: count: The number of favourites for this user. ''' self._favourites_count = count favourites_count = property(GetFavouritesCount, SetFavouritesCount, doc='The number of favourites for this user.') def __ne__(self, other): return not self.__eq__(other) def __eq__(self, other): try: return other and \ self.id == other.id and \ self.name == other.name and \ self.screen_name == other.screen_name and \ self.location == other.location and \ self.description == other.description and \ self.profile_image_url == other.profile_image_url and \ self.profile_background_tile == other.profile_background_tile and \ self.profile_background_image_url == other.profile_background_image_url and \ self.profile_sidebar_fill_color == other.profile_sidebar_fill_color and \ self.profile_background_color == other.profile_background_color and \ self.profile_link_color == other.profile_link_color and \ self.profile_text_color == other.profile_text_color and \ self.protected == other.protected and \ self.utc_offset == other.utc_offset and \ self.time_zone == other.time_zone and \ self.url == other.url and \ self.statuses_count == other.statuses_count and \ self.followers_count == other.followers_count and \ self.favourites_count == other.favourites_count and \ self.friends_count == other.friends_count and \ self.status == other.status except AttributeError: return False def __str__(self): '''A string representation of this twitter.User instance. The return value is the same as the JSON string representation. Returns: A string representation of this twitter.User instance. ''' return self.AsJsonString() def AsJsonString(self): '''A JSON string representation of this twitter.User instance. Returns: A JSON string representation of this twitter.User instance ''' return simplejson.dumps(self.AsDict(), sort_keys=True) def AsDict(self): '''A dict representation of this twitter.User instance. The return value uses the same key names as the JSON representation. Return: A dict representing this twitter.User instance ''' data = {} if self.id: data['id'] = self.id if self.name: data['name'] = self.name if self.screen_name: data['screen_name'] = self.screen_name if self.location: data['location'] = self.location if self.description: data['description'] = self.description if self.profile_image_url: data['profile_image_url'] = self.profile_image_url if self.profile_background_tile is not None: data['profile_background_tile'] = self.profile_background_tile if self.profile_background_image_url: data['profile_sidebar_fill_color'] = self.profile_background_image_url if self.profile_background_color: data['profile_background_color'] = self.profile_background_color if self.profile_link_color: data['profile_link_color'] = self.profile_link_color if self.profile_text_color: data['profile_text_color'] = self.profile_text_color if self.protected is not None: data['protected'] = self.protected if self.utc_offset: data['utc_offset'] = self.utc_offset if self.time_zone: data['time_zone'] = self.time_zone if self.url: data['url'] = self.url if self.status: data['status'] = self.status.AsDict() if self.friends_count: data['friends_count'] = self.friends_count if self.followers_count: data['followers_count'] = self.followers_count if self.statuses_count: data['statuses_count'] = self.statuses_count if self.favourites_count: data['favourites_count'] = self.favourites_count return data @staticmethod def NewFromJsonDict(data): '''Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.User instance ''' if 'status' in data: status = Status.NewFromJsonDict(data['status']) else: status = None return User(id=data.get('id', None), name=data.get('name', None), screen_name=data.get('screen_name', None), location=data.get('location', None), description=data.get('description', None), statuses_count=data.get('statuses_count', None), followers_count=data.get('followers_count', None), favourites_count=data.get('favourites_count', None), friends_count=data.get('friends_count', None), profile_image_url=data.get('profile_image_url', None), profile_background_tile = data.get('profile_background_tile', None), profile_background_image_url = data.get('profile_background_image_url', None), profile_sidebar_fill_color = data.get('profile_sidebar_fill_color', None), profile_background_color = data.get('profile_background_color', None), profile_link_color = data.get('profile_link_color', None), profile_text_color = data.get('profile_text_color', None), protected = data.get('protected', None), utc_offset = data.get('utc_offset', None), time_zone = data.get('time_zone', None), url=data.get('url', None), status=status) class DirectMessage(object): '''A class representing the DirectMessage structure used by the twitter API. The DirectMessage structure exposes the following properties: direct_message.id direct_message.created_at direct_message.created_at_in_seconds # read only direct_message.sender_id direct_message.sender_screen_name direct_message.recipient_id direct_message.recipient_screen_name direct_message.text ''' def __init__(self, id=None, created_at=None, sender_id=None, sender_screen_name=None, recipient_id=None, recipient_screen_name=None, text=None): '''An object to hold a Twitter direct message. This class is normally instantiated by the twitter.Api class and returned in a sequence. Note: Dates are posted in the form "Sat Jan 27 04:17:38 +0000 2007" Args: id: The unique id of this direct message created_at: The time this direct message was posted sender_id: The id of the twitter user that sent this message sender_screen_name: The name of the twitter user that sent this message recipient_id: The id of the twitter that received this message recipient_screen_name: The name of the twitter that received this message text: The text of this direct message ''' self.id = id self.created_at = created_at self.sender_id = sender_id self.sender_screen_name = sender_screen_name self.recipient_id = recipient_id self.recipient_screen_name = recipient_screen_name self.text = text def GetId(self): '''Get the unique id of this direct message. Returns: The unique id of this direct message ''' return self._id def SetId(self, id): '''Set the unique id of this direct message. Args: id: The unique id of this direct message ''' self._id = id id = property(GetId, SetId, doc='The unique id of this direct message.') def GetCreatedAt(self): '''Get the time this direct message was posted. Returns: The time this direct message was posted ''' return self._created_at def SetCreatedAt(self, created_at): '''Set the time this direct message was posted. Args: created_at: The time this direct message was created ''' self._created_at = created_at created_at = property(GetCreatedAt, SetCreatedAt, doc='The time this direct message was posted.') def GetCreatedAtInSeconds(self): '''Get the time this direct message was posted, in seconds since the epoch. Returns: The time this direct message was posted, in seconds since the epoch. ''' return calendar.timegm(rfc822.parsedate(self.created_at)) created_at_in_seconds = property(GetCreatedAtInSeconds, doc="The time this direct message was " "posted, in seconds since the epoch") def GetSenderId(self): '''Get the unique sender id of this direct message. Returns: The unique sender id of this direct message ''' return self._sender_id def SetSenderId(self, sender_id): '''Set the unique sender id of this direct message. Args: sender id: The unique sender id of this direct message ''' self._sender_id = sender_id sender_id = property(GetSenderId, SetSenderId, doc='The unique sender id of this direct message.') def GetSenderScreenName(self): '''Get the unique sender screen name of this direct message. Returns: The unique sender screen name of this direct message ''' return self._sender_screen_name def SetSenderScreenName(self, sender_screen_name): '''Set the unique sender screen name of this direct message. Args: sender_screen_name: The unique sender screen name of this direct message ''' self._sender_screen_name = sender_screen_name sender_screen_name = property(GetSenderScreenName, SetSenderScreenName, doc='The unique sender screen name of this direct message.') def GetRecipientId(self): '''Get the unique recipient id of this direct message. Returns: The unique recipient id of this direct message ''' return self._recipient_id def SetRecipientId(self, recipient_id): '''Set the unique recipient id of this direct message. Args: recipient id: The unique recipient id of this direct message ''' self._recipient_id = recipient_id recipient_id = property(GetRecipientId, SetRecipientId, doc='The unique recipient id of this direct message.') def GetRecipientScreenName(self): '''Get the unique recipient screen name of this direct message. Returns: The unique recipient screen name of this direct message ''' return self._recipient_screen_name def SetRecipientScreenName(self, recipient_screen_name): '''Set the unique recipient screen name of this direct message. Args: recipient_screen_name: The unique recipient screen name of this direct message ''' self._recipient_screen_name = recipient_screen_name recipient_screen_name = property(GetRecipientScreenName, SetRecipientScreenName, doc='The unique recipient screen name of this direct message.') def GetText(self): '''Get the text of this direct message. Returns: The text of this direct message. ''' return self._text def SetText(self, text): '''Set the text of this direct message. Args: text: The text of this direct message ''' self._text = text text = property(GetText, SetText, doc='The text of this direct message') def __ne__(self, other): return not self.__eq__(other) def __eq__(self, other): try: return other and \ self.id == other.id and \ self.created_at == other.created_at and \ self.sender_id == other.sender_id and \ self.sender_screen_name == other.sender_screen_name and \ self.recipient_id == other.recipient_id and \ self.recipient_screen_name == other.recipient_screen_name and \ self.text == other.text except AttributeError: return False def __str__(self): '''A string representation of this twitter.DirectMessage instance. The return value is the same as the JSON string representation. Returns: A string representation of this twitter.DirectMessage instance. ''' return self.AsJsonString() def AsJsonString(self): '''A JSON string representation of this twitter.DirectMessage instance. Returns: A JSON string representation of this twitter.DirectMessage instance ''' return simplejson.dumps(self.AsDict(), sort_keys=True) def AsDict(self): '''A dict representation of this twitter.DirectMessage instance. The return value uses the same key names as the JSON representation. Return: A dict representing this twitter.DirectMessage instance ''' data = {} if self.id: data['id'] = self.id if self.created_at: data['created_at'] = self.created_at if self.sender_id: data['sender_id'] = self.sender_id if self.sender_screen_name: data['sender_screen_name'] = self.sender_screen_name if self.recipient_id: data['recipient_id'] = self.recipient_id if self.recipient_screen_name: data['recipient_screen_name'] = self.recipient_screen_name if self.text: data['text'] = self.text return data @staticmethod def NewFromJsonDict(data): '''Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.DirectMessage instance ''' return DirectMessage(created_at=data.get('created_at', None), recipient_id=data.get('recipient_id', None), sender_id=data.get('sender_id', None), text=data.get('text', None), sender_screen_name=data.get('sender_screen_name', None), id=data.get('id', None), recipient_screen_name=data.get('recipient_screen_name', None)) class Api(object): '''A python interface into the Twitter API By default, the Api caches results for 1 minute. Example usage: To create an instance of the twitter.Api class, with no authentication: >>> import twitter >>> api = twitter.Api() To fetch the most recently posted public twitter status messages: >>> statuses = api.GetPublicTimeline() >>> print [s.user.name for s in statuses] [u'DeWitt', u'Kesuke Miyagi', u'ev', u'Buzz Andersen', u'Biz Stone'] #... To fetch a single user's public status messages, where "user" is either a Twitter "short name" or their user id. >>> statuses = api.GetUserTimeline(user) >>> print [s.text for s in statuses] To use authentication, instantiate the twitter.Api class with a username and password: >>> api = twitter.Api(username='twitter user', password='twitter pass') To fetch your friends (after being authenticated): >>> users = api.GetFriends() >>> print [u.name for u in users] To post a twitter status message (after being authenticated): >>> status = api.PostUpdate('I love python-twitter!') >>> print status.text I love python-twitter! There are many other methods, including: >>> api.PostUpdates(status) >>> api.PostDirectMessage(user, text) >>> api.GetUser(user) >>> api.GetReplies() >>> api.GetUserTimeline(user) >>> api.GetStatus(id) >>> api.DestroyStatus(id) >>> api.GetFriendsTimeline(user) >>> api.GetFriends(user) >>> api.GetFollowers() >>> api.GetFeatured() >>> api.GetDirectMessages() >>> api.PostDirectMessage(user, text) >>> api.DestroyDirectMessage(id) >>> api.DestroyFriendship(user) >>> api.CreateFriendship(user) >>> api.GetUserByEmail(email) ''' DEFAULT_CACHE_TIMEOUT = 60 # cache for 1 minute _API_REALM = 'Twitter API' def __init__(self, username=None, password=None, input_encoding=None, request_headers=None): '''Instantiate a new twitter.Api object. Args: username: The username of the twitter account. [optional] password: The password for the twitter account. [optional] input_encoding: The encoding used to encode input strings. [optional] request_header: A dictionary of additional HTTP request headers. [optional] ''' self._cache = _FileCache() self._urllib = urllib2 self._cache_timeout = Api.DEFAULT_CACHE_TIMEOUT self._InitializeRequestHeaders(request_headers) self._InitializeUserAgent() self._InitializeDefaultParameters() self._input_encoding = input_encoding self.SetCredentials(username, password) def GetPublicTimeline(self, since_id=None): '''Fetch the sequnce of public twitter.Status message for all users. Args: since_id: Returns only public statuses with an ID greater than (that is, more recent than) the specified ID. [Optional] Returns: An sequence of twitter.Status instances, one for each message ''' parameters = {} if since_id: parameters['since_id'] = since_id url = 'http://twitter.com/statuses/public_timeline.json' json = self._FetchUrl(url, parameters=parameters) data = simplejson.loads(json) self._CheckForTwitterError(data) return [Status.NewFromJsonDict(x) for x in data] def GetFriendsTimeline(self, user=None, count=None, since=None, since_id=None): '''Fetch the sequence of twitter.Status messages for a user's friends The twitter.Api instance must be authenticated if the user is private. Args: user: Specifies the ID or screen name of the user for whom to return the friends_timeline. If unspecified, the username and password must be set in the twitter.Api instance. [Optional] count: Specifies the number of statuses to retrieve. May not be greater than 200. [Optional] since: Narrows the returned results to just those statuses created after the specified HTTP-formatted date. [Optional] since_id: Returns only public statuses with an ID greater than (that is, more recent than) the specified ID. [Optional] Returns: A sequence of twitter.Status instances, one for each message ''' if user: url = 'http://twitter.com/statuses/friends_timeline/%s.json' % user elif not user and not self._username: raise TwitterError("User must be specified if API is not authenticated.") else: url = 'http://twitter.com/statuses/friends_timeline.json' parameters = {} if count is not None: try: if int(count) > 200: raise TwitterError("'count' may not be greater than 200") except ValueError: raise TwitterError("'count' must be an integer") parameters['count'] = count if since: parameters['since'] = since if since_id: parameters['since_id'] = since_id json = self._FetchUrl(url, parameters=parameters) data = simplejson.loads(json) self._CheckForTwitterError(data) return [Status.NewFromJsonDict(x) for x in data] def GetUserTimeline(self, user=None, count=None, since=None, since_id=None): '''Fetch the sequence of public twitter.Status messages for a single user. The twitter.Api instance must be authenticated if the user is private. Args: user: either the username (short_name) or id of the user to retrieve. If not specified, then the current authenticated user is used. [optional] count: the number of status messages to retrieve [optional] since: Narrows the returned results to just those statuses created after the specified HTTP-formatted date. [optional] since_id: Returns only public statuses with an ID greater than (that is, more recent than) the specified ID. [Optional] Returns: A sequence of twitter.Status instances, one for each message up to count ''' try: if count: int(count) except: raise TwitterError("Count must be an integer") parameters = {} if count: parameters['count'] = count if since: parameters['since'] = since if since_id: parameters['since_id'] = since_id if user: url = 'http://twitter.com/statuses/user_timeline/%s.json' % user elif not user and not self._username: raise TwitterError("User must be specified if API is not authenticated.") else: url = 'http://twitter.com/statuses/user_timeline.json' json = self._FetchUrl(url, parameters=parameters) data = simplejson.loads(json) self._CheckForTwitterError(data) return [Status.NewFromJsonDict(x) for x in data] def GetStatus(self, id): '''Returns a single status message. The twitter.Api instance must be authenticated if the status message is private. Args: id: The numerical ID of the status you're trying to retrieve. Returns: A twitter.Status instance representing that status message ''' try: if id: long(id) except: raise TwitterError("id must be an long integer") url = 'http://twitter.com/statuses/show/%s.json' % id json = self._FetchUrl(url) data = simplejson.loads(json) self._CheckForTwitterError(data) return Status.NewFromJsonDict(data) def DestroyStatus(self, id): '''Destroys the status specified by the required ID parameter. The twitter.Api instance must be authenticated and thee authenticating user must be the author of the specified status. Args: id: The numerical ID of the status you're trying to destroy. Returns: A twitter.Status instance representing the destroyed status message ''' try: if id: long(id) except: raise TwitterError("id must be an integer") url = 'http://twitter.com/statuses/destroy/%s.json' % id json = self._FetchUrl(url, post_data={}) data = simplejson.loads(json) self._CheckForTwitterError(data) return Status.NewFromJsonDict(data) def PostUpdate(self, status, in_reply_to_status_id=None): '''Post a twitter status message from the authenticated user. The twitter.Api instance must be authenticated. Args: status: The message text to be posted. Must be less than or equal to 140 characters. in_reply_to_status_id: The ID of an existing status that the status to be posted is in reply to. This implicitly sets the in_reply_to_user_id attribute of the resulting status to the user ID of the message being replied to. Invalid/missing status IDs will be ignored. [Optional] Returns: A twitter.Status instance representing the message posted. ''' if not self._username: raise TwitterError("The twitter.Api instance must be authenticated.") url = 'http://twitter.com/statuses/update.json' if len(status) > CHARACTER_LIMIT: raise TwitterError("Text must be less than or equal to %d characters. " "Consider using PostUpdates." % CHARACTER_LIMIT) data = {'status': status} if in_reply_to_status_id: data['in_reply_to_status_id'] = in_reply_to_status_id json = self._FetchUrl(url, post_data=data) data = simplejson.loads(json) self._CheckForTwitterError(data) return Status.NewFromJsonDict(data) def PostUpdates(self, status, continuation=None, **kwargs): '''Post one or more twitter status messages from the authenticated user. Unlike api.PostUpdate, this method will post multiple status updates if the message is longer than 140 characters. The twitter.Api instance must be authenticated. Args: status: The message text to be posted. May be longer than 140 characters. continuation: The character string, if any, to be appended to all but the last message. Note that Twitter strips trailing '...' strings from messages. Consider using the unicode \u2026 character (horizontal ellipsis) instead. [Defaults to None] **kwargs: See api.PostUpdate for a list of accepted parameters. Returns: A of list twitter.Status instance representing the messages posted. ''' results = list() if continuation is None: continuation = '' line_length = CHARACTER_LIMIT - len(continuation) lines = textwrap.wrap(status, line_length) for line in lines[0:-1]: results.append(self.PostUpdate(line + continuation, **kwargs)) results.append(self.PostUpdate(lines[-1], **kwargs)) return results def GetReplies(self, since=None, since_id=None, page=None): '''Get a sequence of status messages representing the 20 most recent replies (status updates prefixed with @username) to the authenticating user. Args: page: since: Narrows the returned results to just those statuses created after the specified HTTP-formatted date. [optional] since_id: Returns only public statuses with an ID greater than (that is, more recent than) the specified ID. [Optional] Returns: A sequence of twitter.Status instances, one for each reply to the user. ''' url = 'http://twitter.com/statuses/replies.json' if not self._username: raise TwitterError("The twitter.Api instance must be authenticated.") parameters = {} if since: parameters['since'] = since if since_id: parameters['since_id'] = since_id if page: parameters['page'] = page json = self._FetchUrl(url, parameters=parameters) data = simplejson.loads(json) self._CheckForTwitterError(data) return [Status.NewFromJsonDict(x) for x in data] def GetFriends(self, user=None, page=None): '''Fetch the sequence of twitter.User instances, one for each friend. Args: user: the username or id of the user whose friends you are fetching. If not specified, defaults to the authenticated user. [optional] The twitter.Api instance must be authenticated. Returns: A sequence of twitter.User instances, one for each friend ''' if not self._username: raise TwitterError("twitter.Api instance must be authenticated") if user: url = 'http://twitter.com/statuses/friends/%s.json' % user else: url = 'http://twitter.com/statuses/friends.json' parameters = {} if page: parameters['page'] = page json = self._FetchUrl(url, parameters=parameters) data = simplejson.loads(json) self._CheckForTwitterError(data) return [User.NewFromJsonDict(x) for x in data] def GetFollowers(self, page=None): '''Fetch the sequence of twitter.User instances, one for each follower The twitter.Api instance must be authenticated. Returns: A sequence of twitter.User instances, one for each follower ''' if not self._username: raise TwitterError("twitter.Api instance must be authenticated") url = 'http://twitter.com/statuses/followers.json' parameters = {} if page: parameters['page'] = page json = self._FetchUrl(url, parameters=parameters) data = simplejson.loads(json) self._CheckForTwitterError(data) return [User.NewFromJsonDict(x) for x in data] def GetFeatured(self): '''Fetch the sequence of twitter.User instances featured on twitter.com The twitter.Api instance must be authenticated. Returns: A sequence of twitter.User instances ''' url = 'http://twitter.com/statuses/featured.json' json = self._FetchUrl(url) data = simplejson.loads(json) self._CheckForTwitterError(data) return [User.NewFromJsonDict(x) for x in data] def GetUser(self, user): '''Returns a single user. The twitter.Api instance must be authenticated. Args: user: The username or id of the user to retrieve. Returns: A twitter.User instance representing that user ''' url = 'http://twitter.com/users/show/%s.json' % user json = self._FetchUrl(url) data = simplejson.loads(json) self._CheckForTwitterError(data) return User.NewFromJsonDict(data) def GetDirectMessages(self, since=None, since_id=None, page=None): '''Returns a list of the direct messages sent to the authenticating user. The twitter.Api instance must be authenticated. Args: since: Narrows the returned results to just those statuses created after the specified HTTP-formatted date. [optional] since_id: Returns only public statuses with an ID greater than (that is, more recent than) the specified ID. [Optional] Returns: A sequence of twitter.DirectMessage instances ''' url = 'http://twitter.com/direct_messages.json' if not self._username: raise TwitterError("The twitter.Api instance must be authenticated.") parameters = {} if since: parameters['since'] = since if since_id: parameters['since_id'] = since_id if page: parameters['page'] = page json = self._FetchUrl(url, parameters=parameters) data = simplejson.loads(json) self._CheckForTwitterError(data) return [DirectMessage.NewFromJsonDict(x) for x in data] def PostDirectMessage(self, user, text): '''Post a twitter direct message from the authenticated user The twitter.Api instance must be authenticated. Args: user: The ID or screen name of the recipient user. text: The message text to be posted. Must be less than 140 characters. Returns: A twitter.DirectMessage instance representing the message posted ''' if not self._username: raise TwitterError("The twitter.Api instance must be authenticated.") url = 'http://twitter.com/direct_messages/new.json' data = {'text': text, 'user': user} json = self._FetchUrl(url, post_data=data) data = simplejson.loads(json) self._CheckForTwitterError(data) return DirectMessage.NewFromJsonDict(data) def DestroyDirectMessage(self, id): '''Destroys the direct message specified in the required ID parameter. The twitter.Api instance must be authenticated, and the authenticating user must be the recipient of the specified direct message. Args: id: The id of the direct message to be destroyed Returns: A twitter.DirectMessage instance representing the message destroyed ''' url = 'http://twitter.com/direct_messages/destroy/%s.json' % id json = self._FetchUrl(url, post_data={}) data = simplejson.loads(json) self._CheckForTwitterError(data) return DirectMessage.NewFromJsonDict(data) def CreateFriendship(self, user): '''Befriends the user specified in the user parameter as the authenticating user. The twitter.Api instance must be authenticated. Args: The ID or screen name of the user to befriend. Returns: A twitter.User instance representing the befriended user. ''' url = 'http://twitter.com/friendships/create/%s.json' % user json = self._FetchUrl(url, post_data={}) data = simplejson.loads(json) self._CheckForTwitterError(data) return User.NewFromJsonDict(data) def DestroyFriendship(self, user): '''Discontinues friendship with the user specified in the user parameter. The twitter.Api instance must be authenticated. Args: The ID or screen name of the user with whom to discontinue friendship. Returns: A twitter.User instance representing the discontinued friend. ''' url = 'http://twitter.com/friendships/destroy/%s.json' % user json = self._FetchUrl(url, post_data={}) data = simplejson.loads(json) self._CheckForTwitterError(data) return User.NewFromJsonDict(data) def CreateFavorite(self, status): '''Favorites the status specified in the status parameter as the authenticating user. Returns the favorite status when successful. The twitter.Api instance must be authenticated. Args: The twitter.Status instance to mark as a favorite. Returns: A twitter.Status instance representing the newly-marked favorite. ''' url = 'http://twitter.com/favorites/create/%s.json' % status.id json = self._FetchUrl(url, post_data={}) data = simplejson.loads(json) self._CheckForTwitterError(data) return Status.NewFromJsonDict(data) def DestroyFavorite(self, status): '''Un-favorites the status specified in the ID parameter as the authenticating user. Returns the un-favorited status in the requested format when successful. The twitter.Api instance must be authenticated. Args: The twitter.Status to unmark as a favorite. Returns: A twitter.Status instance representing the newly-unmarked favorite. ''' url = 'http://twitter.com/favorites/destroy/%s.json' % status.id json = self._FetchUrl(url, post_data={}) data = simplejson.loads(json) self._CheckForTwitterError(data) return Status.NewFromJsonDict(data) def GetUserByEmail(self, email): '''Returns a single user by email address. Args: email: The email of the user to retrieve. Returns: A twitter.User instance representing that user ''' url = 'http://twitter.com/users/show.json?email=%s' % email json = self._FetchUrl(url) data = simplejson.loads(json) self._CheckForTwitterError(data) return User.NewFromJsonDict(data) def SetCredentials(self, username, password): '''Set the username and password for this instance Args: username: The twitter username. password: The twitter password. ''' self._username = username self._password = password def ClearCredentials(self): '''Clear the username and password for this instance ''' self._username = None self._password = None def SetCache(self, cache): '''Override the default cache. Set to None to prevent caching. Args: cache: an instance that supports the same API as the twitter._FileCache ''' self._cache = cache def SetUrllib(self, urllib): '''Override the default urllib implementation. Args: urllib: an instance that supports the same API as the urllib2 module ''' self._urllib = urllib def SetCacheTimeout(self, cache_timeout): '''Override the default cache timeout. Args: cache_timeout: time, in seconds, that responses should be reused. ''' self._cache_timeout = cache_timeout def SetUserAgent(self, user_agent): '''Override the default user agent Args: user_agent: a string that should be send to the server as the User-agent ''' self._request_headers['User-Agent'] = user_agent def SetXTwitterHeaders(self, client, url, version): '''Set the X-Twitter HTTP headers that will be sent to the server. Args: client: The client name as a string. Will be sent to the server as the 'X-Twitter-Client' header. url: The URL of the meta.xml as a string. Will be sent to the server as the 'X-Twitter-Client-URL' header. version: The client version as a string. Will be sent to the server as the 'X-Twitter-Client-Version' header. ''' self._request_headers['X-Twitter-Client'] = client self._request_headers['X-Twitter-Client-URL'] = url self._request_headers['X-Twitter-Client-Version'] = version def SetSource(self, source): '''Suggest the "from source" value to be displayed on the Twitter web site. The value of the 'source' parameter must be first recognized by the Twitter server. New source values are authorized on a case by case basis by the Twitter development team. Args: source: The source name as a string. Will be sent to the server as the 'source' parameter. ''' self._default_params['source'] = source def _BuildUrl(self, url, path_elements=None, extra_params=None): # Break url into consituent parts (scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url) # Add any additional path elements to the path if path_elements: # Filter out the path elements that have a value of None p = [i for i in path_elements if i] if not path.endswith('/'): path += '/' path += '/'.join(p) # Add any additional query parameters to the query string if extra_params and len(extra_params) > 0: extra_query = self._EncodeParameters(extra_params) # Add it to the existing query if query: query += '&' + extra_query else: query = extra_query # Return the rebuilt URL return urlparse.urlunparse((scheme, netloc, path, params, query, fragment)) def _InitializeRequestHeaders(self, request_headers): if request_headers: self._request_headers = request_headers else: self._request_headers = {} def _InitializeUserAgent(self): user_agent = 'Python-urllib/%s (python-twitter/%s)' % \ (self._urllib.__version__, __version__) self.SetUserAgent(user_agent) def _InitializeDefaultParameters(self): self._default_params = {} def _AddAuthorizationHeader(self, username, password): if username and password: basic_auth = base64.encodestring('%s:%s' % (username, password))[:-1] self._request_headers['Authorization'] = 'Basic %s' % basic_auth def _RemoveAuthorizationHeader(self): if self._request_headers and 'Authorization' in self._request_headers: del self._request_headers['Authorization'] def _GetOpener(self, url, username=None, password=None): if username and password: self._AddAuthorizationHeader(username, password) handler = self._urllib.HTTPBasicAuthHandler() (scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url) handler.add_password(Api._API_REALM, netloc, username, password) opener = self._urllib.build_opener(handler) else: opener = self._urllib.build_opener() opener.addheaders = self._request_headers.items() return opener def _Encode(self, s): if self._input_encoding: return unicode(s, self._input_encoding).encode('utf-8') else: return unicode(s).encode('utf-8') def _EncodeParameters(self, parameters): '''Return a string in key=value&key=value form Values of None are not included in the output string. Args: parameters: A dict of (key, value) tuples, where value is encoded as specified by self._encoding Returns: A URL-encoded string in "key=value&key=value" form ''' if parameters is None: return None else: return urllib.urlencode(dict([(k, self._Encode(v)) for k, v in parameters.items() if v is not None])) def _EncodePostData(self, post_data): '''Return a string in key=value&key=value form Values are assumed to be encoded in the format specified by self._encoding, and are subsequently URL encoded. Args: post_data: A dict of (key, value) tuples, where value is encoded as specified by self._encoding Returns: A URL-encoded string in "key=value&key=value" form ''' if post_data is None: return None else: return urllib.urlencode(dict([(k, self._Encode(v)) for k, v in post_data.items()])) def _CheckForTwitterError(self, data): """Raises a TwitterError if twitter returns an error message. Args: data: A python dict created from the Twitter json response Raises: TwitterError wrapping the twitter error message if one exists. """ # Twitter errors are relatively unlikely, so it is faster # to check first, rather than try and catch the exception if 'error' in data: raise TwitterError(data['error']) def _FetchUrl(self, url, post_data=None, parameters=None, no_cache=None): '''Fetch a URL, optionally caching for a specified time. Args: url: The URL to retrieve post_data: A dict of (str, unicode) key/value pairs. If set, POST will be used. parameters: A dict whose key/value pairs should encoded and added to the query string. [OPTIONAL] no_cache: If true, overrides the cache on the current request Returns: A string containing the body of the response. ''' # Build the extra parameters dict extra_params = {} if self._default_params: extra_params.update(self._default_params) if parameters: extra_params.update(parameters) # Add key/value parameters to the query string of the url url = self._BuildUrl(url, extra_params=extra_params) # Get a url opener that can handle basic auth opener = self._GetOpener(url, username=self._username, password=self._password) encoded_post_data = self._EncodePostData(post_data) # Open and return the URL immediately if we're not going to cache if encoded_post_data or no_cache or not self._cache or not self._cache_timeout: url_data = opener.open(url, encoded_post_data).read() opener.close() else: # Unique keys are a combination of the url and the username if self._username: key = self._username + ':' + url else: key = url # See if it has been cached before last_cached = self._cache.GetCachedTime(key) # If the cached version is outdated then fetch another and store it if not last_cached or time.time() >= last_cached + self._cache_timeout: url_data = opener.open(url, encoded_post_data).read() opener.close() self._cache.Set(key, url_data) else: url_data = self._cache.Get(key) # Always return the latest version return url_data class _FileCacheError(Exception): '''Base exception class for FileCache related errors''' class _FileCache(object): DEPTH = 3 def __init__(self,root_directory=None): self._InitializeRootDirectory(root_directory) def Get(self,key): path = self._GetPath(key) if os.path.exists(path): return open(path).read() else: return None def Set(self,key,data): path = self._GetPath(key) directory = os.path.dirname(path) if not os.path.exists(directory): os.makedirs(directory) if not os.path.isdir(directory): raise _FileCacheError('%s exists but is not a directory' % directory) temp_fd, temp_path = tempfile.mkstemp() temp_fp = os.fdopen(temp_fd, 'w') temp_fp.write(data) temp_fp.close() if not path.startswith(self._root_directory): raise _FileCacheError('%s does not appear to live under %s' % (path, self._root_directory)) if os.path.exists(path): os.remove(path) os.rename(temp_path, path) def Remove(self,key): path = self._GetPath(key) if not path.startswith(self._root_directory): raise _FileCacheError('%s does not appear to live under %s' % (path, self._root_directory )) if os.path.exists(path): os.remove(path) def GetCachedTime(self,key): path = self._GetPath(key) if os.path.exists(path): return os.path.getmtime(path) else: return None def _GetUsername(self): '''Attempt to find the username in a cross-platform fashion.''' try: return os.getenv('USER') or \ os.getenv('LOGNAME') or \ os.getenv('USERNAME') or \ os.getlogin() or \ 'nobody' except (IOError, OSError), e: return 'nobody' def _GetTmpCachePath(self): username = self.name() cache_directory = 'python.cache_' + username return os.path.join(tempfile.gettempdir(), cache_directory) def _InitializeRootDirectory(self, root_directory): if not root_directory: root_directory = self._GetTmpCachePath() root_directory = os.path.abspath(root_directory) if not os.path.exists(root_directory): os.mkdir(root_directory) if not os.path.isdir(root_directory): raise _FileCacheError('%s exists but is not a directory' % root_directory) self._root_directory = root_directory def _GetPath(self,key): try: hashed_key = md5(key).hexdigest() except TypeError: hashed_key = md5.new(key).hexdigest() return os.path.join(self._root_directory, self._GetPrefix(hashed_key), hashed_key) def _GetPrefix(self,hashed_key): return os.path.sep.join(hashed_key[0:_FileCache.DEPTH])
100uhaco
trunk/GAE/haco/libs/twitter.py
Python
asf20
67,981
from django.conf.urls.defaults import * from django.contrib.auth import views as auth_views from views import * from views2 import * from twit import * urlpatterns =patterns( '', #url( r'^login/$', # auth_views.login, # {'template_name': 'haco/login.html', # 'redirect_field_name': report}, # name='auth_login'), #(r'^$', # 'django.views.generic.simple.direct_to_template', # {'template': 'index.html'}), #'booklist.views', (r'^list', 'list'), #'haco.views', #(r'^$', 'login'), #url(r'^$', login), url(r'^report/$', report), url(r'^record/$', record), url(r'^matrix/$', matrix), url(r'^map/$', map), url(r'^test/$', test), url(r'^feed/$', feed), url(r'^csv/$',csv), url(r'^repo_all/$',repo_all), url(r'^cron/twitBot/$',twitBot), )
100uhaco
trunk/GAE/haco/urls.py
Python
asf20
862
# -*- coding: utf-8 -*- from decimal import * from math import * def v2W(volt): if float(volt) < 0: return -1 else: watt = (float(volt) * 1100.0 / 1024.0) * 3000 / (0.9 * 100) / 1000 * 100 watt = Decimal(str(watt)).quantize(Decimal('.0'), rounding=ROUND_HALF_UP) return watt def v2L(volt): if float(volt) <= 0: return -1 else: CON = 0.81 OFFS = 1.22 current = (((float(volt) * (1100.0 / 1024.0) )/ 1000.0) / 11.0) * 1000.0 light = pow(10.0, (CON * log(current,10) + OFFS)); light = Decimal(str(light)).quantize(Decimal('.0'), rounding=ROUND_HALF_UP) return light def v2T(volt): if float(volt) < 0: return -1 else: temp = (float(volt) / 1024.0 * 1100.0 / 6.25) + (-424.0 / 6.25) temp = Decimal(str(temp)).quantize(Decimal('.0'), rounding=ROUND_HALF_UP) return temp
100uhaco
trunk/GAE/haco/convert.py
Python
asf20
955
# -*- coding: utf-8 -*- from django.http import HttpResponse from django.http import HttpResponseRedirect from django.utils.translation import ugettext as _ from haco.models import * from haco.jsTime import * import logging import twython from datetime import * def twitBot( request): mes ="<html><head></head><body>" api = apimake() t = api.getUserMentions(count="20") for e in t: q = Mention.all() q =q.filter('postUser',e['user']['screen_name']) q =q.filter('postText',e['text']) q =q.filter('postDate >=',datetime.strptime(e['created_at'], '%a %b %d %H:%M:%S +0000 %Y')+timedelta(hours=9)) if len(q): break else: # post(makeReply(e)) directMessage(e['user']['screen_name'],makeReply(e)) save(e) return HttpResponse( "OK") def post(msg): api = apimake() api.updateStatus(msg) def directMessage(user, msg): api = apimake() api.sendDirectMessage(user, msg) def save( e): mention =Mention() mention.postUser =e['user']['screen_name'] mention.postText =e['text'] mention.postDate =datetime.strptime(e['created_at'], '%a %b %d %H:%M:%S +0000 %Y')+timedelta(hours=9) mention.put() def makeReply( e): #parse text and generate reply text return "OK I'v got your message" def apimake(): return twython.setup(authtype="Basic",username="user",password="pass")
100uhaco
trunk/GAE/haco/twit.py
Python
asf20
1,503
#!/usr/bin/python """ NOTE: Tango is being renamed to Twython; all basic strings have been changed below, but there's still work ongoing in this department. Twython is an up-to-date library for Python that wraps the Twitter API. Other Python Twitter libraries seem to have fallen a bit behind, and Twitter's API has evolved a bit. Here's hoping this helps. TODO: OAuth, Streaming API? Questions, comments? ryan@venodesigns.net """ import httplib, urllib, urllib2, mimetypes, mimetools from urllib2 import HTTPError __author__ = "Ryan McGrath <ryan@venodesigns.net>" __version__ = "0.8.0.1" """Twython - Easy Twitter utilities in Python""" try: import simplejson except ImportError: try: import json as simplejson except: raise Exception("Twython requires the simplejson library (or Python 2.6) to work. http://www.undefined.org/python/") try: import oauth except ImportError: pass class TangoError(Exception): def __init__(self, msg, error_code=None): self.msg = msg if error_code == 400: raise APILimit(msg) def __str__(self): return repr(self.msg) class APILimit(TangoError): def __init__(self, msg): self.msg = msg def __str__(self): return repr(self.msg) class setup: def __init__(self, authtype = "OAuth", username = None, password = None, oauth_keys = None, headers = None): self.authtype = authtype self.authenticated = False self.username = username self.password = password self.oauth_keys = oauth_keys if self.username is not None and self.password is not None: if self.authtype == "OAuth": self.request_token_url = 'https://twitter.com/oauth/request_token' self.access_token_url = 'https://twitter.com/oauth/access_token' self.authorization_url = 'http://twitter.com/oauth/authorize' self.signin_url = 'http://twitter.com/oauth/authenticate' # Do OAuth type stuff here - how should this be handled? Seems like a framework question... elif self.authtype == "Basic": self.auth_manager = urllib2.HTTPPasswordMgrWithDefaultRealm() self.auth_manager.add_password(None, "http://twitter.com", self.username, self.password) self.handler = urllib2.HTTPBasicAuthHandler(self.auth_manager) self.opener = urllib2.build_opener(self.handler) if headers is not None: self.opener.addheaders = [('User-agent', headers)] try: simplejson.load(self.opener.open("http://twitter.com/account/verify_credentials.json")) self.authenticated = True except HTTPError, e: raise TangoError("Authentication failed with your provided credentials. Try again? (%s failure)" % `e.code`, e.code) # OAuth functions; shortcuts for verifying the credentials. def fetch_response_oauth(self, oauth_request): pass def get_unauthorized_request_token(self): pass def get_authorization_url(self, token): pass def exchange_tokens(self, request_token): pass # URL Shortening function huzzah def shortenURL(self, url_to_shorten, shortener = "http://is.gd/api.php", query = "longurl"): try: return urllib2.urlopen(shortener + "?" + urllib.urlencode({query: url_to_shorten})).read() except HTTPError, e: raise TangoError("shortenURL() failed with a %s error code." % `e.code`) def constructApiURL(self, base_url, params): return base_url + "?" + "&".join(["%s=%s" %(key, value) for (key, value) in params.iteritems()]) def getRateLimitStatus(self, rate_for = "requestingIP"): try: if rate_for == "requestingIP": return simplejson.load(urllib2.urlopen("http://twitter.com/account/rate_limit_status.json")) else: if self.authenticated is True: return simplejson.load(self.opener.open("http://twitter.com/account/rate_limit_status.json")) else: raise TangoError("You need to be authenticated to check a rate limit status on an account.") except HTTPError, e: raise TangoError("It seems that there's something wrong. Twitter gave you a %s error code; are you doing something you shouldn't be?" % `e.code`, e.code) def getPublicTimeline(self): try: return simplejson.load(urllib2.urlopen("http://twitter.com/statuses/public_timeline.json")) except HTTPError, e: raise TangoError("getPublicTimeline() failed with a %s error code." % `e.code`) def getFriendsTimeline(self, **kwargs): if self.authenticated is True: try: friendsTimelineURL = self.constructApiURL("http://twitter.com/statuses/friends_timeline.json", kwargs) return simplejson.load(self.opener.open(friendsTimelineURL)) except HTTPError, e: raise TangoError("getFriendsTimeline() failed with a %s error code." % `e.code`) else: raise TangoError("getFriendsTimeline() requires you to be authenticated.") def getUserTimeline(self, id = None, **kwargs): if id is not None and kwargs.has_key("user_id") is False and kwargs.has_key("screen_name") is False: userTimelineURL = self.constructApiURL("http://twitter.com/statuses/user_timeline/" + id + ".json", kwargs) elif id is None and kwargs.has_key("user_id") is False and kwargs.has_key("screen_name") is False and self.authenticated is True: userTimelineURL = self.constructApiURL("http://twitter.com/statuses/user_timeline/" + self.username + ".json", kwargs) else: userTimelineURL = self.constructApiURL("http://twitter.com/statuses/user_timeline.json", kwargs) try: # We do our custom opener if we're authenticated, as it helps avoid cases where it's a protected user if self.authenticated is True: return simplejson.load(self.opener.open(userTimelineURL)) else: return simplejson.load(urllib2.urlopen(userTimelineURL)) except HTTPError, e: raise TangoError("Failed with a %s error code. Does this user hide/protect their updates? If so, you'll need to authenticate and be their friend to get their timeline." % `e.code`, e.code) def getUserMentions(self, **kwargs): if self.authenticated is True: try: mentionsFeedURL = self.constructApiURL("http://twitter.com/statuses/mentions.json", kwargs) return simplejson.load(self.opener.open(mentionsFeedURL)) except HTTPError, e: raise TangoError("getUserMentions() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("getUserMentions() requires you to be authenticated.") def showStatus(self, id): try: if self.authenticated is True: return simplejson.load(self.opener.open("http://twitter.com/statuses/show/%s.json" % id)) else: return simplejson.load(urllib2.urlopen("http://twitter.com/statuses/show/%s.json" % id)) except HTTPError, e: raise TangoError("Failed with a %s error code. Does this user hide/protect their updates? You'll need to authenticate and be friends to get their timeline." % `e.code`, e.code) def updateStatus(self, status, in_reply_to_status_id = None): if self.authenticated is True: if len(list(status)) > 140: raise TangoError("This status message is over 140 characters. Trim it down!") try: return simplejson.load(self.opener.open("http://twitter.com/statuses/update.json?", urllib.urlencode({"status": status, "in_reply_to_status_id": in_reply_to_status_id}))) except HTTPError, e: raise TangoError("updateStatus() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("updateStatus() requires you to be authenticated.") def destroyStatus(self, id): if self.authenticated is True: try: return simplejson.load(self.opener.open("http://twitter.com/status/destroy/%s.json", "POST" % id)) except HTTPError, e: raise TangoError("destroyStatus() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("destroyStatus() requires you to be authenticated.") def endSession(self): if self.authenticated is True: try: self.opener.open("http://twitter.com/account/end_session.json", "") self.authenticated = False except HTTPError, e: raise TangoError("endSession failed with a %s error code." % `e.code`, e.code) else: raise TangoError("You can't end a session when you're not authenticated to begin with.") def getDirectMessages(self, since_id = None, max_id = None, count = None, page = "1"): if self.authenticated is True: apiURL = "http://twitter.com/direct_messages.json?page=" + page if since_id is not None: apiURL += "&since_id=" + since_id if max_id is not None: apiURL += "&max_id=" + max_id if count is not None: apiURL += "&count=" + count try: return simplejson.load(self.opener.open(apiURL)) except HTTPError, e: raise TangoError("getDirectMessages() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("getDirectMessages() requires you to be authenticated.") def getSentMessages(self, since_id = None, max_id = None, count = None, page = "1"): if self.authenticated is True: apiURL = "http://twitter.com/direct_messages/sent.json?page=" + page if since_id is not None: apiURL += "&since_id=" + since_id if max_id is not None: apiURL += "&max_id=" + max_id if count is not None: apiURL += "&count=" + count try: return simplejson.load(self.opener.open(apiURL)) except HTTPError, e: raise TangoError("getSentMessages() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("getSentMessages() requires you to be authenticated.") def sendDirectMessage(self, user, text): if self.authenticated is True: if len(list(text)) < 140: try: return self.opener.open("http://twitter.com/direct_messages/new.json", urllib.urlencode({"user": user, "text": text})) except HTTPError, e: raise TangoError("sendDirectMessage() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("Your message must not be longer than 140 characters") else: raise TangoError("You must be authenticated to send a new direct message.") def destroyDirectMessage(self, id): if self.authenticated is True: try: return self.opener.open("http://twitter.com/direct_messages/destroy/%s.json" % id, "") except HTTPError, e: raise TangoError("destroyDirectMessage() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("You must be authenticated to destroy a direct message.") def createFriendship(self, id = None, user_id = None, screen_name = None, follow = "false"): if self.authenticated is True: apiURL = "" if id is not None: apiURL = "http://twitter.com/friendships/create/" + id + ".json" + "?follow=" + follow if user_id is not None: apiURL = "http://twitter.com/friendships/create.json?user_id=" + user_id + "&follow=" + follow if screen_name is not None: apiURL = "http://twitter.com/friendships/create.json?screen_name=" + screen_name + "&follow=" + follow try: return simplejson.load(self.opener.open(apiURL)) except HTTPError, e: # Rate limiting is done differently here for API reasons... if e.code == 403: raise TangoError("You've hit the update limit for this method. Try again in 24 hours.") raise TangoError("createFriendship() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("createFriendship() requires you to be authenticated.") def destroyFriendship(self, id = None, user_id = None, screen_name = None): if self.authenticated is True: apiURL = "" if id is not None: apiURL = "http://twitter.com/friendships/destroy/" + id + ".json" if user_id is not None: apiURL = "http://twitter.com/friendships/destroy.json?user_id=" + user_id if screen_name is not None: apiURL = "http://twitter.com/friendships/destroy.json?screen_name=" + screen_name try: return simplejson.load(self.opener.open(apiURL)) except HTTPError, e: raise TangoError("destroyFriendship() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("destroyFriendship() requires you to be authenticated.") def checkIfFriendshipExists(self, user_a, user_b): if self.authenticated is True: try: return simplejson.load(self.opener.open("http://twitter.com/friendships/exists.json", urllib.urlencode({"user_a": user_a, "user_b": user_b}))) except HTTPError, e: raise TangoError("checkIfFriendshipExists() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("checkIfFriendshipExists(), oddly, requires that you be authenticated.") def updateDeliveryDevice(self, device_name = "none"): if self.authenticated is True: try: return self.opener.open("http://twitter.com/account/update_delivery_device.json?", urllib.urlencode({"device": device_name})) except HTTPError, e: raise TangoError("updateDeliveryDevice() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("updateDeliveryDevice() requires you to be authenticated.") def updateProfileColors(self, **kwargs): if self.authenticated is True: try: return self.opener.open(self.constructApiURL("http://twitter.com/account/update_profile_colors.json?", kwargs)) except HTTPError, e: raise TangoError("updateProfileColors() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("updateProfileColors() requires you to be authenticated.") def updateProfile(self, name = None, email = None, url = None, location = None, description = None): if self.authenticated is True: useAmpersands = False updateProfileQueryString = "" if name is not None: if len(list(name)) < 20: updateProfileQueryString += "name=" + name useAmpersands = True else: raise TangoError("Twitter has a character limit of 20 for all usernames. Try again.") if email is not None and "@" in email: if len(list(email)) < 40: if useAmpersands is True: updateProfileQueryString += "&email=" + email else: updateProfileQueryString += "email=" + email useAmpersands = True else: raise TangoError("Twitter has a character limit of 40 for all email addresses, and the email address must be valid. Try again.") if url is not None: if len(list(url)) < 100: if useAmpersands is True: updateProfileQueryString += "&" + urllib.urlencode({"url": url}) else: updateProfileQueryString += urllib.urlencode({"url": url}) useAmpersands = True else: raise TangoError("Twitter has a character limit of 100 for all urls. Try again.") if location is not None: if len(list(location)) < 30: if useAmpersands is True: updateProfileQueryString += "&" + urllib.urlencode({"location": location}) else: updateProfileQueryString += urllib.urlencode({"location": location}) useAmpersands = True else: raise TangoError("Twitter has a character limit of 30 for all locations. Try again.") if description is not None: if len(list(description)) < 160: if useAmpersands is True: updateProfileQueryString += "&" + urllib.urlencode({"description": description}) else: updateProfileQueryString += urllib.urlencode({"description": description}) else: raise TangoError("Twitter has a character limit of 160 for all descriptions. Try again.") if updateProfileQueryString != "": try: return self.opener.open("http://twitter.com/account/update_profile.json?", updateProfileQueryString) except HTTPError, e: raise TangoError("updateProfile() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("updateProfile() requires you to be authenticated.") def getFavorites(self, page = "1"): if self.authenticated is True: try: return simplejson.load(self.opener.open("http://twitter.com/favorites.json?page=" + page)) except HTTPError, e: raise TangoError("getFavorites() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("getFavorites() requires you to be authenticated.") def createFavorite(self, id): if self.authenticated is True: try: return simplejson.load(self.opener.open("http://twitter.com/favorites/create/" + id + ".json", "")) except HTTPError, e: raise TangoError("createFavorite() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("createFavorite() requires you to be authenticated.") def destroyFavorite(self, id): if self.authenticated is True: try: return simplejson.load(self.opener.open("http://twitter.com/favorites/destroy/" + id + ".json", "")) except HTTPError, e: raise TangoError("destroyFavorite() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("destroyFavorite() requires you to be authenticated.") def notificationFollow(self, id = None, user_id = None, screen_name = None): if self.authenticated is True: apiURL = "" if id is not None: apiURL = "http://twitter.com/notifications/follow/" + id + ".json" if user_id is not None: apiURL = "http://twitter.com/notifications/follow/follow.json?user_id=" + user_id if screen_name is not None: apiURL = "http://twitter.com/notifications/follow/follow.json?screen_name=" + screen_name try: return simplejson.load(self.opener.open(apiURL, "")) except HTTPError, e: raise TangoError("notificationFollow() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("notificationFollow() requires you to be authenticated.") def notificationLeave(self, id = None, user_id = None, screen_name = None): if self.authenticated is True: apiURL = "" if id is not None: apiURL = "http://twitter.com/notifications/leave/" + id + ".json" if user_id is not None: apiURL = "http://twitter.com/notifications/leave/leave.json?user_id=" + user_id if screen_name is not None: apiURL = "http://twitter.com/notifications/leave/leave.json?screen_name=" + screen_name try: return simplejson.load(self.opener.open(apiURL, "")) except HTTPError, e: raise TangoError("notificationLeave() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("notificationLeave() requires you to be authenticated.") def getFriendsIDs(self, id = None, user_id = None, screen_name = None, page = "1"): apiURL = "" if id is not None: apiURL = "http://twitter.com/friends/ids/" + id + ".json" + "?page=" + page if user_id is not None: apiURL = "http://twitter.com/friends/ids.json?user_id=" + user_id + "&page=" + page if screen_name is not None: apiURL = "http://twitter.com/friends/ids.json?screen_name=" + screen_name + "&page=" + page try: return simplejson.load(urllib2.urlopen(apiURL)) except HTTPError, e: raise TangoError("getFriendsIDs() failed with a %s error code." % `e.code`, e.code) def getFollowersIDs(self, id = None, user_id = None, screen_name = None, page = "1"): apiURL = "" if id is not None: apiURL = "http://twitter.com/followers/ids/" + id + ".json" + "?page=" + page if user_id is not None: apiURL = "http://twitter.com/followers/ids.json?user_id=" + user_id + "&page=" + page if screen_name is not None: apiURL = "http://twitter.com/followers/ids.json?screen_name=" + screen_name + "&page=" + page try: return simplejson.load(urllib2.urlopen(apiURL)) except HTTPError, e: raise TangoError("getFollowersIDs() failed with a %s error code." % `e.code`, e.code) def createBlock(self, id): if self.authenticated is True: try: return simplejson.load(self.opener.open("http://twitter.com/blocks/create/" + id + ".json", "")) except HTTPError, e: raise TangoError("createBlock() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("createBlock() requires you to be authenticated.") def destroyBlock(self, id): if self.authenticated is True: try: return simplejson.load(self.opener.open("http://twitter.com/blocks/destroy/" + id + ".json", "")) except HTTPError, e: raise TangoError("destroyBlock() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("destroyBlock() requires you to be authenticated.") def checkIfBlockExists(self, id = None, user_id = None, screen_name = None): apiURL = "" if id is not None: apiURL = "http://twitter.com/blocks/exists/" + id + ".json" if user_id is not None: apiURL = "http://twitter.com/blocks/exists.json?user_id=" + user_id if screen_name is not None: apiURL = "http://twitter.com/blocks/exists.json?screen_name=" + screen_name try: return simplejson.load(urllib2.urlopen(apiURL)) except HTTPError, e: raise TangoError("checkIfBlockExists() failed with a %s error code." % `e.code`, e.code) def getBlocking(self, page = "1"): if self.authenticated is True: try: return simplejson.load(self.opener.open("http://twitter.com/blocks/blocking.json?page=" + page)) except HTTPError, e: raise TangoError("getBlocking() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("getBlocking() requires you to be authenticated") def getBlockedIDs(self): if self.authenticated is True: try: return simplejson.load(self.opener.open("http://twitter.com/blocks/blocking/ids.json")) except HTTPError, e: raise TangoError("getBlockedIDs() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("getBlockedIDs() requires you to be authenticated.") def searchTwitter(self, search_query, **kwargs): searchURL = self.constructApiURL("http://search.twitter.com/search.json", kwargs) + "&" + urllib.urlencode({"q": search_query}) try: return simplejson.load(urllib2.urlopen(searchURL)) except HTTPError, e: raise TangoError("getSearchTimeline() failed with a %s error code." % `e.code`, e.code) def getCurrentTrends(self, excludeHashTags = False): apiURL = "http://search.twitter.com/trends/current.json" if excludeHashTags is True: apiURL += "?exclude=hashtags" try: return simplejson.load(urllib.urlopen(apiURL)) except HTTPError, e: raise TangoError("getCurrentTrends() failed with a %s error code." % `e.code`, e.code) def getDailyTrends(self, date = None, exclude = False): apiURL = "http://search.twitter.com/trends/daily.json" questionMarkUsed = False if date is not None: apiURL += "?date=" + date questionMarkUsed = True if exclude is True: if questionMarkUsed is True: apiURL += "&exclude=hashtags" else: apiURL += "?exclude=hashtags" try: return simplejson.load(urllib.urlopen(apiURL)) except HTTPError, e: raise TangoError("getDailyTrends() failed with a %s error code." % `e.code`, e.code) def getWeeklyTrends(self, date = None, exclude = False): apiURL = "http://search.twitter.com/trends/daily.json" questionMarkUsed = False if date is not None: apiURL += "?date=" + date questionMarkUsed = True if exclude is True: if questionMarkUsed is True: apiURL += "&exclude=hashtags" else: apiURL += "?exclude=hashtags" try: return simplejson.load(urllib.urlopen(apiURL)) except HTTPError, e: raise TangoError("getWeeklyTrends() failed with a %s error code." % `e.code`, e.code) def getSavedSearches(self): if self.authenticated is True: try: return simplejson.load(self.opener.open("http://twitter.com/saved_searches.json")) except HTTPError, e: raise TangoError("getSavedSearches() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("getSavedSearches() requires you to be authenticated.") def showSavedSearch(self, id): if self.authenticated is True: try: return simplejson.load(self.opener.open("http://twitter.com/saved_searches/show/" + id + ".json")) except HTTPError, e: raise TangoError("showSavedSearch() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("showSavedSearch() requires you to be authenticated.") def createSavedSearch(self, query): if self.authenticated is True: try: return simplejson.load(self.opener.open("http://twitter.com/saved_searches/create.json?query=" + query, "")) except HTTPError, e: raise TangoError("createSavedSearch() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("createSavedSearch() requires you to be authenticated.") def destroySavedSearch(self, id): if self.authenticated is True: try: return simplejson.load(self.opener.open("http://twitter.com/saved_searches/destroy/" + id + ".json", "")) except HTTPError, e: raise TangoError("destroySavedSearch() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("destroySavedSearch() requires you to be authenticated.") # The following methods are apart from the other Account methods, because they rely on a whole multipart-data posting function set. def updateProfileBackgroundImage(self, filename, tile="true"): if self.authenticated is True: try: files = [("image", filename, open(filename).read())] fields = [] content_type, body = self.encode_multipart_formdata(fields, files) headers = {'Content-Type': content_type, 'Content-Length': str(len(body))} r = urllib2.Request("http://twitter.com/account/update_profile_background_image.json?tile=" + tile, body, headers) return self.opener.open(r).read() except HTTPError, e: raise TangoError("updateProfileBackgroundImage() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("You realize you need to be authenticated to change a background image, right?") def updateProfileImage(self, filename): if self.authenticated is True: try: files = [("image", filename, open(filename).read())] fields = [] content_type, body = self.encode_multipart_formdata(fields, files) headers = {'Content-Type': content_type, 'Content-Length': str(len(body))} r = urllib2.Request("http://twitter.com/account/update_profile_image.json", body, headers) return self.opener.open(r).read() except HTTPError, e: raise TangoError("updateProfileImage() failed with a %s error code." % `e.code`, e.code) else: raise TangoError("You realize you need to be authenticated to change a profile image, right?") def encode_multipart_formdata(self, fields, files): BOUNDARY = mimetools.choose_boundary() CRLF = '\r\n' L = [] for (key, value) in fields: L.append('--' + BOUNDARY) L.append('Content-Disposition: form-data; name="%s"' % key) L.append('') L.append(value) for (key, filename, value) in files: L.append('--' + BOUNDARY) L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) L.append('Content-Type: %s' % self.get_content_type(filename)) L.append('') L.append(value) L.append('--' + BOUNDARY + '--') L.append('') body = CRLF.join(L) content_type = 'multipart/form-data; boundary=%s' % BOUNDARY return content_type, body def get_content_type(self, filename): return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
100uhaco
trunk/GAE/haco/twython.py
Python
asf20
26,871
{% extends "base.html" %} {% block title %}Member{% endblock %} {% block content %} <h1>Member</h1> <div> {% for hacoUser in object_list %} {{ hacoUser.user.username }} <br> {% if not forloop.last %} {% endif %} {% endfor %} </div> </ul> {% endblock content %}
100uhaco
trunk/GAE/haco/templates/hacouser_list.html
HTML
asf20
293