Wednesday, January 11, 2017

OnAuthorization in MVC


 public void OnAuthorization(AuthorizationContext filterContext)
        {          
            var skipAutherization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) ||                                filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true);
            if (!skipAutherization)
            {
              if (SessionManagement.UserID == Guid.Empty)
               {
                   filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { Controller = "Account", Action = "Login" }));
                }
            }
        } 


Using above code we can restrict/authenticate the particular actions and controllers 

How to get IPAddress,Browser name and Browser Version


 var ipAddress = Request.ServerVariables["remote_addr"];  //for getting IPAddress of the User 
var userAgent = string.Format("Browser ({0}) : {1}", Request.Browser.Browser, Request.Headers["User-Agent"]);  ///will get browser name and browser version

 var hostName= Dns.GetHostEntry("ip").HostName; // will get computer name of the user 
 

Update Xml Element Using C#


           var xdoc = new XmlDocument();
            xdoc.Load(webConfigPath);
            var endpointNodes = xdoc.SelectSingleNode("/configuration/system.serviceModel/client /endpoint");
            if (endpointNodes != null)
                endpointNodes.Attributes["address"].Value = addressValue;

            xdoc.Save(webConfigPath); 

 

Read and write Xml using C#


          var xdoc = new XmlDocument();
            xdoc.Load(webConfigPath);
            var connStringnodes = xdoc.SelectSingleNode("/configuration/connectionStrings");

            if (connStringnodes != null)
            {
                if (connStringnodes.ChildNodes.Count > 0)
                {
                    var elementNodeList = xdoc.GetElementsByTagName("connectionStrings");
                    foreach (XmlNode node in elementNodeList)
                    {
                        while (node.FirstChild != null)
                            node.RemoveChild(node.FirstChild);
                    }
                }
                var addElement = xdoc.CreateElement("add");
                addElement.SetAttribute("name", "conStringname");
                addElement.SetAttribute("connectionString", connectionStringValue);
                addElement.SetAttribute("providerName", providerNameValue);
                connStringnodes.AppendChild(addElement.Clone());

            }
            xdoc.Save(webConfigPath);

Above code will Change the Connectionstring child elements... 

StringSplitOptions.RemoveEmptyEntries

string somestring = "One,,Two,,,Three,,,Four,,";
somestring.Split(new char[] { ',' },   StringSplitOptions.RemoveEmptyEntries)

StringSplitOptions.RemoveEmptyEntries- Can remove empty strings after comma seperated from the above code


500.19 - Internal Server Error


 The requested page cannot be accessed because the related  configuration data for the page is invalid.

500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid..

if we get error like above we can add below lines in web.config file 
 Unsubscribe.aspx--> accessing page in my scenario.
<location path="Unsubscribe.aspx">
    <system.web>
      <authorization>
        <allow users="*"/>
      </authorization>
    </system.web>
  </location>

NetBIOS name using C#


 Environment.MachineName
 Gets the NetBIOS name of this local computer. 


Using Unit of Work in Controller


UnitOfWork unitOfWork = new UnitOfWork();
var profile = unitOfWork.ProfileRepository.Get(filter: p => p.Code == login);

in the above code filter: will work as where condition 


Model Error in MVC


ModelState.AddModelError("", "Invalid username or password."); 

How to Remove Plural table name from DbContext


 protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            Database.SetInitializer<PMContext>(null);
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            base.OnModelCreating(modelBuilder);            
        }

  modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

by adding this line we can remove the plural table name from DbContext

Saturday, July 30, 2016

windows could not start the mysql56 service on local computer


First try to stop the MySQL service if its in running mode.
In the next step please try to open mysql path (C:\ProgramData\MySQL\MySQL Server 5.7\Data)
Then delete both ib_logfile0 and ib_logfile1.
And finally restart the service

Thursday, June 23, 2016

List to Comma Seperated String in C#


 var SelectedVals = loadedObject.somelist.Select(s =>  s.string).ToList();
 loadedObject.Values = string.Join(",", SelectedVals);

Tuesday, June 21, 2016

How to convert class into xml

    In Model :

    [Serializable]
    [XmlRoot(ElementName = "Process")]
    [XmlType("Exweb.Models.ExampleViewModel")]
    public class ExampleModel
    {
        [XmlElement("Organization")]
        public string Organization { get; set; }
        public string  Name { get; set; }
         
        [XmlIgnoreAttribute]
        public RangeCategory<string> Category { get; set; }
    }

In Controller

XmlDocument xmlDoc = new XmlDocument();
            XmlSerializer xmlSerializer = new XmlSerializer(model.GetType());

            using (MemoryStream xmlStream = new MemoryStream())
            {
                xmlSerializer.Serialize(xmlStream, model);
                xmlStream.Position = 0;
                xmlDoc.Load(xmlStream);

                XmlNodeList xmlnode = xmlDoc.GetElementsByTagName("ProcessControl");
                XmlNode root = xmlDoc.DocumentElement;
                

                string path = AppDomain.CurrentDomain.BaseDirectory + @"\Uploads\Process\";   --- save it into folder
                if (!System.IO.File.Exists(path))
                {
                    System.IO.FileInfo file = new System.IO.FileInfo(path);
                    file.Directory.Create();
                }
                xmlDoc.Save(path + model.ProcessName + ".xml");
            }

XmlAttributes.XmlIgnore Property


 [XmlIgnoreAttribute] 
  public RangeCategory Category { get; set; }

Monday, June 20, 2016

Devexpress mvc if control name contains dot in it


var RaceFrom = ASPxClientControl.GetControlCollection().GetByName("Race.From"); RaceFrom.SetText("SomeText")

How to Get data from input if input name contains "." in it


$("input[name='Religion.From']").val()

How to maintain state of tempdata in mvc


 TempData["Something"] = "value";
 TempData.Keep("Something");

Xml to Model in MVC


 XmlDocument doc = new XmlDocument();
 string path = AppDomain.CurrentDomain.BaseDirectory +  @"\Uploads\Process\" + filename;c var serializer = new  XmlSerializer(typeof(ModelName));
 var processData = XDocument.Load(path);
 FileStream loadStream = new FileStream(path, FileMode.Open,  FileAccess.Read);
 ProcessControlModel loadedObject =  (ModelName)serializer.Deserialize(loadStream);
 loadStream.Close();

Thursday, May 26, 2016

Disable previous dates in devexpress mvc DateEdit


<script type="text/javascript">
    function UpdateInfo() {

        var daysTotal = EFFECTIVE_DATE_TO.GetRangeDayCount();
    }

</script>

    @Html.DevExpress().DateEdit(
    settings =>
     {
      settings.Name = "EFFECTIVE_DATE_TO";
      settings.Properties.ClientInstanceName = "EFFECTIVE_DATE_TO";
      settings.Properties.EditFormat = EditFormat.Custom;
      settings.Properties.EditFormatString = "MM/dd/yyyy";
      settings.Properties.ClientSideEvents.DateChanged = "UpdateInfo";
      settings.Properties.DateRangeSettings.StartDateEditID = "EFFECTIVE_DATE_FROM";
      settings.Properties.ValidationSettings.SetFocusOnError = true;
      settings.Properties.ValidationSettings.Display = Display.Dynamic;
      settings.Properties.ValidationSettings.EnableCustomValidation = true;
     }
    ).Bind(Model.EFFECTIVE_DATE_TO).GetHtml()
                                 

Convert String to XML


     String RECORDSXML= "Some Xml text";
      XmlDocument xdoc = new XmlDocument();

      if (RECORDSXML != null)
      {
          xdoc.LoadXml(Server.HtmlDecode(RECORDSXML));
      }

Protected by Copyscape Plagiarism Software