Showing posts with label view. Show all posts
Showing posts with label view. Show all posts

Saturday, October 6, 2018

Xcode iOS Notability “zoom box”

Leave a Comment

Notability and other note taking apps have this 'zoom box' feature where you can draw in the magnified box at the bottom. Users can also drag the box at the top to change what they want magnified at the bottom. I have tried literally everything I can think of to add this feature in my app. I have added the same document in two views but then I run into many memory issues, I've duplicated the file but again memory issues. Does anyone know a simple way to do this? Is there anyway I can just have a view that is a magnification of another view?

enter image description here

1 Answers

Answers 1

Create a new Cocoa Touch Class (optionally name it MagnifyView) and set it as a subclass of UIView Add the following code in your class:

var viewToMagnify: UIView! var touchPoint: CGPoint!  override init(frame: CGRect) {     super.init(frame: frame)     commonInit() }  required init?(coder aDecoder: NSCoder) {     super.init(coder: aDecoder)     commonInit() }  func commonInit() {     // Set border color, border width and corner radius of the magnify view     self.layer.borderColor = UIColor.lightGray.cgColor     self.layer.borderWidth = 3     self.layer.cornerRadius = 50     self.layer.masksToBounds = true }  func setTouchPoint(pt: CGPoint) {     touchPoint = pt     self.center = CGPoint(x: pt.x, y: pt.y - 100) }  override func draw(_ rect: CGRect) {     let context = UIGraphicsGetCurrentContext()     context!.translateBy(x: 1 * (self.frame.size.width * 0.5), y: 1 * (self.frame.size.height * 0.5))     context!.scaleBy(x: 1.5, y: 1.5) // 1.5 is the zoom scale     context!.translateBy(x: -1 * (touchPoint.x), y: -1 * (touchPoint.y))     self.viewToMagnify.layer.render(in: context!) } 

To use it, implement touchesBegan, touchesMoved and touchesEnd functions in View Controller which you want to have the magnifying effect.

Here is how:

override func touchesBegan(_ touches: Set, with event: UIEvent?) {     let point = touches.first?.location(in: self.view)     if magnifyView == nil     {         magnifyView = MagnifyView.init(frame: CGRect(x: 0, y: 0, width: 100, height: 100))         magnifyView.viewToMagnify = self.view         magnifyView.setTouchPoint(pt: point!)         self.view.addSubview(magnifyView)     } }  override func touchesEnded(_ touches: Set, with event: UIEvent?) {     if magnifyView != nil     {         magnifyView.removeFromSuperview()         magnifyView = nil     } }  override func touchesMoved(_ touches: Set, with event: UIEvent?) {     let point = touches.first?.location(in: self.view)     magnifyView.setTouchPoint(pt: point!)     magnifyView.setNeedsDisplay() } 

original source here

Read More

Tuesday, December 5, 2017

passing value from activity to view class

Leave a Comment

EDIT - I don't necessarily want to use the exact same code. All I want is to change paint color when a checkbox is selected to be able to draw on an image view. Any other approach is welcome.

I did go through related questions but couldn't get the answer. Please help instead of down-voting. I have an activity in which there are 3 checkboxes in different views. These checkboxes are to pick up a color. In the DrawingView class, I have to draw on my canvas with the color that is checked. What I want is to pass an integer value from the activity to the view class and set the color of paint accordingly. itried using getter and setters, but I get black color. I suppose this is because the color is being set in the constructor itself, and it does not change when I check any box.

Edit- Please refer this for updates in the below code

Code: MainActivity- the color/checkbox is selected here. And the drawing is to be done in the layout of this activity itself.

        carImageView.setOnTouchListener(new View.OnTouchListener() {         @Override         public boolean onTouch(View view, MotionEvent motionEvent) {             drawingView=new DrawingView(carImageView.getContext());             drawingView=new DrawingView(carImageView.getContext(),null);             drawingView.setColor(color);             return false;         }     });     scratchesCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {       @Override       public void onCheckedChanged(CompoundButton compoundButton, boolean b) {           if(b)           {               color=1;               chipsCb.setChecked(false);               dentsCb.setChecked(false);           }       }   });     chipsCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {         @Override         public void onCheckedChanged(CompoundButton compoundButton, boolean b) {             if(b)             {                 color=2;                 scratchesCb.setChecked(false);                 dentsCb.setChecked(false);             }         }     });     dentsCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {         @Override         public void onCheckedChanged(CompoundButton compoundButton, boolean b) {             if(b)             {                 color=3;                 chipsCb.setChecked(false);                 scratchesCb.setChecked(false);             }         }     }); } 

View Class-

   public DrawingView(Context context, @Nullable AttributeSet attrs) {    super(context, attrs);     mPaint=new Paint();     if(color==1)         mPaint.setColor(Color.RED);     else if(color==2)         mPaint.setColor(Color.BLUE);     else if(color==3)         mPaint.setColor(Color.GREEN);     this.context=context;     mPath=new Path();     mPaint.setAntiAlias(true);     mPaint.setStyle(Paint.Style.STROKE);     mPaint.setStrokeJoin(Paint.Join.MITER);     mPaint.setStrokeWidth(5f); }      public void setColor(int color){     this.color=color; } public int getColor(){     return this.color; } 

5 Answers

Answers 1

In the MainActivity, you are creating a DrawingView that has no relationship to your image view that is displayed. So, when you change the color, you are not changing the color of the displayed image view but of the unconnected DrawingView. The image view never has a new color defined and always defaults to black.

Here is a video of a small working app based upon your most recently supplied code. Maybe all the colors shouldn't change when a new check box is clicked, but you will be able to address that issue separately.

Changes I have made to the Java code are commented as such. Changes were also made to the XML to allow your code to run in my environment, but those changes were not commented.

enter image description here

MainActivity.java (Updated)

public class MainActivity extends AppCompatActivity {     ImageView caricon;     int itemSelected = 0;     private DrawingView carImageView;     Bitmap bitmap;     ImageView backarrow;     TextView nextcheckinAB2;     Bitmap bmp;     public static int color;     CheckBox scratchesCb, chipsCb, dentsCb;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         carImageView = (DrawingView) findViewById(R.id.carImageView);         scratchesCb = (CheckBox) findViewById(R.id.scratchesCheckBox);         chipsCb = (CheckBox) findViewById(R.id.ChipCheckbx);         dentsCb = (CheckBox) findViewById(R.id.DentsCheckBox);          // Change: Make sure to initialize the color         color = 1;         carImageView.setColor(color);          carImageView.setOnTouchListener(new View.OnTouchListener() {             @Override             public boolean onTouch(View view, MotionEvent motionEvent) {                 // drawingView = new DrawingView(carImageView.getContext(),null);                 carImageView.setColor(color);                 return false;             }         });           scratchesCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {             @Override             public void onCheckedChanged(CompoundButton compoundButton, boolean b) {                 if (b) {                     color = 1;                     carImageView.clearCanvas();                     carImageView.setColor(1); //                     chipsCb.setChecked(false);                     dentsCb.setChecked(false);                 }             }         });         chipsCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {             @Override             public void onCheckedChanged(CompoundButton compoundButton, boolean b) {                 if (b) {                     color = 2;                     carImageView.setColor(2);                     scratchesCb.setChecked(false);                     dentsCb.setChecked(false);                  }             }         });         dentsCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {             @Override             public void onCheckedChanged(CompoundButton compoundButton, boolean b) {                 if (b) {                     color = 3;                     // Change: Do like the other check boxes althogh not really needed.                     carImageView.setColor(3);                     chipsCb.setChecked(false);                     scratchesCb.setChecked(false);                  }             }         });     } } 

DrawingView.java (Updated)

public class DrawingView extends android.support.v7.widget.AppCompatImageView {     private Path mPath;     private Paint mPaint;     private float mX, mY;     private static final float TOLERANCE = 5;     int color;     Context context;      public DrawingView(Context context) {         super(context);         this.context = context;         init();     }      public DrawingView(Context context, @Nullable AttributeSet attrs) {         super(context, attrs);         this.context = context;         init();       }      public void init() {         mPath = new Path();         mPaint = new Paint();         mPaint.setStyle(Paint.Style.STROKE);         mPaint.setStrokeJoin(Paint.Join.MITER);         mPaint.setStrokeWidth(5f);     }      @Override     protected void onSizeChanged(int w, int h, int oldw, int oldh) {         super.onSizeChanged(w, h, oldw, oldh);     }      @Override     protected void onDraw(Canvas canvas) {         super.onDraw(canvas);         canvas.drawPath(mPath, mPaint);     }      public void setColor(int color) {         if (color == 1) {             mPaint.setColor(Color.RED);             this.color = color;             invalidate();         } else if (color == 2) {             mPaint.setColor(Color.BLUE);             this.color = color;             invalidate();         } else if (color == 3) {             mPaint.setColor(Color.GREEN);             this.color = color;             invalidate();         }      }      public int getColor() {         return this.color;     }      private void onStartTouch(float x, float y) {         mPath.moveTo(x, y);         mX = x;         mY = y;     }      private void moveTouch(float x, float y) {         float dx = Math.abs(x - mX);         float dy = Math.abs(y - mY);         if (dx >= TOLERANCE || dy >= TOLERANCE) {             mPath.quadTo(mX, mY, (mX + x) / 2, (mY + y) / 2);             mX = x;             mY = y;         }     }      public void clearCanvas() {         mPath.reset();         mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));         invalidate();     }      private void upTouch() {         mPath.lineTo(mX, mY);     }      @Override     public boolean onTouchEvent(MotionEvent event) {         float x = event.getX();         float y = event.getY();         switch (event.getAction()) {             case MotionEvent.ACTION_DOWN:                 onStartTouch(x, y);                 invalidate();                 break;             case MotionEvent.ACTION_MOVE:                 moveTouch(x, y);                 invalidate();                 break;             case MotionEvent.ACTION_UP:                 upTouch();                 invalidate();                 break;         }          return true;      } } 

activity_main.xml (Updated)

    <LinearLayout         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_marginLeft="5dp"         android:layout_marginRight="5dp"         android:orientation="horizontal"         android:weightSum="3">          <HorizontalScrollView             android:id="@+id/horizontalSrollView"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:layout_weight="1">              <LinearLayout                 android:layout_width="wrap_content"                 android:layout_height="wrap_content"                 android:orientation="horizontal">                  <RelativeLayout                     android:layout_width="wrap_content"                     android:layout_height="wrap_content"                     android:layout_marginLeft="5dp"                     android:layout_weight="1">                      <LinearLayout                         android:layout_width="wrap_content"                         android:layout_height="wrap_content"                         android:layout_marginTop="5dp"                          android:orientation="vertical">                          <LinearLayout                             android:layout_width="wrap_content"                             android:layout_height="wrap_content"                             android:orientation="horizontal"                             android:paddingLeft="15dp"                             android:paddingRight="15dp"                             android:paddingTop="5dp"                             android:weightSum="2">                              <ImageView                                 android:layout_width="20dp"                                 android:layout_height="20dp"                                 android:layout_marginRight="2dp"                                 android:layout_weight="0.5"                                 android:background="@android:color/holo_red_light" />                              <TextView                                 android:layout_width="wrap_content"                                 android:layout_height="wrap_content"                                 android:layout_marginLeft="2dp"                                 android:layout_weight="1.5"                                 android:text="Scratches"                                 android:textColor="#000" />                         </LinearLayout>                          <CheckBox                             android:id="@+id/scratchesCheckBox"                             android:layout_width="wrap_content"                             android:layout_height="wrap_content"                             android:layout_gravity="center"                             android:checked="true" />                     </LinearLayout>                  </RelativeLayout>                  <RelativeLayout                     android:layout_width="wrap_content"                     android:layout_height="wrap_content"                     android:layout_weight="1">                      <LinearLayout                         android:layout_width="wrap_content"                         android:layout_height="wrap_content"                         android:layout_marginTop="5dp"                         android:orientation="vertical">                          <LinearLayout                             android:layout_width="wrap_content"                             android:layout_height="wrap_content"                             android:orientation="horizontal"                             android:paddingLeft="15dp"                             android:paddingRight="15dp"                             android:paddingTop="5dp"                             android:weightSum="2">                              <ImageView                                 android:layout_width="20dp"                                 android:layout_height="20dp"                                 android:layout_marginRight="2dp"                                 android:layout_weight="0.5"                                 android:background="@android:color/holo_blue_light" />                              <TextView                                 android:layout_width="wrap_content"                                 android:layout_height="wrap_content"                                 android:layout_marginLeft="2dp"                                 android:layout_weight="1.5"                                 android:text="Chips"                                 android:textColor="#000" />                         </LinearLayout>                          <CheckBox                             android:id="@+id/ChipCheckbx"                             android:layout_width="wrap_content"                             android:layout_height="wrap_content"                             android:layout_gravity="center" />                     </LinearLayout>                  </RelativeLayout>                  <RelativeLayout                     android:layout_width="wrap_content"                     android:layout_height="wrap_content"                     android:layout_weight="1">                      <LinearLayout                         android:layout_width="wrap_content"                         android:layout_height="wrap_content"                         android:layout_marginTop="5dp"                         android:orientation="vertical">                          <LinearLayout                             android:layout_width="wrap_content"                             android:layout_height="wrap_content"                             android:orientation="horizontal"                             android:paddingLeft="15dp"                             android:paddingRight="15dp"                             android:paddingTop="5dp"                             android:weightSum="2">                              <ImageView                                 android:layout_width="20dp"                                 android:layout_height="20dp"                                 android:layout_marginRight="2dp"                                 android:layout_weight="0.5"                                 android:background="@android:color/holo_green_light" />                              <TextView                                 android:layout_width="wrap_content"                                 android:layout_height="wrap_content"                                 android:layout_marginLeft="2dp"                                 android:layout_weight="1.5"                                 android:text="Dings/Dents"                                 android:textColor="#000" />                         </LinearLayout>                          <CheckBox                             android:id="@+id/DentsCheckBox"                             android:layout_width="wrap_content"                             android:layout_height="wrap_content"                             android:layout_gravity="center" />                     </LinearLayout>                  </RelativeLayout>             </LinearLayout>          </HorizontalScrollView>      </LinearLayout>      <LinearLayout         android:layout_width="match_parent"         android:layout_height="match_parent"         android:layout_weight="8.7">          <[your package name].DrawingView             android:id="@+id/carImageView"             android:layout_width="200dp"             android:layout_height="200dp"             android:src="@mipmap/ic_launcher"             android:layout_gravity="center_vertical" />         <!--<ImageView             android:id="@+id/carImageView"             android:layout_width="match_parent"             android:layout_height="match_parent"             android:layout_gravity="center_vertical"/>-->     </LinearLayout>   </LinearLayout> 

Answers 2

you need change function setColor.

1.change mPaint color.

2.add invalidate() for redraw view.

public void setColor(int color){     this.color=color;      mPaint.setColor(color);     invalidate(); } 

Answers 3

You need to call invalidate() on the View to make it update.

Try this,

final DrawingView drawingView = new DrawingView(carImageView.getContext());  carImageView.setOnTouchListener(new View.OnTouchListener() {     @Override     public boolean onTouch(View view, MotionEvent motionEvent) {         drawingView.setColor(color);         return false;     } });   scratchesCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {   @Override   public void onCheckedChanged(CompoundButton compoundButton, boolean b) {       if(b)       {           color = 1;           drawingView.setColor(color);            chipsCb.setChecked(false);           dentsCb.setChecked(false);       }   } });  chipsCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {     @Override     public void onCheckedChanged(CompoundButton compoundButton, boolean b) {         if(b)         {             color = 2;             drawingView.setColor(color);              scratchesCb.setChecked(false);             dentsCb.setChecked(false);         }     } });   dentsCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {     @Override     public void onCheckedChanged(CompoundButton compoundButton, boolean b) {         if(b)         {             color = 3;             drawingView.setColor(color);              chipsCb.setChecked(false);             scratchesCb.setChecked(false);         }     } }); 

DrawingView.java

public DrawingView(Context context) {     super(context);     this.context = context;     init(); }  public DrawingView(Context context, @Nullable AttributeSet attrs) {     super(context, attrs);     this.context=context;     init(); }  private void init() {     mPath=new Path();      mPaint = new Paint();     mPaint.setAntiAlias(true);     mPaint.setStyle(Paint.Style.STROKE);     mPaint.setStrokeJoin(Paint.Join.MITER);     mPaint.setStrokeWidth(5f);     setColor(color); }   public void setColor(int color){     this.color=color;     if(color==1)         mPaint.setColor(Color.RED);     else if(color==2)         mPaint.setColor(Color.BLUE);     else if(color==3)         mPaint.setColor(Color.GREEN);      // Call invalidate     invalidate(); } 

Answers 4

Define static data member in your DrawingView

static int color = 1; //default

Then, from your activity simply call

DrawingView.color = someValue;

Static Keyword before variable color will make sure there is only one variable reference for all objects of your DrawingView class.

Answers 5

"even if I pass a static value, say 3 in main activity in drawingview.setColor(int) it gives black. This means the setColor function in Drawingview isn't working. "

Does this mean it will call paint.setColor(3) ?

If yes, this will of course turn your color black. Try passing Color.GREEN instead

Read More

Sunday, November 19, 2017

Dragging a rotated view by adjusting layout params

Leave a Comment

I am trying to make a view follow my finger and do some rotation and scaling in multitouch with the following code

@Override public boolean onTouch(View view, MotionEvent motionEvent) {      final int action = motionEvent.getActionMasked();     int newPosX,newPosY;     switch (action) {         case MotionEvent.ACTION_DOWN: {             final int pointerIndex = motionEvent.getActionIndex();             final float x = motionEvent.getX( pointerIndex);             final float y = motionEvent.getY( pointerIndex);              RelativeLayout.LayoutParams parms = (RelativeLayout.LayoutParams) view.getLayoutParams();              // Remember where we started (for dragging)             mLastTouchX = (int) x;             mLastTouchY = (int) y;             // Save the ID of this pointer (for dragging)             mActivePointerId = motionEvent.getPointerId( 0);             break;         }          case MotionEvent.ACTION_MOVE: {             if(motionEvent.getPointerCount()==2){                 float newDist = spacing(motionEvent);                 float scale = newDist / oldDist * view.getScaleX();                 view.setScaleY(scale);                 view.setScaleX(scale);                  float newAngle = rotation(motionEvent);                 float a = newAngle - oldAngle;                 view.animate().rotationBy(a).setDuration(0).setInterpolator(new LinearInterpolator()).start();             }             // Find the index of the active pointer and fetch its position             final int pointerIndex =                     motionEvent.findPointerIndex( mActivePointerId);              final float x = motionEvent.getX( pointerIndex);             final float y = motionEvent.getY( pointerIndex);              // Calculate the distance moved             final float dx = x - mLastTouchX;             final float dy = y - mLastTouchY;             RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();              layoutParams.leftMargin += dx;             layoutParams.topMargin += dy;              view.setLayoutParams(layoutParams);              break;         }         case MotionEvent.ACTION_POINTER_DOWN:{             oldDist = spacing(motionEvent);             oldAngle = rotation(motionEvent);             break;         }          case MotionEvent.ACTION_UP: {             mActivePointerId = INVALID_POINTER_ID;             break;         }          case MotionEvent.ACTION_CANCEL: {             mActivePointerId = INVALID_POINTER_ID;             break;         }          case MotionEvent.ACTION_POINTER_UP: {              final int pointerIndex = motionEvent.getActionIndex();             final int pointerId = motionEvent.getPointerId( pointerIndex);              if (pointerId == mActivePointerId) {                 // This was our active pointer going up. Choose a new                 // active pointer and adjust accordingly.                 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;                 mLastTouchX = (int) motionEvent.getX( newPointerIndex);                 mLastTouchY = (int) motionEvent.getY( newPointerIndex);                 mActivePointerId = motionEvent.getPointerId( newPointerIndex);             }             break;         }     }     return true;  }     private float spacing(MotionEvent event) {     float x = event.getX(0) - event.getX(1);     float y = event.getY(0) - event.getY(1);     return (float) Math.sqrt(x * x + y * y); }  private float rotation(MotionEvent event) {     double delta_x = (event.getX(0) - event.getX(1));     double delta_y = (event.getY(0) - event.getY(1));     double radians = Math.atan2(delta_y, delta_x);     return (float) Math.toDegrees(radians); } 

Everything is working well until the view is rotated. When it is rotated above 90 degrees and we try to drag it it's jumping around the touch point. I think it has something to do with

layoutParams.leftMargin += dx; layoutParams.topMargin += dy;  setLayoutParams(layoutParams); 

I am working to make this work for last two days with no success.

NOTE: what I am trying to achieve is to make a view drag rotate and scale with 2 fingers(drag with single finger also) I followed the drag code from Google's documentation so as to make it not jump while switching fingers. I am using this to rotate view.animate().rotationBy(a).setDuration(0).setInterpolator(new LinearInterpolator()).start();

because when i use view.setRotate(),the view is vibrating.

EDIT 1: I removed

layoutParams.leftMargin += dx; layoutParams.topMargin += dy; 

and replaced it with:

//To get the moved distance of the finger(X and Y)  float diffX = motionEvent.getX(pointerIndex) - mLastTouchX;                     float diffY = motionEvent.getY(pointerIndex) - mLastTouchY;  //to get the distance from touch point and the top or left of the view                     final float dx = motionEvent.getRawX() - (motionEvent.getRawX()-motionEvent.getX());                     final float dy = motionEvent.getRawY() - (motionEvent.getRawY()-motionEvent.getY());                     RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();  //Settings appropriate value for the margin top and margin left.                      layoutParams.leftMargin = (int) ((( motionEvent.getRawX() )-dx )+ diffX );                     layoutParams.topMargin = (int) ((( motionEvent.getRawY() )-dy )+ diffY ); 

Now even after rotating the view is not moving around. but when i switch the active finger its jumping around from the actual position.

On ACTION_POINTER_UP i am doing this to change shift the active finger

case MotionEvent.ACTION_POINTER_UP: {                  final int pointerIndex = motionEvent.getActionIndex();                 final int pointerId = motionEvent.getPointerId( pointerIndex);                  if (pointerId == mActivePointerId) {                     // This was our active pointer going up. Choose a new                     // active pointer and adjust accordingly.                     final int newPointerIndex = pointerIndex == 0 ? 1 : 0;                     Log.d(TAG,"New pointer index :"+newPointerIndex);                     mLastTouchX = (int) motionEvent.getX( newPointerIndex);                     mLastTouchY = (int) motionEvent.getY( newPointerIndex);                     mActivePointerId = motionEvent.getPointerId( newPointerIndex);                 }                 break;             } 

0 Answers

Read More

Sunday, August 14, 2016

Optimizing SELECT query performance

Leave a Comment

I have a SELECT statement that runs really slow, it's holding back our night process.

The query is: (Please don't comment about the implicit join syntax, this is automatically generated by Informatica that runs this code) :

SELECT *   FROM STG_DIM_CRM_CASES,V_CRM_CASE_ID_EXISTS_IN_DWH,stg_scd_customers_key  WHERE STG_DIM_CRM_CASES.CRM_CASE_ID = V_CRM_CASE_ID_EXISTS_IN_DWH.CASE_ID(+)    AND STG_DIM_CRM_CASES.account_number = stg_scd_customers_key.account_number(+)    and STG_DIM_CRM_CASES.Case_Create_Date between  stg_scd_customers_key.start_date(+) and  stg_scd_customers_key.end_date(+) 

edit: The actual query selects only account_number,start_date,end_date and one other column which is not indexed.

Tables info :

STG_DIM_CRM_CASES

Index - (Account_Number,Case_Create_Date) size - 270k records. 

stg_scd_customers_key

Index - Account_Number,Start_Date,End_Date Partitioned - End_Date Size - 500 million records. 

V_CRM_CASE_ID_EXISTS_IN_DWH(View) -

select  t.case_id from crm_ps_rc_case t, dim_crm_cases x where t.case_id=x.crm_case_id; 

dim_crm_cases -

Indexed - (crm_case_id) Size - 100 million . 

crm_ps_rc_case -

Size - 270k records 

Edit - If it wasn't clear, the view returns 270k records .

The query without the join to stg_scd is taking seconds, looks like it is the part that causing the performance issues, the view runs in seconds too although it is being joined to a 100 Million records table. Right now the query is taking somewhere between 12 to 30 minutes, depends how busy our sources are.

Here is the EXECUTION PLAN :

6   |   0 | SELECT STATEMENT                |                             |  3278K|  1297M|   559K  (4)| 02:10:37 |       |       |        |      |            | 7   |   1 |  PX COORDINATOR                 |                             |       |       |            |          |       |       |        |      |            | 8   |   2 |   PX SEND QC (RANDOM)           | :TQ10003                    |  3278K|  1297M|   559K  (4)| 02:10:37 |       |       |  Q1,03 | P->S | QC (RAND)  | 9   |*  3 |    HASH JOIN OUTER              |                             |  3278K|  1297M|   559K  (4)| 02:10:37 |       |       |  Q1,03 | PCWP |            | 10  |   4 |     PX RECEIVE                  |                             | 29188 |    10M| 50662   (5)| 00:11:50 |       |       |  Q1,03 | PCWP |            | 11  |   5 |      PX SEND HASH               | :TQ10002                    | 29188 |    10M| 50662   (5)| 00:11:50 |       |       |  Q1,02 | P->P | HASH       | 12  |*  6 |       HASH JOIN RIGHT OUTER     |                             | 29188 |    10M| 50662   (5)| 00:11:50 |       |       |  Q1,02 | PCWP |            | 13  |   7 |        BUFFER SORT              |                             |       |       |            |          |       |       |  Q1,02 | PCWC |            | 14  |   8 |         PX RECEIVE              |                             | 29188 |   370K| 50575   (5)| 00:11:49 |       |       |  Q1,02 | PCWP |            | 15  |   9 |          PX SEND BROADCAST      | :TQ10000                    | 29188 |   370K| 50575   (5)| 00:11:49 |       |       |        | S->P | BROADCAST  | 16  |  10 |           VIEW                  | V_CRM_CASE_ID_EXISTS_IN_DWH | 29188 |   370K| 50575   (5)| 00:11:49 |       |       |        |      |            | 17  |* 11 |            HASH JOIN            |                             | 29188 |   399K| 50575   (5)| 00:11:49 |       |       |        |      |            | 18  |  12 |             TABLE ACCESS FULL   | CRM_PS_RC_CASE              | 29188 |   199K|   570   (1)| 00:00:08 |       |       |        |      |            | 19  |  13 |             INDEX FAST FULL SCAN| DIM_CRM_CASES$1PK           |   103M|   692M| 48894   (3)| 00:11:25 |       |       |        |      |            | 20  |  14 |        PX BLOCK ITERATOR        |                             | 29188 |    10M|    87   (2)| 00:00:02 |       |       |  Q1,02 | PCWC |            | 21  |  15 |         TABLE ACCESS FULL       | STG_DIM_CRM_CASES           | 29188 |    10M|    87   (2)| 00:00:02 |       |       |  Q1,02 | PCWP |            | 22  |  16 |     BUFFER SORT                 |                             |       |       |            |          |       |       |  Q1,03 | PCWC |            | 23  |  17 |      PX RECEIVE                 |                             |   515M|    14G|   507K  (3)| 01:58:28 |       |       |  Q1,03 | PCWP |            | 24  |  18 |       PX SEND HASH              | :TQ10001                    |   515M|    14G|   507K  (3)| 01:58:28 |       |       |        | S->P | HASH       | 25  |  19 |        PARTITION RANGE ALL      |                             |   515M|    14G|   507K  (3)| 01:58:28 |     1 |  2982 |        |      |            | 26  |  20 |         TABLE ACCESS FULL       | STG_SCD_CUSTOMERS_KEY       |   515M|    14G|   507K  (3)| 01:58:28 |     1 |  2982 |        |      |            | 27  ------------------------------------------------------------------------------------------------------------------------------------------------------------ 28    29  Predicate Information (identified by operation id): 30  --------------------------------------------------- 31    32     3 - access("STG_DIM_CRM_CASES"."ACCOUNT_NUMBER"="STG_SCD_CUSTOMERS_KEY"."ACCOUNT_NUMBER"(+)) 33         filter("STG_DIM_CRM_CASES"."CASE_CREATE_DATE">="STG_SCD_CUSTOMERS_KEY"."START_DATE"(+) AND  34                "STG_DIM_CRM_CASES"."CASE_CREATE_DATE"<="STG_SCD_CUSTOMERS_KEY"."END_DATE"(+)) 35     6 - access("STG_DIM_CRM_CASES"."CRM_CASE_ID"="V_CRM_CASE_ID_EXISTS_IN_DWH"."CASE_ID"(+)) 36    11 - access("T"."CASE_ID"="X"."CRM_CASE_ID") 

Notes: Adding indexes may be an issue, depends on the index. This is not the only place this tables are being used, so indexes may interfere with other commands(Inserts mostly) on these tables.

I've also tried adding a filter on stg_scd and excluding all the dates smaller than the minimum date in Table_Cases, but that didn't help because it filtered only 1 year of records.

Thanks in advance.

6 Answers

Answers 1

THEORY: What I believe to be happening is the engine is having to resolve the 100m+ records from view join to 500m records BEFORE it applies limiting criteria (thus it creates a cross join and even if it can use indexes that's alot of records to generate then parse. So even though you wrote it as an outer join, the engine isn't able to processes it that way (I don't know why)

So at a minimum 100m*500m = 50,000m that's a lot of data to generate and then parse/limit.

By eliminating the view, the engine may be better able to optimize and use the indexes thus eliminating the need for the 50,000m record join.

Areas where I would focus my time in troubleshooting:

  • Eliminate the view just to remove it as a potential overhead issue.
  • Recognize no tie between stg_scd_customers_key and V_CRM_CASE_ID_EXISTS_IN_DWH exists. This means the engine may be doing a cross join BEFORE the results of STG_DIM_CRM_CASES to stg_scd_customers_key have been resolved.

CONSIDER eliminating the view, or using an inline view

Eliminating the view:

SELECT *   FROM STG_DIM_CRM_CASES        ,crm_ps_rc_case t       ,dim_crm_cases x        ,stg_scd_customers_key  WHERE t.case_id=x.crm_case_id    AND STG_DIM_CRM_CASES.CRM_CASE_ID = t.CASE_ID(+)    AND STG_DIM_CRM_CASES.account_number = stg_scd_customers_key.account_number(+)    AND STG_DIM_CRM_CASES.Case_Create_Date         between  stg_scd_customers_key.start_date(+) and stg_scd_customers_key.end_date(+) 

using an inline view:

SELECT *   FROM STG_DIM_CRM_CASES    (select  t.case_id    from crm_ps_rc_case t, dim_crm_cases x    where t.case_id=x.crm_case_id) V_CRM_CASE_ID_EXISTS_IN_DWH       ,stg_scd_customers_key  WHERE STG_DIM_CRM_CASES.CRM_CASE_ID = V_CRM_CASE_ID_EXISTS_IN_DWH.CASE_ID(+)    AND STG_DIM_CRM_CASES.account_number = stg_scd_customers_key.account_number(+)    AND STG_DIM_CRM_CASES.Case_Create_Date         between  stg_scd_customers_key.start_date(+) and stg_scd_customers_key.end_date(+) 

As to why: - http://www.dba-oracle.com/art_hints_views.htm

While order of the where clause SHOULDN'T matter consider: On the off chase the engine is executing in the order listed, limiting the 500m down and then adding the supplemental data from the view would logically be faster.

SELECT *   FROM STG_DIM_CRM_CASES,stg_scd_customers_key,V_CRM_CASE_ID_EXISTS_IN_DWH  WHERE STG_DIM_CRM_CASES.account_number = stg_scd_customers_key.account_number(+)    and STG_DIM_CRM_CASES.Case_Create_Date between  stg_scd_customers_key.start_date(+) and  stg_scd_customers_key.end_date(+)    and STG_DIM_CRM_CASES.CRM_CASE_ID = V_CRM_CASE_ID_EXISTS_IN_DWH.CASE_ID(+) 

Answers 2

Your problem is that Oracle really only has two ways to get the rows it needs from stg_scd_customers_key. Either (A) it does a single FULL SCAN of that table and then filters out the rows it doesn't want or else (B) it does 270,000 index lookups, at 3 to maybe 5 logical I/Os each (depending on the height of your index), plus another 1 logical I/O to actually read the block from the table.

Given the multiblock read and other optimizations available with a FULL SCAN, and based on your table statistics, Oracle's optimizer is guessing that the FULL SCAN would be faster. And there's a good chance that it's right.

What you need to do is give Oracle a better option.

If you cannot use materialized views where you are, a good "poor man's" materialized view is something called a covering index. Now, that's not reasonable for your query, since you do a SELECT *. But do you really need every column from stg_scd_customers_key?

If you can pare down the list of columns you get from stg_scd_customers_key, you can create an index that (A) starts with account_number, start_date, and end_date and (B) includes all the other columns you need to select.

For example:

SELECT stg_im_crm_cases.*, V_CRM_CASE_ID_EXISTS_IN_DWH.*, stg_scd_customers_key.column_1, stg_scd_customers_key.column_2   FROM STG_DIM_CRM_CASES,V_CRM_CASE_ID_EXISTS_IN_DWH,stg_scd_customers_key  WHERE STG_DIM_CRM_CASES.CRM_CASE_ID = V_CRM_CASE_ID_EXISTS_IN_DWH.CASE_ID(+)    AND STG_DIM_CRM_CASES.account_number = stg_scd_customers_key.account_number(+)    and STG_DIM_CRM_CASES.Case_Create_Date between  stg_scd_customers_key.start_date(+) and  stg_scd_customers_key.end_date(+) 

If you could make that your query, and create an index on stg_scd_customers_key (account_number, start_date, end_date, column_1, column_2), then you will have given Oracle a better alternative. Now it can read the index alone, instead of the table.

With tables that big, there are no guarantees until you try it. But covering indexes are often just what the doctor ordered. (All the usual caveats about new indexes apply of course).

Answers 3

some considerations:

1) INDEX
crm_ps_rc_case has no index on case_id this is a problem, you are joining 270k <-> 100m with HASH JOIN (not good)

2) SELECTED COLUMNS
the view V_CRM_CASE_ID_EXISTS_IN_DWH selects t.case_id but it should select x.crm_case_id instead, at least, until you do not resolve indexing of t.case_id. This will spread HASH JOIN over all your execution plan.. (not good)

3) BETWEEN
range joining/filtering is always a problem, especially on large tables but you could restrict the problem adding conditions on range. let me explain, try to add these conditions to your WHERE clause:

AND stg_scd_customers_key.end_date =  (        SELECT min(r.end_date)        FROM stg_scd_customers_key r        WHERE  r.end_date >= STG_DIM_CRM_CASES.Case_Create_Date ) AND stg_scd_customers_key.start_date =  (        SELECT max(r.start_date)        FROM stg_scd_customers_key r        WHERE  r.start_date <= STG_DIM_CRM_CASES.Case_Create_Date ) 

yes, it will calculate 270k * 2 subqueries, but the final join will work on much less recs limiting IO operations (it should be better)

4) INDEX COLUMN ORDER
there are conflicting reports if it does, or if it does not matter, but in my experience.. it does. It could be only a minor improvement but you can try to modify the index on stg_scd_customers_key inverting the order of Start_Date and End_Date, in my experience I have found it more efficient for range filtering to have the upper bound before the lower bound in the index.

Answers 4

The problem is in scanning all partitions:

18 | PX SEND HASH | :TQ10001 | 515M| 14G| 507K (3)| 01:58:28 | | | | S->P | HASH | 25 | 19 | PARTITION RANGE ALL |
| 515M| 14G| 507K (3)| 01:58:28 | 1 | 2982 | |
| | 26 | 20 | TABLE ACCESS FULL | STG_SCD_CUSTOMERS_KEY | 515M| 14G|

It happens because you are using left join to this table. Can you select 1 partition using bind variable? What is partition key? I don't see hint for parallel but according to you plan it uses parallel. Is there parallel degree on any object level? Can you remove parallel and post explain plan without parallel please?

Answers 5

I think the problem is the view, which I suspect is completely executing and returning all rows before conditions are being applied.

The overall effect of the view is to add the column CASE_ID that is not null if CRM_CASE_ID is found in it, null otherwise. I've replaced the view with two direct joins and a CASE expression. By replacing the convenience of the view with logic, you can join directly to each table in it and so avoid one level of join depth.

Try running this version of the query:

SELECT   a.*, b.*, c.*,   CASE WHEN t.case_id is not null and X.case_id is not null then t.case_id END CASE_ID FROM STG_DIM_CRM_CASES a LEFT JOIN crm_ps_rc_case t   ON t.case_id = a.CRM_CASE_ID LEFT JOIN dim_crm_cases x   ON x.crm_case_id = a.CRM_CASE_ID LEFT JOIN V_CRM_CASE_ID_EXISTS_IN_DWH b   ON a.CRM_CASE_ID = b.CASE_ID LEFT JOIN stg_scd_customers_key c   ON a.account_number = c.account_number  and a.Case_Create_Date between c.start_date and  stg_scd_customers_key.end_date 

If you replace a.*, b.*, c.* with only the exact columns you actually need, you'll get a speed up because there's simply less data to return. If you also put indexes on looked-up keys plus all the columns you actually select (a covering index), you will speed it up considerably, because index-only access can be used.

You should verify there are indexes in all joined-to columns as a minimum.

Answers 6

I would consider creating a materialized view (with refresh fast on demand) for the join between Table_cases and stg_scd. I assume much of the work in the join is on rows that don't change from day to day.

Read More

Thursday, April 14, 2016

Blank view when trying to add facebook login

Leave a Comment

I have followed this guide to implement facebook login and while importing the project from Github I've run into an issue. When I run the project from github it works fine however if I try to copy the code into my existing project I get a white view with no button.

The view:

<Page x:Class="IWork4You.LoginView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:IWork4You" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <Grid>     <WebView x:Name="RequestView" Visibility="Collapsed" Width="400" Height="800" NavigationCompleted="RequestView_OnNavigationCompleted"/>     <StackPanel Margin="0, 0, 0, 0" x:Name="AppContent">         <Button Content="Login" Click="OnLoginClicked" HorizontalAlignment="Center" VerticalAlignment="Center" />         <TextBlock x:Name="MyName" Style="{StaticResource SubheaderTextBlockStyle}" />         <Button Content="Invite friends" Click="OnInviteFriendsClicked" x:Name="InviteFriends" Visibility="Collapsed" />          <TextBlock Text="Invited friends" Style="{StaticResource HeaderTextBlockStyle}" x:Name="FriendsHeader" Visibility="Collapsed"/>         <ListView x:Name="Friends" Margin="0, 20, 0, 0" Visibility="Collapsed">             <ListView.ItemTemplate>                 <DataTemplate>                     <StackPanel>                         <TextBlock Text="{Binding Path=FullName}" Style="{StaticResource BodyTextBlockStyle}" />                     </StackPanel>                 </DataTemplate>             </ListView.ItemTemplate>         </ListView>     </StackPanel> </Grid> 

Code:

namespace IWork4You {     /// <summary>     /// An empty page that can be used on its own or navigated to within a Frame.     /// </summary>     public sealed partial class LoginView : Page     {         public string AccessToken;         public DateTime TokenExpiry;         public string ClientId = "xxx";      private async Task Login()     {         //Client ID of the Facebook App (retrieved from the Facebook Developers portal)         //Required permissions         var scope = "public_profile, email";          var redirectUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString();         var fb = new FacebookClient();         var loginUrl = fb.GetLoginUrl(new         {             client_id = ClientId,             redirect_uri = redirectUri,             response_type = "token",             scope = scope         });          Uri startUri = loginUrl;         Uri endUri = new Uri(redirectUri, UriKind.Absolute);           WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startUri, endUri);         await ParseAuthenticationResult(result);       }      public async Task ParseAuthenticationResult(WebAuthenticationResult result)     {         switch (result.ResponseStatus)         {             //connection error             case WebAuthenticationStatus.ErrorHttp:                 Debug.WriteLine("Connection error");                 break;             //authentication successfull             case WebAuthenticationStatus.Success:                 var pattern = string.Format("{0}#access_token={1}&expires_in={2}",                     WebAuthenticationBroker.GetCurrentApplicationCallbackUri(), "(?<access_token>.+)",                     "(?<expires_in>.+)");                 var match = Regex.Match(result.ResponseData, pattern);                  var access_token = match.Groups["access_token"];                 var expires_in = match.Groups["expires_in"];                  AccessToken = access_token.Value;                 TokenExpiry = DateTime.Now.AddSeconds(double.Parse(expires_in.Value));                  await ShowUserInfo();                  InviteFriends.Visibility = Visibility.Visible;                  break;             //operation aborted by the user             case WebAuthenticationStatus.UserCancel:                 Debug.WriteLine("Operation aborted");                 break;             default:                 break;         }      }      private async Task ShowUserInfo()     {         FacebookClient client = new FacebookClient(AccessToken);         dynamic user = await client.GetTaskAsync("me");         MyName.Text = string.Format("I'm {0}", user.name);     }      private async void OnLoginClicked(object sender, RoutedEventArgs e)     {         await Login();     }      private void OnInviteFriendsClicked(object sender, RoutedEventArgs e)     {         AppContent.Visibility = Visibility.Collapsed;         FacebookClient client = new FacebookClient(AccessToken);         dynamic parameters = new ExpandoObject();         parameters.app_id = ClientId;         parameters.message = "Invite your friends";         parameters.title = "Invite friends";         parameters.redirect_uri = "https://wp.qmatteoq.com/";          Uri dialogUrl = client.GetDialogUrl("apprequests", parameters);          RequestView.Visibility = Visibility.Visible;         RequestView.Navigate(dialogUrl);     }      private async void RequestView_OnNavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)     {         if (args.Uri.DnsSafeHost == "wp.qmatteoq.com")         {             sender.Visibility = Visibility.Collapsed;             AppContent.Visibility = Visibility.Visible;              FacebookClient client = new FacebookClient(AccessToken);             dynamic result = client.ParseDialogCallbackUrl(args.Uri);              if (result.error_code == null)             {                 var items = (IDictionary<string, object>)result;                  ObservableCollection<FacebookUser> invitedFriends = new ObservableCollection<FacebookUser>();                  foreach (KeyValuePair<string, object> value in items)                 {                     if (value.Key != "request")                     {                         string query = string.Format("/{0}", value.Value);                         dynamic user = await client.GetTaskAsync(query);                         FacebookUser facebookUser = new FacebookUser();                         facebookUser.FullName = user.name;                         invitedFriends.Add(facebookUser);                     }                 }                  Friends.Visibility = Visibility.Visible;                 FriendsHeader.Visibility = Visibility.Visible;                 Friends.ItemsSource = invitedFriends;             }             else             {                 MessageDialog dialog = new MessageDialog("The user has canceled the operation");                 await dialog.ShowAsync();             }         }     } } } 

I know I am doing something wrong here I just can't figure out what it is.

1 Answers

Answers 1

Maybe I'm missing it but you don't seem to be calling InitializeComponent() anywhere.

Something like

public LoginView() {    InitializeComponent(); } 
Read More