to upload two(photo and signature) image only in database from one page using c# - c#-3.0

There is a page where I've to upload and view photo and signature (the snapshot of the page is attached )but whenever i click the view button the path to the image gets clear and the binary format of the image is saved something like 0x(only this much is saved in database nothing else) format in the database .And the 2nd thing is that both photo and signature are to be seen individually without saving in database.please suggest me a solution for this please.
code
protected void pichck()
{
string picextension = System.IO.Path.GetExtension(imgflup.PostedFile.FileName.ToString()).ToLower();
fs = imgflup.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
picbyte = br.ReadBytes((Int32)fs.Length);
byte[] picarray=new byte[]{255,216,255};
//Boolean match = true;
//int i;
//for (i = 0; i <= picarray.Length - 1;i=i+1 )
//{
// if(picarray[i]!=picbyte[i])
// {
// match = false;
// break;
// }
//}
//if (match == true)
//{
if (picextension == ".jpg" || picextension == ".jpeg")
{
if (imgflup.HasFile == true)
{
if (imgflup.PostedFile.ContentLength < 20000 & imgflup.PostedFile.ContentLength > 50000)
{
Response.Write("<script>alert('the file should be of size 20 mb to 50mb ')</script>");
check();
return;
}
else
{
string base64String = Convert.ToBase64String(picbyte, 0, picbyte.Length);
picimg.ImageUrl = "data:image/png;base64," + base64String;
Label1.Visible = true;
Label1.Visible = true;
Label1.Text = imgflup.PostedFile.FileName;
}
}
//}
else
{
Response.Write("<script>alert('the file should be of jpg or jpeg format')</script>");
check();
return;
}
}
else
{
Response.Write("<script>alert('Please Upload a file')</script>");
check();
return;
}
}
protected void signchckt()
{
string signextension = System.IO.Path.GetExtension(signflup.PostedFile.FileName.ToString()).ToLower();
fs1 = signflup.PostedFile.InputStream;
BinaryReader br1 = new BinaryReader(fs1);
signbyte = br1.ReadBytes((Int32)fs1.Length);
//Boolean match = true;
//int i;
//byte[] signarray=new byte[]{255,216,255};
//for (i = 0; i <= signarray.Length - 1;i=i+1 )
//{
// if(signarray[i]!=signbyte[i])
// {
// match = false;
// break;
// }
//}
//if (match == true)
//{
if (signflup.HasFile == true)
{
if (signextension == ".jpg" || signextension == ".jpeg")
{
if (signflup.PostedFile.ContentLength < 20000 & signflup.PostedFile.ContentLength > 50000)
{
Response.Write("<script>alert('the file should be of size 20 mb to 50mb ')</script>");
check1();
return;
}
else
{
string base64String = Convert.ToBase64String(signbyte, 0, signbyte.Length);
signimg.ImageUrl = "data:image/png;base64," + base64String;
Label2.Visible = true;
Label2.Visible = true;
Label2.Text =signflup.PostedFile.FileName;
}
}
else
{
Response.Write("<script>alert('The signature should be of jpg or jpeg type')</script>");
check1();
return;
}
}
//}
else
{
Response.Write("<script>alert('Please Upload a file')</script>");
check1();
return;
}
}
protected void imgviewbtn_Click(object sender, EventArgs e)
{
pichck();
}
protected void signviewbtn_Click(object sender, EventArgs e)
{
signchckt();
}
protected void updtbtn_Click(object sender, EventArgs e)
{
Int64 aplicationid = Convert.ToInt64(Session["ID"].ToString());
if (Session["ID"].ToString()=="")
{
Response.Write("<script>alert('There is no Application Id')</script>");
Response.Redirect("~/home.aspx");
}
else
{
using (obj.con)
{
pichck();
signchckt();
obj.con.Open();
obj.cmd = new SqlCommand("spPhotoandsignature",obj.con);
obj.cmd.CommandType = System.Data.CommandType.StoredProcedure;
obj.cmd.Parameters.AddWithValue("#Application_Id", aplicationid);
obj.cmd.Parameters.AddWithValue("#Pic_Scan",SqlDbType.Binary).Value =picbyte;
obj.cmd.Parameters.AddWithValue("#Pic_Size", fs);
obj.cmd.Parameters.AddWithValue("#Sign_Scan",SqlDbType.Binary).Value =signbyte;
obj.cmd.Parameters.AddWithValue("#Sign_Size", fs1);
obj.cmd.Parameters.AddWithValue("#Type", System.IO.Path.GetExtension(imgflup.PostedFile.FileName.ToString()).ToLower());
int a= obj.cmd.ExecuteNonQuery();
if (a == 1)
{
Response.Write("<script>alert('your data Submitted successfully')</script>");
Response.Redirect("~/Report.aspx");
}
}
}
}
problempage.png

Related

Unity TCP server freezing

I'm trying to get tcp server working in unity, and it's kinda working. My systems purpose is to read data from another program that sends me bytes and draws me a picture of that data. Main problem is that when I run it, it works for a while (random time) and then whole unity freezes and I need to kill it from the task manager.
void Start()
{
Display1 = gameObject.GetComponent<Renderer>();
mymat = GetComponent<Renderer>().material;
packetReady = false;
tcpListenerThread = new Thread(new ThreadStart(ListenForIncommingRequests));
tcpListenerThread.IsBackground = true;
tcpListenerThread.Start();
bytes = new byte[1024];
tex = new Texture2D(800, 1280, TextureFormat.RGB24, false);
firstTime = true;
ArrayInit(3072060);
packetLength = 3072060;
myThread = new Thread(Draw);
myThread.Start();
}
void Draw()
{
if (Loader == null)
{
return;
}
else if (packetReady)
{
tex.LoadRawTextureData(Loader);
tex.Apply();
mymat.SetTexture("_EmissionMap", tex);
Display1.material.mainTexture = tex;
packetReady = false;
}
}
void Update()
{
Draw();
}
private void ListenForIncommingRequests()
{
try
{
tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 35800);
tcpListener.Start();
while (true)
{
if (!tcpListener.Pending())
{
Thread.Sleep(100);
}
Thread.Sleep(10);
using (connectedTcpClient = tcpListener.AcceptTcpClient())
{
using (NetworkStream stream = connectedTcpClient.GetStream())
{
int length;
while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
{
if (bytes == null)
{
return;
}
else
{
ParseData(bytes);
}
}
}
}
}
}
catch (SocketException socketException)
{
Debug.Log("SocketException " + socketException.ToString());
}
finally
{
tcpListener.Stop();
}
}
I have no idea what is causing this, I've tried to solve the problem but nothing seems to work. Any suggestions?

change pdf image background using Itextsharp

I am trying to change background color of all images of pdf using Itextshap.
How can i loop through all images and change background color of the images
I used below code to extract pdf images
public static void ExtractImagesFromPDF(string sourcePdf, string outputPath)
{
// NOTE: This will only get the first image it finds per page.
PdfReader pdf = new PdfReader(sourcePdf);
RandomAccessFileOrArray raf = new iTextSharp.text.pdf.RandomAccessFileOrArray(sourcePdf);
try
{
for (int pageNumber = 1; pageNumber <= pdf.NumberOfPages; pageNumber++)
{
PdfDictionary pg = pdf.GetPageN(pageNumber);
// recursively search pages, forms and groups for images.
PdfObject obj = FindImageInPDFDictionary(pg);
if (obj != null)
{
int XrefIndex = Convert.ToInt32(((PRIndirectReference)obj).Number.ToString(System.Globalization.CultureInfo.InvariantCulture));
PdfObject pdfObj = pdf.GetPdfObject(XrefIndex);
PdfStream pdfStrem = (PdfStream)pdfObj;
byte[] bytes = PdfReader.GetStreamBytesRaw((PRStream)pdfStrem);
if ((bytes != null))
{
using (System.IO.MemoryStream memStream = new System.IO.MemoryStream(bytes))
{
memStream.Position = 0;
System.Drawing.Image img = System.Drawing.Image.FromStream(memStream);
// must save the file while stream is open.
if (!Directory.Exists(outputPath))
Directory.CreateDirectory(outputPath);
string path = Path.Combine(outputPath, String.Format(#"{0}.jpg", pageNumber));
System.Drawing.Imaging.EncoderParameters parms = new System.Drawing.Imaging.EncoderParameters(1);
parms.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 0);
System.Drawing.Imaging.ImageCodecInfo jpegEncoder = Utilities.GetImageEncoder("JPEG");
img.Save(path, jpegEncoder, parms);
}
}
}
}
}
catch
{
throw;
}
finally
{
pdf.Close();
raf.Close();
}
}
private static PdfObject FindImageInPDFDictionary(PdfDictionary pg)
{
PdfDictionary res =
(PdfDictionary)PdfReader.GetPdfObject(pg.Get(PdfName.RESOURCES));
PdfDictionary xobj =
(PdfDictionary)PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT));
if (xobj != null)
{
foreach (PdfName name in xobj.Keys)
{
PdfObject obj = xobj.Get(name);
if (obj.IsIndirect())
{
PdfDictionary tg = (PdfDictionary)PdfReader.GetPdfObject(obj);
PdfName type =
(PdfName)PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE));
//image at the root of the pdf
if (PdfName.IMAGE.Equals(type))
{
return obj;
}// image inside a form
else if (PdfName.FORM.Equals(type))
{
return FindImageInPDFDictionary(tg);
} //image inside a group
else if (PdfName.GROUP.Equals(type))
{
return FindImageInPDFDictionary(tg);
}
}
}
}
return null;
}
Many thanks in advance

UI Freeze in SWT

I am new to SWT. I am trying to create a small application. Basically it has two screens. In the first screen I have to take user credentials. It has to be validated. If its successful I have to query a table and build a tree structure. Both validation and building the tree freezes my UI. I searched stackoverflow and google. I got the below options.
Display.getDefault().asyncExec() and starting long running process as separate thread from UI thread.
But still my UI freezes.
When the user clicks on Logon button. I created a thread. As a first step I tried to show a indefinite progress bar using asyncExec. Since I have to access the Uname and Password I have to trigger another asyncexec and perform the login. If its successful populated the tree.
I triggered another asyncExec to close the progress bar.
My UI freezes from Logon click till Tree population completion. Where am I going wrong.
new Thread(new Runnable()
{
private int progress = 0;
private static final int INCREMENT = 10;
#Override
public void run()
{
while (!progressBar.isDisposed())
{
Display.getDefault().asyncExec(new Runnable()
{
#Override
public void run()
{
if (!progressBar.isDisposed())
progressBar.setVisible(true);
}
});
Display.getDefault().asyncExec(new Runnable()
{
#Override
public void run()
{
String sAuth = null;
switch(tAuth.getText()){
case "Enterprise": sAuth = "secEnterprise"; break;
case "LDAP": sAuth = "secLDAP"; break;
case "Windows AD": sAuth = "secWinAD"; break;
case "SAP": sAuth = "secSAPR3"; break;
}
try {
log.info("Attempting to create enterprise session");
CoreLogic.logonEnterprise(tUSR.getText().trim(),tPWD.getText().trim(),sAuth,tCMS.getText());
if(CommonVariables.entsession){
log.info("Enterprise session created.");
CoreLogic.getUniverse();
log.info("Populating universe tree");
String[] temp;
for (Entry<Integer, UnvObj> entry : CommonVariables.unvlst.entrySet()) {
UnvObj t = entry.getValue();
temp = t.getPath().split("/");
if (temp[0].equals("Universes")){
int max = temp.length;
int i =0 ;
boolean flag = false;
TreeItem trItem = null;
do{
if(i == 0) {
if(tree.getItemCount() == 0){
flag = false;
}
else
{
for(int k = 0; k < tree.getItemCount(); k++){
if(temp[i].equals(tree.getItem(k).getText())){
i++;
trItem = tree.getItem(k);
flag =true;
break;
}
else
{
flag = false;
}
}
}
}
else{
if(trItem.getItemCount() == 0){
flag = false;
}
else
{
for(int k = 0; k < trItem.getItemCount(); k++){
if(temp[i].equals(trItem.getItem(k).getText())){
i++;
trItem = trItem.getItem(k);
flag =true;
break;
}
else
{
flag = false;
}
}
}
}
}while (flag == true && i < max);
TreeItem Item = null;
if (i == 0){
for (int k = 0; k < max; k++){
if(k == 0) {
Item = new TreeItem(tree,SWT.NONE);
Item.setText(temp[k]);
Item.setData("Type","Folder");
Image image = new Image(display,ResourceLoader.load("/images/Fld.png"));
Item.setImage(image);
}else
{
Item = new TreeItem(Item,SWT.NONE);
Item.setText(temp[k]);
Item.setData("Type","Folder");
Image image = new Image(display,ResourceLoader.load("/images/Fld.png"));
Item.setImage(image);
}
}
} else if( i < max){
for (int k = i; k < max; k++){
trItem = new TreeItem(trItem,SWT.NONE);
trItem.setText(temp[k]);
trItem.setData("Type","Folder");
Image image = new Image(display,ResourceLoader.load("/images/Fld.png"));
trItem.setImage(image);
}
}
if (i == 0){
Item = new TreeItem(Item,SWT.NONE);
Item.setText(t.getName());
Item.setData("Type",t.getKind());
Item.setData("Mapkey",entry.getKey());
if(t.getKind().equals("Universe")){
Image image = new Image(display,ResourceLoader.load("/images/Unv.ico"));
Item.setImage(image);
}
else{
Image image = new Image(display,ResourceLoader.load("/images/Unx.ico"));
Item.setImage(image);
}
} else
{
trItem = new TreeItem(trItem,SWT.NONE);
trItem.setText(t.getName());
trItem.setData("Type",t.getKind());
trItem.setData("Mapkey",entry.getKey());
if(t.getKind().equals("Universe")){
Image image = new Image(display,ResourceLoader.load("/images/Unv.ico"));
trItem.setImage(image);
}
else{
Image image = new Image(display,ResourceLoader.load("/images/Unx.ico"));
trItem.setImage(image);
}
}
}
}
log.info("Universe Tree Populated.");
sl.topControl =Universe;
Main.layout();
}else
{
log.info("Unable to create enterprise session");
MessageBox messageBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
messageBox.setText("Report Extractor");
messageBox.setMessage("Unable to create the enterprise session with the provided credentials. Please verify it.");
messageBox.open();
}
}
catch(Exception exp)
{
log.error("Fail to create enterprise session",exp);
}
}
});
Display.getDefault().asyncExec(new Runnable()
{
#Override
public void run()
{
if (!progressBar.isDisposed())
progressBar.setVisible(false);
}
});
}
}
}).start();

I am getting error while importing Policymanager?

I am writing code for my own media-controller for VideoView.
and my code is as follows
public class FMediaController extends FrameLayout {
private MediaPlayerControl mPlayer;
private Context mContext;
private View mAnchor;
private View mRoot;
private WindowManager mWindowManager;
private Window mWindow;
private View mDecor;
private ProgressBar mProgress;
private TextView mEndTime, mCurrentTime;
private boolean mShowing;
private boolean mDragging;
private static final int sDefaultTimeout = 3000;
private static final int FADE_OUT = 1;
private static final int SHOW_PROGRESS = 2;
private boolean mUseFastForward;
private boolean mFromXml;
private boolean mListenersSet;
private View.OnClickListener mNextListener, mPrevListener;
StringBuilder mFormatBuilder;
Formatter mFormatter;
private ImageButton mPauseButton;
private ImageButton mFfwdButton;
private ImageButton mRewButton;
private ImageButton mNextButton;
private ImageButton mPrevButton;
public FMediaController(Context context, AttributeSet attrs) {
super(context, attrs);
mRoot = this;
mContext = context;
mUseFastForward = true;
mFromXml = true;
}
#Override
public void onFinishInflate() {
if (mRoot != null)
initControllerView(mRoot);
}
public FMediaController(Context context, boolean useFastForward) {
super(context);
mContext = context;
mUseFastForward = useFastForward;
initFloatingWindow();
}
public FMediaController(Context context) {
super(context);
mContext = context;
mUseFastForward = true;
initFloatingWindow();
}
private void initFloatingWindow() {
mWindowManager = (WindowManager)mContext.getSystemService("window");
mWindow = PolicyManager.makeNewWindow(mContext);
mWindow.setWindowManager(mWindowManager, null, null);
mWindow.requestFeature(Window.FEATURE_NO_TITLE);
mDecor = mWindow.getDecorView();
mDecor.setOnTouchListener(mTouchListener);
mWindow.setContentView(this);
mWindow.setBackgroundDrawableResource(android.R.color.transparent);
// While the media controller is up, the volume control keys should
// affect the media stream type
mWindow.setVolumeControlStream(AudioManager.STREAM_MUSIC);
setFocusable(true);
setFocusableInTouchMode(true);
setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
requestFocus();
}
private OnTouchListener mTouchListener = new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (mShowing) {
hide();
}
}
return false;
}
};
public void setMediaPlayer(MediaPlayerControl player) {
mPlayer = player;
updatePausePlay();
}
/**
* Set the view that acts as the anchor for the control view.
* This can for example be a VideoView, or your Activity's main view.
* #param view The view to which to anchor the controller when it is visible.
*/
public void setAnchorView(View view) {
mAnchor = view;
FrameLayout.LayoutParams frameParams = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT
);
removeAllViews();
View v = makeControllerView();
addView(v, frameParams);
}
/**
* Create the view that holds the widgets that control playback.
* Derived classes can override this to create their own.
* #return The controller view.
* #hide This doesn't work as advertised
*/
protected View makeControllerView() {
LayoutInflater inflate = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mRoot = inflate.inflate(R.layout.media_controller, null);
initControllerView(mRoot);
return mRoot;
}
private void initControllerView(View v) {
mPauseButton = (ImageButton) v.findViewById(R.id.pause);
if (mPauseButton != null) {
mPauseButton.requestFocus();
mPauseButton.setOnClickListener(mPauseListener);
}
mFfwdButton = (ImageButton) v.findViewById(R.id.ffwd);
if (mFfwdButton != null) {
mFfwdButton.setOnClickListener(mFfwdListener);
if (!mFromXml) {
mFfwdButton.setVisibility(mUseFastForward ? View.VISIBLE : View.GONE);
}
}
mRewButton = (ImageButton) v.findViewById(R.id.rew);
if (mRewButton != null) {
mRewButton.setOnClickListener(mRewListener);
if (!mFromXml) {
mRewButton.setVisibility(mUseFastForward ? View.VISIBLE : View.GONE);
}
}
// By default these are hidden. They will be enabled when setPrevNextListeners() is called
mNextButton = (ImageButton) v.findViewById(R.id.next);
if (mNextButton != null && !mFromXml && !mListenersSet) {
mNextButton.setVisibility(View.GONE);
}
mPrevButton = (ImageButton) v.findViewById(R.id.prev);
if (mPrevButton != null && !mFromXml && !mListenersSet) {
mPrevButton.setVisibility(View.GONE);
}
mProgress = (ProgressBar) v.findViewById(R.id.mediacontroller_progress);
if (mProgress != null) {
if (mProgress instanceof SeekBar) {
SeekBar seeker = (SeekBar) mProgress;
seeker.setOnSeekBarChangeListener(mSeekListener);
}
mProgress.setMax(1000);
}
mEndTime = (TextView) v.findViewById(R.id.time);
mCurrentTime = (TextView) v.findViewById(R.id.time_current);
mFormatBuilder = new StringBuilder();
mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
installPrevNextListeners();
}
/**
* Show the controller on screen. It will go away
* automatically after 3 seconds of inactivity.
*/
public void show() {
show(sDefaultTimeout);
}
/**
* Show the controller on screen. It will go away
* automatically after 'timeout' milliseconds of inactivity.
* #param timeout The timeout in milliseconds. Use 0 to show
* the controller until hide() is called.
*/
public void show(int timeout) {
if (!mShowing && mAnchor != null) {
setProgress();
int [] anchorpos = new int[2];
mAnchor.getLocationOnScreen(anchorpos);
WindowManager.LayoutParams p = new WindowManager.LayoutParams();
p.gravity = Gravity.TOP;
p.width = mAnchor.getWidth();
p.height = LayoutParams.WRAP_CONTENT;
p.x = 0;
p.y = anchorpos[1] + mAnchor.getHeight() - p.height;
p.format = PixelFormat.TRANSLUCENT;
p.type = WindowManager.LayoutParams.TYPE_APPLICATION_PANEL;
p.flags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
p.token = null;
p.windowAnimations = 0; // android.R.style.DropDownAnimationDown;
mWindowManager.addView(mDecor, p);
mShowing = true;
}
updatePausePlay();
// cause the progress bar to be updated even if mShowing
// was already true. This happens, for example, if we're
// paused with the progress bar showing the user hits play.
mHandler.sendEmptyMessage(SHOW_PROGRESS);
Message msg = mHandler.obtainMessage(FADE_OUT);
if (timeout != 0) {
mHandler.removeMessages(FADE_OUT);
mHandler.sendMessageDelayed(msg, timeout);
}
}
public boolean isShowing() {
return mShowing;
}
/**
* Remove the controller from the screen.
*/
public void hide() {
if (mAnchor == null)
return;
if (mShowing) {
try {
mHandler.removeMessages(SHOW_PROGRESS);
mWindowManager.removeView(mDecor);
} catch (IllegalArgumentException ex) {
Log.w("MediaController", "already removed");
}
mShowing = false;
}
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
int pos;
switch (msg.what) {
case FADE_OUT:
hide();
break;
case SHOW_PROGRESS:
pos = setProgress();
if (!mDragging && mShowing && mPlayer.isPlaying()) {
msg = obtainMessage(SHOW_PROGRESS);
sendMessageDelayed(msg, 1000 - (pos % 1000));
}
break;
}
}
};
private String stringForTime(int timeMs) {
int totalSeconds = timeMs / 1000;
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
mFormatBuilder.setLength(0);
if (hours > 0) {
return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
} else {
return mFormatter.format("%02d:%02d", minutes, seconds).toString();
}
}
private int setProgress() {
if (mPlayer == null || mDragging) {
return 0;
}
int position = mPlayer.getCurrentPosition();
int duration = mPlayer.getDuration();
if (mProgress != null) {
if (duration > 0) {
// use long to avoid overflow
long pos = 1000L * position / duration;
mProgress.setProgress( (int) pos);
}
int percent = mPlayer.getBufferPercentage();
mProgress.setSecondaryProgress(percent * 10);
}
if (mEndTime != null)
mEndTime.setText(stringForTime(duration));
if (mCurrentTime != null)
mCurrentTime.setText(stringForTime(position));
return position;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
show(sDefaultTimeout);
return true;
}
#Override
public boolean onTrackballEvent(MotionEvent ev) {
show(sDefaultTimeout);
return false;
}
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
int keyCode = event.getKeyCode();
if (event.getRepeatCount() == 0 && event.isLongPress() && (
keyCode == KeyEvent.KEYCODE_HEADSETHOOK ||
keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE ||
keyCode == KeyEvent.KEYCODE_SPACE)) {
doPauseResume();
show(sDefaultTimeout);
return true;
} else if (keyCode == KeyEvent.KEYCODE_MEDIA_STOP) {
if (mPlayer.isPlaying()) {
mPlayer.pause();
updatePausePlay();
}
return true;
} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN ||
keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
// don't show the controls for volume adjustment
return super.dispatchKeyEvent(event);
} else if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_MENU) {
hide();
return true;
} else {
show(sDefaultTimeout);
}
return super.dispatchKeyEvent(event);
}
private View.OnClickListener mPauseListener = new View.OnClickListener() {
public void onClick(View v) {
doPauseResume();
show(sDefaultTimeout);
}
};
private void updatePausePlay() {
if (mRoot == null)
return;
ImageButton button = (ImageButton) mRoot.findViewById(R.id.pause);
if (button == null)
return;
if (mPlayer.isPlaying()) {
button.setImageResource(android.R.drawable.ic_media_pause);
} else {
button.setImageResource(android.R.drawable.ic_media_play);
}
}
private void doPauseResume() {
if (mPlayer.isPlaying()) {
mPlayer.pause();
} else {
mPlayer.start();
}
updatePausePlay();
}
private OnSeekBarChangeListener mSeekListener = new OnSeekBarChangeListener() {
long duration;
public void onStartTrackingTouch(SeekBar bar) {
show(3600000);
duration = mPlayer.getDuration();
}
public void onProgressChanged(SeekBar bar, int progress, boolean fromtouch) {
if (fromtouch) {
mDragging = true;
duration = mPlayer.getDuration();
long newposition = (duration * progress) / 1000L;
mPlayer.seekTo( (int) newposition);
if (mCurrentTime != null)
mCurrentTime.setText(stringForTime( (int) newposition));
}
}
public void onStopTrackingTouch(SeekBar bar) {
mDragging = false;
setProgress();
updatePausePlay();
show(sDefaultTimeout);
}
};
#Override
public void setEnabled(boolean enabled) {
if (mPauseButton != null) {
mPauseButton.setEnabled(enabled);
}
if (mFfwdButton != null) {
mFfwdButton.setEnabled(enabled);
}
if (mRewButton != null) {
mRewButton.setEnabled(enabled);
}
if (mNextButton != null) {
mNextButton.setEnabled(enabled && mNextListener != null);
}
if (mPrevButton != null) {
mPrevButton.setEnabled(enabled && mPrevListener != null);
}
if (mProgress != null) {
mProgress.setEnabled(enabled);
}
super.setEnabled(enabled);
}
private View.OnClickListener mRewListener = new View.OnClickListener() {
public void onClick(View v) {
int pos = mPlayer.getCurrentPosition();
pos -= 5000; // milliseconds
mPlayer.seekTo(pos);
setProgress();
show(sDefaultTimeout);
}
};
private View.OnClickListener mFfwdListener = new View.OnClickListener() {
public void onClick(View v) {
int pos = mPlayer.getCurrentPosition();
pos += 15000; // milliseconds
mPlayer.seekTo(pos);
setProgress();
show(sDefaultTimeout);
}
};
private void installPrevNextListeners() {
if (mNextButton != null) {
mNextButton.setOnClickListener(mNextListener);
mNextButton.setEnabled(mNextListener != null);
}
if (mPrevButton != null) {
mPrevButton.setOnClickListener(mPrevListener);
mPrevButton.setEnabled(mPrevListener != null);
}
}
public void setPrevNextListeners(View.OnClickListener next, View.OnClickListener prev) {
mNextListener = next;
mPrevListener = prev;
mListenersSet = true;
if (mRoot != null) {
installPrevNextListeners();
if (mNextButton != null && !mFromXml) {
mNextButton.setVisibility(View.VISIBLE);
}
if (mPrevButton != null && !mFromXml) {
mPrevButton.setVisibility(View.VISIBLE);
}
}
}
public interface MediaPlayerControl {
void start();
void pause();
int getDuration();
int getCurrentPosition();
void seekTo(int pos);
boolean isPlaying();
int getBufferPercentage();
};
}
and I am getting error at "Policy manager" at initfloatwindow method and I have imported import com.android.internal.policy.PolicyManager
private void initFloatingWindow() {
mWindowManager = (WindowManager)mContext.getSystemService("window");
mWindow = PolicyManager.makeNewWindow(mContext);//I got error here
mWindow.setWindowManager(mWindowManager, null, null);
mWindow.requestFeature(Window.FEATURE_NO_TITLE);
mDecor = mWindow.getDecorView();
mDecor.setOnTouchListener(mTouchListener);
mWindow.setContentView(this);
mWindow.setBackgroundDrawableResource(android.R.color.transparent);
// While the media controller is up, the volume control keys should
// affect the media stream type
mWindow.setVolumeControlStream(AudioManager.STREAM_MUSIC);
setFocusable(true);
setFocusableInTouchMode(true);
setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
requestFocus();
}
Please anyone can help me please.Thanks in advance
PolicyManager is an internal class, not in puplic API so you cannot use it.

SWT StyledText - How To Indent/Un-Indent Selected Text With Tab Or Shift+Tab Keys

Using the Eclipse SWT StyledText widget, how can you indent/un-indent a selected block of text with the tab or shift+tab keys?
This seems to do the trick...
protected Control createContents(Composite parent){
......
//add the listeners...
text_code_impl.addVerifyKeyListener(new VerifyKeyListener() {
public void verifyKey(VerifyEvent e) {
if (e.keyCode == SWT.TAB) {
if ((e.stateMask & SWT.SHIFT) != 0){
e.doit = text_code_impl_shift_tab_pressed();
} else {
e.doit = text_code_impl_tab_pressed();
}
}
}
});
text_code_impl.addTraverseListener(new TraverseListener() {
public void keyTraversed(TraverseEvent e) {
if (e.detail == SWT.TRAVERSE_TAB_PREVIOUS) {
e.doit = false; //allows verifyKey listener to fire
}
}
});
}
boolean text_code_impl_tab_pressed()
{
if (text_code_impl.getSelectionText().equals("")){
return true;
}
Point range = text_code_impl.getSelectionRange();
int start = range.x;
int length = text_code_impl.getSelectionCount();
String txt = text_code_impl.getText();
while (start > 0 && txt.charAt(start-1) != '\n') {
start--;
length++;
}
int replace_length = length;
text_code_impl.setSelectionRange(start, length);
text_code_impl.showSelection();
String sel_text = text_code_impl.getSelectionText();
String[] lines = sel_text.split("\n");
String new_text = "";
for (int x=0; x < lines.length; x++){
if (x > 0){
new_text += '\n';
}
new_text += '\t';
length++;
new_text += lines[x];
}
text_code_impl.replaceTextRange(start, replace_length, new_text);
text_code_impl.setSelectionRange(start, length);
text_code_impl.showSelection();
return false;
}
boolean text_code_impl_shift_tab_pressed()
{
if (text_code_impl.getSelectionText().equals("")){
return true;
}
Point range = text_code_impl.getSelectionRange();
int start = range.x;
int length = text_code_impl.getSelectionCount();
String txt = text_code_impl.getText();
while (start > 0 && txt.charAt(start-1) != '\n') {
--start;
++length;
}
int replace_length = length;
text_code_impl.setSelectionRange(start, length);
text_code_impl.showSelection();
String sel_text = text_code_impl.getSelectionText();
String[] lines = sel_text.split("\n");
String new_text = "";
for (int x=0; x < lines.length; x++){
if (x > 0){
new_text += '\n';
}
if (lines[x].charAt(0) == '\t'){
new_text += lines[x].substring(1);
length--;
} else if (lines[x].startsWith(" ")){
new_text += lines[x].substring(1);
length--;
} else {
new_text += lines[x];
}
}
text_code_impl.replaceTextRange(start, replace_length, new_text);
text_code_impl.setSelectionRange(start, length);
text_code_impl.showSelection();
return false;
}