October 2009 - Posts

JQuery Plugin : edit Image FaceBook Style

After reading for 1 day about this, I've just finished making my first jquery plugin. it’s not so hard after all.

this will add a link when hover on image. like if you hover on your profile image on facebook. This Plugin meanwhile works on Div Only

changepicture

   1:  $.fn.editFaceBook = function(options) {
   2:      var opts = jQuery.extend({}, jQuery.fn.editFaceBook.defaults, options);
   3:      return this.each(function() {
   4:          //here is the div/image as 1 element
   5:          $currentdivorimage = jQuery(this);
   6:          $currentdivorimage.width(opts.width);
   7:          $currentdivorimage.css('position', 'relative');
   8:          $divouter = $('<div></div>').appendTo($currentdivorimage);
   9:          $divouter.bind('mouseout', opts.hideedit);
  10:          $divouter.bind('mouseover', opts.showedit);
  11:          var $link = $('<a></a>').appendTo($divouter)
  12:          .attr('href', opts.linkurl);
  13:          $('<img/>').addClass('profileimage')
  14:          .width(opts.width)
  15:          .height(opts.height)
  16:          .attr('src', opts.imgurl)
  17:          .appendTo($link);
  18:   
  19:          var $secondlink = $('<a class="edit_profilepicture hidden" title="Change Picture" href="#">Change Picture</a>')
  20:          .insertAfter($link)
  21:          .bind('mouseover', opts.showeditpencil)
  22:          .bind('mouseout', opts.hideeditpencil)
  23:          .attr('href', opts.linkediturl)
  24:          .bind('click', opts.editlinkclick)
  25:          ;
  26:         
  27:          
  28:   
  29:          $('<span></span').appendTo($secondlink)
  30:          .addClass('edit_profilepicture_icon')
  31:          .html('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
  32:          
  33:          //<span class="edit_profilepicture_icon">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
  34:      });
  35:  };
  36:   
  37:  jQuery.fn.editFaceBook.defaults = {
  38:      linkurl: 'www.dummy.com',
  39:      linkediturl : '/edit.aspx',
  40:      width: 250,
  41:      height: 327,
  42:      imgurl: 'images/upload/noAvatarPicL.jpg',
  43:      editlinkclick:function(){
  44:      },
  45:      showedit: function() {
  46:          $currentelement = jQuery(this);
  47:          $currentelement.find('.edit_profilepicture').removeClass('hidden');
  48:      },
  49:      hideedit: function() {
  50:          $currentelement = jQuery(this);
  51:          $currentelement.find('.edit_profilepicture').addClass('hidden');
  52:      },
  53:      showeditpencil: function() {
  54:      $currentelement = jQuery(this);
  55:          $currentelement.find('.edit_profilepicture_icon').css('background-position', 'right bottom').css('border', '0px')
  56:          },
  57:      hideeditpencil: function() {
  58:          $currentelement = jQuery(this);
  59:          $currentelement.find('.edit_profilepicture_icon').css('background-position', 'right top');
  60:      }
  61:  };

Include this CSS on your Page

.edit_profilepicture {
background:#FFFFFF none repeat scroll 0 0;
height:20px;
padding:5px 27px 0 6px;
position:absolute;
right:0;
top:0px;
}
.edit_profilepicture_icon {
background:transparent url(../images/penciledit.gif) no-repeat scroll right top;
height:18px;
position:relative;
position:absolute !important;
width:18px;
right:4px;
top:4px;
margin-top:0px;
text-decoration:none;
}
.whitepencil
{
 background-position:right bottom;
}
.hidden
{
    display:none; 
}

Include this Pencil Image on your folder

penciledit 

Let me brief the API:

$(‘selectors’).editFaceBook(option);

The option usage is {prop:value,prop:value,n:n}

The availabe options are:

  • linkurl    'the link of our image click url
  • linkediturl  'url for our changemypicture click'
  • width 'width of our image'
  • height ''height of our image'
  • imgurl "imageurl"
  • editlinkclick "function of when changemypicture clicked'
  • showedit 'function of displaying edit section'
  • hideedit 'function of hiding edit section’
  • showeditpencil 'function of showing white pencil'
  • hideeditpencil 'function of hiding white pencil'



Share this post: | | | |
Posted by cipto with 10 comment(s)
Filed under:

Detecting Session is about to expired ,Give warning and redirect if expired

Problem:

you use session on your page. and user could stay or idle away for quite time. and when he return session is expired and he click something that will throws error.

1. we need to detect if user idle

2. we need a server side to detect if session expired when he click links or take something from your ashx.

Solution 1:

So in order to achieve giving warning let’s say about 2 minutes before timeout. than you need to detect user idle or not via javascript.

i’ve found a usefull Plugin . and we can combine that with facebox to give a nice facebook alert.

Explanation:

On ASP world the session is maintain as long as there’s movement of user. if the user idle for a period of time n minutes then it will be recycled. this session timeout is set on your web.config tag session <session timeout =”10”/>

Solution 2:

There is a property that detect if ASP.Net Generates new session ID (which means the old one has been flushed)  : Session.IsNewSession then add check if cookies of asp.netsessionid is there . so to make sure it’s already timeout. put this function on your BasePage and ashx.

Here is the ascx that i built on.

   1:   <script type="text/javascript" src="../includes/js/Idle.js"></script>
   2:   <link href="../css/facebox.css" rel="stylesheet" type="text/css" />
   3:   <script src="../includes/js/facebox.js" type="text/javascript"></script>
   4:   
   5:  <script type="text/javascript">
   6:           function MySession() {
   7:               this.SessionTimeOut = 0,
   8:               this.RedirectTimeOutId=0,
   9:               this.IdleTimeOutId=0,
  10:               this.IsAlertShown=false
  11:           }
  12:           var session = new MySession();
  13:           session.SessionTimeOut = <%= SessionTimeOut %>;
  14:           setIdleTimeout(<%= TimeBeforeEndToPopUp %>);
  15:            
  16:           document.onIdle = function() {            
  17:               if(!session.IsAlertShown)
  18:               jQuery.facebox('Your Session Is About to Expired');
  19:               if(session.RedirectTimeOutId==0)
  20:               session.RedirectTimeOutId= setTimeout(RedirectToLogin,3*60*1000);             
  21:           }
  22:           function RedirectToLogin()
  23:           {
  24:              window.location='<%= RelativeLink.BuildAbsolute("logout") %>';
  25:           }
  26:              document.onBack = function(isIdle, isAway) {
  27:                  if(isIdle){
  28:                  clearTimeout(RedirectTimeOutId);
  29:                  jQuery(document).trigger('close.facebox');
  30:                  }
  31:              }
  32:          $(document).bind('reveal.facebox', function() {
  33:              session.IsAlertShown=true;
  34:          });    
  35:               $(document).bind('close.facebox', function() {
  36:              session.IsAlertShown=false;
  37:          });    
  38:      </script>

Code Behind File

   1:   protected void Page_Load(object sender, EventArgs e)
   2:      {
   3:          SessionTimeOut = Session.Timeout*60*1000;
   4:         //2 minutes before it ends
   5:          TimeBeforeEndToPopUp = SessionTimeOut - (2*60*1000);
   6:      }
   7:   
   8:      protected int SessionTimeOut { get; set; }
   9:   
  10:      protected int TimeBeforeEndToPopUp { get; set; }

 

So before 2 minutes session timeout it will show popup:

expired

after 2 minutes it will redirect to Logout.

Lastly you should put the session timeout checker on your base page, ashx or you could built your httpmodule for this function.

   1:          private void CheckSessionExpired()
   2:          {
   3:              if (Context.Session != null)
   4:              {
   5:                  //Tested and the IsNewSession is more advanced then simply checking if 
   6:                  // a cookie is present, it does take into account a session timeout, because 
   7:                  // I tested a timeout and it did show as a new session
   8:                  if (Session.IsNewSession)
   9:                  {
  10:                      // If it says it is a new session, but an existing cookie exists, then it must 
  11:                      // have timed out (can't use the cookie collection because even on first 
  12:                      // request it already contains the cookie (request and response
  13:                      // seem to share the collection)
  14:                      string szCookieHeader = Request.Headers["Cookie"];
  15:                      if ((null != szCookieHeader) && (szCookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
  16:                      {
  17:                          Response.Redirect(RelativeLink.BuildAbsolute("logout"));
  18:                          Response.End();
  19:                      }
  20:                  }
  21:              }
  22:   
  23:          }

*this comes from this Article

 

That’s it Enjoy

Share this post: | | | |
Posted by cipto with no comments

Create Image WaterMark on Video File or JPeg Thumbnail

If you want to create a text or image on the Video, use ffmpeg vhook feature. Vhook is a plugin to ffmpeg so if you find an unofficial build here, make sure to download the With VHook one because it’s not built in   .. or you can build by your own how to

but the vhook is deprecated or not supported in newest build they urge people to use the other one.

As for Making a Thumbnail  for video file you can use the ffmpeg command ‘vframes’

and then to add the logo/image on that thumbnail

Use GDI+

here is how:

  Image imgPhoto = CreateThumbnail("PATHTOYOURBIGIMAGE", Convert.ToInt32(ConverterConfiguration.ThumbnailWidth), Convert.ToInt32(ConverterConfiguration.ThumbnailHeight));
  int phWidth = imgPhoto.Width; int phHeight = imgPhoto.Height;

            Bitmap bmPhoto = new Bitmap(imgPhoto);
            bmPhoto.SetResolution(72, 72);
            Bitmap bmWatermark = new Bitmap(bmPhoto);
            bmWatermark.SetResolution(
                            imgPhoto.HorizontalResolution,
                                imgPhoto.VerticalResolution);

            Graphics grWatermark =
                 Graphics.FromImage(bmWatermark);

            Image imgWatermark = new Bitmap(Path.GetDirectoryName(Application.ExecutablePath)+@"\"+"YOURLOGO.png");
            int wmWidth = imgWatermark.Width;
            int wmHeight = imgWatermark.Height;

            Graphics grPhoto = Graphics.FromImage(bmPhoto);

            ImageAttributes imageAttributes =
                           new ImageAttributes();
//Uncomment For Effect
            //ColorMap colorMap = new ColorMap();

            //colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            //colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
            //ColorMap[] remapTable = { colorMap };

            //imageAttributes.SetRemapTable(remapTable,
            //                         ColorAdjustType.Bitmap);

            //float[][] colorMatrixElements = { 
            //   new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},
            //   new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},
            //   new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},
            //   new float[] {0.0f,  0.0f,  0.0f,  0.3f, 0.0f},
            //   new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}
            //};

            //ColorMatrix wmColorMatrix = new
            //                ColorMatrix(colorMatrixElements);

            //imageAttributes.SetColorMatrix(wmColorMatrix,
            //                       ColorMatrixFlag.Default,
            //                         ColorAdjustType.Bitmap);

            int xPosOfWm = ((phWidth - wmWidth) - 10);
            int yPosOfWm = (phHeight-wmHeight)-10;

            grWatermark.DrawImage(imgWatermark,
                new Rectangle(xPosOfWm, yPosOfWm, wmWidth,
                                                 wmHeight),
                0,
                0,
                wmWidth,
                wmHeight,
                GraphicsUnit.Pixel,
                imageAttributes);
            imgPhoto = bmWatermark;
            grPhoto.Dispose();
            grWatermark.Dispose();

            //watermark_final.jpg", 
            imgPhoto.Save("PATH OF YOUR PHSYSICAL"+"Name_small.jpg");
            imgPhoto.Dispose();
            imgWatermark.Dispose();
Share this post: | | | |
Posted by cipto with no comments

Create Poll with JQuery and Asp.Net

Recently i’ve got a Task to make a widget of Poll/Survey i found a very nice tutorial on Nettuts and i love the Animation Bar

Here is the link on  Php Version ,

But i modified it a little to suite my needs and My logic.

 

Create an ascx according to your needs.

and The main Brains is

 <div id='poll-container' >
<asp:Repeater ID="QuestionRepeater" runat="server" OnItemCreated="QuestionItemBound">
<HeaderTemplate>
<p><%= QuestionText %></p>
</HeaderTemplate>
<ItemTemplate>
<input type="radio" name="poll" value="<%# "opt" + (Eval("answerid")) %>" id="<%# "opt" + (Container.ItemIndex+1) %>" /><label for='<%# "opt" + (Container.ItemIndex+1) %>'>&nbsp;<%# Eval("answerText") %></label>
&nbsp;<asp:TextBox CssClass="txtEssay" ID="txtEssay" runat="server"></asp:TextBox>
<br />
</ItemTemplate>
<FooterTemplate>
<input type="button" value="Vote &rarr;" onclick="SubmitVote();return false;" />
</FooterTemplate>
</asp:Repeater>
</div>

 

Read From Cookies and if there is then display Vote Result, if Note then Display the question

HttpCookie cookiesvalue = Request.Cookies[CookieName];
//get survey from db
if(cookiesvalue==null)
{
//do something
}
else
{
 //get last from cookie 
//set the poll result
ReadFromCookie();
//dosomething
 string GenaratedTemplate = GetPollTemplate(Convert.ToInt32(SurveyID),

}
Do a for each generating the template of poll result.
GetPollTemplate
string header = "<div id='poll-results'><h3>Poll Results</h3><dl class='graph'>";
string template = "";
//get from db
foreach (GetPollResultResult resultResult in result.ToList())
{
double tempper=Convert.ToDouble(resultResult.votes)/Convert.ToDouble(totalvotes);
int Percentage = Convert.ToInt32(Math.Round(tempper*100));
//<dt class='bar-title'><%# Eval("answerText") %></dt>
template+="<dt class='bar-title'>"+resultResult.answerText+"</dt><dd class='bar-container'>";
template += "<div id='bar" + counter + "' style='width: " + Percentage.ToString() + "%;";
if (resultResult.answerID == Convert.ToInt64(answerid))
template += "background-color: rgb(0, 102, 204);'>";
else
template += "'>";
template += "&nbsp;</div><strong>" + Percentage + "%</strong></dd>";
counter++;
}
template +="</dl></div><div id='Result' style='clear: both'>Total Votes: "+totalvotes+
"</div>";
 
The Animation Heart is using jquery animate to animate the width of each bar
 function animateResults() {
//$("#poll-results div").each(function() {
$(".bar-container div").each(function() {
var percentage = $(this).next().text();
$(this).css({ width: "0%" }).animate({
width: percentage
}, 'slow');
});
}

 

The Submit vote is used to get the optionid and value

 function SubmitVote() {
//event.preventDefault();
$("#poll-container").fadeOut("slow", function() {
//$(this).empty();
//$("#poll-container").innerHTML="";
});
//get value
var id = $("input[@name='poll']:checked").attr("value");
var optionid = id;
id = id.replace("opt", '');
var txtanswer = $('.txtEssay');
var essayvalue = '';
if (txtanswer.length > 0) {
var radioid =txtanswer.attr("radioid");
//check if id equal option id
//if equal meaning the txt answer option id is selected
if (radioid == optionid) {
essayvalue = txtanswer.val();
}
}

//submit via ajax
$.post("../services/vote.ashx", { q: poll.QuestionID.toString(), a: id, s: poll.SurveyID.toString(), p: poll.CurrentQuestionIndex.toString(), tq: poll.TotalQuestions.toString(),e:essayvalue }, FinishedSubmitVote, "text");


}
 
    function FinishedSubmitVote(data) {
$("#poll-container").hide();
$("#pollresult-container").empty();
$("#pollresult-container").append(data).fadeIn("slow", function() {
animateResults();
});
 
We should use empty() to clear all childnodes.
then append poll results and call animate results.
that’s it.

 

Share this post: | | | |
Posted by cipto with no comments

page.resolveclientUrl The Controls collection cannot be modified because the control contains code blocks.

 If you use masterpage and then you want your js to be relative to the URL path you could use the <%= Page.ResolveClientUrl("~/js/myjs.js") %>

the problem is if you use head runat="server"

it will throws error  The Controls collection cannot be modified because the control contains code blocks "<%=   ...  >"

The solution for this is not to use the runtime '=' but to replace it with the binding '#'

then on the page load use the [YourHeadID].Databind();

 

Share this post: | | | |
Posted by cipto with no comments
Filed under: