Generate 16 Digit Unique Number in CSharp

Posted by Venkat | Labels: ,

Now i am going ot discuss about how to Generate 16 digit Unique number
So ,

5 digit Random using System.Random Class

5 digit number by using TimeSpan

6 numbers by System Time (HH:MM:SS)

This is the Code

System.Random fiveRandom = new Random();
TimeSpan tsFive = new TimeSpan();
tsFive = DateTime .Now.Subtract (Convert.ToDateTime ("01/01/1900"));
string rad = fiveRandom.Next(10000, 99999) +  tsFive.Days.ToString() +   System.DateTime.Now.Hour.ToString ("00") +          System.DateTime.Now.Minute.ToString ("00") +   System.DateTime.Now.Second.ToString ("00")  ;

Compare Datetime Objects

Posted by Venkat | Labels: ,

Here i am going to share
1) How to Compare two Datetime object ( here i am mentioning some ways to Compare Datetime Variables )
2) How to get the timeSpan Values from the Hours and add hours to the Datetime its easy.

It can be expressed as a date and time of day.

It compares Date with time.

DateTime chkExpireDateTime = new DateTime(2009, 8, 1, 0, 0, 0);

if (DateTime.Compare(DateTime.Now , chkExpireDateTime)< 0)
{
// the Current Datetime.now is less than ChkExpireDateTime
}
else if (DateTime.Compare(DateTime.Now, chkExpireDateTime) > 0)
{
// the Current Datetime.now is Greater than ChkExpireDateTime
}
else if (DateTime.Compare(DateTime.Now, DateTime.Now) == 0)
{
// the Current Datetime.now and ChkExpireDateTime are Equal
}

You can also Compare this way.

DateTime systemDate = DateTime.Now;
DateTime compareDate = DateTime.Today.AddHours(11D);

// less than
if (compareDate < systemDate)
Console.WriteLine("Less Than");

// equal to
if (compareDate == systemDate)
Console.WriteLine("Equal To");

// greater than
if (compareDate > systemDate)
Console.WriteLine("Greater Than");

// basically you can compare it in all the normal ways
// using !=, ==, , =, etc



The below code is used to get the Timespan for the for the hours and minutes given through the string.

string time = "02:10";
string[] pieces = time.Split(new char[] { '.' },

StringSplitOptions.RemoveEmptyEntries);
TimeSpan difference2 = new TimeSpan(Convert.ToInt32(pieces[0]),

Convert.ToInt32(pieces[1]), 0);
double minutes2 = difference2.TotalMinutes; // 130
double totalSeconds = difference2.TotalSeconds; // 7800

// this will add the seconds to the Datetime

DateTime getOutTime = new DateTime();
getOutTime = DateTime.Now.AddHours(Convert.ToDouble (getHours ));
getOutTime = DateTime.Now.AddSeconds(totalSeconds);

Response.Redirect Vs Server.Transfer

Posted by Venkat | Labels:

1) Response.Redirect(“newpage.aspx”)

In some case , if i use like this it shows ThreadAborExecution error, when the above line execute it Calls the Response.End() and it's Response.End() that calls Thread.Abort() this makes the error.

Response.Redirect(“newpage.aspx”,false) // whereas the second parameter is false / true

Ref: http://www.c6software.com/articles/ThreadAbortException.aspx

and Server.Transfer(“newpage.aspx”)

2) Server.Transfer -  redirects the client with in the same application ie, from one ASP page to other ASP page with in the application. This will not update the history.

Response.Redirect: - This redirects the client to the other URL ie, from one ASP page to other applications page. This will update the history.

3) Response.Redirect involves a roundtrip to the server

whereas Server.Transfer conserves server resources by avoiding the roundtrip. It just changes the focus of the webserver to a different page and transfers the page processing to a different page.

4) Roundtrip means in case of Response.Redirect it first sends the request for the new page to the browser then browser sends the request for the new page to the webserver then after your page changes.

But in case of Server.Transfer it directly communicate with the server to change the page hence it saves a roundtrip in the whole process.

5) If you are using Server.Transfer then you can directly access the values, controls and properties of the previous page - using Context.Item collections

- which you can’t do with Response.Redirect.

6) Response.Redirect changes the URL in the browser’s address bar. So they can be bookmarked.

Whereas Server.Transfer retains the original URL in the browser’s address bar. It just replaces the contents of the previous page with the new one.

7) Response.Redirect can be used to redirect a user to an external websites.
Ex: www.Google.com,www.hyderabadtechies.info..,

Server.Transfer can be used only on sites running on the same server. You cannot use Server.Transfer to redirect the user to a page running on a different server.

Paths/URLs are incorrect, I want absolute/relative URLs? while using TinyMCE

Posted by Venkat | Labels:

Hi Normally if you upload the images on Admin Side - you are going to use the images on General or User folder.so this will take relative Path of the images or file, place the folder inside the Project folder - While giving path to the image on TinyMCE - use Absolute path or Relative path - it will take Relative path of the Images of files.

this is sample TinyMCE Initialization.

<script language="javascript" type="text/javascript" src="../tiny_mce/tiny_mce.js"></script>

<script type="text/javascript">
tinyMCE.init({
    // General options
    mode : "textareas",
     elements: "top1_TextBox,top2_TextBox,top3_TextBox,top4_TextBox,mid1_TextBox,mid2_TextBox,mid3_TextBox,mid4_TextBox,bot1_TextBox,bot2_TextBox,bot3_TextBox,bot4_TextBox",
    theme : "advanced",
     force_p_newlines: false,
            remove_linebreaks : true,
            force_br_newlines : true,
            paste_remove_styles : true,


    plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",


    // Theme options
    theme_advanced_buttons1 : "link,image,|,code",
    theme_advanced_buttons2 : "",
    theme_advanced_buttons3 : "",
    theme_advanced_buttons4 : "",
    theme_advanced_toolbar_location : "top",
    theme_advanced_toolbar_align : "left",
    //theme_advanced_statusbar_location : "bottom"
});
</script>

So get the upDated TinyMCE folder version 3.2.7 download the file from TinyMCE Download latest TinyMCE Editor . 

This link may help u  Path Url Issue

If you anyone face some issue let you comment here..

Visible the Textbox when User Select Others on the Dropdownlist using Javascript

Posted by Venkat | Labels: ,

Hi i have came across one task, ie: I have dropdownlist that has some items along with 'Others' So if the user Choose the value Others -  i have to visible the Textbox and Validator so user should enter somthing on the textbox else it show Validation error if the user choose any other item , i have to disable the Textbox and the Validator.

Using Javascript its easy to do this , i am not good in Javascript i got a help from the Expert to make it work.

ASPX

<asp:DropDownList ID="EducationLevel_DropDownList" runat="server" Width="202px"
                                            Font-Names="Verdana" Font-Size="10pt" AppendDataBoundItems="True">
                                            <asp:ListItem Value="-1">Select</asp:ListItem>
                                            <asp:ListItem Value="1">PhD</asp:ListItem>
                                            <asp:ListItem Value="2">PhD Student</asp:ListItem>
                                            <asp:ListItem Value="3">Master Degree</asp:ListItem>
                                            <asp:ListItem Value="4">Bachelor Degree</asp:ListItem>
                                            <asp:ListItem Value="5">Under Graduate Student</asp:ListItem>
                                            <asp:ListItem Value="6">Others</asp:ListItem>
                                        </asp:DropDownList>
                                        <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="EducationLevel_DropDownList"
                                            Display="Dynamic" ErrorMessage="Education Leve required !" InitialValue="-1"
                                            SetFocusOnError="True" ValidationGroup="Profile" Font-Size="8pt">*</asp:RequiredFieldValidator><asp:TextBox ID="TextBox1"
                                                runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"
                                            Display="Dynamic" ErrorMessage="Education Leve required !" 
                                            SetFocusOnError="True" ValidationGroup="Profile" Font-Size="8pt">*</asp:RequiredFieldValidator>

And the Javascript is given below so here i am pass the Valuefield of Other ie: 6 , when a textbox has validators, they are stored in the Validators collection , so no need to pass the ValidatorID.


JAVASCRIPT


<script type="text/javascript" language ="javascript" >


function getSelectValue(sel) {
   
    var val;
    // only if there is a selected item
    if (sel.selectedIndex>-1) {
        // get the value from the select element
        val=sel.options[sel.selectedIndex].value;
       // alert(val);
    }
   
    return val;
}


        function ddlChange(DropDownID,TextBoxID)
        {
            var c=document.getElementById(DropDownID);
            var div=document.getElementById(TextBoxID);
            if(getSelectValue(c)=='6')
            {
                div.value='';
                div.style.visibility="visible";
                if (div.Validators&&div.Validators.length) {
                   for (var i=0; i<div.Validators.length; i++)
                       ValidatorEnable(div.Validators[i], true)
                }
            }
            else
            {
                div.value='6';
                div.style.visibility="hidden";
                if (div.Validators&&div.Validators.length) {
                   for (var i=0; i<div.Validators.length; i++)
                       ValidatorEnable(div.Validators[i], false)
                }
            }
        }
    </script>

Then On_PageLoad you have to pass the TextboxID and DropdownlistID to the Javascript Function.


EducationLevel_DropDownList.Attributes.Add("onchange", "ddlChange('" + EducationLevel_DropDownList.ClientID + "','" + TextBox1.ClientID + "');");
        TextBox1.Style.Add("visibility", "hidden");

Bind Images from Folder to Datalist

Posted by Venkat | Labels: ,

Here we are going to see how to bind the images from the folder to Datalist. I am storing the images on Server Folder , so i have to show what are the images available on the Folder it may be .png,.jpg or any ...

ASPX

<asp:DataList ID="DataList1" runat="server" RepeatColumns="5" CellPadding="5">
            <ItemTemplate>
            <asp:Image Width="100" ID="Image1" ImageUrl='<%# Bind("Name", "~/images/{0}") %>' runat="server" />
                <br />
                <asp:HyperLink ID="HyperLink1" Text='<%# Bind("Name") %>' NavigateUrl='<%# Bind("Name", "~/images/{0}") %>' runat="server"/>
            </ItemTemplate>
                <ItemStyle BorderColor="Silver" BorderStyle="Dotted" BorderWidth="1px" HorizontalAlign="Center"
                    VerticalAlign="Bottom" />
</asp:DataList> 

see here, we get the files from the folder using System.IO Namesapce  , then i am checking the images on the folder ie: checking the extension that i am going to allow - to show it on Datalist. you can include the Extension whatever you want so that is going to add it on arrayList, then pass the array list to DataSource of the Datalist.


Code-Behind

protected void Page_Load(object sender, EventArgs e)
    {
        ListImages();
    }

    private void ListImages()
    {
        DirectoryInfo dir = new DirectoryInfo(MapPath("~/images"));
        FileInfo[] file = dir.GetFiles();
        ArrayList list = new ArrayList();
        foreach (FileInfo file2 in file)
        {
            if (file2.Extension == ".jpg" || file2.Extension == ".jpeg" || file2.Extension == ".gif")
            {
                list.Add(file2);
            }
        }
        DataList1.DataSource = list;
        DataList1.DataBind();
    }

Validate Checkbox and Checkboxlist

Posted by Venkat | Labels:

If we want to Validate the Textbox, Dropdownlist we used Validation Server Controls available in ASP.NET
Suppose if we want to validate Checboxlist or checkbox , some member validate through Javascript its good , some feed if its similar to Validator controls it should be easy to validate,.

so here is the link its similar to validation Server controls just Download the skmValidator Controls and add it on toolbox just drag and drop and set the errormessage , validationgroup, controltovalidate etc..

http://aspnet.4guysfromrolla.com/articles/092006-1.aspx 

If you want to do on Client side check this link

http://www.dotnetcurry.com/ShowArticle.aspx?ID=197&AspxAutoDetectCookieSupport=1

How to get Control Value From CreateUserWizard Control

Posted by Venkat | Labels: ,

Now I am going to discuss how to get the Controls Values ( ie:  Textbox , Dropdownlist etc.. ) inside the CreateUserWizard control, In CreateUserWizard Control on first view you can't able to get the Controls value directly.

Using FindControl i am getting the control value.

Write these Code on CreateUserWizard_CreatingUser Event

 DropDownList Questionddl = (DropDownList)CreateUserWizard.CreateUserStep.ContentTemplateContainer.FindControl("Question_DropDownList");
CreateUserWizard.Question = Questionddl.SelectedValue;

Set the Value has Selected to Listbox by getting value from Database

Posted by Venkat | Labels:

As we already saw how to get the items(Multiple selection item) from the Listbox. Suppose If we store that value like this(2,4,6,) ie: I concatenate the (,) for each valu -  2,4,6 are the value of the listbox so we are going to rebind this value to List and set it has Selected.

Here the subject is the field on the Table where the [ 2,4,6, ] was stored.

1) First we get the database value to string Variable

2) Then using Split property - remove the (,) from the String and assign to StringArray

3) Atlast use foreach loop to set the item to be selected.

  string subjectList = getUserProfile_SqlDataReader["subject"].ToString();
                            string[] subjectListItems = subjectList.Split(',');
                            foreach (string s in subjectListItems)
                            {
                                foreach (ListItem item in Subject_ListBox.Items)
                                {
                                    if (item.Value == s) item.Selected = true;
                                }
                            }

ETHERPAD

Posted by Venkat |

I Came across new EtherPad , which user can chat and , also edit the code simaltaneously both users

This is my etherPad - Come Here Chat Here..


http://venkat.etherpad.com/1

PayOffers.in