This blog is subject the DISCLAIMER below.
Showing posts with label Tips. Show all posts
Showing posts with label Tips. Show all posts

Thursday, March 03, 2011

"Note in (Google) Reader" issue Fix

Probably you're familiar with the sharing button (at least on Firefox and Chrome) offered by Google reader to help you share stuff that don't have feeds. Today, for some reason I realized that mine wasn't working!

GReader

 

After tweeting about it, thanks to Flavio Gomes and @mtobis, I realized what went wrong. Seems like the JavaScript file used by the button was updated, without updating the button script accordingly.

 

To solve this, all you have to do is set _IS_MULTILOGIN_ENABLED a variable that's not defined (but used) in the script file in the button script. So add something like:

_IS_MULTILOGIN_ENABLED=true;


// or


_IS_MULTILOGIN_ENABLED=false;


// or better


_IS_MULTILOGIN_ENABLED=((typeof(_IS_MULTILOGIN_ENABLED)=="undefined")?false:_IS_MULTILOGIN_ENABLED);




 



at the beginning of the button script, just to set _IS_MULTILOGIN_ENABLED before it's accessed as "undefined" in the script.

.. more.

Monday, September 13, 2010

Do people in non-English-speaking countries code in English?

I was reading a question with the same name on Stack-Exchange Beta site for Non-programmer-related questions (aka Programmers) when I came across this answer posted by a (probably Ukrainian) developer named Igor.

Accompanied by an earlier attempt by a colleague at work to write an enum in Arabic, I tried to write this piece of code:

Strangely enough it compiled and even ran showing the expected output (10)!! Note, the order above of the 2nd & 3rd line is mingled due to RTL issues in Gist. Visual Studio will show it in the right order (or at least, a more readable order for me, copy it & past it in your IDE to know how it looks).

Off course, I’m pretty convinced that this isn’t the best practice you should follow, (check my answer to the same question). Yet, I find this really hilarious! As a matter of fact, I took the claim that it’s bad practice too much for granted to the extent that I’ve never even tired to write such a strange piece of code :D

.. more.

Wednesday, September 08, 2010

Does Google Instant really ruin SEO?

I was just reading an article I found on twitter about how Google Instant (the new Google search enhancement to be rolled out to all users soon) will ruin Search Engine Optimization (SEO) which I find kinda wrong.

First: SEO is a way to aid (content providers to provide ways to) internet users to find their way to their content. ie, it’s a mean to an end, not an end! So if Google (or Bing, etc) added new features to enhance the user experience (UX) and personalize search results that might break SEO, SEO should find a way to adapt. Killing innovation is not an option :)

SEO is not about deceiving people to direct them to your content, whether it’s relevant or not!!

Second: & that’s the main point here: As far as I can see, Google Instant is not ruining SEO as Steve claims. Search results are still gonna be shown as the good old days, the only main difference is that you won’t have to click ENTER after typing your search words. You can get instant feedback about where your search results meet your expectations or not. So if content-providers did their SEO job right, their content will show up according to the relevance of their content to the typed keywords.

So, what do you think? correct me if you can see it in any other way..

Update:

I find this tweet by @Bashmohandes more valid though:

Google Instant is cool, but I worry about advertisers, as some of their impression budgets are used while the user didn't show enough intent

.. more.

Saturday, July 10, 2010

Creating a simple Open Search Provider/Plug-in

Yesterday, I needed to check/search my delicious bookmarks more than once. I then realized that delicious have its a search plug-in as a part of a tool bar (along with other bookmarking tools, few search tools, though), which -I guess- loads all your bookmarks to browser & make them available for search.

As I’m not so much into too much plug-ins, specially if they load lots of data (in contradiction to Pointy-haired Boss) , not to mention that I won’t need bookmarks when I’m offline, anyway, I decided I should create my search provider.

Creating the provider:

Here’s an example:

<?xml version="1.0" encoding="UTF-8"?>
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
   <ShortName>My Delicious</ShortName>
   <Description>Search Shady’s Delicious Bookmarks</Description>
   <Tags>Delicious Bookmarks Search Favorites</Tags>
   <Image width="16" height="16" type="image/x-icon">http://delicious.com/favicon.ico</Image>
   <Url type="text/html"
        template="http://delicious.com/search?p={searchTerms}&amp;context=userposts|m.shady|&amp;lc=1"/>
</OpenSearchDescription>

Away from the fact that I badly need a WYSIWYG code hi-lighter, let’s check that XML. First the ShortName which appears in your search box, something like this:

Click to Enlarge Description and Tags are obvious, & I think optional too.

Image is the small icon that appear beside when you select your provider (check the pic above again). You can either supply it as a URL to an image file (usually .ico or .png) or you can replace it with the base 64 string of the image (though I wasted quite sometime to make that work), like:

<Image width="16" height="16">data:image/x-icon;base64,AAA…AAA==</Image>

Finally, URL note that I’m using {SearchTerms} to pass the string typed in the search box. You can send other parameters to your search page. You might want add another URL for suggestions, here I’m only providing the search URL.

Using the provider:

To add the provider to your browser (as far as I’m concerned it works fine for Firefox & IE) you have one of two options:

Adding it as a suggested search provider: This can be done by adding a single line in your page <Head> tag, note that the attribute title in the below tag refers to the name appearing in the list as [Add “title”], check the image below the tag.

<link rel="search"
           type="application/opensearchdescription+xml"
           href="http://localhost/SearchProviders/delicious.xml"
           title="Delicious" />

Click to Enlarge

Using JavaScript to add the provider: The other available option is to add the provider using scripting, here’s an eg of how you can do that:

<a href="#" onclick="window.external.AddSearchProvider('http://localhost/SearchProviders/delicious.xml')">Add delicious Search to your browser</a>

Clicking a link like the one above will pop up a windows asking if you want to add the search provider.

References: http://www.opensearch.org

.. more.

Friday, July 09, 2010

Changing regional settings for System accounts (including ASPNET) in Windows 7

One of the small issues I faced while switching my development machine to windows 7 was a bug/exception in an application I was working on in parsing date format.

After switching my regional settings to the “expected” format, I still got the same exception. After playing a little with the regional settings, I realized that I was switching only my account date format, not the whole machine's date format. To push those settings to other system accounts (like ASPNET, etc), I did the following steps:

After setting your your account regional settings, switch to “Administrative” tab:

Click to Enlarge

From “Welcome screen and new user accounts”, click “Copy setting”:

Click to EnlargeMake sure “Welcome screen and system accounts”  check box is checked, press ok, and Voila!

.. more.

Saturday, December 05, 2009

How to create a C# Class from XML file (via xsd.exe)

A friend asked me a couple of times about how to I created the class I used in “twitter common friends” to handle xml as objects (includes reading & writing back). Actually the tool (xsd.exe) is pretty simple & takes no more than a couple of commands to create the class for me.

It’s just that I usually forget the keywords/parameters & their order (you can create a dataset or class that can be C# or VB, & there’s a couple of other option I never used before). I usually refer to its MSDN page when asked..

So I thought a post would be easier to remember. First you should create the xsd file out of the xml, using the VS command prompt:

xsd myFile.xml

That will create “myFile.xsd”, now to create “myFile.cs”, write the below line:

xsd myFile.xsd /c

Now you can add the cs file to your project & use it as illustrated in my previous post.

.. more.

Sunday, October 11, 2009

Table-Value and Temp Tables

Table-Value Parameters
Table-value parameters offer more flexibility and better performance than temporary tables to pass a list of parameters. Table-value parameters do not acquire locks for the initial population of data from a client and do not cause a statement to recompile.

Table-value parameters offer the following benefits:
·Provide a simple programming model.
·Enable inclusion of complex business logic in a single routine.
·Reduce round trips to the server.
·Include a table structure of different cardinality.
·Enable strongly typed and set-oriented queries.
·Enable the client to specify sort order and unique keys.

Table-value parameters have the following restrictions:
·Statistics are not maintained on columns of table-value parameters.
·Table-value parameters must be passed as input READONLY parameters to Transact-SQL routines.
·DML operations such as UPDATE, DELETE, or INSERT cannot be performed on a table-value parameter in the body of a routine.
·Table-value parameters cannot be used as the target of a SELECT INTO or INSERT EXEC statement. Table-value parameters can be in the FROM clause of SELECT INTO, or in the INSERT EXEC string or stored procedure.

Source: http://bit.ly/3rmMLK

.. more.

Wednesday, August 19, 2009

Disabling the mouse right click : JavaScript

As mention in the title here is code to disable the right click for the mouse in the browser (tested in IE ).
The code is JavaScript ,the code is readable and can be used to handle other mouse events.
just call DisableRightclick() once in your page.



[script language="javascript" ]
var IE;
var NN;
function right(click)
{
if(IE && (event.button==2 || event.button==3))
{
alert("The right click has been disabled here.");
return false;
}

if(NN && (click.which==2 || click.which==3))
{
alert("The right click has been disabled here.");
return false;
}

return false;
}

function
DisableRightclick()
{


if(navigator.appName=="Microsoft Internet Explorer")
{
IE=true;
}

if(navigator.appName=="Netscape")
{
NN=true;
}


if (document.layers) window.captureEvents(Event.MOUSEDOWN);
if (document.layers) window.captureEvents(Event.MOUSEUP);
document.onmousedown=right;
document.onmouseup=right;
window.document.layers=right;
}
[/script]

.. more.

Check Acrobat Reader (PDF) installed : JavaScript with IE

Here you can find helper function I got by Google and do some changes to it to be suitable for me .It checks if the Acrobat Reader is installed in the browser or not (it tested on IE6 and IE7 with Acrobat 6 and 7).
Function returns : true for OK else false .

function CheckPDF()
{
var isInstalled = false;
var version = null;
if (window.ActiveXObject)
{
var control = null;
try {
// version 7
control = new ActiveXObject('AcroPDF.PDF');
}
catch (e)
{
// Do nothing
}
if (!control)
{
try {
//version 6
control = new ActiveXObject('PDF.PdfCtrl');
}
catch (e)
{
return false ;
}
}
if (control)
{

return true ;
}
else
{
return false ;
}
}
}

.. more.

Sunday, April 12, 2009

Twitter Common Friends

For the past couple of months, A lot of people (who I don't know) have been following my twitter.. Mostly they don't look like anybody I know, not even Egyptians, & I'm not that popular anyway.. I'm ok with people following me anyway.. My twitter is public, & I'm not planning to change that.. But sometimes I need to know if these are real people who are in my twitter "social network" or just some sort of zombies or bots..

I've just created a small app to act like "common friends" in Facebook so I can find out whether I really know them or not.. Actually a couple of these followers are really interesting people & I'm following them now.. The app finds common people you're follwoing.. not common followers, the followers all is almost the same it just need authentacation..



The application depend on a single twitter API which takes the user name as a parameter & returns an xml (or JSON) file of their freinds for eg these are my friends xml file:

http://twitter.com/statuses/friends/mshady.xml



I used the "XML schema definition" tool (Xsd.exe) to generate the class to use the xml nodes directly as nodes rather than querying the XML document.. I'm such a lazy coder.. I know :D..

Once the xml is deserialised into the users datatype like this:


XmlSerializer oXmlSerializer = new XmlSerializer(typeof(users));
users oUsers1 = (users)oXmlSerializer.Deserialize(
                     XmlReader.Create(@"http://twitter.com/statuses/friends/"+textBox1.Text+".xml"
                        ));

All you need to do is to find the intersection set between the two list/sets.. & display them
 
The source code & binaries are available here: http://cid-570d40f05cc0dc13.skydrive.live.com/self.aspx/Sample%20Code/TwitterTest.rar

.. more.

Tuesday, November 18, 2008

Limitations on using Cookies

Make note of the following limitations when using Cookies (I'm not sure if that applies to all Web-technologies or just Asp.Net, but I've just solved a bug related to this issue using Asp.Net):

  • A cookie size is limited to 4096 bytes. It is not much, so cookies should be used to store small amounts of data. For larger amounts of data
  • Also, number of cookies is limited to 20 per website. If you make new cookie when you already have 20 cookies, browser will delete oldest one.
Quoted from beansoftware.com

.. more.

Thursday, July 10, 2008

Code Snippet :Oracle via C#

Select statement :

OracleCommand myOracleCommand = new OracleCommand();

OracleConnection myOracleConn = new OracleConnection();

myOracleConn.ConnectionString = "user id=userid ; data source=ERPDEV ; password=xxxxx";

myOracleConn.Open();

myOracleCommand.Connection = myOracleConn;

try

{

string strSQLFields = "select QUESTIONANSWER from FCIH where QUESTIONTEXT ='any text' ROWNUM <= 2)";

myOracleCommand.CommandText = strSQLFields;

myOracleCommand.CommandType = CommandType.Text;

OracleDataReader OracleDataReader1 = myOracleCommand.ExecuteReader();

if (OracleDataReader1.Read())

{

if (!(OracleDataReader1.IsDBNull(0)))

{

answer = OracleDataReader1.GetString(0);

}

}

if (!OracleDataReader1.IsClosed)

OracleDataReader1.Close();

if (myOracleConn.State == ConnectionState.Open)

myOracleConn.Close();

}

catch (Exception ex)

{

throw new ArgumentException(ex.Message.ToString());

}


Insert statment :

//new record

OracleCommand myOracleCommand4Insert = new OracleCommand();

OracleConnection myOracleConn4Insert = new OracleConnection();

myOracleConn4Insert.ConnectionString = "user id=ultimus ; data source=ERPDEV ; password=kmbpm263";

myOracleConn4Insert.Open();

myOracleCommand4Insert.Connection = myOracleConn4Insert;

try

{

string strSQLFields4Insert = "INSERT INTO FCIHTABLE( TENDERNAME, TENDERNO )";

string strSQLValues4Insert = ":TENDERNAME,TENDERNO.NEXTVAL";

string strSQL4Insert = strSQLFields4Insert + " VALUES (" + strSQLValues4Insert + ")";

myOracleCommand4Insert.CommandText = strSQL4Insert;

myOracleCommand4Insert.CommandType = CommandType.Text;

myOracleCommand4Insert.Parameters.Add("TENDERNAME", "any tender name");

myOracleCommand4Insert.ExecuteNonQuery();

}

catch (Exception ex)

{

throw new ArgumentException("Error In Insert You Suggestions to DataBase: " + ex.Message.ToString());

}

.. more.

Thursday, March 27, 2008

Amazon S3 via C#

Amazon Simple Storage Service (Amazon S3) via C#

Amazon S3 is storage for the Internet. It is designed to make web-scale computing easier for developers. It’s provides a simple web services interface that can be used to store and retrieve any amount of data, at any time, from anywhere on the web.

It uses standards-based REST and SOAP interfaces so it is platform independent and language independent.

It `s commercial but highly scalable, reliable, fast and inexpensive data storage infrastructure.

To know more about its advantage and the cost click here:

http://www.amazon.com/gp/browse.html?node=16427261

I am writing here to give you my experiences and tricks which I faced it when I started in develop the service using Dot Net (C#) and soap.

First trick:

When you work using .Net, you must use WSE 2.0 NOT WSE 3.0 as Amazon support DIME (WSE 2.0) NOT MTOM (WSE 3.0).

Second trick:

You can only using the class System.Web.Services.Protocols.SoapHttpClientProtocol, if you want upload files to AWS (Amazon Web Service) that are less than one Megabytes.

Here is an excellent example that server the required (files less than megabyte) with complete demo code for view and upload files.

http://developer.amazonwebservices.com/connect/entry.jspa?externalID=774&categoryID=55

Third trick:

If your files are bigger than one Megabytes (ten, twenty or may be 50 megabytes), you must to change the class System.Web.Services.Protocols.SoapHttpClientProtocol to Microsoft.Web.Services2.WebServicesClientProtocol . (As mentioned in this link)

http://developer.amazonwebservices.com/connect/entry!default.jspa?categoryID=103&externalID=689&fromSearchPage=true

Then follow the last trick...

Last trick:

You must raise the Timeout property that inherits the Microsoft.Web.Services2.WebServicesClientProtocol (the AmazonS3class if you opened the following example) more time out (this property measures in milliseconds) .

Here it an excellent example that server the required (more than one megabyte) with complete code.

http://developer.amazonwebservices.com/connect/entry!default.jspa?categoryID=47&externalID=690&fromSearchPage=true

The Amazon S3 Developer Guide :

http://docs.amazonwebservices.com/AmazonS3/2006-03-01/

.. more.

Monday, February 18, 2008

A common bar-code problem

A tiny detail that is usually missed when working with bar-codes (written in fonts like: "3 of 9 Extended", etc) is writing the bar-code text between brackets or asterisks:

myLabel.Text = "*"+myBarcode+"*";

or

myLabel.Text = "("+myBarcode+")";

Forgetting using one of the above ways makes the code unreadable by bar-code readers..

.. more.

C# : indexed pixel problem

Here I will mention the solve for a common problem happens when you try to create Graphic object from Bitmap images as in the next two lines..yes, it would fire an exception if your bitmap was indexed pixel .

Bitmap tmp = new Bitmap("Fci-h.jpg");
Graphics grPhoto = Graphics.FromImage(tmp);

Exception : "A Graphics object cannot be created from an image that has an indexed pixel format".

To pass this exception you will need to add some additional lines of code . Just create an image with the same size like the original image (Fci-h.jpg) then draw the original image onto the new Graphics object .

Here is an Example :

Bitmap bm = (Bitmap) System.Drawing.Image.FromFile("Fci-h.jpg",true);
Bitmap tmp=new Bitmap (bm.Width ,bm.Height );
Graphics grPhoto = Graphics.FromImage(tmp);
grPhoto.DrawImage(bm, new Rectangle(0, 0, tmp.Width , tmp.Height ), 0, 0, tmp.Width , tmp.Height , GraphicsUnit.Pixel);

.. more.

Thursday, February 14, 2008

Stamping text file in PDF pages

I wrote C# function that Stamping the content of text file (text and hyper links) at the front of the select pages (selected by the user) from the PDF .

NOTE :
This C# function stamp the text with aligning the text at the center of the selected pages ,the function based on the latest library called ItextCharp ( iTextSharp 4.0.8 (2008-01-25) .
Download the library from here

iText

# (iTextSharp) is a port of the iText open source java library written entirely in C# for the .NET platform.
iText is a library that allows you to generate PDF files on the fly. It is implemented as an assembly.

Parameter Example :

string sourcefile --> "input.pdf"
string SaveFileName--> "output.pdf"
float Y_space --> 405
float lead--> 25
float FontSize --> 12
string TxtFileName--> "textostamp.txt"
string _Font --> "HELVETICA"
string pagesRange --> "3,6,8" or "3-6,9-15"


you must to import this namespaces :)
using System.IO;
using iTextSharp.text.pdf;
using iTextSharp.text;
==

/* StamperTxt is a class which stamps the content of text file (text and hyper links)

* at the front of the select pages (selected by the user)from the PDF .

* */

public StamperTxt(string sourcefile, string SaveFileName, float Y_space, float lead, float FontSize, string TxtFileName, string _Font , string pagesRange)

{

PdfReader pdfreader = new PdfReader(sourcefile);

float pagewidth = pdfreader.GetPageSize(1).Width;

int j = pdfreader.NumberOfPages;

bool[] flag ;

flag = new bool[j];

for (int i = 0; i <>

flag[i] = false;

if ((pagesRange.Trim() == "all" )&&(pagesRange.IndexOf("-") == -1 )&&(pagesRange.IndexOf(",") == -1 ) )

{

for (int ii = 0; ii <>

flag[ii] = true;

}

else if ((pagesRange.IndexOf("-") != -1))

{

string[] tempArr = pagesRange.Trim().Split(',');

foreach (string str in tempArr)

{

string[] tempArrhyphen = str.Trim().Split('-');

int startIndex = 0, endIndex = 0;

startIndex =int.Parse(tempArrhyphen[0].Trim());

endIndex = int.Parse(tempArrhyphen[1].Trim());

for (int s = startIndex; s <= endIndex; s++)

{

flag[s-1] = true;

}

}

}

else if ((pagesRange.IndexOf(',') > -1))

{

string[] tempArr = pagesRange.Trim().Split(',');

foreach (string str in tempArr)

{

int index = int.Parse(str);

flag[index-1] = true;

}

}

PdfGState pdfgstate = new PdfGState();

pdfgstate.FillOpacity = 1.0f;

Stream output_stream = new FileStream(SaveFileName, FileMode.OpenOrCreate);

PdfStamper pdfstamper = new PdfStamper(pdfreader, output_stream);

for (int k = 0; k <>

{

if (flag[k] != true)

continue;

PdfContentByte pdfcontentbyte = pdfstamper.GetOverContent(k+1);

float v_space = Y_space;

pdfcontentbyte.SaveState();

pdfcontentbyte.SetGState(pdfgstate);

BaseFont PF = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, false) ;

pdfcontentbyte. SetFontAndSize(PF , FontSize);

StreamReader SR;

string S;

SR = File.OpenText(TxtFileName);

ArrayList chunklist = new ArrayList();

S = SR.ReadLine();

while (S != null)

{

Chunk chk = new Chunk(S + "\r\n", FontFactory.GetFont(_Font, FontSize, Font.NORMAL));

if (S.IndexOf("http:/") > -1)

{

chk = new Chunk(S + "\r\n", FontFactory.GetFont(_Font, FontSize, Font.UNDERLINE));

chk.SetAnchor(S);

}

chunklist.Add(chk);

S = SR.ReadLine();

}

//Console.WriteLine(S);

SR.Close();

Phrase PH = new Phrase();

PH.Font = FontFactory.GetFont(_Font, FontSize, Font.NORMAL);

PH.AddRange(chunklist);

PH.Leading = lead;

PdfPTable table = new PdfPTable(1);

table.DefaultCell.Border = Rectangle.NO_BORDER;

table.DefaultCell.SetLeading(lead, 0);

table.TotalWidth = pagewidth;

table.HorizontalAlignment = Rectangle.ALIGN_MIDDLE;

table.DefaultCell.HorizontalAlignment = Rectangle.ALIGN_MIDDLE;

table.HorizontalAlignment = Rectangle.ALIGN_CENTER;

table.DefaultCell.HorizontalAlignment = Rectangle.ALIGN_CENTER;

table.AddCell(PH);

table.WriteSelectedRows(0, -1,0, v_space, pdfcontentbyte);

}

byte[] arr = pdfstamper.Writer.XmpMetadata;

pdfstamper.Close();

pdfreader.Close();

Console.WriteLine(SaveFileName + "Was Created in Success...");

}////end Function

.. more.