Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Friday, July 24, 2009

Vertical Subcategory Listing in Entity XMLPackage

Last week, I was dead worried on how to do this.  The default in ASPDNSF is horizontal listing.  Although it's okay for my client to display that way, he wanted a vertical listing more.  I consulted the forum but to no avail.  Finally, I came up with a solution.  It's a very long one, and I must admit, it's not the best one either.  I'm hoping there's a shorter one, but for now, since I have a tight deadline, I'm okay with this solution.

Here's what I did.  I created a new XSLT function that accepts the parameters WebsiteID (This is multistore so WebsiteID is necessary), ParentCategoryID, and the NodeCount (although personally, I don't think this is necessary anymore).  This function does all the work.  I can't think of anything else that will only touch the XMLPackage so I went deeper.

In my XSLT function, I created an ArrayList of Items that will hold the nodes (or the subcategories) of my query.  I also created a temporary ArrayList that will hold each field of my subcategories.  This temporary one will be stored in ArrayList Items.

then made this code:
// sql query to store categor fields into temporary ArrayList
// then stores the temporary ArrayList to Items

double SubCategoryCount = Items.Count;

int ItemsPerColumn = (int) Math.Ceiling(SubCategoryCount / 3); // I only have three columns
int counter = 0;
StringBuilder str = new StringBuilder();

foreach (ArrayList al in Items) //traverses all subcategories in Items
        {
            if (counter < ItemsPerColumn)
            {
                str.Append("<tr>");
                // code for the first column

                if ((counter + ItemsPerColumn) < Items.Count) // checks if this index is not yet out of bounds
                {
                     ArrayList al2 = (ArrayList)Items[counter + ItemsPerColumn];
                     // code for the second column
                }

                if ((counter + ItemsPerColumn + ItemsPerColumn) < Items.Count) // checks if this index is not yet out of bounds
                {
                     ArrayList al3 = (ArrayList)Items[counter + ItemsPerColumn + ItemsPerColumn];
                     // code for the third column
                }

                str.Append("</tr>");
                counter++;
            }
            else
            {
                break;
            }
        }
This is a very long solution but works fine with me, so I'm sticking to this for now.


Thursday, July 23, 2009

VS IDE: Dots and Arrows

I'm a little bit ashamed to post this but somehow, I have a feeling I might be needing this in the future.

I was typing fast and while supposedly pressing a shortcut for something, I accidentally pressed the wrong keys that resulted to dots and arrows, dots replacing normal spaces and arrows replacing tabs.  I tried ignoring them since I don't know how I did that.  But I still found them annoying, and made me lost with my coding.

So I searched for this problem.  Luckily, I wasn't the only one who had this problem.  From a forum, even though the threader starter was OT, other forumers still answered him.

The solution:  Ctrl+Shift+8
If this won't work, try Ctrl+R+W

Simple, isn't it?  That's why I hate myself right now.  Haha!


Thursday, June 18, 2009

String Split using JavaScript

Found this helpful when I'm trying to modify a script that I didn't do...hehehe

Split a string in JavaScript using the following method:

var stringToSplit = "string-to-split";
var splitArray = stringToSplit.split("-"); //splits the string when the system encounters "-", the delimeter
In a function:
<SCRIPT language="JavaScript">
<!--
function split_string() {
var stringToSplit = "string-to-split";
var splitArray = stringToSplit.split("-");
alert(splitArray[0] + "\n" + splitArray[1] + "\n" + splitArray[2]);
}
//-->
</SCRIPT>
<FORM>
<INPUT TYPE="button" onClick="split_string()" value="Split string-to-split!" />
</FORM>

Tuesday, May 12, 2009

Hit Counter in a Web Page

The site I've been working on needs a text hit counter in it.  As usual, I searched the internet to look for answers since I'm new to this.  I found two solutions: through storing in the database and through storing in a text file.  The database looks complicated (and IS complicated) but read it anyway.  It touches some files, and the Global.asax.  But although it looks complicated, I was really trying to avoid the text file solution.  And then I found this forum thread for the same solution.  A user somehow said it's better to use the text file, that's because the solution might not be that reliable after all.

So I'm using the text file, and so far, I like the results.  Here's the code I used (courtesy of Dipal Choksi):
    private int GetHitCounter()
    {
        StreamReader ctrFile;
        FileStream ctrFileW;
        StreamWriter sw;

        string strPath = HttpContext.Current.Server.MapPath("hitcounter.txt");
        string strCounterContents = string.Empty;
        int nCounter = 0;

        if (File.Exists(strPath))
        {
            ctrFile = File.OpenText(strPath);
            strCounterContents = ctrFile.ReadLine().ToString();
            ctrFile.Close();
            nCounter = Convert.ToInt32(strCounterContents);
        }
        else
            nCounter = 0;

        nCounter++;

        ctrFileW = new FileStream(strPath, FileMode.OpenOrCreate, FileAccess.Write);
        sw = new StreamWriter(ctrFileW);
        sw.WriteLine(Convert.ToString(nCounter));
        sw.Close();
        ctrFileW.Close();

        return nCounter;
    }

And then in my public method, I called GetHitCounter()
        string temp = string.Empty;
        int nCount = 0;
        nCount = GetHitCounter();
        temp = nCount.ToString();
        return temp;

My reference used image to return the counter.  He (or She) used the namespace System.Drawing for the image, hence, the GDI+ classes.  I, on the other hand, only needed the string retult, so there's no need for me to use the other method he (or she) used to return the counter.  Anyway, if you just want the current hit count, just remove the nCounter++; from GetHitCounter() method.

That's all.  I hope other people might find this helpful.  Happy coding.. ^_^


Thursday, April 16, 2009

Changing href Link Through JavaScript

I've been looking for ways to change the anchor link through JavaScript. Luckily, I found this site that helped me with the solution: WebSewak's Techjunk.

I just want to post the solution here so that I won't forget about it.
<script language="javascript" type="text/javascript">
var boardpics = new Array();
var boardpicsLarge = new Array();
boardpics['1'] = 'images/product/medium/22_1_.jpg';
boardpicsLarge['1'] = 'images/product/large/22_1_.jpg';
boardpics['2'] = 'images/product/medium/22_2_.jpg';
boardpicsLarge['2'] = 'images/product/large/22_2_.jpg';
boardpics['3'] = 'images/product/medium/22_3_.jpg';
boardpicsLarge['3'] = 'images/product/large/22_3_.jpg';
function changeImagesrc(id){
document.productimg.src = boardpics[id];
document.getElementById('productimgID').href = boardpicsLarge[id];}
function changeImagesrc1(){
document.productimg.src = 'images/product/medium/22.jpg';}
</script>



Tuesday, September 9, 2008

Uploading/Importing File in C# .NET

Just want to share this code I used when uploading a file. I need to read a CSV file and save the data on a database.

First off, of course, is to add a file upload function in my page. I used the following syntax in my page, then code everything else.
<asp:FileUpload ID="fuCSVFile" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
Then in my source code, when click button event is being called, my page will save the file in another folder. Then call a function to process the import to database.
void btnUpload_Click (object sender, EventArgs e){
.
.
.
String Name = "Import_" + System.DateTime.Now.ToLongDateString().Replace(" ", "").Replace("/", "").Replace(":", "").Replace(".", "");
HttpPostedFile hpfCSV = fuCSVFile.PostedFile;
String textFile = HttpContext.Current.Request.MapPath("../" + Name + ".csv");
if (hpfCSV.ContentLength != 0)
{
hpfCSV.SaveAs(textFile);
ImportFromCSV(textFile);
}
.
.
.
}

void ImportFromCSV(String csvFile)
{
StreamReader sr = new StreamReader(CSVFile);
ArrayList values = new ArrayList();

// reading each line of the file
while (!sr.EndOfStream)
{
string[] val = null;
string fields = sr.ReadLine();
if (!fields.Contains("Artikelnummer"))
{
fields = fields.Replace("\"", ""); //remove all double quotes
// split each field
// delimiters depend on what is used in the CSV file.
// mine was a semi-colon
val = fields.Split(new char[] { ';' });
values.Add(val); //save the array of strings to an arraylist
}
}
foreach (string[] v in values)
{
//...
// import each array as one entry in the database
// we may call another function for the import to database
//...
}
}
Everything worked fine, until when I tried importing a CSV file, which is around 6MB. I always get a connection timeout error. My colleague told me to check the maximum file size that ASP.NET allows. And there it is, by default, ASP.NET only permits files with at most 4MB file size. So I researched again for the solution and found this handy solution. This should be put in the Web.config file.
<configuration>
<system.web>
<httpRuntime executionTimeout="90" maxRequestLength="7168"
useFullyQualifiedRedirectUrl="false" minFreeThreads="8"
minLocalRequestFreeThreads="4" appRequestQueueLimit="100" />
</system.web>
</configuration>
Anyway, if you want this setting to all of your workstations, or all of your web pages in your PC, then put this in your Machine.config, which is located in the \System Root\Microsoft.NEt\Framework\Version Number\CONFIG.

So that's it. Just want to take some notes so that I won't forget this. he he

Thursday, July 10, 2008

Resizing Images

Just trying something out. I've used this code to resize my image in a project. hehehehe

protected System.Drawing.Image resizeImage(System.Drawing.Image imgToResize, Size size)
{
int sourceWidth = imgToResize.Width;
int sourceHeight = imgToResize.Height;

float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;

nPercentW = ((float)size.Width / (float)sourceWidth);
nPercentH = ((float)size.Height / (float)sourceHeight);

if (nPercentH < nPercentW)
nPercent = nPercentH;
else
nPercent = nPercentW;

int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);

Bitmap b = new Bitmap(destWidth, destHeight);
Graphics g = Graphics.FromImage((System.Drawing.Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;

g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
g.Dispose();
imgToResize.Dispose();

return (System.Drawing.Image)b;
}

Wednesday, July 2, 2008

FTP Upload in C# .NET

This is my first time to post a code. Well, I'm just so happy that if finally worked after a series of errors. So I want to share this code taken from a reference (ASP Alliance). We can find a lot of similar codes but I chose this reference because this was my starting point (recommended by my Project Manager).

private string ftpUsername; //username
private string ftpPassword; //password

private void UploadImage(string filename)
{
FileInfo fileInf = new FileInfo(filename);
string uri = "ftp://" + ftpAddress + "/" + fileInf.Name;
FtpWebRequest reqFTP;

reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpAddress + "/" + fileInf.Name));
reqFTP.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
reqFTP.Timeout = 1000000000; //set to very high value
reqFTP.KeepAlive = false;
reqFTP.ReadWriteTimeout = 1000000000; //set to very high value
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.UseBinary = true;
reqFTP.UsePassive = false; //my own addition
reqFTP.ContentLength = fileInf.Length;
int buffLength = 2048; //set to 2kb
byte[] buff = new byte[buffLength];
int contentLen;

FileStream fs = fileInf.OpenRead();

try
{
Stream strm = reqFTP.GetRequestStream();
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
strm.Close();
fs.Close();
}
catch (Exception ex) {
throw new ApplicationException(ex.Message);
}
}
So there it is. I added some modifications like reqFTP.UsePassive = false; since I kept getting a "227" error. Found a forum that answers the same error, and suggested to include the said code. And after that, all worked perfectly. Kudos!

Tuesday, January 22, 2008

IE Not Applicable?

I just discovered. "@Get Fancy@" is supposed to be blinking. I guess the text decoration is not compatible with IE. Am I correct or my IE just loads very slow?

Anyway, to see the beauty of the blinking header, open my page with Mozilla Firefox... :P

Monday, June 18, 2007

Server Problems

New tasks came in today, testers will be very busy now. We'll be tackling the Linux version of our software, and we're still in the process of learning it (from insalling Linux to our terminals, to installing mounting it to the network, to installing the software itself). *sigh...so much to do, so little time.

Anyway, we've got bigger problems. We cannot access ALL our servers, they are not connected to the company's network. We have to ask help from our ITS so that we can access it again. *sigh

We can't do anything work-related until these problems are solved. I hope we can start soon.

Well, that's all for now. I'll be posting more of my son's pictures...:D