Create Free Blog | Random Blog »   Report Abuse | Login   

 

Nisumu Bloggers Park

Software Meri Jaan

Shine motors

July13

Java

April3

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

import

 

java.util.Scanner;

 

public

 

class

abh{

 

 

private static String [][] seats = new String

[5][10]; 

 

private static Scanner input = new Scanner(System

.in); 

 

private static void

menu() {

 

System.out.println(“\n========================================”

); 

 

System.out.println(“= Welcome To Ticket System”

); 

 

System.out.println(“========================================”

); 

 

System.out.println(“= 1 – New”

); 

 

System.out.println(“= 2 – Search”

); 

 

System.out.println(“= 3 – Exit”

); 

 

System.out.println(“=====================================================”

); 

 

System.out.println(“= Please Choose Between 1 , 2 & 3 then press Enter Key”

); 

 

System.out.println(“=====================================================”

);}

 

 

public static void main(String

args[]){

 

 

 

 

int

option = 0; 

 

for (int

r = 0; r < seats.length; r++) 

 

for (int

c = 0; c < seats[r].length; c++)seats[r][c] =

 

new String

(); 

 

while

(option != 3){

menu();

option = input.nextInt();

 

 

if

(option == 1){

Newbooking();

}

 

 

else if

(option == 2){

SearchBooking();

}

 

 

else if

(option == 3){

 

 

System.out.println(“Bye”

); 

 

System

.exit(0);}

 

 

else

 

{

 

 

System.out.println(“Invalild Choice”

);}

}

 

}

 

 

 

private static void

Newbooking(){

 

 

String

ticketNo; 

 

String

name;  

 

System.out.println(“\nEnter Seat No. “

);ticketNo = input.next();

 

 

System

.out.println(ticketNo.length()); 

 

char

row = ticketNo.toUpperCase().charAt(0); 

 

int

r=0; 

 

int col = Integer

.parseInt(ticketNo.substring(1)); 

 

int

maxCol = seats[0].length + 1; 

 

 

boolean isValidRow = false

; 

 

switch

(row){

 

 

case ‘A’: r=0; isValidRow = true; break

; 

 

case ‘B’: r=1; isValidRow = true; break

; 

 

case ‘C’: r=2; isValidRow = true; break

; 

 

case ‘D’: r=3; isValidRow = true; break

; 

 

case ‘E’: r=4; isValidRow = true; break

; 

 

/* case ‘F’: r=5; isValidRow = true; break;case ‘G’: r=6; isValidRow = true; break;

case ‘H’: r=7; isValidRow = true; break;

case ‘I’: r=8; isValidRow = true; break;

case ‘J’: r=9; isValidRow = true; break;

case ‘K’: r=10; isValidRow = true; break;

case ‘L’: r=11; isValidRow = true; break;

case ‘M’: r=12; isValidRow = true; break;

case ‘N’: r=13; isValidRow = true; break;

case ‘O’: r=14; isValidRow = true; break;

case ‘P’: r=15; isValidRow = true; break;

case ‘Q’: r=16; isValidRow = true; break;

case ‘R’: r=17; isValidRow = true; break;

case ‘S’: r=18; isValidRow = true; break;

case ‘T’: r=19; isValidRow = true; break;

case ‘U’: r=20; isValidRow = true; break;

case ‘V’: r=21; isValidRow = true; break;

case ‘W’: r=22; isValidRow = true; break;

case ‘X’: r=23; isValidRow = true; break;

case ‘Y’: r=24; isValidRow = true; break;

case ‘Z’: r=25; isValidRow = true; break;*/

 

 

 

default: isValidRow = false; break

;}

 

 

 

if (isValidRow == false

){

 

System.out.println(“Invalid Row”

); 

 

return

;}

 

 

 

if

(col > 0 && col < maxCol){

 

 

if

(seats[r][col - 1].length() > 0){

 

 

System.out.println(“Seats already booked with : “

+ seats[r][col - 1]); 

 

return

;}

 

 

System.out.println(“\nEnter Name : “

);name = input.next();

seats[r][col - 1] = name;

 

 

System.out.println(“*** SEATS BOOKED ****”

);}

 

 

else

 

 

 

System.out.println(“Invalid Seat”

);}

 

 

 

private static void

SearchBooking(){

 

 

String

name; 

 

System.out.println(“\nEnter Name to search : “

);name = input.next();

 

 

for (int

r = 0; r < seats.length; r++) 

 

for (int

c = 0; c < seats[r].length; c++){

 

 

if

(seats[r][c].length() > 0){

 

 

if

(seats[r][c].equals(name)){

 

 

System.out.println(“Your Seat No. : “

+ seatId(r) + (c + 1)); 

 

break

;}

}

}

}

 

 

 

private static char seatId(int

row){

 

 

char r=‘1′

; 

 

switch

(row){

 

 

case 0: r = ‘A’; break

; 

 

case 1: r = ‘B’; break

; 

 

case 2: r = ‘C’; break

; 

 

case 3: r = ‘D’; break

; 

 

case 4: r = ‘E’; break

; 

 

/* case 5: r=5; isValidRow = true; break;case ‘G’: r=6; isValidRow = true; break;

case ‘H’: r=7; isValidRow = true; break;

case ‘I’: r=8; isValidRow = true; break;

case ‘J’: r=9; isValidRow = true; break;

case ‘K’: r=10; isValidRow = true; break;

case ‘L’: r=11; isValidRow = true; break;

case ‘M’: r=12; isValidRow = true; break;

case ‘N’: r=13; isValidRow = true; break;

case ‘O’: r=14; isValidRow = true; break;

case ‘P’: r=15; isValidRow = true; break;

case ‘Q’: r=16; isValidRow = true; break;

case ‘R’: r=17; isValidRow = true; break;

case ‘S’: r=18; isValidRow = true; break;

case ‘T’: r=19; isValidRow = true; break;

case ‘U’: r=20; isValidRow = true; break;

case ‘V’: r=21; isValidRow = true; break;

case ‘W’: r=22; isValidRow = true; break;

case ‘X’: r=23; isValidRow = true; break;

case ‘Y’: r=24; isValidRow = true; break;

case ‘Z’: r=25; isValidRow = true; break;*/

 

}

 

 

return

(r);

Share SocialTwist Tell-a-Friend 

Silverlight Socket Chat

January15

    public static void BeginSend(this Socket socket,
        Packet packet,
        EventHandler<SocketAsyncEventArgs> completionEvent) {           
        SocketAsyncEventArgs sendArgs = new SocketAsyncEventArgs();
        sendArgs.Completed += completionEvent;
        byte[] buffer = Protocol.GetPacket(packet);
        sendArgs.SetBuffer(buffer, 0, buffer.Length);
        socket.SendAsync(sendArgs);
    }
   
    public static void BeginReceive(this Socket socket,
        EventHandler<SocketAsyncEventArgs> completionEvent) {
        SocketAsyncEventArgs sendArgs = new SocketAsyncEventArgs();
        byte[] buffer = new byte[1024];
        sendArgs.SetBuffer(buffer, 0, buffer.Length);
        sendArgs.Completed += completionEvent;
        socket.ReceiveAsync(sendArgs);
    }
   
    #endif

}

When we receive the reply from the server, OnReceiveComplete event is invoked:

void OnReceiveComplete(object sender, SocketAsyncEventArgs e) {
    SocketError error = e.SocketError;
    if (error == SocketError.Success) {
        try {
            Packet packet = Protocol.GetPacket(e.Buffer, e.BytesTransferred);
            if (packet.Operation == Operation.RefreshUsers) {
                this.Dispatcher.BeginInvoke(delegate() {
                    Users.DataSource = packet.Children;
                    Users.ExpandAll();
                });
            } else if (packet.Operation == Operation.Message) {
                this.Dispatcher.BeginInvoke(delegate() {
                    ShowChatWindow(packet.Children[0], packet.Payload);
                });
            }
        } catch {
        }
    }
    _socket.BeginReceive(new EventHandler<SocketAsyncEventArgs>(OnReceiveComplete));
}

Two things to note here. 1: “Users” is an AgDataGrid control:

<TalkControl:AgDataGrid Grid.Row="1" x:Name="Users"
                       ShowGroupPanel="Visible"
                       ColumnsAutoWidth="True"
                       AllowEditing="False">
    <TalkControl:AgDataGrid.Columns>
        <DevExpress:AgDataGridTextColumn HeaderContent="User Name" FieldName="UserName"/>
        <DevExpress:AgDataGridTextColumn HeaderContent="User ID" FieldName="UserId"/>
    </TalkControl:AgDataGrid.Columns>
</TalkControl:AgDataGrid>

And 2, we must synchronize access to the main thread via the Dispatcher object.

 

Preparing the UI

Once the client is connected, a conversation could be started either by receiving a message or by double clicking the a record in the data grid. In both cases, the same ShowChatWindow function is called:

private void ShowChatWindow(User peer, string message) {
    ChatWindow window = ChatWindow.FindWindow(peer.UserId);
    if (window == null) {
        Popup popup = new Popup();
        window = new ChatWindow(popup,
            new User() { UserId = _loginId, UserName = _loginName },
            peer, _socket);
        window.Title.Text = peer.UserName;
        popup.VerticalOffset = 100;
        popup.HorizontalOffset = 100;
        popup.Child = window;
        popup.IsOpen = true;
    }
    if (!string.IsNullOrEmpty(message)) {
        window.AddLine(message, Colors.Red, peer);
    }
    window.parent.IsOpen = true;
    window.Focus();
}

There is no support for double-click in Silverlight so we will have to fake it using a special MouseHelper class that I copied from the AgDataGrid source code.

public delegate void DblClickEvent(object sender, MouseEventArgs e);

public class AgDataGrid : DevExpress.Windows.Controls.AgDataGrid {
    public void Refresh() {
        base.DataController.DoRefresh();
    }

    private static class MouseHelper {
        static int Timeout = 500;
        static bool clicked = false;
        static Point position;
        public static bool IsDoubleClick(MouseButtonEventArgs e) {
            if (clicked) {
                clicked = false;
                return position.Equals(e.GetPosition(null));
            }
            clicked = true;
            position = e.GetPosition(null);
            ParameterizedThreadStart threadStart = new ParameterizedThreadStart(ResetThread);
            Thread thread = new Thread(threadStart);
            thread.Start();
            return false;
        }
        private static void ResetThread(object state) {
            Thread.Sleep(Timeout);
            clicked = false;
        }
    }

    public event DblClickEvent DblClick;

    public override void OnApplyTemplate() {
        base.OnApplyTemplate();
        this.Surface.MouseLeftButtonUp += new MouseButtonEventHandler(Surface_MouseLeftButtonUp);
    }

    void Surface_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) {
        if (MouseHelper.IsDoubleClick(e)) {
            if (DblClick != null) {
                DblClick(sender, e);
            }
            e.Handled = true;
        }
    }
}

And there no build-in windows or dialogs in Silverlight 2. But there is a System.Windows.Controls.Primitives.Popup container and it’s all we need to create a conversation window. A ChatWindow is a simple UserControl and in the ChatWindow.xaml I have one special element TitleBar.

<Grid Background="Black" Grid.Row="0" x:Name="TitleBar">
    <Border BorderBrush="White" BorderThickness="0.3"></Border>
    <TextBlock  IsHitTestVisible="False" x:Name="Title" Text="Title" VerticalAlignment="Center" HorizontalAlignment="Left"
               FontFamily="Tahoma" Foreground="White" FontSize="14"
                FontWeight="Bold"
                Margin="8,0,0,0"></TextBlock>
    <Button Width="32" Margin="4" HorizontalAlignment="Right" Content="X"
        Click="CloseButtonClick"></Button>
</Grid>

It is used to display the NC (non-client) area of the window with the close button and it is also used to control the dragging of the window. We must have cool UI :) . Implementing the window dragging is simple:

public ChatWindow()
    : base() {
    InitializeComponent();
    this.MouseLeftButtonDown += new MouseButtonEventHandler(ChatWindow_MouseLeftButtonDown);
    this.MouseLeftButtonUp += new MouseButtonEventHandler(ChatWindow_MouseLeftButtonUp);
    this.MouseMove += new MouseEventHandler(ChatWindow_MouseMove);
}

bool _hasNCHitTest = false;
Point _initalNCHitTest = new Point();

void ChatWindow_MouseMove(object sender, MouseEventArgs e) {
    if (e.Handled == true)
        return;
    if (_hasNCHitTest && parent != null) {
        Point hitTest;
        hitTest = e.GetPosition(Title);

        Point delta = new Point(
            hitTest.X - _initalNCHitTest.X,
            hitTest.Y - _initalNCHitTest.Y);

        this.parent.HorizontalOffset += delta.X;
        this.parent.VerticalOffset += delta.Y;

        e.Handled = true;
    }
}

void ChatWindow_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) {
    if (e.Handled == true)
        return;
    if (_hasNCHitTest) {
        _hasNCHitTest = false;
        TitleBar.ReleaseMouseCapture();
        e.Handled = true;
    }
}

void ChatWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
    if (e.Handled == true)
        return;
    if (e.Source == TitleBar && parent != null) {
        _hasNCHitTest = true;
        _initalNCHitTest = e.GetPosition(TitleBar);
        TitleBar.CaptureMouse();
        e.Handled = true;
    }
}

For conversation area, I use the AgDataGrid as well with a custom preview template. Where the grid is called ChatBox and is bound to a list of Message objects.

<TalkConrol:AgDataGrid Grid.Row="1" x:Name="ChatBox" AllowEditing="False" ShowColumnHeaders="Collapsed"
                       ShowHorizontalLines="False"
                       ShowVerticalLines="False"
                       PreviewVisibility="ForAllRows"
                       ColumnsAutoWidth="True">
    <TalkConrol:AgDataGrid.DataRowTemplate>
        <ControlTemplate TargetType="DevExpress:AgDataGridRow">
            <Grid Name="RootElement">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" />
                </Grid.ColumnDefinitions>
                <DevExpressInternal:AgLineStackPanel x:Name="CellsPresenterElement" Opacity="0" Height="1" />
                <ContentControl x:Name="PreviewPresenterElement" Height="0"/>
            </Grid>
        </ControlTemplate>
    </TalkConrol:AgDataGrid.DataRowTemplate>
    <TalkConrol:AgDataGrid.PreviewTemplate>
        <DataTemplate>
                <StackPanel Orientation="Vertical" HorizontalAlignment="Left" Margin="6,0,0,0">
                    <TextBlock Text="{Binding Timestamp}" TextWrapping="NoWrap"
                              Margin="2,0,0,0"
                              Width="300"
                              Foreground="Gray"
                              FontFamily="lucida grande,tahoma,verdana,arial,sans-serif"
                              FontSize="11"></TextBlock>
                    <TextBlock Text="{Binding Line}" TextWrapping="Wrap"
                              Margin="16,1,0,0"
                              Width="300"
                              Foreground="{Binding Color}"
                              FontFamily="lucida grande,tahoma,verdana,arial,sans-serif"
                              FontSize="11"></TextBlock>
            </StackPanel>
        </DataTemplate>
    </TalkConrol:AgDataGrid.PreviewTemplate>
</TalkConrol:AgDataGrid>

 
public class Message {
    public string Timestamp { get; set; }
    public string Line { get; set; }
    public Brush Color { get; set; }
}

internal void AddLine(string message, Color color, User peer) {
    var list = this.ChatBox.DataSource as List<Message>;
    list.Add(new Message() {
        Line = string.Format("{0}: {1}", peer.UserName, message),
        Timestamp = DateTime.Now.ToString(), Color = new SolidColorBrush(color)
    });
    ChatBox.Refresh();
}

One last thing, sending the actual message and we are done:

private void Send_Click(object sender, RoutedEventArgs e) {
    if (!string.IsNullOrEmpty(MessageBox.Text)) {
        Packet packet = new Packet() {
            UserId = user.UserId,
            UserName = user.UserName,
            Operation = Operation.Message,
            Payload = MessageBox.Text,
            Children = new List<User>() { new User() { UserId = peer.UserId, UserName = peer.UserName } },
        };
        AddLine(MessageBox.Text, Colors.Black, this.user);
        socket.BeginSend(packet, null);
    }
}

 

Published By: Azret Botash (Developer Express)

Share SocialTwist Tell-a-Friend 

Welcome

October21

Welcome to Nisumu bloggers park, that will host all type of post. Since i am software freak i titled this blog as software meri jaan.

posted under General | 2 Comments »