Whiel using the AJAXToolkit i came up with the situation where i needed to run some javascript after a server-side event was called. After poking around for a bit i found the command “ScriptManager.RegisterClientScriptBlock”. This command sends back asynchronously javascript that will be executed by the clients browser on update. Here is an example:-

string strscript = "var cbut=$get('programmaticPopup');alert(cbut.id+' '+cbut.style.position);";
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "ToggleScript", strscript, true);

this.Page is your pages current Page object, “ToggleScript” is the name you are giving the script block, strscript is a string containg the javascript and following that is true which is there to tell the command to suround the inputed javascript with “

p.s. you will notice the javascript command $get(elementname), this returns the object with the ID you gave it at design time just like document.getElementById();. If you look at the source of a running script all the ID tags have strange strings appended to the start of the ID name you gave it. $get finds the element without all the crap. Its part of the AJAX Toolkit.

Here is a function to redimension an array in csharp:-

private static void ReDim(ref TextBox[] arr, int length)
    {
        try
        {
            if (arr == null)
            {
                arr = new TextBox[length];
            }
            else
            {
                if (arr.Length != length)
                {
                    TextBox[] arrTemp = new TextBox[length];
                    if (length > arr.Length)
                    {
                        Array.Copy(arr, 0, arrTemp, 0, arr.Length);
                        arr = arrTemp;
                    }
                    else
                    {
                        Array.Copy(arr, 0, arrTemp, 0, length);
                        arr = arrTemp;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            string x = ex.ToString();
            //Console.WriteLine(x);
        }
    }

This example is for a string array but you can overload it with whatever type you want.

Here is a way to check if a string is a number:-

public static bool isNumeric(string val, System.Globalization.NumberStyles NumberStyle)
    {
        Double result;
        return Double.TryParse(val, NumberStyle, System.Globalization.CultureInfo.CurrentCulture, out result);
    }

Here is a link so you can figure out what to put in the “NumberStyle” field.
http://msdn.microsoft.com/en-us/library/system.globalization.numberstyles.aspx

In a project i had been working on i wanted to have a central MasterPageFile that had variable sub MasterPageFile’s. I finally figured out that you have to override the “OnPreInit” Event on the page you wish to modify. Here is an example:-

protected override void OnPreInit(EventArgs e)
    {
 
        if (Web_Security.IsSU())
        {
            this.MasterPageFile = "~/management/SUMasterPage.master";
        }
        else
        {
            this.MasterPageFile = "~/management/MemberMasterPage.master";
        }
        base.OnPreInit(e);
 
    }

Hope this saves you some time.

Often it is necessary to resize an image that has been uploaded. To do this you will need the following using classes:-

using System.Drawing;
using System.Drawing.Imaging;

Then here are some examples on functions with the resize code:-

public static string ResizeImageAndSave(int Width, int Height, string imageUrl,string destPath)
	{
 
 
        System.Drawing.Image fullSizeImg = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(imageUrl));
 
        double widthRatio = (double)fullSizeImg.Width / (double)Width;
        double heightRatio = (double)fullSizeImg.Height / (double)Height;
        double ratio = Math.Max(widthRatio, heightRatio);
        int newWidth = (int)(fullSizeImg.Width / ratio);
        int newHeight = (int)(fullSizeImg.Height / ratio);
 
        System.Drawing.Image.GetThumbnailImageAbort dummyCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
        System.Drawing.Image thumbNailImg = fullSizeImg.GetThumbnailImage(newWidth, newHeight,dummyCallBack, IntPtr.Zero);
        DateTime MyDate = DateTime.Now;
        String MyString = MyDate.ToString("ddMMyyhhmmss") + ".png";
        thumbNailImg.Save(HttpContext.Current.Server.MapPath(destPath) + MyString, ImageFormat.Png);
        thumbNailImg.Dispose();
        return MyString;
	}
 
    public static bool ThumbnailCallback()
    {
        return false;
    }

Here is an example on how to delete files in the file sytem:-

public static void DeleteFile(string FilePath)
    {
        try
        {
            FileInfo TheFile = new FileInfo(HttpContext.Current.Server.MapPath(FilePath));
            if (TheFile.Exists)
            {
                File.Delete(HttpContext.Current.Server.MapPath(FilePath));
            }
            else
            {
                throw new FileNotFoundException();
            }
        }
        catch (FileNotFoundException e)
        {
            LogEntry log = new LogEntry();
            log.EventId = 701;
            log.Message = "Error Deleting File\r\n" + FilePath + "\r\n" + e.ToString() + "\r\n" + e.StackTrace;
            log.Categories.Add("General");
            log.Severity = TraceEventType.Information;
            log.Priority = 5;
            Logger.Write(log);
        }
        catch (Exception e)
        {
            LogEntry log = new LogEntry();
            log.EventId = 1301;
            log.Message = "Error Deleting File Exception\r\n" + FilePath + "\r\n" + e.ToString() + "\r\n" + e.StackTrace;
            log.Categories.Add("General");
            log.Severity = TraceEventType.Information;
            log.Priority = 5;
            Logger.Write(log);
        }
 
    }

The example code above has some custom error exception handling that you may want to remove.

when my erstwhile friend daniel first suggested that i should expatiate my views on the problems related with the evolving power of the computer and the concomitant ever increasing perception of the validity of it per se i thought that as a subject it w3aqs axiomatic as to answers that most reasonable people of a generation several ages before my own wherethe computer and the internet were as essential to the survival of a free and law abiding peoples where the brave new world of a sophistecated elite versed in the unequivical necessity of the computer by and large were inept and afraid to face life seen as ultimately rewarding only if virtual reality were the abiding absolute.what a crock of shit i thought;they justify their claims because it as pervasive state of the art technology is here to stayand i may be dumb but im not stupid and it becomes an ineluctable fact that the purpose ofthe computer is to help an increasingly fragile enviroment with faster and more sophisticated means to substantiate an ever stumbling homo sapiens as he lurches like some out of step dipsomaniac more akin to schadenfreude as society invertes on itself as the only cogent means to survive a world where acceptanceof its downward spiral towards the proverbial armageddon and we must make the imperitive of the cosmological essence of mankindes very existence as an emerging type two civilisation make any such argument as mine as out of step with reality as it is as,das ding an sich things as they are in themselves but has it not already made itself redundant by inextricably stating any situation as becoming as important as breathing and that as analogous to cyberspace and stating that without the computer and the net we are doomed to mediocrity and despair unless we do harness the very thing that will separate us from atavism and anomilies in the very structure that propels us towards an increasingly fragile view of ourselves as some how in anthropological terms at least as progressing forward in a benign spiritual quest to see ourselves as a forlorn but essential element in the knowledge of god like control over the cosmos;but the essence of the spurious but de riguer containment of duty to lead our more older and less enlightened older citizens like moses leading the israelites out of servititude but what has humanity learned about its structure vis a vis the soul or spirit as viewed by the buddhists of the hinayanna sect who understands that man and only man can solve the problem of life as illusion;

I was writing dynamic form variables to the page and i needed to retrieve their values when updated. When i tried to access the variables with request.params[] collection i noticed that the keys were what id i had given them with a string appended to the start. I wrote this function to easiliy access the variables:-

public static string PostVal(string key)
    {
        string retval = "";
        foreach (string s in HttpContext.Current.Request.Form.AllKeys)
        {
            string[] sr = s.Split('$');
            if (sr[sr.Length - 1] == key)
            {
                retval = HttpContext.Current.Request.Form[s];
            }
        }
        return retval;
    }

I needed to have custom colours in my project so i looked at a few controls out there and the one i chose is from http://www.obout.com/ It seemed to do the job quite nicely.

I was making a yearly calendar and i needed to output the cells to represent the days in the year. At first i just made a public variable, filled it up with html and then outputed it to the page like this:-

1
<%=variablename%>

This seemed to work well but the page didn’t update on postback methods because the html was being rendered before any methods were executing.
I figured there must be a way to output to the current page so i had a look around and found some code that updated a panel control. To send it raw html use this command:-

1
panMainCalendar.Controls.Add(new LiteralControl("<tr><td height='20'><div align='left'>"));

To add a control try this:-

1
2
3
4
5
6
7
8
Button NLab = new Button();
Unit NU = new Unit(100,UnitType.Percentage);
NLab.Width = NU;
NLab.Height = NU;
NLab.Click += Day_Click;
NLab.CssClass = "ButtonCell";
NLab.ID = "lbCell_"+Day + "_" + Month + "_" + Year;
panMainCalendar.Controls.Add(NLab);

Good Luck

Next Page »