Application Manifest Schema:

Posted by senthil | 12:41:00 AM | , | 0 comments »

Application manifests are not new to the Windows Vista release. Manifests were used in Windows XP to help application developers identify such things as which versions of DLLs the application was tested with. Providing the execution level is an extension to that existing application manifest schema. The Windows Vista application manifest has been enhanced with attributes that permit developers to mark their applications with a requested execution level. The following is the format for this:
<requestedExecutionLevel
level="asInvoker|highestAvailable|requireAdministrator"
uiAccess="true|false"/>
Your application will prompt for elevation if the user is an administrator and UAC is enabled
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
  <security>
   <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
    <!-- UAC Manifest Options
      If you want to change the Windows User Account Control level replace the 
      requestedExecutionLevel node with one of the following.

    <requestedExecutionLevel level="asInvoker" uiAccess="false" />
    <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
    <requestedExecutionLevel level="highestAvailable" uiAccess="false" />

      Specifying requestedExecutionLevel node will disable file and registry virtualization.
      If you want to utilize File and Registry Virtualization for backward 
      compatibility then delete the requestedExecutionLevel node.
    -->
    <requestedExecutionLevel level="highestAvailable" uiAccess="false" />
   </requestedPrivileges>
  </security>
 </trustInfo>
Read more ...

This error i have experienced. when i going to start my application service while happened this error. Just start your service using sample application create one button click and then place this code. Its service start using ServiceController.
private void button1_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ServiceController sc = new ServiceController("YottaMark Code Dispenser");
                if ((sc.Status.Equals(ServiceControllerStatus.Stopped)))
                {
                    sc.Start();

                    MessageBox.Show("Starting the  YottaMark Code Dispenser");
                }
                MessageBox.Show("Started the YottaMark Code Dispenser");
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            }
        }
Read more ...

This code create a new gridview in wpf application. its working good.
<Grid>
        <DataGrid x:Name="MyDataGrid" x:Uid="MyDataGrid" AutoGenerateColumns="False" 
                       AlternationCount="2" SelectionMode="Single" Height="175" VerticalAlignment="Bottom" Background="White" Margin="12,0,12,12" CanUserAddRows="False" CanUserDeleteRows="False">
            <DataGrid.Columns>
                <DataGridTextColumn IsReadOnly="True" Binding="{Binding Path=Name}"
                                    Header="Name" Width="SizeToHeader" />
                <DataGridTextColumn IsReadOnly="True" Binding="{Binding Path=Email}" 
                                    Header="Email" Width="SizeToHeader" />
                <DataGridTextColumn IsReadOnly="True" Binding="{Binding Path=DOB}"
                                    Header="DOB" Width="SizeToHeader" />
                <DataGridTextColumn IsReadOnly="True" Binding="{Binding Path=Address1}"
                                    Header="Address1" Width="SizeToHeader" />
                <DataGridTextColumn IsReadOnly="True" Binding="{Binding Path=City}"
                                    Header="City" Width="SizeToHeader" />
                <DataGridTextColumn IsReadOnly="True" Binding="{Binding Path=Country}"
                                    Header="Country" Width="SizeToHeader" />
                <DataGridTemplateColumn Header="Edit">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Content="Edit" Click="EditButton_Click" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTemplateColumn Header="Delete">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Content="Delete" Click="DeleteButton_Click" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>                    
                </DataGridTemplateColumn>               
            </DataGrid.Columns>
        </DataGrid>
        <Label Content="Printer Configuration" FontSize="16" Foreground="Blue" Height="28" HorizontalAlignment="Left" Margin="8,5,0,0" Name="Title" VerticalAlignment="Top" Width="272" />
        <Button Content="Add Printer" Height="23" HorizontalAlignment="Left" Margin="409,12,0,0" Name="btnAddPrinter" VerticalAlignment="Top" Width="141" Background="Blue" Foreground="White" FontSize="13" Click="btnAddEmploy_Click" />
    </Grid>
Just copy this code and past your wpf xaml file side of the window after that
public void LoadEmploys()
        {
string employconfigFolder="D:\\Employ.xml"
            var doc = new XmlDocument();
            doc.Load(employconfigFolder);

            XmlNodeList employ = doc.GetElementsByTagName("Employ");

            List<EmployAttribute> authors = new List<EmployAttribute>();

            foreach (XmlNode item in employ)
            {
                bool defaultPrinter = false;

                authors.Add(new PrinterAttribute()
                {
                    Name = item.Attributes["Name"].Value,
                    Email = item.Attributes["Email"].Value,
                    DOB = item.Attributes["DOB"].Value,
                    Address1 = item.Attributes["Address1"].Value,
                    City = item.Attributes["City"].Value,
                    Country = item.Attributes["Country"].Value,
                });
            }
            MyDataGrid.ItemsSource = authors;
        }



 public class EmployAttribute
        {
            public string Name { get; set; }
            public string Email { get; set; }
            public string DOB { get; set; }
            public string Address1 { get; set; }
            public bool City { get; set; }
            public bool Country { get; set; }
        }
you can call LoadEmploys() method in your window_Loaded() its working fine.
Read more ...

How to method call using Timer in c#

Posted by senthil | 12:09:00 PM | | 0 comments »

this code using the system timer we can call the method. i tried working good. its a easy way to call the method using Timer interval time. Following the sample code:
private void button1_Click(object sender, RoutedEventArgs e)
        {
            aTimer = new System.Timers.Timer(10000);

            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

            aTimer.Interval = 2000;
            aTimer.Enabled = true;

            Console.WriteLine("Press the Enter key to exit the program.");
            Console.ReadLine();
           
        }

        private static void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            aTimer.Enabled = false;
            Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
        }
Read more ...

This is code when i create my sample web application i want to create html ui in back end code so i created using string builder.
if (dt.Rows.Count > 0)
            {
                StringBuilder strb = new StringBuilder();
                strb.Append("<br/><br/>");
                strb.Append("<table border='1' cellpadding='3'>");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    strb.Append("<tr><td>");
                    strb.Append(dt.Rows[i]["Subject"].ToString());
                    strb.Append("</td>");
                    strb.Append("<td>");
                    strb.Append("<input type=\"text\" name=\"subject\" id=\"txtSubject" + i.ToString() + "\" runat=\"server\" />");
                    strb.Append("<input type=\"hidden\" name=\"hidsubject\" id=\"hidSubject" + i.ToString() + "\" runat=\"server+\" value=" + dt.Rows[i]["Subject_ID"].ToString() + "/>");
                    strb.Append("</td></tr>");
                }
                //subject = subject + "," + dt.Rows[i]["Subject_ID"].ToString();
                //hidSubject.Value = subject;
                strb.Append("</table>");
                divMark.InnerHtml = strb.ToString();
            }
Read more ...

This solution i experienced. when i develop wpf application there i used combobox. when i try to add new student that time combobox items not reloaded. because of application loading time i loaded dynamically. so i don't no how to refresh the combobox list. After that i got this solution. when u add new item while after "objwindow.ShowDialog()" refresh the combobox.
 <ComboBox Name="Student" ItemsSource="{Binding Source={StaticResource Students}, XPath=Student/@StudentName}"
SelectionChanged="{pti:DelegateCreator student_Changed}" MinWidth="150"
Style="{StaticResource RequiredComboBox}" />
if you want to refresh from the controller your combobox name declare commonly like
ComboBox _studentList = FindLogicalNode(window, STUDENT_LIST) as ComboBox;
other wise your refresh from the xaml.cs file there your can declare like "this.FindResource"
private static void studentConfig_Click(object source, RoutedEventArgs args)
        {
            StudentConfiguration objwindow = new StudentConfiguration();
            objwindow.ShowDialog();
            (_studentList.FindResource("Students") as XmlDataProvider).Refresh();            
        }
Read more ...

This code when i want to get all my system printer list and set the default printer in my application while i used this code its working good. because of i want to do bar code printer so i have used more then one printer. Its very easy to get the system printer name using this method.
using System.Text;
using System.Windows.Forms;
using System.Management;
using System.Drawing.Printing;

namespace GetPrintersName
{
    public partial class Form1 : Form
    {
        public Form1()
        {           
            InitializeComponent();
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        printer();
    }

    public static void printer() 
    {
        foreach (string printer in PrinterSettings.InstalledPrinters)
                 Console.WriteLine(printer);
 
            var printerSettings = new PrinterSettings();
            Console.WriteLine(string.Format("The default printer is: {0}",                         printerSettings.PrinterName));                 
     }
}
Read more ...

This is code Add xml node in configuration file using C# method. Step:1 this is sample.config file
<TABLE>
<ROW>
    <COLUMN SOURCE="1" NAME="age" />
    <COLUMN SOURCE="3" NAME="firstname" />
    <COLUMN SOURCE="4" NAME="lastname" />
  </ROW>
</TABLE>
Step:2 I want to add xml node for my application configuration settings. so i want to add configuration setting using user interface Step:3 I created user interface one add page for add xml node. Step:4 I used this method and pass the xml value add the node.
public bool AddconfigFileXmlNode()
        {
            try
            {
                var doc = new XmlDocument();
                doc.Load("D:\\sample.config");
                 
                XmlNode profile;                
                profile = doc.SelectSingleNode("TABLE/ROW");

                XmlElement newChild = doc.CreateElement("COLUMN");

                newChild.SetAttribute("SOURCE", "4");
                newChild.SetAttribute("NAME", "lastname");  
            

                profile.AppendChild(newChild);
                doc.Save("D:\\sample.config");
            }
            catch { }
            return true;
        }
Read more ...

This is split the your string value using the special character
 private void SplitString()
        {
     string _BaseString="RIVE-SENT-KUMA-XXX"
            string[] seperate_filelds = _BaseString.Split('-');
            int counter = 0;
           // bool is_legit = false;

            foreach (string each_field in seperate_filelds)
            {
                counter++;
                // reading the first field which is prefix field
                if (counter == 1)
                {
     //fristValue = "RIVE";
                   string fristValue = each_field  ;

                }
                else if (counter == 2)
                {
                    //secondValue = "SENT";
                   string secondValue = each_field  ;
                }
  else if (counter == 3)
                {
                    //thirdValue = "SENT";
                   string secondValue = each_field  ;
                }
  else if (counter == 4)
                {
                    //furthValue = "XXXX";
                   string furthValue = each_field  ;
                }
               else
                { break; }
            }
                     
        }
Read more ...

This is one way of Encryption and Decryption algorithm. Its working good.
  private const string initVector = "tu89geji340t89u2";

        private const int keysize = 256;

        public static string Encrypt(string Text, string Key)
        {
            byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(Text);
            PasswordDeriveBytes password = new PasswordDeriveBytes(Key, null);
            byte[] keyBytes = password.GetBytes(keysize / 8);
            RijndaelManaged symmetricKey = new RijndaelManaged();
            symmetricKey.Mode = CipherMode.CBC;
            ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
            MemoryStream memoryStream = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
            cryptoStream.FlushFinalBlock();
            byte[] Encrypted = memoryStream.ToArray();
            memoryStream.Close();
            cryptoStream.Close();
            return Convert.ToBase64String(Encrypted);
        }

        public static string Decrypt(string EncryptedText, string Key)
        {
            byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
            byte[] DeEncryptedText = Convert.FromBase64String(EncryptedText);
            PasswordDeriveBytes password = new PasswordDeriveBytes(Key, null);
            byte[] keyBytes = password.GetBytes(keysize / 8);
            RijndaelManaged symmetricKey = new RijndaelManaged();
            symmetricKey.Mode = CipherMode.CBC;
            ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
            MemoryStream memoryStream = new MemoryStream(DeEncryptedText);
            CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
            byte[] plainTextBytes = new byte[DeEncryptedText.Length];
            int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
            memoryStream.Close();
            cryptoStream.Close();
            return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
        }
Read more ...

I want to know my system information using C# 1. ProcessorId 2. Product 3. Manufacturer 4. Signature 5. Caption 6. PhysicalMedia(SerialNumber) 7. Version 8. OperatingSystem(SerialNumber) just call the method like this:
RunQuery("Processor", "ProcessorId");
RunQuery("BaseBoard", "Product");
RunQuery("BaseBoard", "Manufacturer");
RunQuery("DiskDrive", "Signature");
RunQuery("VideoController", "Caption");
RunQuery("PhysicalMedia", "SerialNumber");
RunQuery("BIOS", "Version");
RunQuery("OperatingSystem", "SerialNumber");
 private static string RunQuery(string TableName, string MethodName)
        {
            ManagementObjectSearcher MOS = new ManagementObjectSearcher("Select * from Win32_" + TableName);
            foreach (ManagementObject MO in MOS.Get())
            {
                try
                {
                    return MO[MethodName].ToString();
                }
                catch (Exception e)
                {
                    System.Windows.Forms.MessageBox.Show(e.Message);
                }
            }
            return "";
        }
Read more ...

This code remove the special character from string value using c sharp. when i want to string value only the aliphatic and number. I trim the special character using the method.
private static string RemoveUseLess(string st)
        {
            char ch;
            for (int i = st.Length - 1; i >= 0; i--)
            {
                ch = char.ToUpper(st[i]);

                if ((ch < 'A' || ch > 'Z') &&
                    (ch < '0' || ch > '9'))
                {
                    st = st.Remove(i, 1);
                }
            }
            return st;
        }
Read more ...

Cryptography Alogrithm using C#

Posted by senthil | 10:13:00 PM | | 0 comments »

This is Encryption and Decryption algorithm. Its work good I used on this code working perfectly.
public static string Encrypt(string toEncrypt, bool useHashing)
{
    byte[] keyArray;
    byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

    System.Configuration.AppSettingsReader settingsReader = 
                                        new AppSettingsReader();
    // Get the key from config file

    string key = (string)settingsReader.GetValue("SecurityKey", 
                                                     typeof(String));
    //System.Windows.Forms.MessageBox.Show(key);
    //If hashing use get hashcode regards to your key
    if (useHashing)
    {
        MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
        keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
        //Always release the resources and flush data
        // of the Cryptographic service provide. Best Practice

        hashmd5.Clear();
    }
    else
        keyArray = UTF8Encoding.UTF8.GetBytes(key);

    TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
    //set the secret key for the tripleDES algorithm
    tdes.Key = keyArray;
    //mode of operation. there are other 4 modes.
    //We choose ECB(Electronic code Book)
    tdes.Mode = CipherMode.ECB;
    //padding mode(if any extra byte added)

    tdes.Padding = PaddingMode.PKCS7;

    ICryptoTransform cTransform = tdes.CreateEncryptor();
    //transform the specified region of bytes array to resultArray
    byte[] resultArray = 
      cTransform.TransformFinalBlock(toEncryptArray, 0, 
      toEncryptArray.Length);
    //Release resources held by TripleDes Encryptor
    tdes.Clear();
    //Return the encrypted data into unreadable string format
    return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}





public static string Decrypt(string cipherString, bool useHashing)
{
    byte[] keyArray;
    //get the byte code of the string

    byte[] toEncryptArray = Convert.FromBase64String(cipherString);

    System.Configuration.AppSettingsReader settingsReader = 
                                        new AppSettingsReader();
    //Get your key from config file to open the lock!
    string key = (string)settingsReader.GetValue("SecurityKey", 
                                                 typeof(String));
            
    if (useHashing)
    {
        //if hashing was used get the hash code with regards to your key
        MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
        keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
        //release any resource held by the MD5CryptoServiceProvider

        hashmd5.Clear();
    }
    else
    {
        //if hashing was not implemented get the byte code of the key
        keyArray = UTF8Encoding.UTF8.GetBytes(key);
    }

    TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
    //set the secret key for the tripleDES algorithm
    tdes.Key = keyArray;
    //mode of operation. there are other 4 modes. 
    //We choose ECB(Electronic code Book)

    tdes.Mode = CipherMode.ECB;
    //padding mode(if any extra byte added)
    tdes.Padding = PaddingMode.PKCS7;

    ICryptoTransform cTransform = tdes.CreateDecryptor();
    byte[] resultArray = cTransform.TransformFinalBlock(
                         toEncryptArray, 0, toEncryptArray.Length);
    //Release resources held by TripleDes Encryptor                
    tdes.Clear();
    //return the Clear decrypted TEXT
    return UTF8Encoding.UTF8.GetString(resultArray);
}



<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
Read more ...

This is the print.config file
<PrintingConfiguration>
  <Printers>
    <Printer DisplayName="text1">senthil</Printer>
    <Printer DisplayName="text1">kumar</Printer>
  </Printers>
</PrintingConfiguration>
Step 1 : Create a click event and then load the xml file in XMLDocument object.
Step 2 : Select the corresponding node using "SelectSingleNode".
Step 3 : Next i will pass the delete node value "delectvalue" from the "MyDataGrid" grid view row DisplayName "Text1".
Step 4 : Delete the Selected node.
private void DeleteButton_Click(object sender, RoutedEventArgs e)
        {
            var doc = new XmlDocument();
            doc.Load(AppDomain.CurrentDomain.BaseDirectory + "..\\..\\Printing.config");           

            XmlNode root = doc.SelectSingleNode("//Printers");
            Author customerRow = MyDataGrid.SelectedItem as Author;

            string delectvalue = customerRow.DisplayName;

            string xpath = "//Printer[@DisplayName= \"" + delectvalue + "\"]";
            XmlNode currentNode = root.SelectSingleNode(xpath);
            
            if (currentNode != null)
            {
                // Delete the record.
                root.RemoveChild(currentNode);
            }
            // Save the changes. 
            doc.Save(printconfigFolder);

            LoadCustomers();
            MyDataGrid.Items.Refresh();
        }
Read more ...

Hello, The below code will assist you to debug "Column Sorting with checkbox" using Datatable feature. for example: if you like to make click on the feature and in return the whole column with checkbox will get sorted
       "aoColumns": [
            null,
            null,
            null,
            null,
            null,
            { "sSortDataType": "dom-checkbox" },
            null
        ],

$.fn.dataTableExt.afnSortData['dom-checkbox'] = function (oSettings, iColumn) {
            var aData = [];
            $('td:eq(' + iColumn + ') input', oSettings.oApi._fnGetTrNodes(oSettings)).each(function () {
                aData.push(this.checked == true ? "1" : "0");
            });
            return aData;
        }
hope this help While i have jquery issue in

"Uncaught TypeError: Cannot call method 'fnSetData' of undefined".

and I fixed using the reference link http://datatables.net/forums/discussion/7897/need-help-uncaught-typeerror-cannot-call-method-fnsetdata-of-undefined/p1 the Problem is I missed the red color column highlighted definition like
       "aoColumns": [
            null,
            null,
            null,
            null,
            null,
            { "sSortDataType": "dom-checkbox" },
            null            
        ],
Senthilnathan
Read more ...

UpdateException was caught

Posted by senthil | 6:18:00 PM | , | 0 comments »

MVC4

Answer:

I had this issue when i save my application data. This error may be your Foreign key reference value gave wrongly check and give correctly.
Read more ...

I'm working in MVC4. when i edit my application page i have this error. its very simple.
public ActionResult Edit(int id)
{
var Hospital = HospitalClinicsModels.GetPartnerById(id);

var EditHospital = new EditHospitalClinicsModel()
{

}
return View(EditHospital);
}
Read more ...

Its very useful while click the checkbox the onclick funcation called jquery that hidden value used div will be open while checkbox checked. Uncheck the checkbox the div will be hid.
<input type="checkbox" id="ChangePassword" onclick = "DisplayChangePasswordField();"/>
 <input type="hidden" id="hidChangePassword" name="hidChangePassword" value="0" />
<div id="divchangepassword">
you can hid this div while clicking the checkbox.
</div>
$(document).ready(function () {
            $("#divchangepassword").hide();
        });
        function DisplayChangePasswordField() {
            var hideValue = $("#hidChangePassword").val();
            var newHideValue = 0;

            if (hideValue == 0) {
                newHideValue = 1;
            }
            else {
                newHideValue = 0;
            }
            if (newHideValue == 0) {
                $("#divchangepassword").hide();
            }
            else {
                $("#divchangepassword").show();
            }
            $("#hidChangePassword").val(newHideValue);
            return false;

        }    
Read more ...

This error will happened when we will create new virtual directory in your project. your are miss some property settings. I have also some issue. I fixed easily.
  • Open IIS Manager
  • Select the Application pool drop down
  • Change the ASP.NET V4.0
  • Save the Properties
  • thats all.......
    Read more ...

    Store provider connection not found

    When i have Start in my MVC4 project by the time, I have a this issue, i was very confiused about this issue first i have to install MVC4 only after that i have to install MVC3 then i was installed MySql Connector Net 5.5.1 and Unstalled my MySql Database

    now All's good until I run the app. My "fix" doesn't stick. This error pointed in .edmx file. The main problem is MySql Connector not supported in this application. Its very simple 'fix' after that I installed MySql Connector Net 6.6.5 Advance version to be install it will solved.

    Read more ...

    This server side error usually will be come, when we give the wrong URL. now how we can handle the in your .net application. That time we will show the custom error message. like this create one 404.aspx page in your own way to display that error message using HTML. Next this method is URLRewriter. we can get the error response then response is Empty you can redirect to 404.aspx page.
    public void context_BeginRequest(object sender, EventArgs e)
            {
                HttpApplication application = (HttpApplication)sender;
                HttpContext context = application.Context;
    
                if (HttpContext.Current.Request.Url.ToString().Contains("Redirect.aspx"))
                {
                    if (context.Request.QueryString["key"] != null)
                    {
                        string inputStr = context.Request.QueryString["key"].ToString();
    
                        if (inputStr != "none/")
                        {
                            if (inputStr.EndsWith("/"))
                            {
                                inputStr = inputStr.Substring(0, inputStr.Length - 1);
                            }
    
                            HttpContext.Current.RewritePath(Helper.GetRedirectPage(inputStr), false);
                        }
                    }
                    else
                    {
                        HttpContext.Current.RewritePath("~/Server_Error/404.aspx", false);
                    }
                }
            }
    
    and another one way to handle this error message. simply we can wrote in your web.config file like this...
    <customErrors mode="On">
       <error statusCode="403" redirect="NoAccess.htm"/>
       <error statusCode="404" redirect="~/Server_Error/404.aspx"/>
      </customErrors>
    
    Read more ...

    When accepting input from your user, your program should expect that invalid characters will be entered. For example, your program has a custom file name dialog. You want to quickly detect invalid path characters. So: You can use the Path.GetInvalidFileNameChars and Path.GetInvalidPathChars methods. Tip: You can use the character arrays returned by Path.GetInvalidFileNameChars and Path.GetInvalidPathChars with a Dictionary.
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    
    class Program
    {
        static void Main()
        {
     // First, we build a Dictionary of invalid characters.
     var dict = GetInvalidFileNameChars();
     // Next, we test the dictionary to see if the asterisk (star) is valid.
     if (dict.ContainsKey('*'))
     {
         // This will run, because the star is in the Dictionary.
         Console.WriteLine("* is an invalid char");
     }
        }
    
        /// <summary>
        /// Get a Dictionary of the invalid file name characters.
        /// </summary>
        static Dictionary<char, bool> GetInvalidFileNameChars()
        {
     // This method uses lambda expressions with ToDictionary.
     return Path.GetInvalidFileNameChars().ToDictionary(c => c, c => true);
        }
    }
    
    Outpuut

    * is an invalid char
    
    Read more ...

    Program that uses Path.Combine [C#]

    Posted by senthil | 8:18:00 PM | , | 0 comments »

    Path.Combine is a useful method, but there are edge cases it cannot solve. It can't figure out what you want if what it receives is confusing. But different inputs can yield the same result path. Next: Here's a screenshot where we combine the folder "Content\\" with the file name "file.txt".
    using System;
    
    class Program
    {
        static void Main()
        {
     //
     // Combine two path parts.
     //
     string path1 = System.IO.Path.Combine("Content", "file.txt");
     Console.WriteLine(path1);
    
     //
     // Same as above but with a trailing separator.
     //
     string path2 = System.IO.Path.Combine("Content\\", "file.txt");
     Console.WriteLine(path2);
        }
    }
    
    Output

    Content\file.txt
    Content\file.txt
    
    Read more ...

    Program that uses GetExtension [C#]

    Posted by senthil | 8:14:00 PM | , | 0 comments »

    The Path type includes also support for extensions. We can get an extension, with GetExtension, or even change an extension with ChangeExtension. The method names are obvious and easy-to-remember. GetExtension handles extensions of four letters. It also handles the case where a file name has more than one period in it. This next program briefly tests GetExtension. You can find further details and benchmarks.
    using System;
    using System.IO;
    
    class Program
    {
        static void Main()
        {
     // ... Path values.
     string value1 = @"C:\perls\word.txt";
     string value2 = @"C:\file.excel.dots.xlsx";
    
     // ... Get extensions.
     string ext1 = Path.GetExtension(value1);
     string ext2 = Path.GetExtension(value2);
     Console.WriteLine(ext1);
     Console.WriteLine(ext2);
        }
    }
    
    Output

    .txt
    .xlsx
    
    Read more ...

    Extensions GetFileName­WithoutExtension will return the entire file name if there's no extension on the file.Path.GetDirectoryName returns the entire string except the file name and the slash before it.

    Syntax


    When specifying paths in C# programs, we must use two backslashes "\\" unless we use the verbatim string syntax. A verbatim string uses the prefix character "@". Only one backslash is needed in this literal syntax.
    using System;
    using System.IO;
    
    class Program
    {
        static void Main()
        {
     // ... Verbatim string syntax.
     string value = @"C:\directory\word.txt";
     Console.WriteLine(Path.GetFileName(value));
        }
    }
    
    OutPut
    word.txt
    Read more ...

    Program that tests Path class [C#]

    Posted by senthil | 7:56:00 PM | , | 0 comments »

    The extension of the file, the actual filename, the filename without extension, and path root. The path root will always be "C:\\", with the trailing separator, even when the file is nested in many folders. GetFileName. You can get the filename alone by calling the Path.GetFileName method. This will return the filename at the end of the path, along with the extension, such as .doc or .exe.

    extension —Path.GetFileNameWithoutExtension.

    It is useful to see the results of the Path methods on various inputs. Sometimes the methods handle invalid characters as you might expect. Sometimes they do not. This program calls three Path methods on an array of possible inputs.
    using System;
    using System.IO;
    
    class Program
    {
        static void Main()
        {
     string[] pages = new string[]
     {
         "cat.aspx",
         "really-long-page.aspx",
         "test.aspx",
         "invalid-page",
         "something-else.aspx",
         "Content/Rat.aspx",
         "http://dotnetperls.com/Cat/Mouse.aspx",
         "C:\\Windows\\File.txt",
         "C:\\Word-2007.docx"
     };
     foreach (string page in pages)
     {
         string name = Path.GetFileName(page);
         string nameKey = Path.GetFileNameWithoutExtension(page);
         string directory = Path.GetDirectoryName(page);
         //
         // Display the Path strings we extracted.
         //
         Console.WriteLine("{0}, {1}, {2}, {3}",
      page, name, nameKey, directory);
     }
        }
    }
    
    OutPut

    Input:                       cat.aspx
    GetFileName:                 cat.aspx
    GetFileNameWithoutExtension: cat
    GetDirectoryName:            -
    
    Input:                       really-long-page.aspx
    GetFileName:                 really-long-page.aspx
    GetFileNameWithoutExtension: really-long-page
    GetDirectoryName:            -
    
    Input:                       test.aspx
    GetFileName:                 test.aspx
    GetFileNameWithoutExtension: test
    GetDirectoryName:            -
    
    Input:                       invalid-page
    GetFileName:                 invalid-page
    GetFileNameWithoutExtension: invalid-page
    GetDirectoryName:            -
    
    Input:                       Content/Rat.aspx
    GetFileName:                 Rat.aspx
    GetFileNameWithoutExtension: Rat
    GetDirectoryName:            Content
    
    Input:                       http://dotnetperls.com/Cat/Mouse.aspx
    GetFileName:                 Mouse.aspx
    GetFileNameWithoutExtension: Mouse
    GetDirectoryName:            http:\dotnetperls.com\Cat
    
    Input:                       C:\Windows\File.txt
    GetFileName:                 File.txt
    GetFileNameWithoutExtension: File
    GetDirectoryName:            C:\Windows
    
    Input:                       C:\Word-2007.docx
    GetFileName:                 Word-2007.docx
    GetFileNameWithoutExtension: Word-2007
    GetDirectoryName:            C:\
    
    Read more ...

    Program that uses Path methods [C#]

    Posted by senthil | 7:40:00 PM | , | 0 comments »

    Path handles file path processing.Its a major thing the Path type in the System.IO namespace. Its very critical when using directly with paths.

    Examples

    If you need to extract filename path in your program. You can access it by adding "using System.IO" at the top of your class.

    Console


    using System;
    using System.IO;
    
    class Program
    {
        static void Main()
        {
     string path = "C:\\stagelist.txt";
    
     string extension = Path.GetExtension(path);
     string filename = Path.GetFileName(path);
     string filenameNoExtension = Path.GetFileNameWithoutExtension(path);
     string root = Path.GetPathRoot(path);
    
     Console.WriteLine("{0}\n{1}\n{2}\n{3}",
         extension,
         filename,
         filenameNoExtension,
         root);
        }
    }
    
    Output

    .txt
    stagelist.txt
    stagelist
    C:\
    
    Read more ...

    There are only follow the three steps. it will getting a easy to set the popup background transparent. I tried to do this its good. Just copy and paste save the html file. put the code the warm server then only jquery file will work then it will open the popup. besides to use what you need.
    <style> .blockbkg { background-color: black; opacity: 90%; filter:alpha(opacity=90); background-color: rgba(0,0,0,0.90); width: 100%; min-height: 100%; overflow: hidden; float: absolute; position: fixed; top: 0; left: 0; color: white; } .cont { background-color: white; color: black; font-size: 16px; border: 1px solid gray; padding: 20px; display:block; position: absolute; top: 10%; left: 35%; width: 400px; height: 400px; overflow-y: scroll; } .closebtn { width: 20px; height: 20px; padding: 5px; margin: 2px; float: right; top: 0; background-image: url(x.png); background-repeat: no-repeat; background-position:center; background-color: lightgray; display: block; } .closebtn:hover { cursor: pointer; } .normal { background-color: lightblue; width: 900px; min-height: 200px; padding: 20px; } </style>

    Step:2

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript">
    </script>
    
    <script>
    $(document).ready(function () {
    $("#closebtn").click(function () {
    $("#dlg").hide('800', "swing", function () { $("#bkg").fadeOut("500"); });
    });
    $("#opn").click(function () {
    if (document.getElementById('bkg').style.visibility == 'hidden') {
    document.getElementById('bkg').style.visibility = '';
    $("#bkg").hide();
    }
    if (document.getElementById('dlg').style.visibility == 'hidden') {
    document.getElementById('dlg').style.visibility = '';
    $("#dlg").hide();
    }
    $("#bkg").fadeIn(500, "linear", function () { $("#dlg").show(800, "swing"); });
    });
    
    });
    </script>
    

    Step:3

    <body> <div class="normal"> <h1>Modal Dialogs</h1> <p> This is an example of how to create <strong>modal dialog popup windows</strong> for your pages using javascript and CSS. Modal dialog popups are better than window-based popups, because a new browser window is not required and the user does not have to leave the page. This is great for when you need an easy way for the user to carry out a specific action on the same page and control the modality of the window. </p> <p><a href="#" id="opn">Click here</a> to display the javascript modal popup dialog!</p> </div> <div class="blockbkg" id="bkg" style="visibility: hidden;"> <div class="cont" id="dlg" style="visibility: hidden;"> <div class="closebtn" title="Close" id="closebtn"></div> <h1>Hello World!</h1> <p> This is a neat little trick to get a modal popup dialog box in your web pages without disturbing the user experience or dsitracting them with popup windows or new tabs... </p> <p> The <strong>popup dialog</strong> uses javascript (jQuery) and CSS to create a modal dialog that will retain focus over the parent window until it is closed. The trick is simple. We use block-elements (divs) to create the dialog window. The CSS rules for <em>position</em>, <em>float</em>, <em>top</em>, <em>left</em>/<em>right</em>, and <em>opacity</em> (or CSS3 transparency) allows us to create a semi-transparent div over the entire page, thereby creating the illusion of modalness. The other div then takes focus over the center of the window. </p> <img src="https://sheriframadan.com/examples/uploadit/uploads/50f00e1434e8b.jpg" width="200" height="252"> <p> We can also retain content view control over the modal dialog with the <em>overflow</em> CSS property. This means no matter what we place inside of our dialog window the content will remain inside of the defined bounds even if scrolling becomes necessary within the div. </p> </div> </div> </body> <html>
    Read more ...

    Related Posts Plugin for WordPress, Blogger...